diff --git a/.github/scripts/ci-contract/workflows.test.mjs b/.github/scripts/ci-contract/workflows.test.mjs index 99d9d02a5a..f03dbe81d5 100644 --- a/.github/scripts/ci-contract/workflows.test.mjs +++ b/.github/scripts/ci-contract/workflows.test.mjs @@ -183,6 +183,15 @@ function hostedContract(config, kind) { { name: 'Test helper', run: `${helper} test` }, { name: 'Lint helper', run: `${helper} lint` }, { name: 'Test regression pixel oracle', run: 'bash experiments/tart-regression/test-oracle.sh "$PWD/.build/regression-oracle"' }, + { + name: 'Check media fixture', + run: 'mkdir -p "$PWD/.build"\n' + + 'python3 -B experiments/tart-regression/MediaFixture/build.py check --output "$PWD/.build/mediafixture-ci"\n', + }, + { + name: 'Test media fixture build recipe', + run: "python3 -B -m unittest discover -s experiments/tart-regression/MediaFixture/Tests -p 'test_build.py'", + }, ] : [ { name: 'Install contract test dependency', run: install }, { name: 'Test workflow contracts', run: 'npm test --prefix .github/scripts/ci-contract' }, @@ -525,6 +534,53 @@ const mutations = [ ['helper credentials persisted', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { c.jobs.validate.steps[0].with['persist-credentials'] = true; }], ['helper write permissions', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { c.permissions.contents = 'write'; }], ['helper runtime step', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { c.jobs.validate.steps.push({ run: `${helper} run inspect` }); }], + ['media fixture on Ubuntu', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + c.jobs.validate['runs-on'] = 'ubuntu-latest'; + }], + ['skipped media fixture job', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + c.jobs.validate.if = 'false'; + }], + ['ignored media fixture job failures', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + c.jobs.validate['continue-on-error'] = true; + }], + ['missing media fixture parent directory', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + const fixture = step(c.jobs.validate, 'Check media fixture'); + fixture.run = fixture.run.replace('mkdir -p "$PWD/.build"\n', ''); + }], + ['media fixture app build instead of check', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + const fixture = step(c.jobs.validate, 'Check media fixture'); + fixture.run = fixture.run.replace('build.py check', 'build.py build'); + }], + ['filtered media fixture recipe tests', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + step(c.jobs.validate, 'Test media fixture build recipe').run += ' -k test_check'; + }], + ['media fixture recipe before parent preparation', 'notch_control', (c) => hostedContract(c, 'helper'), (c) => { + const steps = c.jobs.validate.steps; + const recipe = steps.splice(steps.findIndex((s) => s.name === 'Test media fixture build recipe'), 1)[0]; + steps.splice(steps.findIndex((s) => s.name === 'Check media fixture'), 0, recipe); + }], + ...['Check media fixture', 'Test media fixture build recipe'].flatMap((name) => [ + ['missing', (c) => { c.jobs.validate.steps = c.jobs.validate.steps.filter((s) => s.name !== name); }], + ['skipped', (c) => { step(c.jobs.validate, name).if = 'false'; }], + ['ignored failures', (c) => { step(c.jobs.validate, name)['continue-on-error'] = true; }], + ['masked exit status', (c) => { + const fixture = step(c.jobs.validate, name); + fixture.run = `${fixture.run.trimEnd()} || true`; + }], + ['non-failing shell', (c) => { step(c.jobs.validate, name).shell = 'bash {0}'; }], + ['before oracle gate', (c) => { + const steps = c.jobs.validate.steps; + const fixture = steps.splice(steps.findIndex((s) => s.name === name), 1)[0]; + steps.splice(steps.findIndex((s) => s.name === 'Test regression pixel oracle'), 0, fixture); + }], + ].map(([mutation, mutate]) => [ + `${name}: ${mutation}`, 'notch_control', (c) => hostedContract(c, 'helper'), mutate, + ])), + ...['Check media fixture', 'Test media fixture build recipe'].map((name) => [ + `${name}: added to Ubuntu contracts`, 'ci_contract_tests', (c) => hostedContract(c, 'contracts'), (c) => { + c.jobs.test.steps.push(step(workflow('notch_control').jobs.validate, name)); + }, + ]), ['missing policy regression run', 'ci_contract_tests', (c) => hostedContract(c, 'contracts'), (c) => { c.jobs.test.steps = c.jobs.test.steps.filter(({ name }) => name !== 'Test PR target policy'); }], diff --git a/.github/workflows/notch_control.yml b/.github/workflows/notch_control.yml index 9024d95535..044aefe728 100644 --- a/.github/workflows/notch_control.yml +++ b/.github/workflows/notch_control.yml @@ -29,3 +29,9 @@ jobs: run: bash scripts/notch-control/control.sh lint - name: Test regression pixel oracle run: bash experiments/tart-regression/test-oracle.sh "$PWD/.build/regression-oracle" + - name: Check media fixture + run: | + mkdir -p "$PWD/.build" + python3 -B experiments/tart-regression/MediaFixture/build.py check --output "$PWD/.build/mediafixture-ci" + - name: Test media fixture build recipe + run: python3 -B -m unittest discover -s experiments/tart-regression/MediaFixture/Tests -p 'test_build.py' diff --git a/.swiftlint.yml b/.swiftlint.yml index a36601cfcd..f53b354e65 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -70,7 +70,6 @@ identifier_name: - vm - s - NotchLayout - - NotchPocketFaceAnimation - MusicLiveActivity - HelpText - NotchBehaviour diff --git a/AGENTS.md b/AGENTS.md index faa99ef85d..645c6df800 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -239,7 +239,8 @@ commands. The parent reconciles the actual diff before executing any gates. Require the human-supplied full existing **Developer ID Application** certificate name, explicit ten-character team ID and a new canonical absolute build directory beneath this checkout's existing `.build/`. Do not inspect Keychain, -read/copy `local.env`, import/export certificates or embed personal selectors. +read/copy `local.env`, import/export Keychain certificates or private keys, or +embed personal selectors. No path reuse, overwriting, input-app mutation, installation or app launch: ```bash @@ -249,6 +250,34 @@ python3 -B scripts/distribution.py \ --build-dir "$PWD/.build/np9-signing-001" ``` +The canonical command retains existing full-name selection without an extra +flag. **Optional variant for duplicate certificate names:** + +```bash +python3 -B scripts/distribution.py \ + --identity 'Developer ID Application: YOUR CERTIFICATE NAME (YOURTEAMID)' \ + --team 'YOURTEAMID' \ + --certificate-sha1 'PUBLIC_CERTIFICATE_SHA1_40_HEX_CHARACTERS' \ + --build-dir "$PWD/.build/np9-signing-sha1-001" +``` + +`--certificate-sha1` belongs to **`scripts/distribution.py` only**. +`scripts/notarize.py` DMG signing and the hosted release pipeline remain +name-selected and unchanged; neither accepts or forwards this option. +The optional public leaf fingerprint uses exactly 40 hexadecimal characters +(either case, no separators or prefix). Name and team remain mandatory. +Use a human-provided known certificate fingerprint, or the +[README's artifact-only extraction example](README.md#local-developer-id-candidate-9-bounded-slice) +with an explicit already-approved signed artifact: +`codesign --extract-certificates` into a new task-owned temporary directory, then +`openssl x509` for the public leaf's SHA-1 fingerprint. This is public artifact +metadata only, not permission for Keychain inspection/enumeration, access +changes, private-key export or artifact mutation. Extraction is not signature +verification or proof that the signing identity is usable. The fingerprint +selects Xcode/resource/outer-app signing and constrains every final bundle/Mach-O +verification on all architectures; chain, name/team and all other signature +checks remain required. No fallback to the common name on failure. + The parent creates the `.build/` parent if needed and substitutes the approved selector/team; placeholders are not configured values. The command discovers full Xcode 26+ (rejecting invalid explicit `DEVELOPER_DIR` or CLT-only setups), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2077677d09..a8b7fbd883 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -139,7 +139,7 @@ hosted run or distribution succeeded. | [Native helper](.github/workflows/notch_control.yml) | Unfiltered `pocket` push/PR on `macos-26`, read-only contents, non-persisted checkout credentials, 20-minute timeout. Canonical build, all 69 package tests, and exactly ten Swift lint inputs. No app launch, screenshots, privacy grants, signing secrets, or publication. | | [CI contracts](.github/workflows/ci_contract_tests.yml), [tests/package](.github/scripts/ci-contract/) | Unfiltered `pocket` push/PR, read-only contents, non-persisted credentials, five-minute timeout. Node's built-in test runner and one exact-pinned YAML parser inspect actual workflow structure, reject malformed/duplicate YAML, and test deliberately mutated configurations. Workflow `run` blocks are data, never executed by these structural tests. Also runs the existing 22 PR-policy tests and the named portable local-packaging, distribution-signing, notarization-preparation and hosted-release unittest steps; no native signing, packaging or uploads on Ubuntu. | | [Local packaging](scripts/package.py), [portable tests](scripts/tests/test_package.py) | Explicit already-built Release app and new DMG paths; Python 3.9+ standard library, existing hash-pinned DMG builder unchanged. Native identity/signature checks, private copy, read-only image verification, exact-input content comparison, owned-device detach, no-clobber promotion. No implicit build/sign/install/launch, secrets, `local.env`, release credentials, or publication. See [usage and missing-dependency recovery](README.md#local-dmg-preparation). | -| [Local distribution signing](scripts/distribution.py), [portable tests](scripts/tests/test_distribution.py) | Separately approved NP-9-local-signing-v1: explicit existing Developer ID Application name/team and a fresh private build directory. Xcode Release signing overrides, planned signing of the resource-only MediaRemoteAdapterTestClient plus outer app seal, and all-Mach-O/all-architecture signature evidence. Existing local defaults and packager unchanged. **NOT YET NOTARIZED**; no Keychain management, installation, app launch or publication. See [usage](README.md#local-developer-id-candidate-9-bounded-slice). | +| [Local distribution signing](scripts/distribution.py), [portable tests](scripts/tests/test_distribution.py) | Separately approved NP-9-local-signing-v1: explicit existing Developer ID Application name/team, optional public certificate SHA-1 selector and a fresh private build directory. Xcode Release signing overrides, planned signing of the resource-only MediaRemoteAdapterTestClient plus outer app seal, and all-Mach-O/all-architecture signature evidence. Existing local defaults and packager unchanged. **NOT YET NOTARIZED**; no Keychain management, installation, app launch or publication. See [usage](README.md#local-developer-id-candidate-9-bounded-slice). | | [Notarization preparation](scripts/notarize.py), [portable tests](scripts/tests/test_notarize.py) | Explicit signed app, signer/team, existing notarytool profile and fresh output directory. Copies without changing the source, notarizes/staples the app, reuses exact-input packaging, then signs/notarizes/staples and verifies the final DMG. Native execution uploads to Apple; portable CI does not. No GitHub/Homebrew publication or installation. See [release gates and recovery](docs/releases.md). | | [Notch Pocket notarized release](.github/workflows/pocket-native-release.yml), [portable boundaries](scripts/tests/test_pocket_release.py) | Product tag `notch-pocket-v*` or explicit existing-tag dispatch from `pocket`; strict version/ancestry gate and all nine successful exact-commit product jobs from the latest `pocket` push runs. Separate hosted macOS 26 / full Xcode 26.6 signing job uses isolated temporary credentials; Ubuntu publication checks transferred and remote asset bytes before publishing a draft as latest. Final DMG plus public manifest only. Scoped Homebrew token opens a draft cask PR, never merges or writes `main`. Empty configuration fails with named missing secrets. See [setup, permissions and recovery](docs/releases.md#hosted-actions-workflow). | | [PR target check](.github/workflows/base_ref_check.yml), [guidance](.github/workflows/base_ref_check_comment.yml) | Existing `pull_request_target` events and check identities remain unchanged: `Fork PR target check` and `Sync PR target guidance comment`. Only `pocket` is an allowed base. Guidance uses its existing comment permissions; product-CI changes do not broaden them. | @@ -293,7 +293,7 @@ Neither an owned partial output nor a competing output is deleted. ### Local distribution signing outcome and evidence -`scripts/distribution.py --identity FULL_DEVELOPER_ID_NAME --team TEAM_ID --build-dir ABSOLUTE_NEW_BUILD` +`scripts/distribution.py --identity FULL_DEVELOPER_ID_NAME --team TEAM_ID --build-dir ABSOLUTE_NEW_BUILD [--certificate-sha1 PUBLIC_CERTIFICATE_SHA1_40_HEX_CHARACTERS]` is the **NP-9-local-signing-v1** entrypoint. Follow the [exact signed-app → existing packager workflow](README.md#local-developer-id-candidate-9-bounded-slice). It never loads `local.env`, changes project/local-test signing defaults, touches @@ -302,6 +302,29 @@ submits anything to Apple. Existing app/helper IDs, version 0.1.0 and declared entitlements are checked, not overridden. The helper's existing sandbox `false` entitlement is retained rather than replaced with app entitlements. +The optional `--certificate-sha1` disambiguates certificates sharing the same +common name without enumerating identities. It accepts exactly 40 hexadecimal +characters (case-insensitive, no separators/prefix); an empty or malformed value +fails before tool discovery or build-directory creation. Missing option values +are argument errors. The full name and team remain required, even with a +fingerprint. The normalized uppercase fingerprint replaces only the native +signing selector, in both Xcode and the resource/outer-app `codesign --sign` +commands. Omitting it preserves full-name selection and the existing result +shape. An unavailable certificate is a native build/signing failure, not +permission to retry by name or change credentials. + +`--certificate-sha1` belongs to **`scripts/distribution.py` only**. +`scripts/notarize.py` DMG signing and the hosted release pipeline remain +name-selected and unchanged; neither accepts or forwards this option. +Use a human-provided known public certificate fingerprint, or follow the +[README's artifact-only extraction example](README.md#local-developer-id-candidate-9-bounded-slice): +`codesign --extract-certificates` reads the embedded public certificate of an +already-approved signed artifact into a new task-owned temporary directory, then +`openssl x509` reports the leaf's SHA-1 fingerprint. No Keychain inspection or +enumeration, private-key export, or artifact mutation is authorized. This does +not replace any signer, chain, team, timestamp, runtime, entitlement or +all-architecture verification below. + The explicit plain command-line `CODE_SIGN_IDENTITY=...` and `DEVELOPMENT_TEAM=...` overrides take precedence over project settings, including SDK-conditional identities. Do not pass `CODE_SIGN_IDENTITY[sdk=macosx*]=...` @@ -340,7 +363,11 @@ loosen the contract. Final verification requires the Apple Developer ID Application certificate chain and supplied team using an inline `codesign -R` requirement; both app -and helper also require their exact identifiers. Every physical Mach-O file, +and helper also require their exact identifiers. If a fingerprint was supplied, +the requirement additionally includes `certificate leaf = H"<40_HEX_SHA1>"`. +It checks Xcode-signed code before resource signing, then every bundle and +physical Mach-O file during final verification, with `--all-architectures`. +A different leaf fails even if its common name and team match. Every physical Mach-O file, including nested resources and framework versions, is verified for all architectures and inspected per architecture for the requested certificate name, team, hardened-runtime flag, secure `Timestamp` (not merely `Signed Time`) @@ -351,9 +378,9 @@ remain sealed resources, not a claim about interpreter runtime policy. | Exit | Outcome | | --- | --- | -| 0 | `ok: true`, `status: "signed"`; exact `app`, `build_dir`, `configuration`, `version`, developer directory, team, app/helper identifiers and `code` evidence for each architecture | +| 0 | `ok: true`, `status: "signed"`; exact `app`, `build_dir`, `configuration`, `version`, developer directory, team, app/helper identifiers and `code` evidence for each architecture; uppercase public `certificate_sha1` only when supplied and verified | | 2 | `invalid_arguments`; no supplied argument contents echoed | -| 3 | `invalid_input`; invalid identity/team, unsafe paths or entitlement declarations | +| 3 | `invalid_input`; invalid identity/team/certificate SHA-1, unsafe paths or entitlement declarations | | 4 | `missing_tool`, `unsupported_platform`; full Xcode 26+/macOS 15.6+ required | | 5 | `signature_failed`; no fallback, with original `tool_exit` when a native signing/verification command failed | | 6 | `build_failed`; original Xcode `tool_exit`, or explicit `timed_out` | diff --git a/README.md b/README.md index 99f881ad3a..ecc1729fe6 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,22 @@ and the file shelf. **Spotify is the only committed player support.** Other inherited integrations remain in the source; their presence is not a broader support commitment or a roadmap for new features. +**Idle appearance:** the decorative face and its Appearance setting are removed +([#50](https://github.com/jdylanmc/notch/issues/50)). A previously stored +`showNotHumanFace=true` is ignored, not migrated or deleted. Media, Shelf, the +full panel and retained appearance customization are unchanged. Historical +translations for the removed control remain in the owned string catalog; +they do not enable a runtime feature. + +**Notification replies:** AI-generated reply suggestions and their Settings +control are removed. Notifications and manual replies remain, including drafts, +focus/compose holds, timeout errors and existing delivery/app/clipboard fallbacks. +The separate `canReply` eligibility behavior is unchanged. A stored +`smartRepliesEnabled=true` is ignored, not migrated or deleted; historical +translations remain in the catalog. The +[installed-app regression](experiments/tart-regression/scenarios/notifications-ai-replies-removed.md) +checks Settings output, not live banner capture or message delivery. +

Notch Pocket utility pocket icon

@@ -220,6 +236,60 @@ python3 -B scripts/distribution.py \ --build-dir "$PWD/.build/np9-signing-001" ``` +The canonical command above retains full-name selection without an extra flag. +**Optional variant for duplicate certificate names:** when multiple certificates +share the same common name, use `--certificate-sha1` with a new build directory: + +```bash +python3 -B scripts/distribution.py \ + --identity 'Developer ID Application: YOUR CERTIFICATE NAME (YOURTEAMID)' \ + --team 'YOURTEAMID' \ + --certificate-sha1 'PUBLIC_CERTIFICATE_SHA1_40_HEX_CHARACTERS' \ + --build-dir "$PWD/.build/np9-signing-sha1-001" +``` + +This option belongs to **`scripts/distribution.py` only**. +`scripts/notarize.py` DMG signing and the hosted release pipeline remain +name-selected and unchanged; neither accepts or forwards this option. +Supply the approved **public leaf certificate's SHA-1 fingerprint**, exactly +40 hexadecimal characters, without spaces, colons or a `0x` prefix (either case +is accepted). +The full `--identity` and `--team` remain mandatory and are independently checked. +The fingerprint selects the certificate for Xcode, the approved built resource +and the outer app seal; every final bundle/Mach-O verification also requires +that exact leaf on all architectures. It is not a private key or a replacement for the +Developer ID chain, name/team, timestamp, runtime or entitlement checks. +The command does not discover certificates or change Keychain access; an +unavailable selector or mismatched signer fails without falling back to the name. + +Use a **human-provided known certificate fingerprint**, or derive it from the +embedded **public certificate of an already-approved signed artifact** at an +explicit approved path. Do not enumerate or inspect Keychain, export private +keys, or search for another artifact. For the artifact-only method, the following +creates a **new task-owned temporary directory** and reads the embedded public +certificate chain without changing or signing the artifact: + +```bash +( + umask 077 && + certificate_dir="$(mktemp -d "${TMPDIR:-/tmp}/notch-public-certificate.XXXXXX")" && + printf 'Public certificate scratch directory: %s\n' "$certificate_dir" && + codesign --display --extract-certificates="$certificate_dir/cert-" \ + '/absolute/path/to/already-approved/notch-pocket.app' && + openssl x509 -inform DER -in "$certificate_dir/cert-0" \ + -noout -fingerprint -sha1 +) +``` + +`cert-0` is the public leaf certificate. Remove only the displayed fingerprint's +label and colon separators to obtain the required 40 hexadecimal characters. +Extraction is not signature verification, approval of a new signer, or proof +that the signing identity is usable. Stop on any failure; do not fall back to +Keychain inspection. Retain the reported scratch path until its files are +accounted for; clean up only this invocation's extracted public certificate files +and then its empty directory. All signing and verification gates below remain +required. + Choose a **new** build directory beneath this checkout's `.build/`; its parent must already exist, be user-owned and not group/world-writable. Paths must be absolute, without symlink components or `..`. Existing directories, files and @@ -275,6 +345,8 @@ Only a zero exit with `ok: true, status: "signed"` identifies the successful candidate. Its JSON includes the exact `app`, build directory, identities, version, developer directory and per-code/per-architecture signing evidence, with `notarization: "NOT YET NOTARIZED"` and `gatekeeper_assessed: false`. +When supplied and successfully verified, `certificate_sha1` records the public +fingerprint in uppercase; the field is absent for full-name-only selection. Native diagnostic logs and the supplied certificate name are not echoed. See the [failure/evidence contract](CONTRIBUTING.md#local-distribution-signing-outcome-and-evidence). diff --git a/docs/regression-coverage.md b/docs/regression-coverage.md index 0fe07b018f..142cf92040 100644 --- a/docs/regression-coverage.md +++ b/docs/regression-coverage.md @@ -4,8 +4,9 @@ Working inventory for [#75](https://github.com/jdylanmc/notch/issues/75), under [#18](https://github.com/jdylanmc/notch/issues/18) and [#14](https://github.com/jdylanmc/notch/issues/14). Baseline: product source at `c89961a3dcd88dcd20be30f9effadd32549aab49`, plus the Dashboard Defaults isolation -tests accompanying this inventory. An unmerged feature branch is not part of -this matrix; in particular, idle-launcher PR #86 is not assumed implemented. +tests accompanying this inventory. The PR #86 continuation adds the scoped +idle-launcher coverage below; source/test presence does not imply merge or a +successful native run. **This is a coverage map, not a whole-app pass.** Test links identify executable coverage that exists, not a fresh successful run. Record the tested commit, exact @@ -90,20 +91,21 @@ regression preservation, not a new player support commitment. | Welcome, camera/calendar/reminder/audio/Accessibility/music permission steps and finish; [onboarding](../notchPocket/components/Onboarding/OnboardingView.swift) | No dedicated onboarding journey suite. | Inject first-launch/settings and permission providers; exercise skip/allow/deny routing without OS dialogs. | Actual OS permission prompts require human approval; do not automate them. | | Closed/open panel, hover delay/exit, sharing guard, shortcuts; [ContentView](../notchPocket/ContentView.swift), [model](../notchPocket/models/NotchPocketViewModel.swift) | Identity tests cover native selector forwarding, refusal/no-op and window invariants. [Helper contracts](../scripts/notch-control/Tests/ControlCoreTests/NotchActionTests.swift) cover single-dispatch and observed model state. | Native open/close exists; automate exact-candidate setup/restoration and hover/animation observation separately. | Accessibility grant for control; capture grant only for pixel evidence. | | Home/Dashboard/Shelf, hidden tabs, disabled/empty Shelf; [header](../notchPocket/components/Notch/NotchPocketHeader.swift) | [Navigation policy](../notchPocketTests/DashboardWidgetInteractionTests.swift) and helper tab-selection contracts. | Native tab selection exists. Runner must inspect fresh panel IDs, verify selection and restore original tab. | Accessibility; missing Shelf is not permission to enable it. | -| Compact player-only view, normal layout and fullscreen hiding; [composition](../notchPocket/ContentView.swift) | Navigation policy does not prove layout pixels or fullscreen detection. | Isolated appearance settings, synthetic media state and app-owned captures; assert hit regions and hover-close behavior. | Fullscreen application/display setup for the real integration case. | +| Full-panel layout and fullscreen hiding; [composition](../notchPocket/ContentView.swift) | [Compact-mode removal source contracts](../scripts/tests/test_regression_probe.py) preserve routes, standard geometry, Calendar/Mirror conditions and shared media controls; no player-only bypass remains. | Required independent Tart full-panel open/tab/output proof at app defaults, plus separately authorized conditional Calendar/Mirror fixtures; Settings absence is not panel evidence. Fullscreen behavior remains separately unverified. | Existing grants and suitable displays/camera/calendar fixtures; no permission or ownership changes. | | Add/remove widgets; Edit/Done/Cancel; per-display ownership; [Dashboard](../notchPocket/components/Dashboard/DashboardView.swift) | [Controller tests](../notchPocketTests/DashboardControllerTests.swift) cover draft ownership, commit/cancel and lifecycle; [Defaults isolation tests](../notchPocketTests/DashboardDefaultsIsolationTests.swift) cross the real adapter. | No helper widget actions yet. Add bounded, versioned identifiers/actions routed to the existing controller and observed configuration. | Accessibility for native dispatch, not for model/storage tests. | | Widget move/resize, menu alternatives, collision/reflow/scroll; [widget card](../notchPocket/components/Dashboard/DashboardWidgetCard.swift) | [Layout](../notchPocketTests/DashboardLayoutEngineTests.swift), [geometry](../notchPocketTests/DashboardEditGeometryTests.swift), [interaction](../notchPocketTests/DashboardWidgetInteractionTests.swift), [atomic resize commit](../notchPocketTests/DashboardWidgetEditCommitterTests.swift). | Native pointer drag/cancel and scroll tests are missing. Semantic menu actions and model geometry are separate evidence levels, not substitutes for drag sessions. | Permission and a shareable app-owned window for native/pixel checks. | | Widget item-count setting; unknown widget placeholder; [configuration](../notchPocket/models/DashboardConfiguration.swift) | [Configuration preservation](../notchPocketTests/DashboardConfigurationTests.swift), controller settings tests and Defaults commit/reconstruction test. | Add observation of instance IDs/settings and unknown-widget rendering using fixture payloads; no new destructive recovery UI. | None for deterministic fixtures. | | Dashboard revisions, corrupt/future/numeric payloads, persistence and teardown; [store](../notchPocket/components/Dashboard/DashboardConfigurationStore.swift) | Configuration/numeric/controller suites; real Defaults suites cover seed identity, reconstructed stores, stale commits and exact recovery bytes. | Process restart durability and whole-app fixture selection remain missing; same-process reconstruction is not relaunch proof. | None for deterministic storage integration. | | Shelf Summary count, open-Shelf/drop actions, disabled/editing state; [widget policy](../notchPocket/components/Dashboard/ShelfSummaryWidgetPolicy.swift) | [Shelf Summary policy](../notchPocketTests/ShelfSummaryWidgetPolicyTests.swift), [overlapping drop state](../notchPocketTests/DropInteractionStateTests.swift). | Seed isolated Shelf state; observe count/drop acceptance; actual drop sessions remain separate from policy calls. | File access only for explicitly owned fixture files. | | Playback, seek, volume, shuffle/repeat/favorite, source fallback; [MusicManager](../notchPocket/managers/MusicManager.swift), [Home](../notchPocket/components/Notch/NotchHomeView.swift) | [Now Playing availability](../notchPocketTests/NowPlayingAvailabilityTests.swift) and [playback equality/event tests](../notchPocketTests/NotchUIEventTests.swift). | Manager/view provider injection and scenario assertions for command dispatch, progress and runtime failure/recovery. | Spotify installation/account/playback consent for end-to-end checks; inherited players are not promised support. | +| Idle music launcher (#53 / PR #86); [MusicSectionView](../notchPocket/components/Music/MusicSectionView.swift) | Presentation, playing/idle target resolution, bounded launch transaction, stale-completion/single-operation and localized feedback unit contracts. Two [installed-app regressions](../experiments/tart-regression/scenarios/music-idle-launcher.md) exercise real no-target/unavailable clicks, versioned dismissal, visible error output and failure-only focus preservation with restoration. | Independent exact-candidate Tart execution remains required. Actual OS Now Playing pause/stop/resume, playing-album-art routing, non-covering feedback and successful activation without playback need a real external guest player, not injected app state. | Clean idle guest with no remembered source; unavailable case needs Spotify genuinely absent. External test-player proof is not actual Spotify account/playback proof. | | Lyrics, artwork/tinting, visualizer and output-route selection; [lyrics](../notchPocket/managers/LyricsService.swift), [audio capture](../notchPocket/managers/AudioCaptureManager.swift), [routes](../notchPocket/managers/AudioRouteManager.swift) | No dedicated provider or native interaction suite. | Synthetic metadata/lyrics/audio levels/output devices; missing/error/stale response scenarios; verify routing separately from UI. | Network/provider availability, audio-capture grant and physical output devices for live cases. | | Shelf file/text/link/image drop, deduplication and selection; [drop service](../notchPocket/components/Shelf/Services/ShelfDropService.swift), [state](../notchPocket/components/Shelf/ViewModels/ShelfStateViewModel.swift) | Drop-target aggregation tests do not cover payload ingestion or the state singleton. | Inject owned storage/services; deterministic item-provider cases, internal-drag rejection, selection and cancellation. | Security-scoped access to owned fixtures; no use of personal shelf items. | | Shelf Quick Look, open/copy/share, drag out and removal; [actions](../notchPocket/components/Shelf/Services/ShelfActionService.swift), [Quick Look](../notchPocket/components/Shelf/Services/QuickLookService.swift), [share](../notchPocket/components/Shelf/Services/QuickShareService.swift) | No dedicated native journey suite. | App-scoped keyboard/drag/focus scenarios and injectable share/open sinks; verify no unrelated files removed and restore transient selection. | Opening external apps or sending shares requires separate effects approval. | | Shelf save/load, stale bookmarks, temporary data and quit flush; [persistence](../notchPocket/components/Shelf/Services/ShelfPersistenceService.swift) | [Owned-directory tests](../notchPocketTests/ShelfPersistenceIsolationTests.swift) cover real JSON/filesystem save/load, same-process service reconstruction, awaited async save, directory isolation and malformed/mixed input bytes. Identity test covers path naming. | Bookmark refresh, temporary-file services, view-model/quit flushing, process relaunch and whole-profile isolation remain missing. | Real bookmark security scope under the signed candidate, not bypasses. | | Notification capture/filter/queue/expiry/cycling, draft preservation; [manager](../notchPocket/managers/SystemNotificationManager.swift), [helper watcher](../notchPocketXPCHelper/NotificationWatcher.swift) | Bundle-ID normalization/cache tests; notification expanded-view pixel test is local rendering, not banner delivery. | Synthetic notification source/clock and state scenarios before controlled live banners; fresh XPC reconnect/queue cases. | Accessibility; controlled sender/account consent. Attribution follow-up [#12](https://github.com/jdylanmc/notch/issues/12). | | Notification reply/action/open, verification-code copy and debug window; [notification UI](../notchPocket/components/Notch/NotificationLiveActivity.swift), [debug UI](../notchPocket/components/NotificationDebugWindow.swift) | OTP DEBUG self-check is not a canonical XCTest gate. No end-to-end send evidence. | Mock send/clipboard/open sinks; verify drafts survive failures, failed sends never count as delivered, and diagnostics avoid private text. | Real message sending/clipboard changes are separately approved effects. Never dump personal notification trees. | -| Contact avatars and optional smart replies; [avatars](../notchPocket/managers/ContactAvatarManager.swift), [smart replies](../notchPocket/managers/SmartReplyManager.swift) | No dedicated availability/generation or contact-provider tests. | Inject contacts/model availability and synthetic content; test unavailable/failed output and fallback rendering. | Contacts grant; macOS 26+ and Apple Intelligence availability for live generation. | +| Contact avatars; [avatars](../notchPocket/managers/ContactAvatarManager.swift) | No dedicated contact-provider tests. AI reply suggestions are removed; Contacts remains shared with avatars and manual WhatsApp handoff. | Inject contacts and synthetic content; test unavailable/failed lookup and fallback rendering. | Contacts grant for live lookup. | | Calendar/day/week/reminders, filters, selection, completion and meeting links; [view](../notchPocket/components/Calendar/NotchPocketCalendar.swift), [service](../notchPocket/Providers/CalendarServiceProviding.swift) | [Meeting link detection](../notchPocketTests/MeetingLinkDetectorTests.swift); Graph core tests below are not EventKit integration. | Inject EventKit service/clock into manager; synthetic events/reminders, date boundaries and approved mutation sinks. | Calendar/reminder grants and account access; real completion/join actions separately approved. | | Battery status/popover/charging alerts; [model](../notchPocket/models/BatteryStatusViewModel.swift), [activity manager](../notchPocket/managers/BatteryActivityManager.swift) | No dedicated battery-provider tests. | Inject power readings/time; test transition/debounce/visibility and popover hover guard. | Real battery/adapter state and physical power changes. | | Volume/brightness/backlight indicators and media keys; [on-screen display settings](../notchPocket/components/Settings/Views/OSDSettingsView.swift), [interceptor](../notchPocket/observers/MediaKeyInterceptor.swift) | Presentation bus tests, not actual hardware adjustment or key interception. | Provider-level synthetic controls and bounded native scenarios preserving prior volume/brightness. | Accessibility and explicit device-setting changes. BetterDisplay/Lunar require their apps; do not change their settings for a test implicitly. | @@ -117,15 +119,33 @@ regression preservation, not a new player support commitment. Pane inventory comes from [SettingsTab](../notchPocket/components/Settings/SettingsView.swift). Only **General** and **About** have current helper navigation. Enumerating a control does not mean it has automation or can safely be changed in live data. -All other pane navigation/restoration is an engineering gap, not a demand for -routine human clicks. Preference writes need a whole-app fixture profile first. +The separate guest-only Appearance, Notifications and General removal regressions below are +authored but still need independent old/new proof; they do not extend the helper. Other pane +navigation/restoration remains an engineering gap, not a demand for routine +human clicks. Preference writes need a whole-app fixture profile first. + +The scoped [panel-swipe removal](../experiments/tart-regression/scenarios/general-panel-swipes-removed.md) +changes only the prior General master-label expectation from **Enable gestures** +to **Enable media gestures**. The subsequent scoped +[compact-mode removal](../experiments/tart-regression/scenarios/general-compact-mode-removed.md) +intentionally drops only **Compact mode** from the prior General positive set; +the other twelve labels, removed-control absence and capture/restoration gates remain. +The measured static-text/Vision alignment correction has targeted +failure-boundary contracts and one author OLD-only check (13 retained labels +true, haptic absence false), not fresh independent or NEW-candidate signoff. +That historical check used a pre-rename harness; the current haptic case must +not be applied to the older baseline's **Enable gestures** label. Panel-swipe +remediation 1/5 adds synthetic footer-only Accessibility/OCR matching cases and +an unconditional media-pulse cleanup source contract, not executed gesture +proof. Candidate `03f9` predates the product fix and is stale; parent-owned fresh +full validation and independent native evidence require a rebuild. | Pane / source | Important controls and journeys | Existing evidence / remaining work | | --- | --- | --- | -| [General](../notchPocket/components/Settings/Views/GeneralSettingsView.swift) | Menu icon, launch at login, language/restart, display selection/height, hover, gestures, animation, compact/remembered tabs. | Candidate-specific selection/capture/close evidence above; no preference-toggle coverage. Isolate persistent settings and launch-at-login effects. | -| [Appearance](../notchPocket/components/Settings/Views/AppearanceSettingsView.swift) | Tab visibility, settings icon, waveform, tinting/lighting, slider color and idle face. | Tab policy only; fixture setting/pixel and audio-availability assertions missing. | +| [General](../notchPocket/components/Settings/Views/GeneralSettingsView.swift) | Menu icon, launch at login, language/restart, display selection/height, hover/click/keyboard, media gestures, animation, remembered tabs; haptics, vertical panel swipes and music-only compact mode removed. | [Haptic removal](../experiments/tart-regression/scenarios/general-haptics-removed.md), [panel-swipe removal](../experiments/tart-regression/scenarios/general-panel-swipes-removed.md) and [compact-mode removal](../experiments/tart-regression/scenarios/general-compact-mode-removed.md): twelve retained labels including the media master, scoped removed-control absence, real pane navigation, bound top/bottom pixels and scroll restoration. Source contracts preserve media keys/gates and independent opening routes; fresh independent OLD/NEW Tart proof is parent-owned and pending. Conditional media settings, preference propagation, actual gestures and static transport still need runtime proof. | +| [Appearance](../notchPocket/components/Settings/Views/AppearanceSettingsView.swift) | Tab visibility, settings icon, waveform, tinting/lighting and slider color; idle face removed (#50). | [Registered removal scenario](../experiments/tart-regression/scenarios/appearance-idle-face-removed.md): seven retained-label output assertions, face/section absence, structural pane/full-form/header-class proof. Source/oracle contracts and author diagnosis are not signoff: the first independent old-app run blocked before output; fresh independent old/new executable-hash and source-provenance proof remains pending. Preference-toggle/audio behavior is not covered. | | [Media](../notchPocket/components/Settings/Views/MediaSettingsView.swift) | Source, live activity, sneak peek, idle timing, lyrics and fallback retry. | Availability-model tests; no pane/controller/provider end-to-end suite. | -| [Notifications](../notchPocket/components/Settings/Views/NotificationSettingsView.swift) | Enable watching, all-apps/allow-list selection, smart replies and availability. | No settings journey test; real enable can start live capture and must not run in a personal profile. | +| [Notifications](../notchPocket/components/Settings/Views/NotificationSettingsView.swift) | Enable watching and all-apps/allow-list selection; AI suggestions removed, manual replies retained. | [Registered removal scenario](../experiments/tart-regression/scenarios/notifications-ai-replies-removed.md): two retained-label output assertions, suggestion absence and bound top/bottom captures with stable endpoints and measured overlap at 1440x900. Disabled labels require geometry/pixels, not interaction eligibility. Source contracts preserve manual draft/focus/timeout/fallback call sites, not live behavior. Author diagnosis is not signoff; fresh independent old/new proof and NEW-only full-suite validation remain parent-owned. No preference changes or live capture/send coverage; `canReply` false positives remain out of scope. | | [Calendar](../notchPocket/components/Settings/Views/CalendarSettingsView.swift) | Visibility, completed/all-day filters, full titles, next event, week start, meeting tap, calendar/reminder lists and denied access. | Meeting-link parsing only; inject service/permission results and prevent real reminder mutations. | | [On-screen display](../notchPocket/components/Settings/Views/OSDSettingsView.swift) | Replacement, inline display, source providers, authorization, color/shadow/percentage and Option-key behavior. | Event bus only; fake controls before live device changes, including provider restoration. | | [Battery](../notchPocket/components/Settings/Views/BatterySettingsView.swift) | Indicator, status notifications, percentage, icons and charging wattage. | No dedicated pane tests; synthetic battery readings needed. | diff --git a/docs/specs/mvp-widget-foundation.md b/docs/specs/mvp-widget-foundation.md index ebac23ee9d..286f5b1eb2 100644 --- a/docs/specs/mvp-widget-foundation.md +++ b/docs/specs/mvp-widget-foundation.md @@ -57,7 +57,7 @@ Configurable panel width/height remains required for #33, but is a **dependent s |---|---| | `notchPocket/enums/generic.swift` | Add `.dashboard`; keep `.home` and `.shelf`. | | `notchPocket/components/Tabs/TabSelectionView.swift` | Render Dashboard/Home/Shelf using the existing coordinator-owned selection. Stable enum identity replaces per-render random tab UUID identity. | -| `notchPocket/ContentView.swift` | Route `.dashboard` to `DashboardView` using existing coordinator selection; keep compact mode, expanded notifications, closed-state activities, hover-close, sharing guards, and existing Home/Shelf rendering unchanged. | +| `notchPocket/ContentView.swift` | Route `.dashboard` to `DashboardView` using existing coordinator selection; keep expanded notifications, closed-state activities, hover-close, sharing guards, and existing Home/Shelf rendering unchanged. The separate owner-selected [compact-mode removal](../../experiments/tart-regression/scenarios/general-compact-mode-removed.md) retires the player-only bypass. | | `notchPocket/models/DropInteractionState.swift` | Add source-scoped Dashboard-widget targeting to the existing aggregate drop-target state so overlapping widgets and teardown do not clear unrelated Shelf/general targets or bypass the existing close debounce. | | `notchPocket/managers/NotchWindowManager.swift` | **Dependent panel-limit slice only:** resize/recenter each owned window when effective panel limits change, preserving its top edge, level, collection behavior, sharing type, observation source, and nonactivating focus policy. Update drag/hover geometry from the same resolved size. | | `notchPocket/models/NotchPocketViewModel.swift` | **Dependent panel-limit slice only:** expose resolved open panel size from shared limits and current screen. Do not relocate `currentView`. | @@ -117,7 +117,7 @@ Configurable panel width/height remains required for #33, but is a **dependent s 10. **Panel resize — dependent slice:** Changing limits updates all live panel windows from the shared setting while each remains top-centered, non-main, nonactivating outside text input, at the existing level, and with existing screen-sharing behavior. 11. **Close/reopen:** Existing `openShelfByDefault` and “Remember last tab” behavior remains unchanged. Dashboard persistence does not synchronize or restore open/closed or tab state. 12. **Corrupt/future data:** Malformed, duplicate-identity, unsupported-number, or future-version data preserves original bytes, surfaces recovery-required state, and cannot be overwritten by ordinary editing. Unknown widget payloads containing supported exact values survive supported-schema round trips. No older schema exists yet. -13. **Compact/notification precedence:** Compact mode still bypasses tabs for its existing player-only surface. Expanded notifications still take precedence over tabs and Dashboard. +13. **Full-panel/notification precedence:** The separate compact-mode removal retires the player-only bypass; stored legacy `compactMode` values are ignored without migration. Expanded notifications still take precedence over tabs and Dashboard. 14. **Accessibility:** Dashboard controls have stable labels/values; edit handles expose move/resize meaning and keyboard alternatives. No interaction requires the panel to become the main window. ## Test-first implementation sequence diff --git a/experiments/tart-regression/GuestRegressionProbe/AboutOutputOracle.swift b/experiments/tart-regression/GuestRegressionProbe/AboutOutputOracle.swift index b452d7b30f..c4e073bf04 100644 --- a/experiments/tart-regression/GuestRegressionProbe/AboutOutputOracle.swift +++ b/experiments/tart-regression/GuestRegressionProbe/AboutOutputOracle.swift @@ -11,6 +11,16 @@ struct AboutOutputOracle { text.split(whereSeparator: \.isWhitespace).joined(separator: " ") } + static func rowText(anchor: Observation, observations: [Observation]) -> String { + let row = observations.filter { + let overlap = min($0.frame.maxY, anchor.frame.maxY) - max($0.frame.minY, anchor.frame.minY) + return $0.frame.midX >= anchor.frame.minX + && $0.frame.height <= anchor.frame.height * 2 + && overlap >= min($0.frame.height, anchor.frame.height) / 2 + }.sorted { $0.frame.minX < $1.frame.minX } + return normalize(row.map(\.text).joined(separator: " ")) + } + static func rowValue(_ label: String, observations: [Observation]) -> String? { let anchors = observations.filter { let text = normalize($0.text) @@ -18,13 +28,7 @@ struct AboutOutputOracle { && !(label == "Version" && text.hasPrefix("Version info")) } guard anchors.count == 1, let anchor = anchors.first, anchor.frame.height > 0 else { return nil } - let row = observations.filter { - let overlap = min($0.frame.maxY, anchor.frame.maxY) - max($0.frame.minY, anchor.frame.minY) - return $0.frame.midX >= anchor.frame.minX - && $0.frame.height <= anchor.frame.height * 2 - && overlap >= min($0.frame.height, anchor.frame.height) / 2 - }.sorted { $0.frame.minX < $1.frame.minX } - let text = normalize(row.map(\.text).joined(separator: " ")) + let text = rowText(anchor: anchor, observations: observations) guard text == label || text.hasPrefix(label + " ") else { return nil } return normalize(String(text.dropFirst(label.count))) } diff --git a/experiments/tart-regression/GuestRegressionProbe/AppearanceOutputOracle.swift b/experiments/tart-regression/GuestRegressionProbe/AppearanceOutputOracle.swift new file mode 100644 index 0000000000..9142e3b28a --- /dev/null +++ b/experiments/tart-regression/GuestRegressionProbe/AppearanceOutputOracle.swift @@ -0,0 +1,31 @@ +import CoreGraphics +import Foundation + +struct AppearanceOutputOracle { + static let retainedLabels = [ + "Always show tabs", "Show settings icon in notch", "Colored spectrogram", + "Real-time audio waveform", "Player tinting", "Enable blur effect behind album art", "Slider color" + ] + static let faceLabel = "Show cool face animation while inactive" + + static func evaluate( + _ observations: [AboutOutputOracle.Observation], + contentFrame: CGRect, + controls: [String: Bool] + ) -> [String: Bool] { + let content = observations.filter { + $0.frame.height > 0 && contentFrame.contains(CGPoint(x: $0.frame.midX, y: $0.frame.midY)) + } + let rows = content.map { AboutOutputOracle.rowText(anchor: $0, observations: content) } + var result = Dictionary(uniqueKeysWithValues: retainedLabels.map { + let label = $0 + return (label, rows.contains { $0 == label || $0.hasPrefix(label + " ") } && controls[label] == true) + }) + // The native full-form fit checks Accessibility; pixels independently reject a rendered remnant. + let rendered = rows.joined(separator: " ").lowercased() + result["faceControlAbsent"] = controls["faceControlAbsent"] == true && !rendered.contains("face animation") + result["additionalFeaturesAbsent"] = + controls["additionalFeaturesAbsent"] == true && !rendered.contains("additional features") + return result + } +} diff --git a/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift b/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift index ced3f9c70e..a004e8ca58 100644 --- a/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift +++ b/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift @@ -7,12 +7,12 @@ import Vision import XCTest final class GuestRegressionProbe: XCTestCase { - private enum Blocked: Error { + enum Blocked: Error { case reason(String) } @MainActor - private final class RunState { + final class RunState { var verdict = "BLOCKED" var reason = "preconditions_not_established" var cleanup = "not_needed" @@ -31,14 +31,25 @@ final class GuestRegressionProbe: XCTestCase { var openedSettings = false var pointerReturn: XCUICoordinate? var discovery: [String: Any] = [:] + var appearanceContentFrame: CGRect? + var appearanceControls: [String: Bool] = [:] + var settingsCaptures: [[String: Any]] = [] + var originalGeneralScroll: [CGRect]? + var originalMusicSource: String? + var musicSourceNeedsRestoration = false + var originalForeground: NSRunningApplication? + var originalPanelState: String? + var originalTab: String? + var musicPointerReturn: XCUICoordinate? + var originalMediaController: String? } private let candidate = URL(fileURLWithPath: "/Applications/notch-pocket.app") - private var expectedHash: String { + var expectedHash: String { ProcessInfo.processInfo.environment["NOTCH_VM_EXPECTED_SHA256"] ?? "" } - private func require(_ condition: Bool, _ reason: String) throws { + func require(_ condition: Bool, _ reason: String) throws { guard condition else { throw Blocked.reason(reason) } } @@ -55,14 +66,14 @@ final class GuestRegressionProbe: XCTestCase { return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } - private func currentCandidatePID() -> pid_t? { + func currentCandidatePID() -> pid_t? { let running = NSRunningApplication.runningApplications(withBundleIdentifier: "com.jdylanmc.notchpocket") guard running.count == 1, running[0].bundleURL == candidate else { return nil } return running[0].processIdentifier } @MainActor - private func waitHittable(_ element: XCUIElement) -> Bool { + func waitHittable(_ element: XCUIElement) -> Bool { let ready = XCTNSPredicateExpectation( predicate: NSPredicate(format: "exists == true AND hittable == true"), object: element ) @@ -72,6 +83,14 @@ final class GuestRegressionProbe: XCTestCase { @MainActor private func restore(_ state: RunState) { state.cleanup = state.needsRestoration || state.attemptedSettingsOpen ? "pending" : "not_needed" + if state.musicSourceNeedsRestoration { + do { + try restoreMusicSource(state) + } catch { + state.cleanup = "blocked" + return + } + } state.pointerReturn?.hover() if state.needsRestoration, let settings = state.window { let targetPane = state.openedSettings ? "General" : state.originalPane @@ -79,12 +98,12 @@ final class GuestRegressionProbe: XCTestCase { state.cleanup = "blocked" return } - let control = settings.staticTexts[targetPane] guard currentCandidatePID() == state.originalPID && settings.exists else { state.cleanup = "blocked" return } let row = settings.descendants(matching: .outlineRow).containing(.staticText, identifier: targetPane).firstMatch + let control = row.staticTexts[targetPane] let alreadySelected = row.exists && row.isSelected state.discovery["restorationPaneAlreadySelected"] = alreadySelected if !alreadySelected { @@ -99,6 +118,28 @@ final class GuestRegressionProbe: XCTestCase { state.cleanup = "blocked" return } + if let original = state.originalGeneralScroll { + do { + let form = try settingsForm(settings, scenario: .general) + let current = try form.snapshot().children + .filter { $0.elementType != .scrollBar && !$0.frame.isEmpty }.map(\.frame) + guard let first = current.first, let target = original.first else { + state.cleanup = "blocked" + return + } + form.scroll(byDeltaX: 0, deltaY: target.minY - first.minY) + let restored = try form.snapshot().children + .filter { $0.elementType != .scrollBar && !$0.frame.isEmpty }.map(\.frame) + state.discovery["generalScrollRestored"] = restored == original + guard restored == original else { + state.cleanup = "blocked" + return + } + } catch { + state.cleanup = "blocked" + return + } + } if state.openedSettings { let close = settings.buttons[XCUIIdentifierCloseWindow] guard waitHittable(close) else { @@ -129,13 +170,20 @@ final class GuestRegressionProbe: XCTestCase { } state.cleanup = "restored_original_state" } + if state.originalPanelState != nil { + do { + try restoreMusicPanel(state) + } catch { + state.cleanup = "blocked" + } + } } else if state.attemptedSettingsOpen { state.cleanup = "blocked" } } @MainActor - private func finish(_ state: RunState, runID: String, mode: String) { + private func finish(_ state: RunState, runID: String, mode: String, testName: String) { let primaryVerdict = state.verdict let primaryReason = state.reason let nativeFailures = testRun?.failureCount ?? 0 @@ -156,7 +204,7 @@ final class GuestRegressionProbe: XCTestCase { } var receipt: [String: Any] = [ "runID": runID, "scenario": mode, "verdict": state.verdict, "reason": state.reason, - "testIdentifier": "GuestRegressionProbe/GuestRegressionProbe/testInstalledAboutOutput", + "testIdentifier": "GuestRegressionProbe/GuestRegressionProbe/\(testName)", "cleanup": state.cleanup, "expectedCandidateSHA256": expectedHash, "candidateVerified": state.candidateVerified, "observedPublicText": state.observed, "openedSettings": state.openedSettings, "discovery": state.discovery, @@ -165,6 +213,10 @@ final class GuestRegressionProbe: XCTestCase { "nativeFailureCountBeforeReport": nativeFailures ] if let hash = state.screenshotHash { receipt["screenshotSHA256"] = hash } + if !state.settingsCaptures.isEmpty, let scenario = SettingsRemovalScenario(rawValue: mode) { + receipt[scenario.captureVersionKey] = 1 + receipt["captures"] = state.settingsCaptures + } if let error = state.nativeError { receipt["nativeError"] = error } do { let data = try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys]) @@ -178,6 +230,279 @@ final class GuestRegressionProbe: XCTestCase { @MainActor func testInstalledAboutOutput() { + runInstalledSettingsOutput(testName: "testInstalledAboutOutput", modes: [ + "visual-pass", "visual-fail", "stale-evidence", "visual-no-reveal", + "native-abort-after-open", "native-abort-after-about" + ]) + } + + @MainActor + func testInstalledAppearanceWithoutIdleFace() { + runInstalledSettingsOutput(testName: "testInstalledAppearanceWithoutIdleFace", + modes: ["appearance-idle-face-removed"]) + } + + @MainActor + func testInstalledNotificationsWithoutAIReplies() { + runInstalledSettingsOutput(testName: "testInstalledNotificationsWithoutAIReplies", + modes: ["notifications-ai-replies-removed"]) + } + + @MainActor + func testInstalledGeneralWithoutHaptics() { + runInstalledSettingsOutput(testName: "testInstalledGeneralWithoutHaptics", + modes: ["general-haptics-removed"]) + } + + @MainActor + func testInstalledGeneralWithoutPanelSwipes() { + runInstalledSettingsOutput(testName: "testInstalledGeneralWithoutPanelSwipes", + modes: ["general-panel-swipes-removed"]) + } + + @MainActor + func testInstalledGeneralWithoutCompactMode() { + runInstalledSettingsOutput(testName: "testInstalledGeneralWithoutCompactMode", + modes: ["general-compact-mode-removed"]) + } + + @MainActor + private func settingsForm(_ settings: XCUIElement, scenario: SettingsRemovalScenario) throws -> XCUIElement { + let scrollViews = settings.scrollViews.allElementsBoundByIndex + let sidebars = scrollViews.filter { $0.outlines.count == 1 } + let forms = scrollViews.filter { $0.outlines.count == 0 } + try require(sidebars.count == 1 && forms.count == 1, "\(scenario.prefix)_form_ambiguous") + let form = forms[0] + try require(form.frame.minX >= sidebars[0].frame.maxX && settings.frame.contains(form.frame), + "\(scenario.prefix)_form_mapping_unverified") + return form + } + + @MainActor + private func inspectScrollableSettings( + _ settings: XCUIElement, scenario: SettingsRemovalScenario, state: RunState, runID: String + ) throws { + let prefix = scenario.prefix + if scenario.pane == "General" { + if state.originalPane == "General" { + let originalForm = try settingsForm(settings, scenario: .general) + let frames = try originalForm.snapshot().children + .filter { $0.elementType != .scrollBar && !$0.frame.isEmpty }.map(\.frame) + try require(!frames.isEmpty, "general_original_scroll_unavailable") + state.originalGeneralScroll = frames + } + let aboutRow = settings.descendants(matching: .outlineRow) + .containing(.staticText, identifier: "About").firstMatch + let about = aboutRow.staticTexts["About"] + try require(waitHittable(about), "general_navigation_control_unavailable") + about.click() + let away = XCTNSPredicateExpectation(predicate: NSPredicate(format: "selected == true"), object: aboutRow) + try require(XCTWaiter.wait(for: [away], timeout: 5) == .completed, "general_navigation_not_observed") + state.discovery["generalNavigationObserved"] = true + } + let row = settings.descendants(matching: .outlineRow) + .containing(.staticText, identifier: scenario.pane).firstMatch + let pane = row.staticTexts[scenario.pane] + try require(waitHittable(pane), "\(prefix)_control_unavailable") + pane.click() + let selected = XCTNSPredicateExpectation(predicate: NSPredicate(format: "selected == true"), object: row) + try require(XCTWaiter.wait(for: [selected], timeout: 5) == .completed, "\(prefix)_selection_not_observed") + state.discovery[prefix + "PaneSelected"] = row.isSelected + try require(settings.frame.width >= 700 && settings.frame.height >= 600, "\(prefix)_window_too_small") + let form = try settingsForm(settings, scenario: scenario) + state.discovery[prefix + "FormMapped"] = true + + let windowFrame = settings.frame + let formFrame = form.frame + try require(NSScreen.screens.count == 1, "\(prefix)_single_display_required") + let display = CGDisplayBounds(CGMainDisplayID()) + try require(display.contains(windowFrame), "\(prefix)_window_offscreen") + func windowID() throws -> Int { + try require(currentCandidatePID() == state.originalPID && row.isSelected + && settings.frame == windowFrame && form.frame == formFrame, + "\(prefix)_capture_identity_changed") + let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], + kCGNullWindowID) as? [[String: Any]] ?? [] + let matches = windows.filter { + guard $0[kCGWindowOwnerPID as String] as? Int == Int(state.originalPID ?? -1), + let bounds = $0[kCGWindowBounds as String] as? NSDictionary, + let frame = CGRect(dictionaryRepresentation: bounds) else { return false } + return frame == windowFrame + } + try require(matches.count == 1, "\(prefix)_native_window_ambiguous") + guard let identifier = matches[0][kCGWindowNumber as String] as? Int else { + throw Blocked.reason("\(prefix)_native_window_unavailable") + } + return identifier + } + let identifier = try windowID() + func content() throws -> [XCUIElementSnapshot] { + let snapshot = try form.snapshot() + let items = snapshot.children.filter { $0.elementType != .scrollBar && !$0.frame.isEmpty } + try require(snapshot.frame == formFrame && !items.isEmpty && items.count <= 100 + && items.allSatisfy { + $0.frame.minX >= formFrame.minX && $0.frame.maxX <= formFrame.maxX + && $0.frame.minY.isFinite && $0.frame.maxY.isFinite + }, "\(prefix)_content_geometry_unavailable") + return items + } + func rect(_ frame: CGRect) -> [String: CGFloat] { + ["x": frame.minX, "y": frame.minY, "width": frame.width, "height": frame.height] + } + func normalized(_ frame: CGRect) -> CGRect { + CGRect(x: (frame.minX - windowFrame.minX) / windowFrame.width, + y: (windowFrame.maxY - frame.maxY) / windowFrame.height, + width: frame.width / windowFrame.width, height: frame.height / windowFrame.height) + } + var endpointContent: [[XCUIElementSnapshot]] = [] + var outputs: [[String: Bool]] = [] + for (role, delta) in [("top", 10_000.0), ("bottom", -10_000.0)] { + form.scroll(byDeltaX: 0, deltaY: delta) + let first = try content() + form.scroll(byDeltaX: 0, deltaY: delta) + let confirmed = try content() + try require(first.map(\.frame) == confirmed.map(\.frame) + && first.map(\.elementType) == confirmed.map(\.elementType), + "\(prefix)_scroll_endpoint_unverified") + let frames = confirmed.map(\.frame) + try require(role == "top" ? frames.allSatisfy { $0.minY >= formFrame.minY } + : frames.allSatisfy { $0.maxY <= formFrame.maxY }, + "\(prefix)_scroll_endpoint_incomplete") + try require(try windowID() == identifier, "\(prefix)_capture_identity_changed") + + // General's Launch at login/Remember last tab also expose static-text AXValue, not checkbox titles. + // Disabled text can still render. Interaction eligibility is not presence. + var controls: [String: Bool] = [:] + var labelFrames: [String: CGRect] = [:] + for label in scenario.retainedLabels { + let matches = form.staticTexts.matching(identifier: label) + let visible = matches.count == 1 && !matches.firstMatch.frame.isEmpty + && formFrame.contains(matches.firstMatch.frame) + controls[label] = visible + if visible { labelFrames[label] = normalized(matches.firstMatch.frame) } + } + controls[scenario.absenceKey] = scenario.removedLabelsAbsent { form.staticTexts[$0].exists } + let capture = settings.screenshot() + try require(try windowID() == identifier, "\(prefix)_capture_identity_changed") + let after = try content() + try require(after.map(\.frame) == frames + && after.map(\.elementType) == confirmed.map(\.elementType), + "\(prefix)_capture_content_changed") + guard let image = capture.image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + throw Blocked.reason("capture_pixels_unavailable") + } + let request = VNRecognizeTextRequest() + request.recognitionLevel = .accurate + request.recognitionLanguages = ["en-US"] + request.usesLanguageCorrection = false + try VNImageRequestHandler(cgImage: image).perform([request]) + let observations = (request.results ?? []).compactMap { observation -> AboutOutputOracle.Observation? in + guard let text = observation.topCandidates(1).first?.string else { return nil } + return AboutOutputOracle.Observation(text: text, frame: observation.boundingBox) + } + try require(!observations.isEmpty, "ocr_unavailable") + let observed = SettingsRemovalOutputOracle.evaluate( + observations, scenario: scenario, contentFrame: normalized(formFrame), + controls: controls, labelFrames: labelFrames, pixelWidth: image.width, + windowWidthPoints: windowFrame.width + ) + let name = "guest-public-\(prefix)-\(runID)-\(role)" + let hash = SHA256.hash(data: capture.pngRepresentation).map { String(format: "%02x", $0) }.joined() + let attachment = XCTAttachment(screenshot: capture) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + state.settingsCaptures.append([ + "role": role, "name": name, "sha256": hash, "runID": runID, + "scenario": scenario.rawValue, + "testIdentifier": "GuestRegressionProbe/GuestRegressionProbe/\(scenario.testName)", + "candidateSHA256": expectedHash, "candidatePID": Int(state.originalPID ?? -1), + "appPath": candidate.path, + "windowID": identifier, "windowMarker": "NotchPocketSettingsWindow", "pane": scenario.pane, + "windowFrame": rect(windowFrame), "formFrame": rect(formFrame), + "contentFrames": frames.map(rect), "endpointFrames": first.map { rect($0.frame) }, + "contentTypes": confirmed.map { $0.elementType.rawValue }, + "labelFrames": labelFrames.mapValues(rect), "observedPublicText": observed, + "pixelWidth": image.width, "pixelHeight": image.height + ]) + endpointContent.append(confirmed) + outputs.append(observed) + } + let head = endpointContent[0] + let tail = endpointContent[1] + let offset = head[0].frame.minY - tail[0].frame.minY + let overlap = formFrame.height - offset + try require(head.count == tail.count && offset >= 0 && overlap >= 64 + && zip(head, tail).allSatisfy { + $0.elementType == $1.elementType + && $0.frame.offsetBy(dx: 0, dy: -offset) == $1.frame + }, "\(prefix)_scroll_coverage_incomplete") + state.discovery[prefix + "ScrollComplete"] = true + state.discovery[prefix + "ScrollOffsetPoints"] = offset + state.discovery[prefix + "OverlapPoints"] = overlap + state.observed = SettingsRemovalOutputOracle.combine(outputs, scenario: scenario) + } + + @MainActor + private func inspectAppearance(_ settings: XCUIElement, state: RunState) throws { + let row = settings.descendants(matching: .outlineRow).containing(.staticText, identifier: "Appearance").firstMatch + let appearance = row.staticTexts["Appearance"] + try require(waitHittable(appearance), "appearance_control_unavailable") + appearance.click() + let selected = XCTNSPredicateExpectation(predicate: NSPredicate(format: "selected == true"), object: row) + try require(XCTWaiter.wait(for: [selected], timeout: 5) == .completed, "appearance_selection_not_observed") + state.discovery["appearancePaneSelected"] = row.isSelected + try require(settings.frame.width >= 700 && settings.frame.height >= 600, "appearance_window_too_small") + let scrollViews = settings.scrollViews.allElementsBoundByIndex + let sidebars = scrollViews.filter { $0.outlines.count == 1 } + let forms = scrollViews.filter { $0.outlines.count == 0 } + try require(sidebars.count == 1 && forms.count == 1, "appearance_form_ambiguous") + let form = forms[0] + try require(form.frame.minX >= sidebars[0].frame.maxX && settings.frame.contains(form.frame), + "appearance_form_mapping_unverified") + state.discovery["appearanceFormMapped"] = true + + // SwiftUI row text uses AXValue; section headers use AXLabel on the same static-text class. + func header(_ title: String) -> XCUIElementQuery { + form.staticTexts.matching(NSPredicate(format: "label == %@", title)) + } + try require(header("General").count == 1 && header("Media").count == 1, + "appearance_section_header_class_unverified") + state.discovery["appearanceSectionHeaderClassVerified"] = true + + // One capture is valid only when the whole form fits at both native scroll endpoints. + // This guard uses container geometry, never the controls whose presence is under test. + func contentFrames() throws -> [CGRect] { + let snapshot = try form.snapshot() + let content = snapshot.children.filter { $0.elementType != .scrollBar && !$0.frame.isEmpty } + try require(!content.isEmpty && content.allSatisfy { snapshot.frame.contains($0.frame) }, + "appearance_full_form_not_visible") + return content.map(\.frame) + } + form.scroll(byDeltaX: 0, deltaY: 10_000) + let headFrames = try contentFrames() + form.scroll(byDeltaX: 0, deltaY: -10_000) + let tailFrames = try contentFrames() + try require(headFrames == tailFrames, "appearance_full_form_not_visible") + state.discovery["appearanceFullFormVisible"] = true + let frame = form.frame + let windowFrame = settings.frame + state.appearanceContentFrame = CGRect( + x: (frame.minX - windowFrame.minX) / windowFrame.width, + y: (windowFrame.maxY - frame.maxY) / windowFrame.height, + width: frame.width / windowFrame.width, height: frame.height / windowFrame.height + ) + state.appearanceControls = Dictionary(uniqueKeysWithValues: AppearanceOutputOracle.retainedLabels.map { + let controls = form.staticTexts.matching(identifier: $0) + return ($0, controls.count == 1 && controls.firstMatch.isHittable) + }) + state.appearanceControls["faceControlAbsent"] = + !form.staticTexts[AppearanceOutputOracle.faceLabel].exists + state.appearanceControls["additionalFeaturesAbsent"] = header("Additional features").count == 0 + } + + @MainActor + func runInstalledSettingsOutput(testName: String, modes: [String]) { continueAfterFailure = false let state = RunState() let environment = ProcessInfo.processInfo.environment @@ -189,7 +514,7 @@ final class GuestRegressionProbe: XCTestCase { state.buildLabel = buildLabel // Teardown is LIFO: emit even if native XCTest unwinding aborts restoration. - addTeardownBlock { @MainActor in self.finish(state, runID: runID, mode: mode) } + addTeardownBlock { @MainActor in self.finish(state, runID: runID, mode: mode, testName: testName) } addTeardownBlock { @MainActor in self.restore(state) } do { @@ -205,8 +530,7 @@ final class GuestRegressionProbe: XCTestCase { && !expectedVersion.isEmpty && !expectedBuild.isEmpty, "candidate_expectations_missing") try require(Set(["Release name", "Notch Pocket", "Version", expectedVersion, buildLabel]).count == 5, "candidate_expectations_ambiguous") - try require(["visual-pass", "visual-fail", "stale-evidence", "visual-no-reveal", - "native-abort-after-open", "native-abort-after-about"].contains(mode), "scenario_invalid") + try require(modes.contains(mode), "scenario_invalid") try require(try candidateHash() == expectedHash, "candidate_hash_mismatch") let bundle = Bundle(url: candidate) try require(bundle?.bundleIdentifier == "com.jdylanmc.notchpocket" @@ -219,9 +543,13 @@ final class GuestRegressionProbe: XCTestCase { let application = XCUIApplication(url: candidate) state.app = application + if IdleMusicScenario(rawValue: mode) != nil { + state.originalForeground = NSWorkspace.shared.frontmostApplication + try recordMusicPanelFixture(application, state: state) + } application.activate() let matches = application.descendants(matching: .any).matching(identifier: "NotchPocketSettingsWindow") - state.discovery = ["initialSettingsMarkerCount": matches.count] + state.discovery["initialSettingsMarkerCount"] = matches.count let settings = matches.firstMatch state.window = settings if !settings.exists { @@ -269,32 +597,47 @@ final class GuestRegressionProbe: XCTestCase { return } if generalRow.exists && !generalRow.isSelected { - let general = settings.staticTexts["General"] + let general = generalRow.staticTexts["General"] try require(waitHittable(general), "general_control_unavailable") general.click() let selected = XCTNSPredicateExpectation(predicate: NSPredicate(format: "selected == true"), object: generalRow) try require(XCTWaiter.wait(for: [selected], timeout: 5) == .completed, "general_selection_not_observed") } try require(generalRow.exists && generalRow.isSelected, "prepared_general_pane_required") - let about = settings.staticTexts["About"] - try require(waitHittable(about), "about_control_unavailable") - about.click() - let version = settings.staticTexts["Version"] - try require(waitHittable(version), "version_control_unavailable") - if mode == "native-abort-after-about" { - state.reason = "native_interaction_aborted" - XCTFail("Controlled native XCTest failure after About selected") + if let scenario = IdleMusicScenario(rawValue: mode) { + try inspectIdleMusicLauncher(settings, scenario: scenario, state: state, runID: runID) + state.verdict = state.observed.values.allSatisfy { $0 } ? "PASS" : "FAIL" + state.reason = state.verdict == "PASS" ? "rendered_output_verified" : "rendered_output_mismatch" return - } - let revealed = settings.staticTexts[buildLabel] - if mode != "visual-no-reveal" { version.click() } - let buildObserved = mode != "visual-no-reveal" && revealed.waitForExistence(timeout: 3) - state.discovery["buildRevealObserved"] = buildObserved - if mode == "visual-fail" { - try require(buildObserved, "negative_control_prerequisite_missing") - version.click() - let hidden = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: revealed) - _ = XCTWaiter.wait(for: [hidden], timeout: 3) + } else if mode == "appearance-idle-face-removed" { + try inspectAppearance(settings, state: state) + } else if let scenario = SettingsRemovalScenario(rawValue: mode) { + try inspectScrollableSettings(settings, scenario: scenario, state: state, runID: runID) + state.verdict = state.observed.values.allSatisfy { $0 } ? "PASS" : "FAIL" + state.reason = state.verdict == "PASS" ? "rendered_output_verified" : "rendered_output_mismatch" + return + } else { + let about = settings.descendants(matching: .outlineRow) + .containing(.staticText, identifier: "About").firstMatch.staticTexts["About"] + try require(waitHittable(about), "about_control_unavailable") + about.click() + let version = settings.staticTexts["Version"] + try require(waitHittable(version), "version_control_unavailable") + if mode == "native-abort-after-about" { + state.reason = "native_interaction_aborted" + XCTFail("Controlled native XCTest failure after About selected") + return + } + let revealed = settings.staticTexts[buildLabel] + if mode != "visual-no-reveal" { version.click() } + let buildObserved = mode != "visual-no-reveal" && revealed.waitForExistence(timeout: 3) + state.discovery["buildRevealObserved"] = buildObserved + if mode == "visual-fail" { + try require(buildObserved, "negative_control_prerequisite_missing") + version.click() + let hidden = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: revealed) + _ = XCTWaiter.wait(for: [hidden], timeout: 3) + } } try require(currentCandidatePID() == state.originalPID, "candidate_process_changed") @@ -315,9 +658,23 @@ final class GuestRegressionProbe: XCTestCase { return AboutOutputOracle.Observation(text: text, frame: observation.boundingBox) } try require(!observations.isEmpty, "ocr_unavailable") - state.observed = AboutOutputOracle.evaluate(observations, version: expectedVersion, build: expectedBuild) + if mode == "appearance-idle-face-removed" { + guard let contentFrame = state.appearanceContentFrame else { + throw Blocked.reason("appearance_content_frame_unavailable") + } + state.observed = AppearanceOutputOracle.evaluate( + observations, contentFrame: contentFrame, controls: state.appearanceControls + ) + } else { + state.observed = AboutOutputOracle.evaluate(observations, version: expectedVersion, build: expectedBuild) + } let attachment = XCTAttachment(screenshot: capture) - attachment.name = "guest-public-about-\(runID)" + let pane: String + switch mode { + case "appearance-idle-face-removed": pane = "appearance" + default: pane = "about" + } + attachment.name = "guest-public-\(pane)-\(runID)" attachment.lifetime = .keepAlways add(attachment) state.verdict = state.observed.values.allSatisfy { $0 } ? "PASS" : "FAIL" diff --git a/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj b/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj index c4a16ff692..a6443e22fd 100644 --- a/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj +++ b/experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj @@ -11,9 +11,17 @@ A00000000000000000000010 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AboutOutputOracle.swift; sourceTree = ""; }; A00000000000000000000011 = {isa = PBXBuildFile; fileRef = A00000000000000000000012; }; A00000000000000000000012 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsFixture.swift; sourceTree = ""; }; - A00000000000000000000004 = {isa = PBXGroup; children = (A00000000000000000000002, A00000000000000000000010, A00000000000000000000012, A00000000000000000000005); sourceTree = ""; }; + A00000000000000000000013 = {isa = PBXBuildFile; fileRef = A00000000000000000000014; }; + A00000000000000000000014 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppearanceOutputOracle.swift; sourceTree = ""; }; + A00000000000000000000015 = {isa = PBXBuildFile; fileRef = A00000000000000000000016; }; + A00000000000000000000016 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsRemovalOutputOracle.swift; sourceTree = ""; }; + A00000000000000000000017 = {isa = PBXBuildFile; fileRef = A00000000000000000000018; }; + A00000000000000000000018 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdleMusicLauncherScenario.swift; sourceTree = ""; }; + A00000000000000000000019 = {isa = PBXBuildFile; fileRef = A0000000000000000000001A; }; + A0000000000000000000001A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdleMusicOutputOracle.swift; sourceTree = ""; }; + A00000000000000000000004 = {isa = PBXGroup; children = (A00000000000000000000002, A00000000000000000000010, A00000000000000000000012, A00000000000000000000014, A00000000000000000000016, A00000000000000000000018, A0000000000000000000001A, A00000000000000000000005); sourceTree = ""; }; A00000000000000000000005 = {isa = PBXGroup; children = (A00000000000000000000003); name = Products; sourceTree = ""; }; - A00000000000000000000006 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A00000000000000000000001, A0000000000000000000000F, A00000000000000000000011); runOnlyForDeploymentPostprocessing = 0; }; + A00000000000000000000006 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A00000000000000000000001, A0000000000000000000000F, A00000000000000000000011, A00000000000000000000013, A00000000000000000000015, A00000000000000000000017, A00000000000000000000019); runOnlyForDeploymentPostprocessing = 0; }; A00000000000000000000007 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; A00000000000000000000008 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; A00000000000000000000009 = { diff --git a/experiments/tart-regression/GuestRegressionProbe/IdleMusicLauncherScenario.swift b/experiments/tart-regression/GuestRegressionProbe/IdleMusicLauncherScenario.swift new file mode 100644 index 0000000000..338afa8f7f --- /dev/null +++ b/experiments/tart-regression/GuestRegressionProbe/IdleMusicLauncherScenario.swift @@ -0,0 +1,254 @@ +import AppKit +import CoreGraphics +import CryptoKit +import Vision +import XCTest + +extension GuestRegressionProbe { + @MainActor + func testInstalledIdleMusicWithoutTarget() { + runInstalledSettingsOutput(testName: "testInstalledIdleMusicWithoutTarget", modes: [IdleMusicScenario.noTarget.rawValue]) + } + + @MainActor + func testInstalledIdleMusicUnavailableTarget() { + runInstalledSettingsOutput(testName: "testInstalledIdleMusicUnavailableTarget", modes: [IdleMusicScenario.unavailable.rawValue]) + } + + @MainActor + private func musicPanel(_ app: XCUIApplication) throws -> XCUIElement { + let panels = app.dialogs.matching( + NSPredicate(format: "identifier BEGINSWITH %@", "com.jdylanmc.notchpocket.notch.v1.window.") + ) + try require(panels.count == 1, "exact_notch_panel_required") + return panels.firstMatch + } + + @MainActor + private func waitValue(_ element: XCUIElement, _ value: String) -> Bool { + let expected = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", value), object: element) + return XCTWaiter.wait(for: [expected], timeout: 5) == .completed + } + + @MainActor + private func activateForeground(_ app: NSRunningApplication) throws { + try require(!app.isTerminated && app.activate(), "music_foreground_unavailable") + let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier + }, object: nil) + try require(XCTWaiter.wait(for: [ready], timeout: 5) == .completed, "music_foreground_not_observed") + } + + @MainActor + func recordMusicPanelFixture(_ app: XCUIApplication, state: RunState) throws { + let domain = "com.jdylanmc.notchpocket" as CFString + try require(CFPreferencesAppSynchronize(domain), "music_preferences_unavailable") + try require(CFPreferencesCopyAppValue("didChooseMediaController" as CFString, domain) as? Bool == true, + "music_fixture_requires_explicit_original_source") + try require(CFPreferencesCopyAppValue("lastSupportedNowPlayingBundleIdentifier" as CFString, domain) == nil, + "music_fixture_requires_no_remembered_source") + try require(CFPreferencesCopyAppValue("lastNowPlayingLauncherBundleIdentifier" as CFString, domain) == nil, + "music_fixture_requires_no_remembered_launcher_source") + state.originalMediaController = CFPreferencesCopyAppValue("mediaController" as CFString, domain) as? String + try require(state.originalMediaController != nil, "music_original_preference_unavailable") + let panel = try musicPanel(app) + // These journeys start closed; an existing open workspace is not a disposable fixture. + try require(panel.value as? String == "closed", "closed_music_panel_fixture_required") + guard let pointer = CGEvent(source: nil)?.location else { throw Blocked.reason("guest_pointer_unavailable") } + state.originalPanelState = "closed" + state.musicPointerReturn = panel.coordinate(withNormalizedOffset: .zero).withOffset( + CGVector(dx: pointer.x - panel.frame.minX, dy: pointer.y - panel.frame.minY) + ) + state.discovery["musicFixture"] = "idle_guest_no_current_or_remembered_now_playing_source" + } + + @MainActor + private func openMusicPanel(_ app: XCUIApplication) throws -> XCUIElement { + let panel = try musicPanel(app) + panel.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: panel.frame.width / 2, dy: 5)).hover() + try require(waitValue(panel, "open"), "music_panel_open_not_observed") + return panel + } + + @MainActor + private func musicSourcePicker(_ settings: XCUIElement) throws -> XCUIElement { + let row = settings.descendants(matching: .outlineRow).containing(.staticText, identifier: "Media").firstMatch + let media = row.staticTexts["Media"] + try require(waitHittable(media), "media_settings_unavailable") + if !row.isSelected { media.click() } + let selected = XCTNSPredicateExpectation(predicate: NSPredicate(format: "selected == true"), object: row) + try require(XCTWaiter.wait(for: [selected], timeout: 5) == .completed, "media_settings_not_selected") + let matches = settings.popUpButtons.matching(identifier: "Music Source") + try require(matches.count == 1 && waitHittable(matches.firstMatch), "music_source_picker_unavailable") + return matches.firstMatch + } + + @MainActor + private func chooseMusicSource(_ name: String, picker: XCUIElement, app: XCUIApplication) throws { + if picker.value as? String != name { + picker.click() + let option = app.menuItems[name] + if !waitHittable(option) || !option.isEnabled { + app.typeKey(.escape, modifierFlags: []) + throw Blocked.reason("music_source_option_unavailable") + } + option.click() + } + try require(waitValue(picker, name), "music_source_selection_not_observed") + } + + @MainActor + func restoreMusicSource(_ state: RunState) throws { + guard let app = state.app, let settings = state.window, let original = state.originalMusicSource else { + throw Blocked.reason("music_restoration_identity_missing") + } + try require(currentCandidatePID() == state.originalPID, "candidate_process_changed") + if !settings.exists { + let panel = try openMusicPanel(app) + let gear = panel.buttons.matching( + NSPredicate(format: "label IN %@ OR identifier IN %@", ["Settings", "gear"], ["Settings", "gear"]) + ) + try require(gear.count == 1 && waitHittable(gear.firstMatch), "music_restoration_gear_unavailable") + gear.firstMatch.click() + try require(settings.waitForExistence(timeout: 5), "music_restoration_settings_unavailable") + } + let picker = try musicSourcePicker(settings) + try chooseMusicSource(original, picker: picker, app: app) + let domain = "com.jdylanmc.notchpocket" as CFString + try require(CFPreferencesAppSynchronize(domain) + && CFPreferencesCopyAppValue("mediaController" as CFString, domain) as? String == state.originalMediaController + && CFPreferencesCopyAppValue("didChooseMediaController" as CFString, domain) as? Bool == true + && CFPreferencesCopyAppValue("lastSupportedNowPlayingBundleIdentifier" as CFString, domain) == nil + && CFPreferencesCopyAppValue("lastNowPlayingLauncherBundleIdentifier" as CFString, domain) == nil, + "music_preferences_not_restored") + state.discovery["musicSourceRestored"] = picker.value as? String == original + state.discovery["musicPreferencesRestored"] = true + state.musicSourceNeedsRestoration = false + } + + @MainActor + func restoreMusicPanel(_ state: RunState) throws { + guard let app = state.app else { throw Blocked.reason("music_restoration_identity_missing") } + let panel = try openMusicPanel(app) + if let tab = state.originalTab { + let button = panel.buttons[tab] + try require(waitHittable(button), "music_original_tab_unavailable") + if button.value as? String != "selected" { button.click() } + try require(waitValue(button, "selected"), "music_original_tab_not_restored") + } + state.musicPointerReturn?.hover() + try require(waitValue(panel, "closed"), "music_panel_not_restored") + state.discovery["musicPanelRestored"] = true + if let original = state.originalForeground { + try activateForeground(original) + } + } + + @MainActor + func inspectIdleMusicLauncher( + _ settings: XCUIElement, scenario: IdleMusicScenario, state: RunState, runID: String + ) throws { + guard let app = state.app else { throw Blocked.reason("candidate_process_missing") } + if scenario == .unavailable { + try require(NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.spotify.client") == nil, + "fixture_requires_spotify_not_installed") + } + let picker = try musicSourcePicker(settings) + guard let original = picker.value as? String, + ["Now Playing", "Apple Music", "Spotify", "YouTube Music"].contains(original) else { + throw Blocked.reason("original_music_source_unavailable") + } + state.originalMusicSource = original + state.musicSourceNeedsRestoration = true + try chooseMusicSource(scenario.source, picker: picker, app: app) + state.observed["selectedSourceVerified"] = picker.value as? String == scenario.source + settings.buttons[XCUIIdentifierCloseWindow].click() + let closed = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: settings) + try require(XCTWaiter.wait(for: [closed], timeout: 5) == .completed, "music_settings_close_not_observed") + + let panel = try openMusicPanel(app) + let tabs = panel.buttons.matching(NSPredicate( + format: "identifier BEGINSWITH %@ AND value == %@", "com.jdylanmc.notchpocket.notch.v1.tab.", "selected" + )) + try require(tabs.count == 1, "music_fixture_requires_visible_tabs") + state.originalTab = tabs.firstMatch.identifier + let home = panel.buttons["com.jdylanmc.notchpocket.notch.v1.tab.home"] + try require(waitHittable(home), "music_home_tab_unavailable") + if home.value as? String != "selected" { home.click() } + try require(waitValue(home, "selected"), "music_home_not_selected") + let foregroundApps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.finder") + try require(foregroundApps.count == 1, "music_fixture_requires_running_guest_finder") + let foreground = foregroundApps[0] + try activateForeground(foreground) + + let launcher = panel.buttons["com.jdylanmc.notchpocket.music.v1.idle-launcher"] + state.observed["idleLauncherVisible"] = waitHittable(launcher) + state.observed["transportAbsent"] = panel.sliders.count == 0 + state.observed["headerPreserved"] = home.exists && panel.buttons.matching( + NSPredicate(format: "label IN %@ OR identifier IN %@", ["Settings", "gear"], ["Settings", "gear"]) + ).count == 1 + if state.observed["idleLauncherVisible"] == true { launcher.click() } + let status = panel.staticTexts["com.jdylanmc.notchpocket.music.v1.launch-status"] + let appeared = status.waitForExistence(timeout: 5) + state.observed["launchStatusVisible"] = appeared + && ((status.value as? String) ?? status.label) == scenario.message && panel.frame.contains(status.frame) + state.observed["noFocusChangeOnFailedLaunch"] = + NSWorkspace.shared.frontmostApplication?.processIdentifier == foreground.processIdentifier + try captureMusicStatus(panel, status: appeared ? status : nil, scenario: scenario, state: state, runID: runID) + let dismiss = panel.buttons["com.jdylanmc.notchpocket.music.v1.launch-dismiss"] + if appeared && waitHittable(dismiss) { dismiss.click() } + let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: status) + state.observed["statusDismissed"] = appeared && XCTWaiter.wait(for: [gone], timeout: 5) == .completed + state.observed["launcherRestored"] = waitHittable(launcher) + } + + @MainActor + private func captureMusicStatus( + _ panel: XCUIElement, status: XCUIElement?, scenario: IdleMusicScenario, state: RunState, runID: String + ) throws { + let frame = panel.frame + try require(currentCandidatePID() == state.originalPID && CGDisplayBounds(CGMainDisplayID()).contains(frame), + "music_capture_identity_unavailable") + let windowID = Int(panel.identifier.replacingOccurrences(of: "com.jdylanmc.notchpocket.notch.v1.window.", with: "")) + let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? [] + let matches = windows.filter { + $0[kCGWindowNumber as String] as? Int == windowID + && $0[kCGWindowOwnerPID as String] as? Int == Int(state.originalPID ?? -1) + } + try require(matches.count == 1, "music_capture_window_ambiguous") + guard let sharing = matches[0][kCGWindowSharingState as String] as? Int, + sharing != 0, let bounds = matches[0][kCGWindowBounds as String] as? NSDictionary, + CGRect(dictionaryRepresentation: bounds) == frame else { + throw Blocked.reason("music_capture_window_unshareable") + } + let capture = panel.screenshot() + try require(currentCandidatePID() == state.originalPID && panel.frame == frame, "music_capture_identity_changed") + guard let image = capture.image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + throw Blocked.reason("capture_pixels_unavailable") + } + let request = VNRecognizeTextRequest() + request.recognitionLevel = .accurate + request.recognitionLanguages = ["en-US"] + request.usesLanguageCorrection = false + try VNImageRequestHandler(cgImage: image).perform([request]) + let observations = (request.results ?? []).compactMap { observation -> AboutOutputOracle.Observation? in + guard let text = observation.topCandidates(1).first?.string else { return nil } + return .init(text: text, frame: observation.boundingBox) + } + let statusFrame = status.map { + CGRect(x: ($0.frame.minX - frame.minX) / frame.width, y: (frame.maxY - $0.frame.maxY) / frame.height, + width: $0.frame.width / frame.width, height: $0.frame.height / frame.height) + } + state.observed["statusPixels"] = IdleMusicOutputOracle.statusVisible(observations, scenario: scenario, statusFrame: statusFrame) + state.screenshotHash = SHA256.hash(data: capture.pngRepresentation).map { String(format: "%02x", $0) }.joined() + state.discovery["musicCandidatePID"] = Int(state.originalPID ?? -1) + state.discovery["musicWindowID"] = windowID + state.discovery["musicWindowMarker"] = panel.identifier + state.discovery["musicCaptureRunID"] = runID + state.discovery["musicSource"] = scenario.source + let attachment = XCTAttachment(screenshot: capture) + attachment.name = "guest-public-music-\(runID)" + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/experiments/tart-regression/GuestRegressionProbe/IdleMusicOutputOracle.swift b/experiments/tart-regression/GuestRegressionProbe/IdleMusicOutputOracle.swift new file mode 100644 index 0000000000..358e77d103 --- /dev/null +++ b/experiments/tart-regression/GuestRegressionProbe/IdleMusicOutputOracle.swift @@ -0,0 +1,27 @@ +import CoreGraphics +import Foundation + +enum IdleMusicScenario: String { + case noTarget = "music-idle-no-target" + case unavailable = "music-idle-unavailable" + + var source: String { self == .noTarget ? "Now Playing" : "Spotify" } + var message: String { self == .noTarget ? "No music app selected." : "Spotify is not installed." } +} + +enum IdleMusicOutputOracle { + static func statusVisible( + _ observations: [AboutOutputOracle.Observation], scenario: IdleMusicScenario, statusFrame: CGRect? + ) -> Bool { + guard let statusFrame, !statusFrame.isEmpty, + CGRect(x: 0, y: 0, width: 1, height: 1).contains(statusFrame) else { return false } + let rows = observations.filter { + let overlap = min($0.frame.maxY, statusFrame.maxY) - max($0.frame.minY, statusFrame.minY) + return $0.frame.minX >= statusFrame.minX + && $0.frame.maxX <= statusFrame.maxX + && overlap >= min($0.frame.height, statusFrame.height) / 2 + && $0.frame.height > 0 && $0.frame.height <= statusFrame.height + }.sorted { $0.frame.minX < $1.frame.minX } + return AboutOutputOracle.normalize(rows.map(\.text).joined(separator: " ")) == scenario.message + } +} diff --git a/experiments/tart-regression/GuestRegressionProbe/SettingsFixture.swift b/experiments/tart-regression/GuestRegressionProbe/SettingsFixture.swift index b792dd5af6..f6b18da4bb 100644 --- a/experiments/tart-regression/GuestRegressionProbe/SettingsFixture.swift +++ b/experiments/tart-regression/GuestRegressionProbe/SettingsFixture.swift @@ -67,8 +67,8 @@ final class SettingsFixture: XCTestCase { } } else { let pane = fixture == "general" ? "General" : "About" - let control = settings.staticTexts[pane] let row = settings.descendants(matching: .outlineRow).containing(.staticText, identifier: pane).firstMatch + let control = row.staticTexts[pane] if !row.exists || !row.isSelected { let ready = XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true"), object: control) XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 5), .completed) diff --git a/experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift b/experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift new file mode 100644 index 0000000000..47eed66c07 --- /dev/null +++ b/experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift @@ -0,0 +1,130 @@ +import CoreGraphics +import Foundation + +enum SettingsRemovalScenario: String { + case notifications = "notifications-ai-replies-removed" + case general = "general-haptics-removed" + case panelSwipes = "general-panel-swipes-removed" + case compactMode = "general-compact-mode-removed" + + var pane: String { self == .notifications ? "Notifications" : "General" } + var prefix: String { pane.lowercased() } + var captureVersionKey: String { prefix + "CaptureVersion" } + var testName: String { + switch self { + case .notifications: return "testInstalledNotificationsWithoutAIReplies" + case .general: return "testInstalledGeneralWithoutHaptics" + case .panelSwipes: return "testInstalledGeneralWithoutPanelSwipes" + case .compactMode: return "testInstalledGeneralWithoutCompactMode" + } + } + var retainedLabels: [String] { + switch self { + case .notifications: return ["Show notifications in the notch", "From all apps"] + case .general, .panelSwipes, .compactMode: + return [ + "Show menu bar icon", "Launch at login", "Language", "Show on all displays", + "Preferred display", "Automatically switch displays", + "Notch height on notch displays", "Notch height on non-notch displays", + "Open notch on hover", "Remember last tab", "Notch animation", + "Enable media gestures" + ] + } + } + var removedLabels: [String] { + switch self { + case .notifications: return ["Suggest replies with Apple Intelligence"] + case .general: return ["Enable haptic feedback"] + case .panelSwipes: + return [ + "Enable gestures", "Close gesture", + "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when Open notch on hover option is disabled" + ] + case .compactMode: + return [ + "Compact mode", + "Shows a smaller opened notch with just the music player — no tabs, calendar or mirror." + ] + } + } + func removedLabelsAbsent(isPresent: (String) -> Bool) -> Bool { + removedLabels.allSatisfy { !isPresent($0) } + } + var absenceKey: String { + switch self { + case .notifications: return "suggestionControlAbsent" + case .general: return "hapticControlAbsent" + case .panelSwipes: return "panelGestureControlsAbsent" + case .compactMode: return "compactModeControlAbsent" + } + } + var forbiddenText: [String] { + switch self { + case .notifications: return ["suggest replies", "apple intelligence"] + case .general: return ["haptic"] + case .panelSwipes: return ["enable gestures", "close gesture", "two-finger swipe up", "two-finger swipe down"] + case .compactMode: return ["compact mode", "shows a smaller opened notch", "no tabs, calendar or mirror"] + } + } +} + +struct SettingsRemovalOutputOracle { + static func evaluate( + _ observations: [AboutOutputOracle.Observation], + scenario: SettingsRemovalScenario, + contentFrame: CGRect, + controls: [String: Bool], + labelFrames: [String: CGRect], + pixelWidth: Int, + windowWidthPoints: CGFloat + ) -> [String: Bool] { + let content = observations.filter { + !$0.frame.isEmpty && contentFrame.contains($0.frame) + } + let intersecting = observations.filter { !$0.frame.isEmpty && contentFrame.intersects($0.frame) } + let rows = intersecting.map { AboutOutputOracle.rowText(anchor: $0, observations: intersecting) } + var result = Dictionary(uniqueKeysWithValues: scenario.retainedLabels.map { + let label = $0 + guard let frame = labelFrames[label], !frame.isEmpty, contentFrame.contains(frame), + controls[label] == true else { return (label, false) } + let aligned = content.filter { + let anchor = CGPoint(x: $0.frame.minX, y: $0.frame.midY) + let alignment = frame.insetBy(dx: -0.005, dy: -0.005) + if scenario.pane == "General", anchor.x < frame.minX { + guard pixelWidth > 0, windowWidthPoints.isFinite, windowWidthPoints > 0, + anchor.y >= alignment.minY, anchor.y <= alignment.maxY else { + return false + } + let pixelsPerPoint = CGFloat(pixelWidth) / windowWidthPoints + guard (1...4).contains(pixelsPerPoint) else { return false } + // The recorded 1x overhang is four native points. Snap both distances in pixels, + // not absolute edges, so fractional scale/edge phase cannot change the allowance. + let leadingPixels = ((frame.minX - anchor.x) * CGFloat(pixelWidth)).rounded() + let maximumLeadingPixels = (4 * pixelsPerPoint).rounded() + return leadingPixels >= 0 && leadingPixels <= maximumLeadingPixels + } + return alignment.contains(anchor) + } + return (label, aligned.contains { + let row = AboutOutputOracle.rowText(anchor: $0, observations: content) + return row == label || row.hasPrefix(label + " ") + }) + }) + let rendered = rows.joined(separator: " ").lowercased() + result[scenario.absenceKey] = !content.isEmpty && controls[scenario.absenceKey] == true + && !scenario.forbiddenText.contains { rendered.contains($0) } + return result + } + + static func combine(_ captures: [[String: Bool]], scenario: SettingsRemovalScenario) -> [String: Bool] { + let keys = Set(scenario.retainedLabels + [scenario.absenceKey]) + guard captures.count == 2 && captures.allSatisfy({ Set($0.keys) == keys }) else { + return Dictionary(uniqueKeysWithValues: keys.map { ($0, false) }) + } + var result = Dictionary(uniqueKeysWithValues: scenario.retainedLabels.map { label in + (label, captures.contains { $0[label] == true }) + }) + result[scenario.absenceKey] = captures.allSatisfy { $0[scenario.absenceKey] == true } + return result + } +} diff --git a/experiments/tart-regression/GuestRegressionProbe/run-guest.py b/experiments/tart-regression/GuestRegressionProbe/run-guest.py index 1d6dcba5ed..fcb9d11b20 100644 --- a/experiments/tart-regression/GuestRegressionProbe/run-guest.py +++ b/experiments/tart-regression/GuestRegressionProbe/run-guest.py @@ -9,6 +9,9 @@ import sys import uuid +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from capture_contract import settings_captures, SCENARIOS, VERSION_KEYS, idle_music_assertions, IDLE_MUSIC_SCENARIOS + def blocked(reason, **details): print(json.dumps({"verdict": "BLOCKED", "reason": reason, **details}), flush=True) @@ -149,11 +152,26 @@ def main(): if not framework_matches: return blocked("framework_verdict_mismatch", runID=run_id) if verdict in ["PASS", "FAIL"]: - if (not receipt.get("candidateVerified") or not receipt.get("screenshotSHA256") + if (not receipt.get("candidateVerified") or receipt.get("cleanup") not in ["restored_general", "restored_closed_settings", "restored_original_state"]): return blocked("required_evidence_or_cleanup_missing", runID=run_id) - if not isinstance(receipt["screenshotSHA256"], str) or not re.fullmatch(r"[a-f0-9]{64}", receipt["screenshotSHA256"]): - return blocked("capture_digest_invalid", runID=run_id) + if args.scenario in SCENARIOS: + try: + settings_captures(receipt) + except (ValueError, TypeError, KeyError): + return blocked(SCENARIOS[args.scenario]["pane"].lower() + "_assertions_unverified", runID=run_id) + else: + if "captures" in receipt or VERSION_KEYS.intersection(receipt): + return blocked("unexpected_capture_schema", runID=run_id) + if not receipt.get("screenshotSHA256"): + return blocked("required_evidence_or_cleanup_missing", runID=run_id) + if not isinstance(receipt["screenshotSHA256"], str) or not re.fullmatch(r"[a-f0-9]{64}", receipt["screenshotSHA256"]): + return blocked("capture_digest_invalid", runID=run_id) + if args.scenario in IDLE_MUSIC_SCENARIOS: + try: + idle_music_assertions(receipt) + except (ValueError, TypeError, KeyError): + return blocked("music_assertions_unverified", runID=run_id) subprocess.run(["/usr/bin/codesign", "--verify", "--deep", "--strict", "/Applications/notch-pocket.app"], check=True, capture_output=True, timeout=30) exits = {"PASS": 0, "FAIL": 10, "BLOCKED": 20} diff --git a/experiments/tart-regression/MediaFixture/Info.plist b/experiments/tart-regression/MediaFixture/Info.plist new file mode 100644 index 0000000000..1d296580d0 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleIdentifier + com.jdylanmc.notchpocket.regression.mediafixture + CFBundleExecutable + NotchMediaFixture + CFBundleName + Notch Media Fixture + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + 14.0 + NSHighResolutionCapable + + NSPrincipalClass + NSApplication + + diff --git a/experiments/tart-regression/MediaFixture/README.md b/experiments/tart-regression/MediaFixture/README.md new file mode 100644 index 0000000000..3ceb3f1645 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/README.md @@ -0,0 +1,206 @@ +# Test-only OS Now Playing producer + +Bounded source fixture for issue #53 / PR #86, authored against +`35656780a87613fa95e8b873c687a6275b222d73`. This is **not a product target, +dependency, import, backend or registered regression scenario**. It uses only +public AppKit, AVFoundation and MediaPlayer APIs. No notifications, models, +preferences or AppDelegate hooks are injected into Notch. + +The independent worker must prove OS delivery to the exact approved Notch +candidate. Producer-local counters, metadata assignments and static checks +are **not native proof**, Spotify account proof or whole-suite signoff. +The existing thirteen-case registry is unchanged. Its no-target cases require +a separate clean guest with no fixture history; do not mix them with this +history-producing fixture or erase history to make them pass. + +## Source and local checks + +Run from the repository root, with native macOS, Python 3 and a compatible +installed Swift/macOS SDK (Xcode 26+, Swift 6, minimum deployment macOS 14). +The receipt records the exact compiler/SDK used. No third-party packages. An explicit `DEVELOPER_DIR` +may select the parent's approved Xcode; nothing sources `local.env`. + +```bash +python3 -B experiments/tart-regression/MediaFixture/build.py check \ + --output "$PWD/.build/mediafixture-check-001" +python3 -B -m unittest discover \ + -s experiments/tart-regression/MediaFixture/Tests -p 'test_build.py' +``` + +This compiles the full native source to **object files only** for arm64 and +x86_64 (no app bundle or native app executable), then compiles/runs only +Foundation/Darwin state, WAV and owned-storage contracts. It never instantiates +AppKit, MediaPlayer or an audio player. The test executable may receive the +toolchain's implicit linker ad-hoc seal needed for execution; no certificate +selection, `codesign`, Keychain lookup or identity signing occurs. Six contract +groups include failed play/pause/stop, no synthetic elapsed advancement, +activation/reopen without playback, explicit remote commands, end/cleanup state, +malformed/redirected storage, exclusive producer ownership and wrong-outcome +controls. Those are synthetic assertions, not guest interactions. +Seven Python recipe controls mock the compiler; they check exact fixture-only +inputs, no app execution/signing and refusal of redirected/unsafe/reused outputs. + +Every invocation requires a **new immediate child** of this worktree's `.build`. +No existing output is reused or overwritten. Outputs/failures are retained; +`build.json` identifies source hashes, compiler, SDK and the actual check mode. +The script performs no network, product build, signing, installation or app +execution. Local tests write only their own output folder. + +## Parent-owned build and signing (not author-executed) + +```bash +python3 -B experiments/tart-regression/MediaFixture/build.py build \ + --output "$PWD/.build/mediafixture-build-001" +``` + +Result: native-host-architecture **unsigned** `NotchMediaFixture.app`, empty +private sibling `MediaFixtureData/`, and `build.json`. The executable disables +linker ad-hoc signing. No Xcode project changes or product dependency resolution. +Use arm64 for an Apple Silicon Tart guest; x86_64 is object-compiled, not runtime +validated. Build output is not a runnable approved artifact until the parent +applies its separately approved signing process. + +Generic parent-only signing example, using the **same already approved public +selector** as the candidate, not a hardcoded certificate or newly discovered +identity: + +```bash +: "${APPROVED_SIGNING_SELECTOR:?Parent supplies the existing approved name or public SHA-1 selector}" +FIXTURE_APP="$PWD/.build/mediafixture-build-001/NotchMediaFixture.app" +codesign --sign "$APPROVED_SIGNING_SELECTOR" --options runtime --timestamp=none "$FIXTURE_APP" +codesign --verify --strict --verbose=2 "$FIXTURE_APP" +codesign --display --verbose=4 "$FIXTURE_APP" +``` + +This is a **local-only** signing recipe, no secure timestamp or notarization +claim. Do not enumerate/export/import keys or certificates, inspect Keychain, +source local settings, add entitlements, use `--deep`, re-sign Notch, or fall +back to another selector. The parent checks the exact bundle ID, expected team +and signer against its approved artifact, records pre/post-sign executable +hashes and signature verification, and retains the source manifest. Approval +and signer availability are external prerequisites; the author exercises none. +Do not bypass Gatekeeper, strip quarantine or automate consent. + +Transfer the exact parent-approved fixture bundle with its empty +`MediaFixtureData` sibling into a **new guest-owned private folder**, for example +`$HOME/NotchMediaFixture-run-001/`, using the parent's established transfer +process. Keep directory modes private (`0700` for data). Never install it on the +host, replace a real player, use a Spotify bundle ID, or store it directly in a +shared Applications folder. Normal guest launch registers this distinct app +with LaunchServices; the worker must verify exact path/PID/bundle/signature +resolution before trusting Notch's `NSWorkspace` activation. + +## Native behavior and public observations + +- Identity: `com.jdylanmc.notchpocket.regression.mediafixture`. Starts **idle**, + zero per-process commands/play attempts, no metadata and stopped publication. + Neither launch, activation nor reopen calls playback. Quit/last-window close + normally stops the engine, clears `nowPlayingInfo`, sets `playbackState` to + stopped and writes `shutdown_cleared`. Forced kill/crash cannot guarantee that. +- Play invokes an actual `AVAudioPlayer` over a generated local mono 16-bit PCM + WAV: 30 seconds, 22,050 Hz, 440 Hz, bounded amplitude with short edge fades. + No looping, network, microphone, account, private clip, artwork or media + library. Output volume is fixed at zero. Muted real playback is not proof of + audible output. Only a successful `play()` plus `isPlaying` publishes playing. +- Elapsed observations come exclusively from `AVAudioPlayer.currentTime`. + One-second samples do not increment or extrapolate a clock. Play failures, + decoder errors, inconsistent observations or receipt failures are explicit; + playback is stopped and publication cleared on failure. Notch/OS may + independently extrapolate their own clock; that is not producer evidence. +- Pause pauses the engine and retains fixed metadata with rate zero and + `.paused`. Stop resets the engine to zero and clears metadata with `.stopped`. + Natural completion also clears metadata. Play resumes pause or starts after + stop; remote play/pause/stop/toggle commands operate the same real engine and + are counted separately, including attempts that fail. + `play-starts` counts successful `play()` calls, including a repeated Play + while already playing; it is not an acoustic output or hardware-start count. +- Launch count persists only in the fixture folder. Activation/reopen counters + and command counters are per-process. A new process starts idle even when the + prior process was playing. Activation counters report AppKit callbacks, **not + the caller** or the number of `NSWorkspace` requests. Already-active apps need + not emit another activation. The worker must first foreground another app. + Remote counters cover commands **delivered to this producer**, not commands + the OS drops or routes elsewhere; retain the actual candidate interaction and + adapter observations rather than claiming global command tracing. +- UI fields are read-only native static texts with stable + `mediafixture.v1.` identifiers. Buttons: `play`, `pause`, `stop`, `quit`; + window: `window`; labels: `identity`, `status`, `engine`, `elapsed`, + `publication`, `launch-count`, `activation-count`, `reopen-count`, `active`, + `play-attempts`, `play-starts`, `ui-commands`, `remote-commands`, `natural-ends`, + `error`. `identity` includes PID. Query static-text **values**, not captions. + +Only sibling `MediaFixtureData/` is used for runtime application file I/O: +`producer.lock`, atomic `launch-count.json`, and new `launch-NNNNNN/` folders +containing `tone.wav` and `receipts.jsonl`. No preferences or user-media paths. +A nonprivate/redirected/unowned directory, concurrent producer, corrupt counter +or reused launch directory fails closed, never resets history. Receipts are +flushed JSON lines (schema 1), max 8 MiB per launch; overflow stops playback and +displays `receipt_write_failed`. Each contains PID, sequence, fixed event, +launch/activation/command counts, actual engine samples and publication intent. +They deliberately contain no personal media, caller identity, private errors +or secrets. `publicationIsConsumerProof` is always false. Read receipts only; +never edit them to induce state. Failed initial setup has a visible error and +public stderr code, not a fabricated successful launch receipt. + +## Independent guest proof still required + +The parent owns the signed fixture/candidate and independent worker. No guest, +host UI, player process, signing or VM command is run by this author. Use the +existing headless Tart/Aqua-session/candidate guards, native AppKit controls, +bounded waits and exact-candidate receipts, not model injection or screenshots +without assertions. This source-only slice deliberately adds no harness +selector/registry entry and makes no claim to cover the outstanding journey. + +1. On a prepared isolated guest, launch fixture normally. Assert identity and + fresh idle counters. Activate/reopen it without Play: engine elapsed remains + zero, no metadata and no commands. Select available **Now Playing** in + Notch's actual Settings. Its fallback to another backend is BLOCKED, not a + fixture pass. +2. Click fixture Play. Within five seconds require two advancing real engine + elapsed samples and `engine=playing`, no error. Require the actual candidate + to display `Regression Tone` / `Notch Test Fixture`, the full player and its + transport, from its real adapter stream. Bind candidate and producer + identities/hashes separately. Metadata-only display without engine progress + is invalid playback evidence. +3. Click Pause; require stable engine time, retained metadata/rate zero and + Notch's immediate opened-section launcher without the slider. Snapshot + counters after another guest app becomes foreground. Click **Notch's** + launcher, not a fixture activation substitute. Require the fixture frontmost, + same PID and launch count, increased activation count, and unchanged UI/ + remote command counts, play attempts/starts and paused engine time. Observe + for at least two engine sampling intervals, not just one immediate frame. +4. Click fixture Play; require resumed real elapsed progression and Notch full + player. Repeat with Stop, requiring cleared publication and idle launcher. + Launcher activation must not play. Explicit fixture Play must restore the + full player. Complete each playing segment within the 30-second duration. +5. For retained-history routing, establish actual playback first, then **Quit** + the fixture normally. Require `shutdown_cleared`, exited PID and disappearance + of the current producer in the actual OS/adapter observation. Keep Notch + running. Its launcher must reopen this exact bundle from retained history: + new PID, launch count +1, idle, zero per-process commands/play, metadata + still cleared. Explicit Play must then restore real consumer playback. + If OS retains a stale current source, retained-*history-only* routing is + **unproven**, not a pass inferred from the fixture's cleanup receipt. +6. Restore the guest's original UI/source/focus and normally quit fixture. + Generated remembered history cannot be restored by deleting preferences: + use an isolated disposable guest baseline owned by the parent. Retain + failures and both artifact identities in the worker's report. + +**Negative controls:** omit Play (must fail advancing-engine/full-player +requirements); deliberately click Play after the paused activation baseline +(must fail unchanged command/start counts, even if subsequently paused); omit +the Notch launcher click (must fail foreground/activation requirements); quit +and relaunch (must fail the running-process same-PID control, while belonging +only in the separately asserted exit/history journey). Wrong/missing title, +slider left visible when paused, stale PID/path or absent cleanup must not pass. +Execute controls via real guest UI, not counter edits, fake adapter input or a +product fixture switch. Unit controls only establish analogous policy behavior. + +**Hardware/environment unknown:** public MediaPlayer registration, remote +command delivery, LaunchServices resolution, audio-device availability and +AVAudioPlayer progress in the prepared Tart guest. In particular Tart +`--no-audio` viability is unverified. If it prevents engine progress or OS +publication, report an environment BLOCKED with exact evidence; do not fake a +clock, claim sound from metadata, silently change VM/audio configuration, or +substitute host execution. Spotify live-account behavior and other layouts/ +gestures remain separate required evidence, not coverage supplied by this app. diff --git a/experiments/tart-regression/MediaFixture/Sources/FixtureState.swift b/experiments/tart-regression/MediaFixture/Sources/FixtureState.swift new file mode 100644 index 0000000000..0fa80c71ec --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Sources/FixtureState.swift @@ -0,0 +1,143 @@ +import Foundation + +enum FixtureIdentity { + static let bundleID = "com.jdylanmc.notchpocket.regression.mediafixture" + static let title = "Regression Tone" + static let artist = "Notch Test Fixture" + static let album = "Local Synthetic Audio" + static let duration: Double = 30 +} + +enum FixtureCommand: String, Codable, CaseIterable { + case play, pause, stop, toggle +} + +enum FixtureOrigin: String, Codable { + case ui, remote +} + +struct PlayerObservation: Equatable { + let isPlaying: Bool + let elapsed: Double +} + +struct FixtureState: Codable, Equatable { + enum Phase: String, Codable { + case idle, playing, paused, stopped, failed + } + + let launchCount: Int + private(set) var activationCount = 0 + private(set) var reopenCount = 0 + private(set) var active = false + private(set) var phase = Phase.idle + private(set) var engineIsPlaying = false + private(set) var engineElapsed: Double = 0 + private(set) var metadataPublished = false + private(set) var playAttempts = 0 + private(set) var playStarts = 0 + private(set) var naturalEnds = 0 + private(set) var uiCommands: [String: Int] = [:] + private(set) var remoteCommands: [String: Int] = [:] + private(set) var errorCode: String? + + mutating func activation(_ active: Bool) { + self.active = active + if active { activationCount += 1 } + } + + mutating func reopen() { + reopenCount += 1 + } + + mutating func request(_ command: FixtureCommand, origin: FixtureOrigin) -> FixtureCommand { + switch origin { + case .ui: uiCommands[command.rawValue, default: 0] += 1 + case .remote: remoteCommands[command.rawValue, default: 0] += 1 + } + let resolved = command == .toggle ? (engineIsPlaying ? .pause : .play) : command + if resolved == .play { playAttempts += 1 } + return resolved + } + + mutating func started(success: Bool, observation: PlayerObservation) { + guard accept(observation) else { return } + guard success, observation.isPlaying else { + fail("audio_start_failed") + return + } + phase = .playing + metadataPublished = true + playStarts += 1 + errorCode = nil + } + + mutating func paused(observation: PlayerObservation) { + guard accept(observation) else { return } + guard !observation.isPlaying else { + fail("audio_pause_failed") + return + } + if metadataPublished { phase = .paused } + } + + mutating func stopped(observation: PlayerObservation) { + guard accept(observation) else { return } + guard !observation.isPlaying else { + fail("audio_stop_failed") + return + } + phase = .stopped + metadataPublished = false + errorCode = nil + } + + mutating func sample(_ observation: PlayerObservation) { + guard accept(observation) else { return } + if phase == .playing, !observation.isPlaying { + phase = .stopped + metadataPublished = false + } else if phase != .playing, observation.isPlaying { + fail("unexpected_audio_playback") + } + } + + mutating func finished(success: Bool, observation: PlayerObservation) { + if success { + stopped(observation: observation) + naturalEnds += 1 + } else { + _ = accept(observation) + fail("audio_finish_failed") + } + } + + mutating func fail(_ code: String) { + phase = .failed + metadataPublished = false + errorCode = code + } + + private mutating func accept(_ observation: PlayerObservation) -> Bool { + engineIsPlaying = observation.isPlaying + guard observation.elapsed.isFinite, + (0...FixtureIdentity.duration).contains(observation.elapsed) else { + fail("invalid_audio_observation") + return false + } + engineElapsed = observation.elapsed + return true + } +} + +struct FixtureReceipt: Encodable { + let schemaVersion = 1 + let bundleIdentifier = FixtureIdentity.bundleID + let pid: Int32 + let event: String + let sequence: Int + let state: FixtureState + let muted = true + // This describes the local public API assignment, not OS delivery to Notch. + let publicationIsConsumerProof = false +} diff --git a/experiments/tart-regression/MediaFixture/Sources/FixtureStore.swift b/experiments/tart-regression/MediaFixture/Sources/FixtureStore.swift new file mode 100644 index 0000000000..a99bc38233 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Sources/FixtureStore.swift @@ -0,0 +1,109 @@ +import Darwin +import Foundation + +enum FixtureStoreError: Error { + case unsafeDirectory, unsafeFile, alreadyRunning, invalidCounter, ioFailure, receiptLimit +} + +final class FixtureStore { + let launchCount: Int + let audioURL: URL + let receiptURL: URL + private let lockFD: Int32 + private let receipt: FileHandle + private var bytesWritten = 0 + private var sequence = 0 + + init(root: URL) throws { + guard root.isFileURL, root.path == root.resolvingSymlinksInPath().path else { + throw FixtureStoreError.unsafeDirectory + } + var directory = stat() + guard lstat(root.path, &directory) == 0, + directory.st_mode & S_IFMT == S_IFDIR, + directory.st_uid == getuid(), + directory.st_mode & 0o077 == 0 else { + throw FixtureStoreError.unsafeDirectory + } + let descriptor = open(root.appendingPathComponent("producer.lock").path, + O_CREAT | O_RDWR | O_NOFOLLOW, 0o600) + guard descriptor >= 0 else { throw FixtureStoreError.ioFailure } + var transferred = false + defer { if !transferred { close(descriptor) } } + try Self.validateFile(descriptor) + guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { + throw FixtureStoreError.alreadyRunning + } + + let counterURL = root.appendingPathComponent("launch-count.json") + let counterFD = open(counterURL.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) + let previous: Int + if counterFD >= 0 { + let handle = FileHandle(fileDescriptor: counterFD, closeOnDealloc: true) + try Self.validateFile(counterFD) + guard let bytes = try handle.read(upToCount: 1_025), bytes.count <= 1_024 else { + throw FixtureStoreError.invalidCounter + } + let counter = try JSONDecoder().decode(Counter.self, from: bytes) + guard counter.schemaVersion == 1, (1..<1_000_000).contains(counter.launches) else { + throw FixtureStoreError.invalidCounter + } + previous = counter.launches + try handle.close() + } else if errno == ENOENT { + previous = 0 + } else { + throw FixtureStoreError.unsafeFile + } + + launchCount = previous + 1 + let run = root.appendingPathComponent(String(format: "launch-%06d", launchCount)) + guard mkdir(run.path, 0o700) == 0 else { throw FixtureStoreError.ioFailure } + audioURL = run.appendingPathComponent("tone.wav") + receiptURL = run.appendingPathComponent("receipts.jsonl") + try GeneratedAudio.wave().write(to: audioURL, options: .withoutOverwriting) + let receiptFD = open(receiptURL.path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW, 0o600) + guard receiptFD >= 0 else { throw FixtureStoreError.ioFailure } + receipt = FileHandle(fileDescriptor: receiptFD, closeOnDealloc: true) + try JSONEncoder().encode(Counter(schemaVersion: 1, launches: launchCount)) + .write(to: counterURL, options: .atomic) + lockFD = descriptor + transferred = true + } + + func append(event: String, state: FixtureState) throws { + let entry = FixtureReceipt( + pid: getpid(), event: event, sequence: sequence + 1, state: state + ) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + var data = try encoder.encode(entry) + data.append(0x0a) + guard bytesWritten + data.count <= 8 * 1_024 * 1_024 else { + throw FixtureStoreError.receiptLimit + } + try receipt.write(contentsOf: data) + try receipt.synchronize() + bytesWritten += data.count + sequence += 1 + } + + private struct Counter: Codable { + let schemaVersion: Int + let launches: Int + } + + private static func validateFile(_ descriptor: Int32) throws { + var info = stat() + guard fstat(descriptor, &info) == 0, + info.st_mode & S_IFMT == S_IFREG, + info.st_uid == getuid(), info.st_nlink == 1, + info.st_mode & 0o022 == 0 else { + throw FixtureStoreError.unsafeFile + } + } + + deinit { + close(lockFD) + } +} diff --git a/experiments/tart-regression/MediaFixture/Sources/GeneratedAudio.swift b/experiments/tart-regression/MediaFixture/Sources/GeneratedAudio.swift new file mode 100644 index 0000000000..3d57ee94aa --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Sources/GeneratedAudio.swift @@ -0,0 +1,34 @@ +import Foundation + +enum GeneratedAudio { + static let sampleRate = 22_050 + static let frameCount = Int(FixtureIdentity.duration) * sampleRate + + static func wave() -> Data { + let byteCount = frameCount * 2 + var result = Data() + func ascii(_ text: String) { result.append(contentsOf: text.utf8) } + func integer(_ value: T) { + var littleEndian = value.littleEndian + withUnsafeBytes(of: &littleEndian) { result.append(contentsOf: $0) } + } + ascii("RIFF") + integer(UInt32(36 + byteCount)) + ascii("WAVEfmt ") + integer(UInt32(16)) + integer(UInt16(1)) + integer(UInt16(1)) + integer(UInt32(sampleRate)) + integer(UInt32(sampleRate * 2)) + integer(UInt16(2)) + integer(UInt16(16)) + ascii("data") + integer(UInt32(byteCount)) + for frame in 0.. Bool { + state.reopen() + window?.makeKeyAndOrderFront(nil) + record("reopen") + return true + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } + + func applicationWillTerminate(_ notification: Notification) { + timer?.invalidate() + for (command, target) in commandTargets { + command.removeTarget(target) + command.isEnabled = false + } + player?.stop() + player?.currentTime = 0 + state.stopped(observation: observation) + publish() + record("shutdown_cleared") + } + + private var observation: PlayerObservation { + PlayerObservation(isPlaying: player?.isPlaying ?? false, elapsed: player?.currentTime ?? 0) + } + + private func perform(_ command: FixtureCommand, origin: FixtureOrigin) -> MPRemoteCommandHandlerStatus { + let action = state.request(command, origin: origin) + guard let player, !receiptFailed else { + fail("producer_unavailable") + return .commandFailed + } + switch action { + case .play: + if player.currentTime >= player.duration { player.currentTime = 0 } + let success = player.play() + state.started(success: success, observation: observation) + case .pause: + player.pause() + state.paused(observation: observation) + case .stop: + player.stop() + player.currentTime = 0 + state.stopped(observation: observation) + case .toggle: + preconditionFailure("Toggle is resolved by FixtureState.request") + } + if state.errorCode != nil { player.stop() } + state.sample(observation) + publish() + record("\(origin.rawValue)_\(command.rawValue)") + return state.errorCode == nil ? .success : .commandFailed + } + + private func configureRemoteCommands() { + let commands = MPRemoteCommandCenter.shared() + let enabled: [(MPRemoteCommand, FixtureCommand)] = [ + (commands.playCommand, .play), + (commands.pauseCommand, .pause), + (commands.stopCommand, .stop), + (commands.togglePlayPauseCommand, .toggle) + ] + for (remote, command) in enabled { + remote.isEnabled = true + let token = remote.addTarget { [weak self] _ in + // MediaPlayer may deliver off-main; all player/UI state is main-actor owned. + if Thread.isMainThread { + return MainActor.assumeIsolated { + self?.perform(command, origin: .remote) ?? .commandFailed + } + } + return DispatchQueue.main.sync { + self?.perform(command, origin: .remote) ?? .commandFailed + } + } + commandTargets.append((remote, token)) + } + } + + private func publish() { + if state.metadataPublished { + center.nowPlayingInfo = [ + MPMediaItemPropertyTitle: FixtureIdentity.title, + MPMediaItemPropertyArtist: FixtureIdentity.artist, + MPMediaItemPropertyAlbumTitle: FixtureIdentity.album, + MPMediaItemPropertyPlaybackDuration: FixtureIdentity.duration, + MPNowPlayingInfoPropertyElapsedPlaybackTime: state.engineElapsed, + MPNowPlayingInfoPropertyPlaybackRate: state.engineIsPlaying ? 1.0 : 0.0, + MPNowPlayingInfoPropertyDefaultPlaybackRate: 1.0, + MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue + ] + center.playbackState = state.engineIsPlaying ? .playing : .paused + } else { + center.nowPlayingInfo = nil + center.playbackState = .stopped + } + } + + private func sample() { + guard let player, !receiptFailed else { return } + let wasPlaying = state.engineIsPlaying + guard wasPlaying || player.isPlaying else { return } + state.sample(observation) + if let code = state.errorCode { + fail(code) + return + } + publish() + if wasPlaying || state.engineIsPlaying { + record("engine_sample") + } else { + refreshLabels() + } + } + + nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { + if Thread.isMainThread { + MainActor.assumeIsolated { finished(success: flag) } + } else { + DispatchQueue.main.sync { self.finished(success: flag) } + } + } + + nonisolated func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { + if Thread.isMainThread { + MainActor.assumeIsolated { fail("audio_decode_failed") } + } else { + DispatchQueue.main.sync { self.fail("audio_decode_failed") } + } + } + + private func finished(success: Bool) { + state.finished(success: success, observation: observation) + if let code = state.errorCode { + fail(code) + return + } + publish() + record("audio_finished") + } + + private func fail(_ code: String) { + player?.stop() + state.sample(observation) + state.fail(code) + publish() + fputs("NOTCH_MEDIA_FIXTURE_ERROR \(code)\n", stderr) + record("failure") + } + + private func record(_ event: String) { + if let store, !receiptFailed { + do { + try store.append(event: event, state: state) + } catch { + receiptFailed = true + player?.stop() + state.sample(observation) + state.fail("receipt_write_failed") + publish() + fputs("NOTCH_MEDIA_FIXTURE_ERROR receipt_write_failed\n", stderr) + } + } + refreshLabels() + } + + @objc private func playPressed() { _ = perform(.play, origin: .ui) } + @objc private func pausePressed() { _ = perform(.pause, origin: .ui) } + @objc private func stopPressed() { _ = perform(.stop, origin: .ui) } + @objc private func quitPressed() { NSApp.terminate(nil) } + + private func makeWindow() { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 680, height: 590), + styleMask: [.titled, .closable, .miniaturizable], backing: .buffered, defer: false + ) + self.window = window + window.title = "Notch Regression Media Fixture" + window.setAccessibilityIdentifier("mediafixture.v1.window") + window.isReleasedWhenClosed = false + window.isRestorable = false + window.center() + let stack = NSStackView() + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = 8 + stack.translatesAutoresizingMaskIntoConstraints = false + let heading = NSTextField(labelWithString: "Local test producer - muted 30-second generated tone") + heading.font = .boldSystemFont(ofSize: 15) + stack.addArrangedSubview(heading) + let controls = NSStackView() + for (title, identifier, selector) in [ + ("Play", "play", #selector(playPressed)), + ("Pause", "pause", #selector(pausePressed)), + ("Stop", "stop", #selector(stopPressed)), + ("Quit", "quit", #selector(quitPressed)) + ] { + let button = NSButton(title: title, target: self, action: selector) + button.bezelStyle = .rounded + button.setAccessibilityIdentifier("mediafixture.v1.\(identifier)") + controls.addArrangedSubview(button) + if identifier != "quit" { buttons.append(button) } + } + stack.addArrangedSubview(controls) + for name in ["identity", "status", "engine", "elapsed", "publication", "launch-count", + "activation-count", "reopen-count", "active", "play-attempts", "play-starts", + "ui-commands", "remote-commands", "natural-ends", "error"] { + let field = NSTextField(labelWithString: "") + field.font = .monospacedSystemFont(ofSize: 12, weight: .regular) + field.setAccessibilityIdentifier("mediafixture.v1.\(name)") + field.setAccessibilityLabel(name) + labels[name] = field + stack.addArrangedSubview(field) + } + stack.addArrangedSubview(NSTextField( + wrappingLabelWithString: + "Counters and publication are producer-local, not proof of OS delivery or audible output." + )) + guard let content = window.contentView else { preconditionFailure("Missing window content") } + content.addSubview(stack) + NSLayoutConstraint.activate([ + stack.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 20), + stack.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20), + stack.topAnchor.constraint(equalTo: content.topAnchor, constant: 20), + stack.bottomAnchor.constraint(lessThanOrEqualTo: content.bottomAnchor, constant: -20) + ]) + installMenu() + } + + private func installMenu() { + let menu = NSMenu() + let applicationItem = NSMenuItem() + let applicationMenu = NSMenu() + applicationMenu.addItem(withTitle: "Quit Media Fixture", action: #selector(quitPressed), keyEquivalent: "q") + .target = self + applicationItem.submenu = applicationMenu + menu.addItem(applicationItem) + NSApp.mainMenu = menu + } + + private func refreshLabels() { + func commands(_ counts: [String: Int]) -> String { + FixtureCommand.allCases.map { "\($0.rawValue)=\(counts[$0.rawValue, default: 0])" }.joined(separator: " ") + } + let values = [ + "identity": "\(FixtureIdentity.bundleID) pid=\(getpid())", + "status": state.phase.rawValue, + "engine": state.engineIsPlaying ? "playing" : "not-playing", + "elapsed": String(format: "%.3f / 30.000", state.engineElapsed), + "publication": state.metadataPublished ? state.phase.rawValue : "cleared", + "launch-count": String(state.launchCount), + "activation-count": String(state.activationCount), + "reopen-count": String(state.reopenCount), + "active": String(state.active), + "play-attempts": String(state.playAttempts), + "play-starts": String(state.playStarts), + "ui-commands": commands(state.uiCommands), + "remote-commands": commands(state.remoteCommands), + "natural-ends": String(state.naturalEnds), + "error": state.errorCode ?? "none" + ] + for (name, value) in values { labels[name]?.stringValue = value } + for button in buttons { button.isEnabled = player != nil && !receiptFailed } + } +} + +@main +enum MediaFixtureMain { + @MainActor static func main() { + let app = NSApplication.shared + let delegate = MediaFixtureApp() + app.setActivationPolicy(.regular) + app.delegate = delegate + withExtendedLifetime(delegate) { app.run() } + } +} diff --git a/experiments/tart-regression/MediaFixture/Tests/FixtureTests.swift b/experiments/tart-regression/MediaFixture/Tests/FixtureTests.swift new file mode 100644 index 0000000000..02bb87a931 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Tests/FixtureTests.swift @@ -0,0 +1,205 @@ +import Darwin +import Foundation + +enum TestFailure: Error { + case assertion(String) +} + +@main +enum FixtureTests { + private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) throws { + guard condition() else { throw TestFailure.assertion(message) } + } + + static func main() throws { + guard CommandLine.arguments.count == 2 else { throw TestFailure.assertion("Missing owned test root") } + try lifecycle() + try transport() + try failures() + try activationControls() + try audio() + try storage(URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)) + print("PASS: 6 fixture contract groups (pure/synthetic + local storage; no native media or UI execution)") + } + + private static func lifecycle() throws { + var state = FixtureState(launchCount: 7) + try expect(state.phase == .idle && !state.metadataPublished && !state.engineIsPlaying, "Idle launch") + state.activation(true) + state.reopen() + state.activation(false) + state.activation(true) + try expect(state.launchCount == 7 && state.activationCount == 2 && state.reopenCount == 1, "Lifecycle counts") + try expect(state.phase == .idle && state.engineElapsed == 0, "Activation cannot change transport") + try expect(state.playAttempts == 0 && state.playStarts == 0, "Activation cannot request play") + try expect(state.uiCommands.isEmpty && state.remoteCommands.isEmpty, "Lifecycle is not a command") + } + + private static func playing() -> FixtureState { + var state = FixtureState(launchCount: 1) + _ = state.request(.play, origin: .ui) + state.started(success: true, observation: PlayerObservation(isPlaying: true, elapsed: 0)) + return state + } + + private static func transport() throws { + var state = playing() + try expect(state.phase == .playing && state.metadataPublished && state.playStarts == 1, "Successful play") + state.sample(PlayerObservation(isPlaying: true, elapsed: 1.25)) + state.sample(PlayerObservation(isPlaying: true, elapsed: 1.25)) + try expect(state.engineElapsed == 1.25, "A repeated engine sample cannot fabricate progress") + _ = state.request(.pause, origin: .ui) + state.paused(observation: PlayerObservation(isPlaying: false, elapsed: 1.25)) + try expect(state.phase == .paused && state.metadataPublished, "Pause retains metadata") + state.activation(true) + state.reopen() + try expect(state.phase == .paused && state.playAttempts == 1, "Paused activation cannot resume") + let resolved = state.request(.toggle, origin: .remote) + try expect(resolved == .play && state.remoteCommands["toggle"] == 1, "Remote resume recorded") + state.started(success: true, observation: PlayerObservation(isPlaying: true, elapsed: 1.25)) + try expect(state.playAttempts == 2 && state.playStarts == 2, "Explicit resume") + try expect(state.request(.toggle, origin: .remote) == .pause, "Playing toggle resolves to pause") + state.paused(observation: PlayerObservation(isPlaying: false, elapsed: 1.25)) + _ = state.request(.stop, origin: .ui) + state.stopped(observation: PlayerObservation(isPlaying: false, elapsed: 0)) + try expect(state.phase == .stopped && !state.metadataPublished, "Stop clears metadata") + state.reopen() + try expect(state.playAttempts == 2 && state.phase == .stopped, "Stopped reopen cannot play") + _ = state.request(.play, origin: .remote) + state.started(success: true, observation: PlayerObservation(isPlaying: true, elapsed: 0)) + state.finished(success: true, observation: PlayerObservation(isPlaying: false, elapsed: 30)) + try expect(state.naturalEnds == 1 && !state.metadataPublished && state.phase == .stopped, "Natural end") + try expect(state.remoteCommands["play"] == 1 && state.uiCommands["play"] == 1, "Origin separation") + } + + private static func failures() throws { + var state = FixtureState(launchCount: 1) + _ = state.request(.play, origin: .ui) + state.started(success: false, observation: PlayerObservation(isPlaying: false, elapsed: 0)) + try expect(state.phase == .failed && state.playStarts == 0 && !state.metadataPublished, "Failed start") + state = playing() + state.paused(observation: PlayerObservation(isPlaying: true, elapsed: 1)) + try expect(state.errorCode == "audio_pause_failed" && !state.metadataPublished, "Failed pause") + state = playing() + state.stopped(observation: PlayerObservation(isPlaying: true, elapsed: 1)) + try expect(state.errorCode == "audio_stop_failed", "Failed stop") + for elapsed in [Double.nan, .infinity, -1, 31] { + state = playing() + state.sample(PlayerObservation(isPlaying: true, elapsed: elapsed)) + try expect(state.errorCode == "invalid_audio_observation", "Reject invalid elapsed") + } + state = FixtureState(launchCount: 1) + state.sample(PlayerObservation(isPlaying: true, elapsed: 0)) + try expect(state.errorCode == "unexpected_audio_playback", "Unrequested playback is an error") + state = playing() + state.finished(success: false, observation: PlayerObservation(isPlaying: false, elapsed: 1)) + try expect(state.phase == .failed && state.naturalEnds == 0, "Failed decoder/finish is not normal completion") + } + + // A synthetic version of the worker's running-process activation assertion. + // It cannot establish the caller, the frontmost application or OS delivery. + private static func activationOnly(before: FixtureState, after: FixtureState) -> Bool { + before.launchCount == after.launchCount + && after.activationCount > before.activationCount && after.active + && before.playAttempts == after.playAttempts && before.playStarts == after.playStarts + && before.uiCommands == after.uiCommands && before.remoteCommands == after.remoteCommands + && before.phase == after.phase && before.engineElapsed == after.engineElapsed + && !after.engineIsPlaying && after.errorCode == nil + } + + private static func activationControls() throws { + var before = playing() + _ = before.request(.pause, origin: .ui) + before.paused(observation: PlayerObservation(isPlaying: false, elapsed: 2)) + var after = before + after.activation(true) + after.reopen() + try expect(activationOnly(before: before, after: after), "Positive activation control") + try expect(!activationOnly(before: before, after: before), "No activation must fail") + var wrong = after + _ = wrong.request(.play, origin: .remote) + wrong.started(success: true, observation: PlayerObservation(isPlaying: true, elapsed: 2)) + try expect(!activationOnly(before: before, after: wrong), "Accidental remote play must fail") + wrong.paused(observation: PlayerObservation(isPlaying: false, elapsed: 2)) + try expect(!activationOnly(before: before, after: wrong), "Play then pause cannot hide command") + wrong = after + _ = wrong.request(.play, origin: .remote) + wrong.started(success: false, observation: PlayerObservation(isPlaying: false, elapsed: 2)) + try expect(!activationOnly(before: before, after: wrong), "Even failed play request must fail") + wrong = FixtureState(launchCount: 2) + wrong.activation(true) + try expect(!activationOnly(before: before, after: wrong), "Process replacement must fail") + } + + private static func audio() throws { + let data = GeneratedAudio.wave() + try expect(data == GeneratedAudio.wave(), "Repeatable generated waveform") + try expect(data.count == 44 + 30 * 22_050 * 2, "Bounded 30-second mono PCM") + try expect(String(data: data[0..<4], encoding: .utf8) == "RIFF", "RIFF header") + try expect(String(data: data[8..<16], encoding: .utf8) == "WAVEfmt ", "WAVE header") + func uint32(_ offset: Int) -> UInt32 { + (0..<4).reduce(0) { $0 | (UInt32(data[offset + $1]) << ($1 * 8)) } + } + try expect(uint32(4) == data.count - 8 && uint32(40) == data.count - 44, "Chunk lengths") + try expect(uint32(24) == 22_050 && uint32(28) == 44_100, "PCM clock") + try expect(data[20] == 1 && data[22] == 1 && data[32] == 2 && data[34] == 16, "PCM format") + var nonzero = 0 + for index in stride(from: 44, to: data.count, by: 2) { + let sample = Int16(bitPattern: UInt16(data[index]) | UInt16(data[index + 1]) << 8) + try expect(abs(Int(sample)) <= 4_000, "Amplitude bounded") + if sample != 0 { nonzero += 1 } + } + try expect(nonzero > GeneratedAudio.frameCount / 2, "Real generated signal, not a silence placeholder") + } + + private static func storage(_ root: URL) throws { + let manager = FileManager.default + try manager.createDirectory(at: root, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + var first: FixtureStore? = try FixtureStore(root: root) + try expect(first?.launchCount == 1, "First persistent launch") + do { + _ = try FixtureStore(root: root) + throw TestFailure.assertion("Concurrent producer accepted") + } catch FixtureStoreError.alreadyRunning { } + let state = FixtureState(launchCount: 1) + try first?.append(event: "unit_idle", state: state) + guard let receiptURL = first?.receiptURL, let audioURL = first?.audioURL else { + throw TestFailure.assertion("Missing test store") + } + let receipt = try JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any] + try expect(receipt?["bundleIdentifier"] as? String == FixtureIdentity.bundleID, "Receipt identity") + try expect(receipt?["publicationIsConsumerProof"] as? Bool == false, "Receipt scope") + let writtenAudio = try Data(contentsOf: audioURL) + try expect(writtenAudio == GeneratedAudio.wave(), "Owned audio file") + first = nil + var second: FixtureStore? = try FixtureStore(root: root) + try expect(second?.launchCount == 2, "Launch count survives process-store lifetime") + try expect(FixtureState(launchCount: 2).playAttempts == 0, "Transport never restored from disk") + second = nil + let counter = root.appendingPathComponent("launch-count.json") + try Data("invalid".utf8).write(to: counter) + do { + _ = try FixtureStore(root: root) + throw TestFailure.assertion("Malformed counter accepted") + } catch is DecodingError { } + try manager.removeItem(at: counter) + try manager.createSymbolicLink(at: counter, withDestinationURL: audioURL) + do { + _ = try FixtureStore(root: root) + throw TestFailure.assertion("Redirected counter accepted") + } catch FixtureStoreError.unsafeFile { } + try manager.removeItem(at: counter) + try Data("{\"schemaVersion\":1,\"launches\":1}".utf8).write(to: counter) + do { + _ = try FixtureStore(root: root) + throw TestFailure.assertion("Existing launch directory reused") + } catch FixtureStoreError.ioFailure { } + try manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: root.path) + do { + _ = try FixtureStore(root: root) + throw TestFailure.assertion("Nonprivate fixture root accepted") + } catch FixtureStoreError.unsafeDirectory { } + try manager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path) + } +} diff --git a/experiments/tart-regression/MediaFixture/Tests/test_build.py b/experiments/tart-regression/MediaFixture/Tests/test_build.py new file mode 100644 index 0000000000..7a8266a8f7 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/Tests/test_build.py @@ -0,0 +1,129 @@ +"""Permission-free recipe controls; all native commands mocked, no app build/sign/launch.""" + +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + + +SOURCE = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("media_fixture_build", SOURCE / "build.py") +BUILD = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(BUILD) + + +class BuildContracts(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory( + prefix="mediafixture-recipe-tests-", dir=BUILD.REPO / ".build" + ) + self.addCleanup(self.temporary.cleanup) + self.repo = Path(self.temporary.name) / "repository" + self.repo.mkdir(mode=0o700) + self.output = self.repo / ".build" / "case" + self.commands = [] + + def fake_run(self, arguments, cwd, timeout=180): + args = list(map(str, arguments)) + self.commands.append(args) + if args == ["xcrun", "--sdk", "macosx", "--show-sdk-path"]: + return "/mock/MacOSX.sdk" + if args == ["xcrun", "--find", "swiftc"]: + return "/mock/swiftc" + if args == ["/mock/swiftc", "--version"]: + return "MOCK Swift toolchain, recipe test only" + if args[0] == "/mock/swiftc": + if "-o" in args: + Path(args[args.index("-o") + 1]).write_bytes(b"MOCK-COMPILE-NOT-EXECUTABLE") + return "" + if args[0] == str(self.output / "fixture-contract-tests"): + return "MOCK contract invocation, not native proof" + raise AssertionError(f"Unexpected external command: {args}") + + def invoke(self, mode, output=None): + with ( + patch.object(BUILD, "REPO", self.repo), + patch.object(BUILD, "run", side_effect=self.fake_run), + patch.object(BUILD.platform, "system", return_value="Darwin"), + patch.object(BUILD.platform, "machine", return_value="arm64"), + patch("sys.argv", ["build.py", mode, "--output", str(output or self.output)]), + contextlib.redirect_stdout(io.StringIO()), + ): + BUILD.main() + + def test_check_compiles_both_architectures_without_building_native_app(self): + self.invoke("check") + compiles = [command for command in self.commands if command[0] == "/mock/swiftc"] + objects = [command for command in compiles if "-emit-object" in command] + self.assertEqual(2, len(objects)) + self.assertEqual( + {"arm64-apple-macosx14.0", "x86_64-apple-macosx14.0"}, + {command[command.index("-target") + 1] for command in objects}, + ) + test_compile = [command for command in compiles if "-o" in command and "-emit-object" not in command] + self.assertEqual(1, len(test_compile)) + self.assertNotIn(str(SOURCE / "Sources/MediaFixtureApp.swift"), test_compile[0]) + self.assertFalse((self.output / "NotchMediaFixture.app").exists()) + receipt = json.loads((self.output / "build.json").read_text()) + self.assertFalse(receipt["nativeAppExecuted"]) + self.assertFalse(receipt["identitySigningPerformed"]) + + def test_unsigned_build_recipe_is_fixture_only_and_does_not_execute_it(self): + self.invoke("build") + compile_command = next(command for command in self.commands if "-o" in command) + self.assertIn("-no_adhoc_codesign", compile_command) + self.assertIn("MediaPlayer", compile_command) + self.assertEqual( + set(map(str, BUILD.APP)), {value for value in compile_command if value.endswith(".swift")} + ) + receipt = json.loads((self.output / "build.json").read_text()) + self.assertEqual("unsigned", receipt["signature"]) + self.assertEqual(BUILD.BUNDLE_ID, receipt["bundleIdentifier"]) + self.assertFalse(receipt["nativeAppExecuted"]) + self.assertFalse(receipt["identitySigningPerformed"]) + self.assertEqual(0o700, (self.output / "MediaFixtureData").stat().st_mode & 0o777) + self.assertTrue(all(command[0] in ("xcrun", "/mock/swiftc") for command in self.commands)) + + def test_refuses_output_outside_build_root(self): + with self.assertRaises(ValueError): + self.invoke("check", self.repo / "outside") + self.assertEqual([], self.commands) + + def test_refuses_nested_or_traversing_output(self): + for path in [self.output / "nested", self.repo / ".build" / ".." / "escaped"]: + with self.subTest(path=path), self.assertRaises(ValueError): + self.invoke("check", path) + self.assertEqual([], self.commands) + + def test_refuses_existing_output_without_modification(self): + self.output.mkdir(parents=True) + marker = self.output / "preserved" + marker.write_text("existing") + with self.assertRaises(FileExistsError): + self.invoke("check") + self.assertEqual("existing", marker.read_text()) + self.assertEqual([], self.commands) + + def test_refuses_symlinked_build_root(self): + destination = self.repo / "redirected" + destination.mkdir() + (self.repo / ".build").symlink_to(destination, target_is_directory=True) + with self.assertRaises(ValueError): + self.invoke("check") + self.assertEqual([], list(destination.iterdir())) + self.assertEqual([], self.commands) + + def test_refuses_writable_build_root(self): + self.output.parent.mkdir(mode=0o700) + self.output.parent.chmod(0o777) + with self.assertRaises(ValueError): + self.invoke("check") + self.assertEqual([], self.commands) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/tart-regression/MediaFixture/build.py b/experiments/tart-regression/MediaFixture/build.py new file mode 100644 index 0000000000..c27e760962 --- /dev/null +++ b/experiments/tart-regression/MediaFixture/build.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Local-only, standard-library fixture compiler. Never signs, installs or launches an app.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import plistlib +import stat +import subprocess +import sys + + +SOURCE = Path(__file__).resolve().parent +REPO = SOURCE.parents[2] +CORE = [ + SOURCE / "Sources/FixtureState.swift", + SOURCE / "Sources/GeneratedAudio.swift", + SOURCE / "Sources/FixtureStore.swift", +] +APP = CORE + [SOURCE / "Sources/MediaFixtureApp.swift"] +BUNDLE_ID = "com.jdylanmc.notchpocket.regression.mediafixture" + + +def run(arguments, cwd, timeout=180): + result = subprocess.run( + [str(value) for value in arguments], cwd=cwd, check=True, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, + ) + if result.stderr: + print(result.stderr, file=sys.stderr, end="") + return result.stdout.strip() + + +def owned_directory(path): + info = path.lstat() + if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() + or info.st_mode & 0o022 or path.resolve() != path): + raise ValueError("Output ancestry must be canonical, owned and not group/world writable") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("check", "build")) + parser.add_argument("--output", required=True, type=Path, + help="New immediate child of this worktree's .build") + args = parser.parse_args() + if platform.system() != "Darwin" or platform.machine() not in ("arm64", "x86_64"): + raise ValueError("Requires native macOS arm64 or x86_64 and an installed macOS Swift SDK") + build_root = REPO / ".build" + output = args.output + if (not output.is_absolute() or output.parent != build_root + or output.name in ("", ".", "..") or output != output.resolve()): + raise ValueError("Output must be a new canonical immediate child of this worktree's .build") + owned_directory(REPO) + if not build_root.exists(): + build_root.mkdir(mode=0o700) + owned_directory(build_root) + output.mkdir(mode=0o700) + sdk = run(["xcrun", "--sdk", "macosx", "--show-sdk-path"], output) + compiler = run(["xcrun", "--find", "swiftc"], output) + version = run([compiler, "--version"], output) + cache = output / "module-cache" + cache.mkdir(mode=0o700) + common = [ + compiler, "-swift-version", "6", "-warnings-as-errors", "-sdk", sdk, + "-module-cache-path", cache, + ] + info = plistlib.loads((SOURCE / "Info.plist").read_bytes()) + if info["CFBundleIdentifier"] != BUNDLE_ID or info["LSMinimumSystemVersion"] != "14.0": + raise ValueError("Fixture identity/deployment mismatch") + + manifest = { + "schemaVersion": 1, "mode": args.mode, "bundleIdentifier": BUNDLE_ID, + "compiler": version, "sdk": sdk, "nativeAppExecuted": False, + "identitySigningPerformed": False, + "sources": { + str(path.relative_to(SOURCE)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in APP + [SOURCE / "Info.plist", SOURCE / "build.py", SOURCE / "Tests/FixtureTests.swift"] + }, + } + if args.mode == "check": + for arch in ("arm64", "x86_64"): + run(common + [ + "-target", f"{arch}-apple-macosx14.0", "-emit-object", "-whole-module-optimization", + ] + APP + ["-o", output / f"native-{arch}.o"], output) + test = output / "fixture-contract-tests" + run(common + [ + "-target", f"{platform.machine()}-apple-macosx14.0", + ] + CORE + [SOURCE / "Tests/FixtureTests.swift", "-o", test], output) + manifest["contracts"] = run([test, output / "test-data"], output) + manifest["compiledObjectArchitectures"] = ["arm64", "x86_64"] + print(manifest["contracts"]) + else: + app = output / "NotchMediaFixture.app" + executable = app / "Contents/MacOS/NotchMediaFixture" + executable.parent.mkdir(parents=True, mode=0o700) + (app / "Contents/Info.plist").write_bytes((SOURCE / "Info.plist").read_bytes()) + (output / "MediaFixtureData").mkdir(mode=0o700) + run(common + [ + "-target", f"{platform.machine()}-apple-macosx14.0", + "-O", "-Xlinker", "-no_adhoc_codesign", + ] + APP + [ + "-framework", "AppKit", "-framework", "AVFoundation", "-framework", "MediaPlayer", + "-o", executable, + ], output) + manifest.update( + app=str(app), architecture=platform.machine(), signature="unsigned", + executableSHA256=hashlib.sha256(executable.read_bytes()).hexdigest(), + ) + print(f"UNSIGNED fixture only, not launched: {app}") + (output / "build.json").write_text(json.dumps(manifest, indent=2) + "\n") + print(f"Local compile receipt: {output / 'build.json'}") + + +if __name__ == "__main__": + try: + main() + except subprocess.CalledProcessError as error: + print(error.stdout or "", file=sys.stderr, end="") + print(error.stderr or "", file=sys.stderr, end="") + print(f"Fixture command failed, status {error.returncode}; retain owned output.", file=sys.stderr) + sys.exit(1) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + print(f"Fixture check/build failed: {error}; retain owned output.", file=sys.stderr) + sys.exit(1) diff --git a/experiments/tart-regression/OracleContractTests.swift b/experiments/tart-regression/OracleContractTests.swift index 17b80c7202..db3a085090 100644 --- a/experiments/tart-regression/OracleContractTests.swift +++ b/experiments/tart-regression/OracleContractTests.swift @@ -39,5 +39,395 @@ enum OracleContractTests { try check("no version row", [box("Release name", 0.3, 0.8), box("Notch Pocket", 0.75, 0.8), box("1.2.3", 0.85, 0.2)], version: false, build: false) print("About output oracle: \(count) cases passed.") + try checkAppearance() + try checkSettingsRemoval(.notifications) + try checkSettingsRemoval(.general) + try checkSettingsRemoval(.panelSwipes) + try checkSettingsRemoval(.compactMode) + try checkGeneralNativeLabelGeometry(.general) + try checkGeneralNativeLabelGeometry(.panelSwipes) + try checkGeneralNativeLabelGeometry(.compactMode) + try checkIdleMusic() + } + + private static func checkIdleMusic() throws { + typealias Observation = AboutOutputOracle.Observation + let frame = CGRect(x: 0.1, y: 0.3, width: 0.6, height: 0.1) + var count = 0 + for scenario in [IdleMusicScenario.noTarget, .unavailable] { + let text = Observation(text: scenario.message, frame: frame) + let wrong = Observation(text: "Music app could not be opened.", frame: frame) + let elsewhere = Observation(text: scenario.message, frame: frame.offsetBy(dx: 0, dy: 0.2)) + let cases: [([Observation], CGRect?, Bool)] = [ + ([text], frame, true), ([wrong], frame, false), ([elsewhere], frame, false), + ([], frame, false), ([text], nil, false), ([text], .zero, false), + ([text, text], frame, false), + ([text], CGRect(x: -0.1, y: 0.3, width: 0.6, height: 0.1), false) + ] + for (observations, region, expected) in cases { + guard IdleMusicOutputOracle.statusVisible(observations, scenario: scenario, statusFrame: region) == expected else { + throw NSError(domain: "IdleMusicOracle", code: 1, + userInfo: [NSLocalizedDescriptionKey: "\(scenario.rawValue) oracle mismatch"]) + } + count += 1 + } + } + print("Idle music output oracle: \(count) cases passed.") + } + + private static func checkSettingsRemoval(_ scenario: SettingsRemovalScenario) throws { + typealias Observation = AboutOutputOracle.Observation + let labels = scenario.retainedLabels + let absence = scenario.absenceKey + let content = CGRect(x: 0.3, y: 0, width: 0.7, height: 1) + let rendered = labels.enumerated().map { index, label in + Observation(text: label, frame: CGRect(x: 0.4, y: 0.9 - Double(index) * 0.05, width: 0.5, height: 0.03)) + } + var controls = Dictionary(uniqueKeysWithValues: labels.map { ($0, true) }) + controls[absence] = true + let labelFrames = Dictionary(uniqueKeysWithValues: rendered.map { ($0.text, $0.frame) }) + var count = 0 + func check(_ name: String, _ observations: [Observation], _ accessible: [String: Bool], passes: Bool) throws { + let result = SettingsRemovalOutputOracle.evaluate( + observations, scenario: scenario, contentFrame: content, controls: accessible, + labelFrames: labelFrames, pixelWidth: 700, windowWidthPoints: 700 + ) + guard result.count == labels.count + 1 && result.values.allSatisfy({ $0 }) == passes else { + throw NSError(domain: "\(scenario.pane)OracleContractTests", code: 1, + userInfo: [NSLocalizedDescriptionKey: "\(name): \(result)"]) + } + count += 1 + } + try check("retained controls and pixels", rendered, controls, passes: true) + if scenario == .panelSwipes { + for label in ["Change media with horizontal gestures", "Gesture sensitivity", "Normalize gesture direction"] { + try check("media configuration is not panel copy: \(label)", rendered + [ + Observation(text: label, frame: CGRect(x: 0.4, y: 0.1, width: 0.5, height: 0.03)) + ], controls, passes: true) + } + let footerSource = "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when **Open notch on hover** option is disabled" + let footer = footerSource.replacingOccurrences(of: "**", with: "") + for sourceTrue in [false, true] { + for visible in [false, true] { + var accessible = controls + accessible[absence] = scenario.removedLabelsAbsent { $0 == footer && sourceTrue } + let pixels = rendered + (visible ? [ + Observation(text: footer, frame: CGRect(x: 0.4, y: 0.1, width: 0.5, height: 0.03)) + ] : []) + let result = SettingsRemovalOutputOracle.evaluate( + pixels, scenario: scenario, contentFrame: content, controls: accessible, + labelFrames: labelFrames, pixelWidth: 700, windowWidthPoints: 700 + ) + guard accessible[absence] == !sourceTrue, + result[absence] == (!sourceTrue && !visible), + labels.allSatisfy({ result[$0] == true }) else { + throw NSError(domain: "PanelFooterOnly", code: 1, userInfo: [ + NSLocalizedDescriptionKey: "sourceTrue=\(sourceTrue), visible=\(visible): \(result)" + ]) + } + count += 1 + } + } + } + if scenario == .compactMode { + for label in ["Notch sizing", "Match real notch height", "Custom height", + "Change media with horizontal gestures", "Gesture sensitivity"] { + try check("retained sizing and media copy: \(label)", rendered + [ + Observation(text: label, frame: CGRect(x: 0.4, y: 0.1, width: 0.5, height: 0.03)) + ], controls, passes: true) + } + } + try check("empty pixels cannot prove removal", [], controls, passes: false) + try check("missing accessibility cannot prove removal", rendered, [:], passes: false) + for (index, label) in labels.enumerated() { + let others = rendered.filter { $0.text != label } + try check("missing retained pixels: \(label)", others, controls, passes: false) + let missingOutput = SettingsRemovalOutputOracle.evaluate( + others, scenario: scenario, contentFrame: content, controls: controls, + labelFrames: labelFrames, pixelWidth: 700, windowWidthPoints: 700 + ) + guard missingOutput[label] == false, missingOutput[absence] == true, + labels.filter({ $0 != label }).allSatisfy({ missingOutput[$0] == true }) else { + throw NSError(domain: "SingleMissingLabel", code: 1, + userInfo: [NSLocalizedDescriptionKey: "\(label): \(missingOutput)"]) + } + count += 1 + var missing = controls + missing[label] = false + try check("missing retained control: \(label)", rendered, missing, passes: false) + let original = rendered[index] + let words = label.split(separator: " ", maxSplits: 1).map(String.init) + if words.count == 2 { + let left = Observation(text: words[0], + frame: CGRect(x: 0.4, y: original.frame.minY, width: 0.1, height: 0.03)) + let right = Observation(text: words[1], + frame: CGRect(x: 0.51, y: original.frame.minY, width: 0.3, height: 0.03)) + try check("split same-row label: \(label)", others + [left, right], controls, passes: true) + let differentRow = Observation(text: words[1], + frame: CGRect(x: 0.51, y: 0.02, width: 0.3, height: 0.03)) + try check("different rows are not a label: \(label)", others + [left, differentRow], controls, passes: false) + } + let suffix = Observation(text: label + "x", frame: original.frame) + try check("near label: \(label)", others + [suffix], controls, passes: false) + let offscreen = Observation(text: label, frame: CGRect(x: 0.4, y: 1.1, width: 0.5, height: 0.03)) + try check("offscreen label: \(label)", others + [offscreen], controls, passes: false) + } + var old = controls + old[absence] = false + try check("old app control rejected even if OCR misses it", rendered, old, passes: false) + for text in scenario.removedLabels + scenario.forbiddenText { + let remnant = Observation(text: text, frame: CGRect(x: 0.4, y: 0.1, width: 0.5, height: 0.03)) + try check("old app pixels: \(text)", rendered + [remnant], controls, passes: false) + } + let removedWords = scenario.removedLabels[0].split(separator: " ", maxSplits: 1).map(String.init) + let splitRemoved = [ + Observation(text: removedWords[0], frame: CGRect(x: 0.4, y: 0.1, width: 0.1, height: 0.03)), + Observation(text: removedWords[1], frame: CGRect(x: 0.51, y: 0.1, width: 0.35, height: 0.03)) + ] + try check("split removed label", rendered + splitRemoved, controls, passes: false) + let sidebarOnly = rendered.map { + Observation(text: $0.text, frame: CGRect(x: 0, y: $0.frame.minY, width: 0.2, height: 0.03)) + } + try check("sidebar is not detail output", sidebarOnly, controls, passes: false) + let emptyOutput = SettingsRemovalOutputOracle.evaluate( + sidebarOnly, scenario: scenario, contentFrame: content, controls: controls, + labelFrames: labelFrames, pixelWidth: 700, windowWidthPoints: 700 + ) + guard emptyOutput[absence] == false else { + throw NSError(domain: "\(scenario.pane)EmptyViewport", code: 1) + } + count += 1 + try check("clipped remnant still rejects absence", rendered + [ + Observation(text: scenario.removedLabels[0], frame: CGRect(x: 0.4, y: 0.99, width: 0.3, height: 0.03)) + ], controls, passes: false) + for frames in [[:], [labels[0]: rendered[0].frame], + labelFrames.mapValues { $0.offsetBy(dx: 0, dy: -0.1) }, + labelFrames.mapValues { $0.offsetBy(dx: 0, dy: 1) }] { + let output = SettingsRemovalOutputOracle.evaluate( + rendered, scenario: scenario, contentFrame: content, controls: controls, + labelFrames: frames, pixelWidth: 700, windowWidthPoints: 700 + ) + guard output.values.contains(false) else { + throw NSError(domain: "\(scenario.pane)LabelGeometry", code: 1) + } + count += 1 + } + let top = controls + var bottom = Dictionary(uniqueKeysWithValues: labels.map { ($0, false) }) + bottom[absence] = true + var oldBottom = bottom + oldBottom[absence] = false + var missingTop = top + missingTop[labels[0]] = false + var splitBottom = bottom + splitBottom[labels[0]] = true + for (captures, expected) in [ + ([top, bottom], true), ([top], false), ([], false), ([top, bottom, bottom], false), + ([top, [:]], false), ([top, oldBottom], false), ([missingTop, bottom], false), + ([missingTop, splitBottom], true), + ] { + guard SettingsRemovalOutputOracle.combine(captures, scenario: scenario).values.allSatisfy({ $0 }) == expected else { + throw NSError(domain: "\(scenario.pane)CaptureCombination", code: 1) + } + count += 1 + } + print("\(scenario.rawValue) output oracle: \(count) cases passed.") + } + + private static func checkGeneralNativeLabelGeometry(_ scenario: SettingsRemovalScenario) throws { + typealias Observation = AboutOutputOracle.Observation + let content = CGRect(x: 208.0 / 700, y: 0, width: 492.0 / 700, height: 548.0 / 600) + let cases: [(String, CGRect, CGRect)] = [ + ("Launch at login", + CGRect(x: 0.34, y: 0.7316666666666667, width: 93.0 / 700, height: 16.0 / 600), + CGRect(x: 0.33428571560714287, y: 0.72666666633333343, + width: 0.13999999999999996, height: 0.026666666666666616)), + ("Remember last tab", + CGRect(x: 0.34, y: 0.5716666666666667, width: 114.0 / 700, height: 16.0 / 600), + CGRect(x: 0.33428571214285724, y: 0.56999999983333338, + width: 0.17142857142857143, height: 0.026666666666666616)), + ("Notch animation", + CGRect(x: 0.34, y: 0.27166666666666667, width: 100.0 / 700, height: 16.0 / 600), + CGRect(x: 0.3342857123928572, y: 0.2666666665416667, + width: 0.1514285714285714, height: 0.029999999999999916)), + ("Notch height on non-notch displays", + CGRect(x: 0.34, y: 0.6141666666666666, width: 217.0 / 700, height: 16.0 / 600), + CGRect(x: 0.3342857103214287, y: 0.609999999875, + width: 0.3171428571428571, height: 0.030000000000000027)) + ] + var count = 0 + for (label, frame, pixels) in cases { + func check(_ name: String, _ text: String, _ box: CGRect, expected: Bool, + present: Bool = true, frames: [String: CGRect]? = nil, width: Int = 700, + windowWidthPoints: CGFloat = 700) throws { + let output = SettingsRemovalOutputOracle.evaluate( + [Observation(text: text, frame: box)], scenario: scenario, contentFrame: content, + controls: [label: present, scenario.absenceKey: false], + labelFrames: frames ?? [label: frame], pixelWidth: width, + windowWidthPoints: windowWidthPoints + ) + guard output[label] == expected, output[scenario.absenceKey] == false, output.count == 13 else { + throw NSError(domain: "GeneralNativeLabelGeometry", code: 1, + userInfo: [NSLocalizedDescriptionKey: "\(label) \(name): \(output)"]) + } + count += 1 + } + try check("recorded 1x guest OCR and AXValue", label, pixels, expected: true) + for scale in [1, 2, 3, 4] { + let width = 700 * scale + try check("synthetic \(scale)x four-point overhang", label, pixels, expected: true, width: width) + try check("missing native label at \(scale)x", label, pixels, + expected: false, present: false, width: width) + try check("missing native frame at \(scale)x", label, pixels, + expected: false, frames: [:], width: width) + try check("missing pixels at \(scale)x", "", pixels, expected: false, width: width) + try check("near text at \(scale)x", label + "x", pixels, expected: false, width: width) + try check("wrong row at \(scale)x", label, pixels.offsetBy(dx: 0, dy: -0.05), + expected: false, width: width) + try check("wrong right-hand label at \(scale)x", label, + CGRect(x: frame.maxX + 0.006, y: pixels.minY, + width: pixels.width, height: pixels.height), expected: false, width: width) + for (extraPixels, expected) in [(0.0, true), (0.49, true), (0.51, false)] { + let leadingPoints = 4 + extraPixels / Double(scale) + try check("four-point pixel-snap boundary +\(extraPixels)px at \(scale)x", label, + CGRect(x: frame.minX - leadingPoints / 700, y: pixels.minY, + width: pixels.width, height: pixels.height), expected: expected, width: width) + } + try check("five points is outside allowance at \(scale)x", label, + CGRect(x: frame.minX - 5.0 / 700, y: pixels.minY, + width: pixels.width, height: pixels.height), expected: false, width: width) + try check("clipped label frame at \(scale)x", label, pixels, expected: false, + frames: [label: frame.offsetBy(dx: 0, dy: 1)], width: width) + try check("clipped OCR box at \(scale)x", label, + CGRect(x: content.minX - 0.001, y: pixels.minY, + width: pixels.width, height: pixels.height), expected: false, width: width) + try check("vertical allowance just inside at \(scale)x", label, + CGRect(x: pixels.minX, y: frame.maxY + 0.0049 - pixels.height / 2, + width: pixels.width, height: pixels.height), expected: true, width: width) + try check("vertical allowance just outside at \(scale)x", label, + CGRect(x: pixels.minX, y: frame.maxY + 0.0051 - pixels.height / 2, + width: pixels.width, height: pixels.height), expected: false, width: width) + } + for width in [-1, 0, 699, 2801] { + try check("invalid capture pixel width \(width)", label, pixels, expected: false, width: width) + } + for points: CGFloat in [0, -1, .nan, .infinity, -.infinity] { + try check("invalid window point width \(points)", label, pixels, + expected: false, windowWidthPoints: points) + } + } + let frame = cases[0].1 + for label in scenario.retainedLabels { + for points: CGFloat in [700, 900, 1024] { + for scale: CGFloat in [1, 1.25, 1.5, 2, 3, 4] { + let width = Int(points * scale) + for phase: CGFloat in [0, 0.25, 0.5, 0.75] { + let native = CGRect(x: 0.4 + phase / points, y: 0.5, + width: 120 / points, height: 0.03) + for leading: CGFloat in [4, 5] { + let box = native.offsetBy(dx: -leading / points, dy: 0) + for text in [label, label + "x", "x" + label] { + let output = SettingsRemovalOutputOracle.evaluate( + [Observation(text: text, frame: box)], scenario: scenario, + contentFrame: content, controls: [label: true, scenario.absenceKey: true], + labelFrames: [label: native], pixelWidth: width, windowWidthPoints: points + ) + guard output[label] == (leading == 4 && text == label) else { + throw NSError(domain: "CommonGeneralLeadingBound", code: 1, userInfo: [ + NSLocalizedDescriptionKey: + "\(label), \(points)pt, \(scale)x, phase \(phase), leading \(leading)pt, \(text): \(output)" + ]) + } + count += 1 + } + } + } + } + } + } + for leading in [3.0, 4.0] { + let output = SettingsRemovalOutputOracle.evaluate( + [Observation(text: "From all apps", + frame: frame.offsetBy(dx: -leading / 700, dy: 0))], + scenario: .notifications, contentFrame: content, + controls: ["From all apps": true, "suggestionControlAbsent": true], + labelFrames: ["From all apps": frame], pixelWidth: 700, windowWidthPoints: 700 + ) + guard output["From all apps"] == (leading == 3) else { + throw NSError(domain: "UnchangedNotificationsAlignment", code: 1) + } + count += 1 + } + print("\(scenario.rawValue) recorded 1x and synthetic DPI geometry: \(count) cases passed.") + } + + private static func checkAppearance() throws { + typealias Observation = AboutOutputOracle.Observation + let labels = AppearanceOutputOracle.retainedLabels + let content = CGRect(x: 0.3, y: 0, width: 0.7, height: 1) + let rendered = labels.enumerated().map { index, label in + Observation(text: label, frame: CGRect(x: 0.4, y: 0.9 - Double(index) * 0.1, width: 0.5, height: 0.03)) + } + var controls = Dictionary(uniqueKeysWithValues: labels.map { ($0, true) }) + controls["faceControlAbsent"] = true + controls["additionalFeaturesAbsent"] = true + var count = 0 + func check(_ name: String, _ observations: [Observation], _ accessible: [String: Bool], passes: Bool) throws { + let result = AppearanceOutputOracle.evaluate(observations, contentFrame: content, controls: accessible) + guard result.count == labels.count + 2 && result.values.allSatisfy({ $0 }) == passes else { + throw NSError(domain: "AppearanceOracleContractTests", code: 1, + userInfo: [NSLocalizedDescriptionKey: "\(name): \(result)"]) + } + count += 1 + } + try check("retained controls and pixels", rendered, controls, passes: true) + try check("empty pixels cannot prove absence", [], controls, passes: false) + try check("missing accessibility cannot prove absence", rendered, [:], passes: false) + for label in labels { + try check("missing pixel: \(label)", rendered.filter { $0.text != label }, controls, passes: false) + var missing = controls + missing[label] = false + try check("missing control: \(label)", rendered, missing, passes: false) + } + for removed in ["faceControlAbsent", "additionalFeaturesAbsent"] { + var old = controls + old[removed] = false + try check("old app exposes \(removed) even if OCR misses it", rendered, old, passes: false) + } + for removed in [AppearanceOutputOracle.faceLabel, "Additional features"] { + let extra = Observation(text: removed, frame: CGRect(x: 0.4, y: 0.1, width: 0.5, height: 0.03)) + try check("old app pixels: \(removed)", rendered + [extra], controls, passes: false) + } + let sidebarOnly = rendered.map { + Observation(text: $0.text, frame: CGRect(x: 0, y: $0.frame.minY, width: 0.2, height: 0.03)) + } + try check("sidebar text is not detail output", sidebarOnly, controls, passes: false) + for (index, label) in labels.enumerated() { + let original = rendered[index] + let words = label.split(separator: " ", maxSplits: 1).map(String.init) + let left = Observation(text: words[0], + frame: CGRect(x: 0.4, y: original.frame.minY, width: 0.1, height: 0.03)) + let right = Observation(text: words[1], + frame: CGRect(x: 0.51, y: original.frame.minY, width: 0.3, height: 0.03)) + let others = rendered.filter { $0.text != label } + try check("exact split OCR row: \(label)", others + [left, right], controls, passes: true) + let differentRow = Observation(text: words[1], + frame: CGRect(x: 0.51, y: 0.02, width: 0.3, height: 0.03)) + try check("fragments on different rows: \(label)", others + [left, differentRow], controls, passes: false) + let suffix = Observation(text: label + "x", frame: original.frame) + try check("near-match is not exact label: \(label)", others + [suffix], controls, passes: false) + let offscreen = Observation(text: label, frame: CGRect(x: 0.4, y: 1.1, width: 0.5, height: 0.03)) + try check("offscreen text is not visible output: \(label)", others + [offscreen], controls, passes: false) + } + let splitSection = [ + Observation(text: "Additional", frame: CGRect(x: 0.4, y: 0.1, width: 0.15, height: 0.03)), + Observation(text: "features", frame: CGRect(x: 0.56, y: 0.1, width: 0.15, height: 0.03)) + ] + try check("split removed header is still detected", rendered + splitSection, controls, passes: false) + var missingControls = controls + missingControls["Colored spectrogram"] = false + missingControls["Slider color"] = false + try check("former prerequisite controls are output failures", rendered, missingControls, passes: false) + print("Appearance output oracle: \(count) cases passed.") } } diff --git a/experiments/tart-regression/README.md b/experiments/tart-regression/README.md index 7acaa37aa3..e47403097b 100644 --- a/experiments/tart-regression/README.md +++ b/experiments/tart-regression/README.md @@ -1,7 +1,7 @@ # Source-only installed-app probe This is the initial **registered installed-app regression suite**, built from the -XCTest/Vision Tart experiment. It currently covers one application journey and +XCTest/Vision Tart experiment. It currently covers eight application journeys and five explicit oracle/restoration controls, not the whole app. See the [VM reconstruction recipe](../../docs/agents/vm-regression.md) first. @@ -55,6 +55,48 @@ PY Candidate selection, provenance and a before/after code-signature check remain the operator's responsibility. A valid signature is not a notarization claim. +For the Appearance old/new comparison, the independent report must record both +executable hashes and source/build provenance separately; both apps can be +0.1.0 (272). The available old artifact is the PR97 preview from `4fff039`, not a +build of the removal branch's base. See the scenario's exact pins and report +requirements; the minimal launcher manifest alone is insufficient provenance. +The Notifications removal instead uses the previous-face candidate installed +in the guest: source `2e28bd1920265ee30d8761ad03c0b420e3f2168b`, executable +`7a30c4d4939da81c165744050bc38e0a91ea699786cddd605de9c4735d6c5aa0`. +Do not substitute the host installation/PR97 preview or copy host evidence. +Run only its Notifications wrong-behavior scenario on OLD; run the full eight +cases across the existing fixtures on NEW only. See its +[scenario note](scenarios/notifications-ai-replies-removed.md). +The General haptic-removal comparison requires its own identified OLD +haptic-bearing artifact, not an inferred base build or another removal's proof. +Run only its new scenario on OLD, then all nine registered cases on NEW across +the existing fixtures; see the [General scenario](scenarios/general-haptics-removed.md). +That is the historical haptic-removal registry. The scoped +[panel-swipe removal](scenarios/general-panel-swipes-removed.md) adds a tenth case: +run its new scenario on an identified OLD panel-swipe candidate, then all **ten** +on NEW. The prior General scenario now requires **Enable media gestures** +instead of the deliberately removed **Enable gestures** panel master; its +other retained labels, haptic absence and measured OCR policy are unchanged. +Do not apply that post-rename General expectation to an older pre-rename haptic +baseline. Historical negative evidence has its own recorded harness revision +requiring **Enable gestures**; see the +[historical haptic comparison](scenarios/general-haptics-removed.md#historical-haptic-comparison-harness). + +The scoped [compact-mode removal](scenarios/general-compact-mode-removed.md) +adds an eleventh case and intentionally drops **Compact mode** from both prior +General retained-label lists. All other twelve labels and each prior removal's +absence, capture and restoration requirements remain. Run its new case on an +identified OLD compact-bearing candidate, then all **eleven** on NEW. +Full-panel open/tab/Calendar/Mirror output is separate required parent-owned +independent Tart proof, not evidence supplied by this Settings-only case. + +The [idle music launcher](scenarios/music-idle-launcher.md) adds two real +Settings-to-panel click/error/dismissal journeys: Now Playing with no target, +and Spotify genuinely unavailable. Full scope is now **thirteen** cases. +Their prepared idle guest, explicit original source, absent remembered source +and preference/focus restoration requirements are separate from Settings-only +fixtures. Compilation is not native proof; playing/pause/resume and successful +external app activation remain separate exact-candidate runtime gates. ## Exercise the installed app in the guest @@ -124,20 +166,81 @@ panes are an explicit unsupported fixture, not silently replaced. | `visual-no-reveal` | FAIL / 10; XCTest 65 | Missing revealed build text reaches the pixel oracle, not an environment-block classification | | `native-abort-after-open` | BLOCKED / 20; XCTest 65 | A real XCTest failure after opening Settings still runs teardown and reports restoration | | `native-abort-after-about` | BLOCKED / 20; XCTest 65 | A real XCTest failure after About selection still restores the fixture | +| `notifications-ai-replies-removed` | PASS / 0 on new candidate | Retained notification labels render; suggestion control is absent in Accessibility and pixels | +| `general-haptics-removed` | PASS / 0 on new candidate | Twelve retained General labels render; haptic option is absent in Accessibility and pixels | +| `general-panel-swipes-removed` | PASS / 0 on new candidate | Twelve retained labels including the media gesture master render; panel gesture controls/instructions are absent in Accessibility and both endpoint pixels | +| `general-compact-mode-removed` | PASS / 0 on new candidate | Twelve retained General labels render; Compact mode and its player-only description are absent in Accessibility and both endpoint pixels | +| `music-idle-no-target` | PASS / 0 on new candidate | Idle launcher click renders no-target feedback, preserves focus, dismisses and restores source/UI | +| `music-idle-unavailable` | PASS / 0 on new candidate | Real missing-Spotify lookup renders unavailable feedback, preserves focus, dismisses and restores source/UI | Do not convert the two negative controls into passing application tests. `runs//` holds invocation/framework/result receipts, log and `.xcresult`; `jobs/` holds the bounded launcher receipts. Missing receipts, wrong test counts, skips, unexpected outcomes or unverified restoration are non-success. Export attachments with `xcrun xcresulttool export attachments`, verify the named -public About image hash against the receipt, and inspect the pixels locally. +public image hashes against the receipt, and inspect the pixels locally. +Notifications uses `notificationsCaptureVersion: 1`; all three General removals use +`generalCaptureVersion: 1`. Each requires exactly two named +top/bottom captures rather than `screenshotSHA256`; the suite's `captures` report +field binds both native attachment names/hashes/dimensions. Other cases retain +their single `capture` contract. Retained automatic system attachments are disabled. ## Limits -- The example expects an English About UI and the repository's versioned panel +- The examples expect an English Settings UI and the repository's versioned panel and Settings markers, with one guest display and a visible Settings gear. -- It covers only this journey. New features need their own independent scenarios. +- It covers About version/build, + [Appearance idle-face removal](scenarios/appearance-idle-face-removed.md) and + [Notifications AI-reply removal](scenarios/notifications-ai-replies-removed.md) and + [General haptic removal](scenarios/general-haptics-removed.md) and + [General panel-swipe removal](scenarios/general-panel-swipes-removed.md) and + [General compact-mode removal](scenarios/general-compact-mode-removed.md), not + all retained features. New features need their own independent scenarios. +- Appearance uses typed static-text value lookup, row-scoped sidebar navigation, + and structural form mapping. Its single screenshot requires positive full-form + fit at both scroll endpoints, plus the same AXLabel/static-text header class + for General/Media and the removed section. Missing retained controls are + output failures after pane setup, never setup guards. OCR shares About's + same-row fragment geometry; this does not authorize offscreen absence claims. +- Notifications and General share a bounded capture helper with four fixed + scenario descriptors, not an arbitrary UI service. They use row-scoped + navigation, typed static-text value lookup and + structural form mapping at the existing 1440x900 display. Two actual endpoint + captures cover the scrollable form: stable repeated endpoint geometry, no + clipped content before the top/after the bottom, uniform translation and at + least 64 points of overlap. Incomplete coverage is BLOCKED, not absence proof. + Disabled retained labels need presence, visible geometry and aligned OCR, not + `isHittable`. No preferences or window/display dimensions change. Both captures + carry exact run/candidate/PID/native-window/pane identity; retained labels + combine with OR, removed-control absence with AND. Existing restoration is + unchanged; General additionally records and verifies a pre-existing General + form's scroll position through teardown, including failed assertions. + General's Launch at login and Remember last tab were empirically confirmed as + static-text AXValue, not checkbox titles. Retained compact-candidate images + also measure the same four-native-point leading Vision-box overhang for Notch + animation and Notch height on non-notch displays: four pixels in the recorded + 700x600-point, 700x600-pixel (1x) window. All twelve General labels share that + four-point calibration. The oracle uses actual `pixelWidth / windowFrame.width` + to round the displacement and four-point limit to pixels, not a universal + four-pixel cap or a per-label whitelist. Synthetic 1x/2x/3x/4x and fractional-scale + tests establish unit consistency, not additional native/Retina runtime evidence. + Five-point offsets fail at every tested scale. Native frames, exact label-token/same-row text, + vertical/right-edge alignment, viewport containment and Notifications policy + remain unchanged. See the [offline diagnosis and boundary evidence](scenarios/general-compact-mode-removed.md#fresh-remediation-25-offline-general-alignment-2026-10-02). + Historical failed receipts remain immutable. Offline replay is not a new + native result, an independent verification pass or integrity-block clearance. + The prior General master-label expectation deliberately follows the scoped + panel-swipe removal. Compact mode's separate owner-selected deletion removes + only that positive expectation; the other twelve labels remain. + Conditional media configuration and live horizontal gestures have source + contracts, not native interaction proof from this Settings-only scenario. + Removed panel instructions are queried as rendered static text, without + Markdown emphasis markers; footer-only AX/OCR matching is unit-covered. + The media pulse cleanup has an unconditional-reset source contract, not + executed gesture/timer proof. After remediation 1/5, old-source candidate + `03f9` is stale; fresh full validation and native evidence require a rebuilt + candidate and current harness. - Readiness and cleanup are checked, but this remains prototype code, not a hardened multi-user execution service or an authorization boundary. - User-controlled OS consent, guest idle lock, hardware and application readiness @@ -197,5 +300,33 @@ python3 -B -m unittest discover -s scripts/tests -p 'test_regression_probe.py' bash experiments/tart-regression/test-oracle.sh "$PWD/.local/vm-regression/work/oracle-contract" ``` -Run these commands from the repository root. Hosted CI runs these deterministic -checks only; it does not launch a VM or establish native UI evidence. +Run these commands from the repository root. Hosted CI runs deterministic checks +only; it does not launch a VM or establish native UI evidence. + +### Public media fixture checks + +The [test-only public-API media fixture](MediaFixture/README.md) is separate from +the thirteen registered scenarios. After the helper and pixel-oracle gates, +`notch_control.yml` runs these additional checks on **macos-26**, for every +`pocket` push and pull request, without path filters: + +```bash +mkdir -p "$PWD/.build" +python3 -B experiments/tart-regression/MediaFixture/build.py check --output "$PWD/.build/mediafixture-ci" +python3 -B -m unittest discover -s experiments/tart-regression/MediaFixture/Tests -p 'test_build.py' +``` + +Run from the repository root with the fixture sources present. `.build` must +exist before Python recipe discovery; the check output must be a **new immediate +child** of it (choose another name for a local rerun, never overwrite retained +evidence). Check mode compiles arm64/x86_64 objects and runs only Foundation/ +Darwin state, generated-WAV bytes and owned-storage contracts. Python recipe +tests mock native tools. Neither check signs, installs or launches a player, +executes AppKit/MediaPlayer or plays audio; no UI, VM or credentials are used. +For this fixture, the Ubuntu workflow checks only workflow structure; no native +fixture code runs there. + +These gates preserve fixture source/build correctness, not actual OS Now Playing +delivery, successful Notch activation or **Spotify account/playback proof**. +The [idle launcher scenario](scenarios/music-idle-launcher.md) and fixture guide +retain the separate exact-candidate independent guest proof requirements. diff --git a/experiments/tart-regression/capture_contract.py b/experiments/tart-regression/capture_contract.py new file mode 100644 index 0000000000..f6b44d25f8 --- /dev/null +++ b/experiments/tart-regression/capture_contract.py @@ -0,0 +1,178 @@ +"""Fixed scrollable Settings removal cases; legacy single captures stay unchanged.""" + +import math +import re +import uuid + + +GENERAL_LABELS = { + "Show menu bar icon", "Launch at login", "Language", "Show on all displays", + "Preferred display", "Automatically switch displays", + "Notch height on notch displays", "Notch height on non-notch displays", + "Open notch on hover", "Remember last tab", "Notch animation", "Enable media gestures", +} +SCENARIOS = { + "notifications-ai-replies-removed": { + "pane": "Notifications", "test": "testInstalledNotificationsWithoutAIReplies", + "labels": {"Show notifications in the notch", "From all apps"}, "absence": "suggestionControlAbsent", + }, + "general-haptics-removed": { + "pane": "General", "test": "testInstalledGeneralWithoutHaptics", + "labels": GENERAL_LABELS, "absence": "hapticControlAbsent", + }, + "general-panel-swipes-removed": { + "pane": "General", "test": "testInstalledGeneralWithoutPanelSwipes", + "labels": GENERAL_LABELS, "absence": "panelGestureControlsAbsent", + }, + "general-compact-mode-removed": { + "pane": "General", "test": "testInstalledGeneralWithoutCompactMode", + "labels": GENERAL_LABELS, "absence": "compactModeControlAbsent", + }, +} +VERSION_KEYS = {"notificationsCaptureVersion", "generalCaptureVersion"} +FIELDS = { + "role", "name", "sha256", "runID", "scenario", "testIdentifier", "candidateSHA256", + "candidatePID", "appPath", "windowID", "windowMarker", "pane", "windowFrame", "formFrame", + "contentFrames", "endpointFrames", "contentTypes", "labelFrames", "observedPublicText", + "pixelWidth", "pixelHeight", +} +IDLE_MUSIC_SCENARIOS = { + "music-idle-no-target": ("Now Playing", "testInstalledIdleMusicWithoutTarget"), + "music-idle-unavailable": ("Spotify", "testInstalledIdleMusicUnavailableTarget"), +} +IDLE_MUSIC_ASSERTIONS = { + "selectedSourceVerified", "idleLauncherVisible", "transportAbsent", "headerPreserved", + "launchStatusVisible", "noFocusChangeOnFailedLaunch", "statusPixels", "statusDismissed", "launcherRestored", +} + + +def idle_music_assertions(receipt): + source, test = IDLE_MUSIC_SCENARIOS[receipt["scenario"]] + observed = booleans(receipt.get("observedPublicText"), IDLE_MUSIC_ASSERTIONS) + discovery = receipt.get("discovery") + require(isinstance(discovery, dict) + and discovery.get("musicSource") == source + and all(discovery.get(key) is True for key in + ["musicSourceRestored", "musicPreferencesRestored", "musicPanelRestored"])) + for key in ["musicWindowID", "musicCandidatePID"]: + require(type(discovery.get(key)) is int and discovery[key] > 0) + require(discovery.get("musicWindowMarker") + == f'com.jdylanmc.notchpocket.notch.v1.window.{discovery["musicWindowID"]}') + require(discovery.get("musicCaptureRunID") == receipt.get("runID") + and isinstance(receipt.get("runID"), str) + and str(uuid.UUID(receipt["runID"])) == receipt["runID"] + and receipt.get("testIdentifier") == "GuestRegressionProbe/GuestRegressionProbe/" + test) + passes = all(observed.values()) + require(receipt.get("verdict") == ("PASS" if passes else "FAIL") + and receipt.get("reason") == ("rendered_output_verified" if passes else "rendered_output_mismatch")) + + +def require(condition): + if not condition: + raise ValueError("Settings capture/scroll evidence is incomplete or inconsistent") + + +def number(value): + return type(value) in (int, float) and math.isfinite(value) and abs(value) < 1_000_000 + + +def rectangle(value): + require(isinstance(value, dict) and set(value) == {"x", "y", "width", "height"}) + require(all(number(n) for n in value.values()) and value["width"] > 0 and value["height"] > 0) + return value + + +def contains(outer, inner): + return (outer["x"] <= inner["x"] and outer["y"] <= inner["y"] + and inner["x"] + inner["width"] <= outer["x"] + outer["width"] + and inner["y"] + inner["height"] <= outer["y"] + outer["height"]) + + +def booleans(value, assertions): + require(isinstance(value, dict) and set(value) == assertions + and all(type(item) is bool for item in value.values())) + return value + + +def settings_captures(receipt): + scenario = receipt.get("scenario") + require(scenario in SCENARIOS) + descriptor = SCENARIOS[scenario] + pane, labels, absence = descriptor["pane"], descriptor["labels"], descriptor["absence"] + prefix = pane.lower() + test = "GuestRegressionProbe/GuestRegressionProbe/" + descriptor["test"] + version_key = prefix + "CaptureVersion" + assertions = labels | {absence} + require(type(receipt.get(version_key)) is int and receipt[version_key] == 1 + and VERSION_KEYS.intersection(receipt) == {version_key} and "screenshotSHA256" not in receipt) + captures = receipt.get("captures") + require(isinstance(captures, list) and len(captures) == 2) + run_id = receipt.get("runID") + require(isinstance(run_id, str)) + require(str(uuid.UUID(run_id)) == run_id) + require(receipt.get("testIdentifier") == test) + for role, capture in zip(["top", "bottom"], captures): + require(isinstance(capture, dict) and set(capture) == FIELDS) + require(capture["role"] == role and capture["runID"] == run_id + and capture["name"] == f"guest-public-{prefix}-{run_id}-{role}" + and capture["scenario"] == scenario and capture["testIdentifier"] == test + and capture["candidateSHA256"] == receipt.get("expectedCandidateSHA256") + and capture["appPath"] == "/Applications/notch-pocket.app" + and capture["windowMarker"] == "NotchPocketSettingsWindow" and capture["pane"] == pane) + require(isinstance(capture["sha256"], str) and re.fullmatch(r"[a-f0-9]{64}", capture["sha256"])) + for key in ["candidatePID", "windowID", "pixelWidth", "pixelHeight"]: + require(type(capture[key]) is int and capture[key] > 0) + window, form = rectangle(capture["windowFrame"]), rectangle(capture["formFrame"]) + require(window["width"] >= 700 and window["height"] >= 600 and contains(window, form)) + scale = capture["pixelWidth"] / window["width"] + require(1 <= scale <= 4 and capture["pixelHeight"] / window["height"] == scale) + frames, types = capture["contentFrames"], capture["contentTypes"] + require(isinstance(frames, list) and 1 <= len(frames) <= 100 + and isinstance(types, list) and len(types) == len(frames) + and all(type(item) is int and item > 0 for item in types) + and capture["endpointFrames"] == frames) + for frame in frames: + rectangle(frame) + require(frame["x"] >= form["x"] and frame["x"] + frame["width"] <= form["x"] + form["width"]) + require(frame["y"] >= form["y"] if role == "top" + else frame["y"] + frame["height"] <= form["y"] + form["height"]) + observed = booleans(capture["observedPublicText"], assertions) + label_frames = capture["labelFrames"] + require(isinstance(label_frames, dict) and set(label_frames).issubset(labels)) + normalized = {"x": (form["x"] - window["x"]) / window["width"], + "y": (window["y"] + window["height"] - form["y"] - form["height"]) / window["height"], + "width": form["width"] / window["width"], "height": form["height"] / window["height"]} + for frame in label_frames.values(): + require(contains(normalized, rectangle(frame))) + require(all(not observed[label] or label in label_frames for label in labels)) + top, bottom = captures + for key in ["candidatePID", "windowID", "windowFrame", "formFrame", "contentTypes", "pixelWidth", "pixelHeight"]: + require(top[key] == bottom[key]) + offset = top["contentFrames"][0]["y"] - bottom["contentFrames"][0]["y"] + overlap = top["formFrame"]["height"] - offset + require(offset >= 0 and overlap >= 64) + for head, tail in zip(top["contentFrames"], bottom["contentFrames"]): + require(dict(head, y=head["y"] - offset) == tail) + require(offset == 0 or top["sha256"] != bottom["sha256"]) + discovery = receipt.get("discovery") + require(isinstance(discovery, dict)) + require(all(discovery.get(key) is True for key in [ + prefix + "PaneSelected", prefix + "FormMapped", prefix + "ScrollComplete", + ])) + require(number(discovery.get(prefix + "ScrollOffsetPoints")) + and number(discovery.get(prefix + "OverlapPoints")) + and discovery[prefix + "ScrollOffsetPoints"] == offset + and discovery[prefix + "OverlapPoints"] == overlap) + if pane == "General": + require(discovery.get("generalNavigationObserved") is True + and receipt.get("originalPane") in {"closed", "General", "About"}) + if receipt["originalPane"] == "General": + require(discovery.get("generalScrollRestored") is True) + combined = {label: any(c["observedPublicText"][label] for c in captures) for label in labels} + combined[absence] = all(c["observedPublicText"][absence] for c in captures) + require(booleans(receipt.get("observedPublicText"), assertions) == combined) + require(receipt.get("verdict") in {"PASS", "FAIL"} + and (receipt["verdict"] == "PASS") == all(combined.values()) + and receipt.get("reason") == ("rendered_output_verified" if all(combined.values()) + else "rendered_output_mismatch")) + return captures diff --git a/experiments/tart-regression/run-suite.py b/experiments/tart-regression/run-suite.py index 2f267dcd6a..8fc1c3418a 100644 --- a/experiments/tart-regression/run-suite.py +++ b/experiments/tart-regression/run-suite.py @@ -8,11 +8,15 @@ from pathlib import Path import re import subprocess +import struct import sys import time import uuid ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +from capture_contract import settings_captures, SCENARIOS, VERSION_KEYS, idle_music_assertions, IDLE_MUSIC_SCENARIOS + ID = re.compile(r"[a-z][a-z0-9-]{0,63}") TEST = re.compile(r"GuestRegressionProbe/[A-Za-z_][A-Za-z0-9_]*/test[A-Za-z0-9_]+") EXITS = {"PASS": 0, "FAIL": 10, "BLOCKED": 20} @@ -83,11 +87,41 @@ def evaluate(case, receipt, framework, command_exit, candidate_hash): return "BLOCKED", "raw_framework_mismatch" if receipt.get("xcodeExit") != (0 if raw == "PASS" else 65): return "BLOCKED", "raw_xctest_exit_mismatch" - if raw in {"PASS", "FAIL"} and ( + scrollable = case["scenario"] in SCENARIOS + if not scrollable and ("captures" in receipt or VERSION_KEYS.intersection(receipt)): + return "BLOCKED", "unexpected_capture_schema" + if not scrollable and raw in {"PASS", "FAIL"} and ( not isinstance(receipt.get("screenshotSHA256"), str) or not re.fullmatch(r"[a-f0-9]{64}", receipt["screenshotSHA256"]) ): return "BLOCKED", "capture_identity_missing" + if case["id"] == "appearance-idle-face-removed" and raw in {"PASS", "FAIL"}: + expected = { + "Always show tabs", "Show settings icon in notch", "Colored spectrogram", + "Real-time audio waveform", "Player tinting", "Enable blur effect behind album art", + "Slider color", "faceControlAbsent", "additionalFeaturesAbsent", + } + observed = receipt.get("observedPublicText") + discovery = receipt.get("discovery") + if (not isinstance(observed, dict) or set(observed) != expected + or any(type(value) is not bool for value in observed.values()) + or (raw == "PASS") != all(observed.values()) + or not isinstance(discovery, dict) + or any(discovery.get(field) is not True for field in [ + "appearancePaneSelected", "appearanceFormMapped", "appearanceFullFormVisible", + "appearanceSectionHeaderClassVerified", + ])): + return "BLOCKED", "appearance_assertions_unverified" + if scrollable and raw in {"PASS", "FAIL"}: + try: + settings_captures(receipt) + except (ValueError, TypeError, KeyError): + return "BLOCKED", SCENARIOS[case["scenario"]]["pane"].lower() + "_assertions_unverified" + if case["scenario"] in IDLE_MUSIC_SCENARIOS and raw in {"PASS", "FAIL"}: + try: + idle_music_assertions(receipt) + except (ValueError, TypeError, KeyError): + return "BLOCKED", "music_assertions_unverified" if case["kind"] == "regression": if raw == "PASS" and receipt.get("reason") != case["expectedReason"]: return "BLOCKED", "success_assertion_not_reached" @@ -103,6 +137,46 @@ def export_capture(run, destination, receipt): "--path", str(run / "result.xcresult"), "--output-path", str(destination)], check=True, capture_output=True, timeout=30) files = [p for p in destination.iterdir() if p.is_file() and p.name != "manifest.json"] + if receipt.get("scenario") in SCENARIOS: + captures = settings_captures(receipt) + descriptor = SCENARIOS[receipt["scenario"]] + manifest = json.loads((destination / "manifest.json").read_text()) + if not isinstance(manifest, list) or len(manifest) != 1 or len(files) != len(captures): + raise ValueError("Unexpected Settings attachment count") + test = manifest[0] + if (not isinstance(test, dict) + or test.get("testIdentifier") != "GuestRegressionProbe/" + descriptor["test"] + "()"): + raise ValueError("Unexpected Settings attachment test") + attachments = test.get("attachments") + if not isinstance(attachments, list) or len(attachments) != len(captures): + raise ValueError("Missing or extra Settings attachment manifest") + results = [] + used = set() + for capture in captures: + matches = [item for item in attachments if isinstance(item, dict) + and isinstance(item.get("suggestedHumanReadableName"), str) + and item["suggestedHumanReadableName"].startswith(capture["name"] + "_")] + if len(matches) != 1: + raise ValueError("Missing or duplicate Settings capture role") + filename = matches[0].get("exportedFileName") + if not isinstance(filename, str) or Path(filename).name != filename or filename in used: + raise ValueError("Invalid or duplicate Settings capture filename") + used.add(filename) + image = destination / filename + if image not in files or image.is_symlink() or image.suffix != ".png" or image.stat().st_size > 2_000_000: + raise ValueError("Unexpected Settings capture artifact") + data = image.read_bytes() + if (hashlib.sha256(data).hexdigest() != capture["sha256"] or len(data) < 24 + or data[:16] != b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" + or struct.unpack(">II", data[16:24]) != (capture["pixelWidth"], capture["pixelHeight"])): + raise ValueError("Settings capture digest or pixel dimensions mismatch") + results.append({"role": capture["role"], "name": capture["name"], + "sha256": capture["sha256"], "path": str(image)}) + if used != {image.name for image in files}: + raise ValueError("Unbound Settings attachment") + return results + if "captures" in receipt or VERSION_KEYS.intersection(receipt): + raise ValueError("Unexpected capture schema for single-capture scenario") expected = receipt.get("screenshotSHA256") if len(files) != (1 if expected else 0): raise ValueError("Unexpected result attachment count") @@ -112,6 +186,22 @@ def export_capture(run, destination, receipt): raise ValueError("Unexpected capture artifact") if hashlib.sha256(image.read_bytes()).hexdigest() != expected: raise ValueError("Exported capture digest mismatch") + if receipt.get("scenario") in IDLE_MUSIC_SCENARIOS: + idle_music_assertions(receipt) + manifest = json.loads((destination / "manifest.json").read_text()) + test = IDLE_MUSIC_SCENARIOS[receipt["scenario"]][1] + if (not isinstance(manifest, list) or len(manifest) != 1 + or not isinstance(manifest[0], dict) + or manifest[0].get("testIdentifier") != "GuestRegressionProbe/" + test + "()"): + raise ValueError("Unexpected music capture test") + attachments = manifest[0].get("attachments") + if (not isinstance(attachments, list) or len(attachments) != 1 + or not isinstance(attachments[0], dict) + or attachments[0].get("exportedFileName") != image.name + or not isinstance(attachments[0].get("suggestedHumanReadableName"), str) + or not attachments[0].get("suggestedHumanReadableName", "").startswith( + "guest-public-music-" + receipt["runID"] + "_")): + raise ValueError("Unbound music capture attachment") return str(image) return None @@ -192,7 +282,8 @@ def run(args): rawXcodeExit=receipt.get("xcodeExit"), rawScenarioExit=result.returncode, receipt=receipt, evidenceDirectory=str(native_run), jobUnloaded=True) if status in {"PASS", "FAIL"}: - row["capture"] = export_capture(native_run, output / (case["id"] + "-captures"), receipt) + exported = export_capture(native_run, output / (case["id"] + "-captures"), receipt) + row["captures" if case["scenario"] in SCENARIOS else "capture"] = exported if case["kind"] == "regression" and status == "FAIL": report["potentialBugs"].append({ "scenario": case["id"], "candidateSHA256": candidate["executableSHA256"], diff --git a/experiments/tart-regression/scenarios/appearance-idle-face-removed.md b/experiments/tart-regression/scenarios/appearance-idle-face-removed.md new file mode 100644 index 0000000000..ab1dfcb5d6 --- /dev/null +++ b/experiments/tart-regression/scenarios/appearance-idle-face-removed.md @@ -0,0 +1,128 @@ +# Appearance without the idle face + +Issue: [#50](https://github.com/jdylanmc/notch/issues/50). +Scenario: `appearance-idle-face-removed`. +Selector: `GuestRegressionProbe/GuestRegressionProbe/testInstalledAppearanceWithoutIdleFace`. + +## Contract + +Exercise the **installed candidate**, not the app module or a Settings replica. +From General, click the actual Appearance **outline row** and verify selection. +Map the detail scroll view separately from the sidebar's outline-containing +scroll view; do not locate the form using a control under test. SwiftUI exposes +row text as static-text **AXValue**, with empty label/identifier; XCTest's typed +`staticTexts.matching(identifier:)` lookup resolves it. Section headers instead +expose **AXLabel** on that same static-text class. Verify the General and Media +headers through this exact class/label mapping before asserting Additional +features absent. Scope every sidebar click, including General restoration, to +its outline row: Appearance also has a General section header. + +Visit both native scroll endpoints and require identical, fully contained direct +content frames. This bounded full-form-fit contract proves that a single capture +covers the whole form, including the former Additional features tail; an +overflowing/moving form is unsupported, not evidence that offscreen text is absent. +Assert the old face label and section are absent from Accessibility and screenshot +text. Require all seven retained labels in both +Accessibility and the screenshot's detail region: Always show tabs, Show +settings icon in notch, Colored spectrogram, Real-time audio waveform, Player +tinting, Enable blur effect behind album art, and Slider color. + +The receipt contains those nine Boolean assertions in `observedPublicText` +and four true discovery receipts: `appearancePaneSelected`, +`appearanceFormMapped`, `appearanceFullFormVisible`, and +`appearanceSectionHeaderClassVerified`. The suite rejects incomplete or +inconsistent assertions or missing geometry/header-class proof even with an +otherwise successful XCTest receipt. OCR joins exact same-row fragments using +the About oracle's normalization/row geometry; unrelated rows and near-matching +labels are not accepted. +One `guest-public-appearance-` PNG attachment is bound by SHA-256 to the +receipt and exported/verified by the existing suite. No desktop capture. + +## Fixture, guards and restoration + +Use the existing unprivileged, logged-in, unlocked headless Tart guest, English +UI, one display, normal onboarding complete and visible notch Settings gear. +Settings must be at least 700 x 600, with the entire Appearance form visible at +both scroll endpoints. Unsupported window size or ambiguous/unavailable form +navigation blocks. **None of the seven retained controls is a setup guard.** +In particular, missing Colored spectrogram or Slider color on the proven pane +reaches screenshot/OCR and **FAIL / rendered_output_mismatch**, not BLOCKED. +Missing output never passes merely because a screenshot was taken. + +The existing candidate path, bundle ID, version/build, executable SHA-256, +running PID, guest-session, signature, run identity, single-test, screenshot +digest, exclusive-lock and restoration guards remain. The scenario does not +toggle controls, launch players, touch Shelf or edit preferences. Closed +Settings is restored to General and closed; pre-existing General/About stays +open on its original pane, including About build visibility. Other initial +panes remain unsupported. The existing LIFO teardown runs on native failure. + +## Wrong-behavior proof and limits + +An independent worker must run this **same scenario and assertions** against +the available **PR97 development preview**, built from +`4fff039f5a62249c7ac84466c5cb0c124b2c9a06`, executable SHA-256 +`32331e682ed6fb6bba460019c1a949dee39e32ce92decafda48312ef0ce3aaaf`. +It is **not** an artifact built from branch base +`547d65916aa73fefb632e0bb58f34aa4a0d835df`. Expect functional **FAIL**, +`rendered_output_mismatch`, with the old face control observed and verified +restoration. Then run the exact new candidate: expect **PASS**, +`rendered_output_verified`. A blocked old-app run is not negative proof. +Keep both reports and images; do not register the old behavior as an expected +failure of the new candidate or replace any of the five existing controls. +Both candidates may report **0.1.0 (272)**; version/build equality is not identity +or source provenance. The independent comparison report **must** record each +old/new executable SHA-256, exact app path, before/after signature and hash +checks, source revision and build provenance (including a diff digest if built +from uncommitted source), and the independently deployed harness source hashes. +Bind each native receipt and exported image digest to that candidate. Record +unavailable provenance as a gap, never infer it from a version or the branch base. +The minimal three-field launcher manifest does not replace this report requirement. +The worker also runs the full seven-case registry and restores closed, +pre-existing General and pre-existing About fixtures. + +This authoring slice supplies no native signoff. Permission-free tests cover the +output oracle, receipt policy and source-removal boundary. They do not prove +pixel recognition, native scrolling, restoration, media playback or Shelf +behavior. Native old/new signoff remains independently worker-owned. Author development +diagnostics and a harness build are not independent verification. +A stored `showNotHumanFace=true` has no remaining product reader/default/observer; +the source contract guards that boundary without deleting existing user data. +A parent-approved legacy-true guest fixture can additionally verify idle-panel +behavior; this Settings scenario neither seeds that preference nor claims that +extra runtime coverage. + +## Removal trace + +Paths below are repository-relative; named symbols/sections identify the hunks. + +| Ledger | Path | Hunk | +| --- | --- | --- | +| FACE-REMOVE | `notchPocket/ContentView.swift` | Delete observer, face-only `computedChinWidth` branch, `NotchLayout` branch and `NotchPocketFaceAnimation` | +| FACE-REMOVE | `notchPocket/models/Constants.swift` | Delete `showNotHumanFace` key | +| FACE-REMOVE | `notchPocket/components/Settings/Views/AppearanceSettingsView.swift` | Delete Additional features section | +| FACE-REMOVE | `notchPocket/components/AnimatedFace.swift` | Delete entire face-only file | +| FACE-REMOVE | `notchPocket.xcodeproj/project.pbxproj` | Delete four AnimatedFace build/file/group/source references | +| FACE-REMOVE | `.swiftlint.yml` | Remove stale NotchPocketFaceAnimation identifier exclusion; retain every lint rule/severity | +| FACE-CONTRACT | `README.md` | Add Idle appearance removal/data-compatibility note | +| FACE-CONTRACT | `scripts/tests/test_regression_probe.py` | Guard source removal, stale lint cleanup, provenance, and non-prerequisite control queries | +| FACE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift` | Appearance AXValue/header AXLabel mapping, structural form identity, full-form fit, output-only controls, row-scoped navigation/restoration | +| FACE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/SettingsFixture.swift` | Scope fixture sidebar clicks to outline rows, avoiding Appearance's General header | +| FACE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/AboutOutputOracle.swift` | Extract unchanged row geometry for Appearance fragment reuse | +| FACE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/AppearanceOutputOracle.swift` | Retained/removed output assertions with exact same-row OCR fragment merging | +| FACE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj` | Add oracle source membership | +| FACE-NATIVE | `experiments/tart-regression/run-suite.py` | Require complete, consistent Appearance observations and pane/form/viewport/header-class receipts | +| FACE-NATIVE | `experiments/tart-regression/suite.json` | Append `appearance-idle-face-removed`; preserve six prior entries | +| FACE-NATIVE | `experiments/tart-regression/OracleContractTests.swift` | Add positive and wrong/missing Appearance output cases; keep About cases | +| FACE-NATIVE | `experiments/tart-regression/test-oracle.sh` | Include Appearance oracle in permission-free compilation | +| FACE-NATIVE | `scripts/tests/test_regression_probe.py` | Extend registry and Appearance receipt policy contracts | +| FACE-NATIVE | `experiments/tart-regression/README.md` | Document second journey and coverage limits | +| FACE-CONTRACT | `docs/regression-coverage.md` | Record Appearance coverage and pending independent evidence | +| FACE-NATIVE | `experiments/tart-regression/scenarios/appearance-idle-face-removed.md` | New scenario contract, fixtures, negative proof and handoff | + +`AnimatedFace`, `Eye`, `Mouth` and its preview had no other callers; they used +SwiftUI shapes, not asset-catalog images. Retained media/full-panel/appearance +branches are not rewritten. `Localizable.xcstrings` is unchanged: historical +`Show cool face animation while inactive` and `Additional features` entries +remain for catalog-owner maintenance. License notices and retained headers/art +are unchanged. diff --git a/experiments/tart-regression/scenarios/general-compact-mode-removed.md b/experiments/tart-regression/scenarios/general-compact-mode-removed.md new file mode 100644 index 0000000000..526899d2d0 --- /dev/null +++ b/experiments/tart-regression/scenarios/general-compact-mode-removed.md @@ -0,0 +1,415 @@ +# General: music-only compact mode removed + +Ledger: **CMP-REMOVE / CMP-CONTRACT / CMP-NATIVE**. Initial author-only work in +`chore/remove-compact-mode`, local-stack base +`30c85008d7ef817344ccc51a742b21da7ef4bf93`. That snapshot and remediation 1/5 +against merged parent `229721a820f98d16f87aa226c334ebd0190b8ba3` are historical. +Current remediation 2/5 is uncommitted against +`cbd856a3513aa24aac96c06cbc0813fe9d14f4de`, limited to harness/contracts/docs. +The owner selected the full panel instead of the smaller music-only mode. +No gesture, lock-screen, native on-screen display, notification reply, permission, +identity, data-reset or signing changes are authorized. + +## Dependency trace and compatibility + +| Owned surface | Decision | +| --- | --- | +| `compactMode` Defaults key and General toggle/footer | Remove declaration and all readers, not the stored value. Existing `compactMode=true`, false or absent values have no effect. No migration, write, domain reset or data deletion. | +| `ContentView` opened shape/height/header and player-only branch | Always use the existing full-panel 19/24 opened corners and model height. Preserve notification precedence and its 132-point height/header suppression. Route Dashboard/Home/Shelf through the existing coordinator. | +| `compactCornerRadiusInsets` and fixed 336-point compact content width | Remove exclusively compact layout values; keep full-panel, closed-notch and per-display sizing unchanged. | +| `CompactHomeView` and private `CompactControlButton` | Remove compact-only view/state/transport/layout. No compact-specific bundled image asset exists: its artwork came from shared media state, system symbols and `appIcon`. No shared assets are deleted. | +| `AudioOutputPicker` / `MediaOutputSlotButton`, formerly in that file | Move their bodies unchanged into `MediaOutputSlotButton.swift`; replace the source/group/build-phase project reference. The full player's `.mediaOutput` slot still opens, refreshes, selects and dismisses the same picker. | +| `AudioRouteManager`, output resolver, slider options, battery scaling | Shared media functionality remains. Only obsolete comments change. Preserve transport, seeking, shuffle/repeat/favorite, lyrics, volume, output routing, artwork and small app icons. | +| Header `exposesCompactTabAccessibility`, external closed-notch spacer, compact progress bars | Unrelated to the music-only preference; retain. No name-based cleanup. | +| Calendar/Mirror/Shelf/Dashboard and keyboard controls | Preserve existing defaults, conditional rendering, tab selection, model ownership and access routes. Calendar and Mirror both default to **false**; full panel does not force them on. | +| Parent media gate | Preserve `enableHorizontalMediaGestures && enableMediaGestures` and the fallback-notice guard. The persisted master remains `"enableGestures"` with default false; no automatic re-enable. | +| Localization | Delete only `Compact mode` and its player-only footer entries (both empty locale records). Preserve every other key/locale/placeholder, including shared Output/Looking for devices text. | + +## Executable Settings scenario + +`general-compact-mode-removed` selects +`GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutCompactMode`. +This is the **eleventh** registered case. All ten previous registrations and +five oracle/restoration controls remain. The owner-selected deletion deliberately +removes only **Compact mode** from the two prior General retained-label lists. +Neither haptic nor panel-swipe absence is relaxed. + +Use the exact installed hash-bound candidate inside the existing unlocked, +English, single-display 1440x900 headless Tart fixture. Normal Settings dimensions +and preferences remain unchanged. The native selector reuses the fixed +`runInstalledSettingsOutput` / `inspectScrollableSettings` implementation: +real About then General sidebar navigation, structural form mapping, native +endpoint scrolling and two app-window screenshot/Vision assertions. + +Require these twelve retained labels in native visible geometry and aligned +pixels in at least one endpoint: + +- Show menu bar icon; Launch at login; Language; Show on all displays. +- Preferred display; Automatically switch displays. +- Notch height on notch displays; Notch height on non-notch displays. +- Open notch on hover; Remember last tab; Notch animation; Enable media gestures. + +Require **Compact mode** and its **Shows a smaller opened notch with just the +music player** footer absent in Accessibility and both endpoint pixels. +The oracle also rejects the footer's **no tabs, calendar or mirror** fragment. +Retained sizing/media copy is not forbidden. Disabled labels need presence and +aligned pixels, not `isHittable`. + +Use unchanged `generalCaptureVersion: 1`, exact run/test/scenario/candidate +hash/PID/native-window/pane binding, stable repeated endpoint geometry, no +clipped top/bottom, uniform translation and at least 64-point overlap. +Presence combines with OR; absence with AND. The measured four-leading-pixel +allowance now applies uniformly to all twelve General labels, with +unchanged native frames, vertical alignment and exact label-token/same-row text. +It compares rounded pixel edges, not an expanding normalized tolerance or a +label whitelist; see remediation 2/5 below. Wrong/missing +output after valid setup is **FAIL / rendered_output_mismatch**; incomplete +identity, coverage or restoration is **BLOCKED**, never absence proof. + +Restore the same closed/General/About fixtures, pointer, original pane/About +build visibility and exact pre-existing General scroll frames, including on +failure. Close Settings only if this scenario opened it. No preference writes, +app imports/build dependencies, OS consent, host UI or new ownership mechanism. + +## Required independent parent proof + +**Pending, not author signoff.** Identify an actual OLD compact-bearing +executable with SHA-256 and source/build provenance. Run only this new scenario +on OLD and require all twelve retained labels true and `compactModeControlAbsent` +false with complete captures and successful restoration. OLD's preference can +stay at its default: General exposes the toggle regardless of its value. +A blocked run or a missing retained label is not correct negative proof. + +Run the full **eleven-case** registry on the exact NEW signed candidate across +closed/General/About fixtures, recording candidate and test-source identities +separately. Export and verify both attachment hashes; inspect the bound +app-window pixels locally. Preserve failures and do not reuse previous proofs. + +**Full-panel output remains a separate required independent Tart proof.** +The Settings scenario does not establish panel rendering merely because it +opened the notch to reach the gear. Its current capture schema observes a +Settings form, not panel/tab/media/Calendar/camera output. Extending that schema +or adding panel-output actions is beyond this removal-state authoring slice; +the parent must supply a separately bounded executable scenario and evidence, +not count the eleven-case Settings suite as that proof: + +1. On an ordinary app-default fixture (`alwaysShowTabs=true`, Calendar/Mirror + false, Shelf true), open a freshly mapped app-owned panel through its existing + native action. Assert actual full-panel pixels and visible Home/media/header + controls, then exercise Dashboard/Home and available Shelf tabs with observed + selection **and content**, restoring the original tab/open state. No forced + tab visibility, invented available Shelf content, or model-only pass. +2. Verify default-hidden Calendar and Mirror controls, not falsely demand them + at defaults. In separately approved, recorded/restored feature-on fixtures, + assert Calendar controls and the existing Mirror button/preview conditions + (`showMirror`, camera availability and expanded state). No automated calendar + or camera grants, no app ownership changes and no personal-data captures. + Unavailable hardware/grants are a declared block, never a silent skip. +3. A test-owned legacy-true fixture must still show the full panel after launch, + leaving the stored legacy value untouched. Do not seed or reset the user's + host profile. Cover notched and external-display closed sizing on suitable + fixtures; a single virtual display cannot prove a physical cutout. +4. Preserve keyboard access, shared media behavior and the parent's two-switch + media gate. No playback/output-device action without separately approved + synthetic fixtures/effects. Notification precedence is preserved by source + contracts here, not claimed as native reply proof. + +Parent owns full app/helper/CI gates, independent review, Tart execution and +candidate signing. No VM/host UI, remote, agents, private keys, Keychain, +`local.env`, signing or commits are needed or authorized for this authoring. + +## Exact changed-path ledger + +Paths are relative to this checkout. + +| Ledger | Path | Change | +| --- | --- | --- | +| CMP-REMOVE | `notchPocket/ContentView.swift` | Remove compact routing/shape/height/header bypass; retain notification and full-panel routes. Fresh remediation fixes opened padding without changing its closed branch. | +| CMP-REMOVE | `notchPocket/models/Constants.swift` | Remove only compact preference declaration. | +| CMP-REMOVE | `notchPocket/sizing/matters.swift` | Remove compact-only opened corners. | +| CMP-REMOVE | `notchPocket/components/Settings/Views/GeneralSettingsView.swift` | Remove only compact section/footer. | +| CMP-REMOVE | `notchPocket/components/Notch/CompactHomeView.swift` | Delete compact view and private control. | +| CMP-REMOVE | `notchPocket/components/Notch/MediaOutputSlotButton.swift` | Retain shared picker/slot bodies in their own source. | +| CMP-REMOVE | `notchPocket.xcodeproj/project.pbxproj` | Replace compact source membership with retained media-output source. | +| CMP-REMOVE | `notchPocket/components/Notch/NotchHomeView.swift` | Comment-only update; shared slider and all full-player behavior unchanged. | +| CMP-REMOVE | `notchPocket/components/LiveActivities/NotchPocketBattery.swift` | Comment-only update; scaled small battery unchanged. | +| CMP-REMOVE | `notchPocket/managers/AudioRouteManager.swift` | Comment-only update; shared route manager unchanged. | +| CMP-CONTRACT | `notchPocket/Localizable.xcstrings` | Delete exactly two compact-only entries. | +| CMP-CONTRACT | `scripts/tests/test_regression_probe.py` | Source preservation, preference/default and receipt failure contracts; surgical prior compact expectation removal. Fresh remediation pins padding, shared absence semantics and twelve retained labels. | +| CMP-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift` | Add one native selector using existing fixed capture/restore. | +| CMP-NATIVE | `experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift` | Fixed compact descriptor, scoped forbidden text, twelve unchanged retained labels. | +| CMP-NATIVE | `experiments/tart-regression/capture_contract.py` | Bind new descriptor to unchanged evidence contract; remove prior compact positive label. | +| CMP-NATIVE / CMP-CONTRACT | `experiments/tart-regression/OracleContractTests.swift` | New output failures and retained-label/measured-geometry boundaries. | +| CMP-NATIVE | `experiments/tart-regression/suite.json` | Add case eleven; preserve ten previous entries. | +| CMP-CONTRACT | `experiments/tart-regression/README.md` | Current registry and evidence limits. | +| CMP-CONTRACT | `experiments/tart-regression/scenarios/general-haptics-removed.md` | Owner-directed compact expectation removal; historical evidence unchanged. | +| CMP-CONTRACT | `experiments/tart-regression/scenarios/general-panel-swipes-removed.md` | Same narrow current expectation update; mark pre-merge tables historical without changing their results. | +| CMP-CONTRACT | `docs/regression-coverage.md` | Current removal coverage and required panel proof gap. | +| CMP-CONTRACT | `docs/specs/mvp-widget-foundation.md` | Retire obsolete compact bypass expectation; preserve notification precedence. | +| CMP-CONTRACT / CMP-NATIVE | `experiments/tart-regression/scenarios/general-compact-mode-removed.md` | This trace, ledger, scenario and parent evidence contract. | + +## HISTORICAL pre-merge author validation (2026-10-02) + +These results describe the initial author snapshot before the parent panel-swipe +remediation was merged, not HEAD `229721a820f98d16f87aa226c334ebd0190b8ba3` +or the fresh remediation below. The merged parent adds four footer-only oracle +cases and uses the shared `removedLabelsAbsent` matcher. Do not reuse the old +73/462 counts or syntax-only result as current compilation evidence. + +Commands ran from this worktree. Swift/Xcode used +`DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`, with generated homes, +temporary directories and module caches under the named ignored `.build/` +directories. Python fixtures used `.build/cmp-contracts/tmp`. No app/runtime +execution, VM operation, signing, remote operation, agent or credential access. + +| Command / check | Historical result | +| --- | --- | +| `python3 -B -m unittest discover -s scripts/tests -p 'test_regression_probe.py'` | **73 passed**. Initial run caught a new test's incorrect assumed label `Show mirror`; verified existing source/catalog uses `Enable mirror`, corrected only that expectation, then reran all 73. Both logs retained. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/cmp-contracts/oracle"` | **462 synthetic cases passed**: About 11, Appearance 52, Notifications 35, haptics 92, panel swipes 100, compact removal 100, plus 24 measured-label boundaries for each of the three General descriptors. Prior General totals each drop six compact-positive cases only; their other properties remain. | +| `xcodebuild -quiet build-for-testing -project experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj -scheme GuestRegressionProbe -configuration Debug -destination 'platform=macOS,arch=arm64' -derivedDataPath "$PWD/.build/cmp-harness/DerivedData" -resultBundlePath "$PWD/.build/cmp-harness/build.xcresult" -disableAutomaticPackageResolution -skipPackageUpdates CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO` | **Succeeded**. Standalone unsigned harness compilation only; no test execution or signed candidate. | +| `xcrun swiftc -frontend -parse` on all eight changed/added product Swift files | **Passed**. Syntax only, not app build/type-check or hosted XCTest. | +| `swiftlint lint --quiet --no-cache --config .swiftlint.yml --reporter json` on those same eight files | **Exit 0**, 92 warnings, no errors. No rule suppression or unrelated baseline fixes. | +| Read-only base comparison | Ten prior registry entries identical; exactly two catalog entries removed and all 394 others unchanged, including locale records; both moved shared output-control bodies identical; three shared product edits comment-only; native capture/restore helpers identical; media handlers/conjunction preserved; 196 other tracked product paths and all 27 asset paths unchanged. | +| `plutil -lint notchPocket.xcodeproj/project.pbxproj`; `git diff --check` | **Passed**. Branch/base unchanged, nothing staged; the 23-path ledger matches the actual tracked/untracked diff. | + +Retained local evidence: `.build/cmp-contracts/{python.log,python-rerun.log,oracle.log,product-parse.log,product-lint.json,product-lint.log,preservation.json}` +and `.build/cmp-harness/{build.log,build.xcresult}`. Generated build/cache residue +under those two directories is intentionally ignored and retained for the parent. +No full app/helper/CI gates, independent review, OLD/NEW native Settings proof or +full-panel native proof ran here; all remain required parent-owned work. + +## Fresh remediation 1/5 (2026-10-02) + +Uncommitted against `229721a820f98d16f87aa226c334ebd0190b8ba3`, limited to +**CMP-REMOVE / CMP-CONTRACT**: + +- `notchPocket/ContentView.swift:199` still used the deleted `openedInsets`. + Use `cornerRadiusInsets.opened.top` for opened horizontal padding; the closed + branch remains `cornerRadiusInsets.closed.bottom`. The source contract rejects + any `openedInsets` remnant and pins both padding branches. +- The compact native source contract expected the pre-merge inline predicate. + It now requires `scenario.removedLabelsAbsent { form.staticTexts[$0].exists }` + and pins the shared helper's `removedLabels.allSatisfy { !isPresent($0) }` + semantics. All twelve retained labels are pinned; earlier scenario assertions, + the four footer-only cases, capture/restore code and oracle implementation + remain unchanged. +- This table and the panel-swipe author tables distinguish historical pre-merge + evidence from fresh current-source results. No product feature scope changed. + +Before this fix, both retained canonical `scripts/build.sh` attempts exited +**65** with `ContentView.swift:199:50: error: cannot find 'openedInsets' in scope`. +Their evidence is in session files +`overnight-retention-20261001/compact-local-validation/`, including +`01-app-build.full.log`, `01b-app-build-retry.full.log` and `report.json`. +**No successful old artifact was produced by those failed builds.** No OLD +candidate identity or native negative proof can be inferred from build residue. +The stale Python expectation is confirmed by source comparison; no pre-fix +Python run is claimed for this remediation. + +### Fresh current-source results + +Commands ran from this worktree after both fixes, with no pre-fix rerun. +Swift/Xcode used `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`; +the canonical app build used Debug, scheme `notchPocket`, `platform=macOS`. +`SIGN_IDENTITY` was unset and `local.env` was absent (existence check only). +Build scripts/project signing settings were unchanged; Xcode's normal local +ad-hoc build is not separately prepared candidate signing or distribution proof. + +| Command / check | Fresh result | +| --- | --- | +| `python3 -B -m unittest discover -v -s scripts/tests -p 'test_regression_probe.py'` | **74 passed**, no failures, errors or skips. All 74 existing test methods remain; only the two coupled compact contracts changed, and the other 72 are identical to HEAD. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/cmp-fresh-remediation1-5/oracle"` | **466 synthetic cases passed**: About 11, Appearance 52, Notifications 35, haptics 92, panel swipes 104, compact removal 100, plus 24 measured-label boundaries for each of the three General descriptors. The four merged footer-only cases explain 466 versus historical 462. | +| `scripts/build.sh` | **Exit 0, BUILD SUCCEEDED**, 2026-10-02 07:43:37-07:43:56 UTC. Actual `SwiftCompile normal arm64` for this worktree's `notchPocket/ContentView.swift`, module emission and newly linked executable verified from the fresh build activity log and output timestamps. Compiler name resolution, not a parse proxy. | +| Read-only preservation / `git diff --check` | Passed. Oracle cases/implementation, native capture/restore, capture contract and eleven-case registry are byte-identical to HEAD. Twelve retained labels remain required. Python temporary fixtures were cleaned. | + +Evidence is retained in ignored `.build/cmp-fresh-remediation1-5/`: +`python.log`, `oracle.log`, `build.{json,stdout.log,stderr.log}`, +`app-build.xcactivitylog`, `compiler-trace.txt`, `compiler-evidence.json`, +`preservation.json`, `source.patch` and `source-before.sha256`. +The compiler evidence records exact source/object/product paths and hashes. +The generated Debug app was not installed or launched. This fresh build is not +an OLD compact-bearing artifact or an independently signed native candidate. + +Only the two source/test files and two scenario documents changed. No VM, +host UI, separate signing, remote, commit, agent, Keychain or `local.env` +operations occurred. No application XCTest, helper, lint, full CI or native +Settings/panel gates ran; those remain parent-owned. + +## Fresh remediation 2/5: offline General alignment (2026-10-02) + +**CMP-NATIVE / CMP-CONTRACT only.** App source/build identity remains +`cbd856a3513aa24aac96c06cbc0813fe9d14f4de`, tree +`ea9c7194fe2d42c06ddef91bc62bca0b49a46b4c`, executable SHA-256 +`97f172349c106d6425b36bd4a783b35ac77cf6beac55b3add63a8537ac75583e`. +The changed oracle is uncommitted test source, not a rebuilt app candidate. +The initial remediation-2/5 oracle's SHA-256, before the point-unit follow-up, was +`f8e218f263cac73981a781ddd6b57983887e830303f426629385c29043f16f8a`; +its historical test-source manifest is in `source-identity.json` below. + +### Immutable independent failure + +The primary checkout's +`.local/vm-regression/evidence/compact-new-independent-cbd856a/report.json` +has SHA-256 +`91ca8bf95bed747af04faf4c5d79302896086f964c144c6e75c83f27324d8038`. +Its complete eleven-case registry across closed/General/About ran **33 cases**: +raw **9 PASS / 15 FAIL / 9 BLOCKED**, interpreted **24 PASS / 9 FAIL**. +All nine General cases have eleven retained labels true, only **Notch animation** +false, and their respective absence assertion true. The three compact cases +all have `compactModeControlAbsent=true`. No case was skipped or retried. + +**All prior failed receipts are immutable**, including this report, its raw +receipts, images and framework counts, the prior OLD/NEW comparison evidence, +the haptic diagnosis and remediation-1 failed builds. Do not overwrite, relabel +or substitute an offline output for any of them. The original native suite +remains **FAIL**, overall report **BLOCKED**. + +### Measured cause, before editing the oracle + +Read all nine original General receipts and eighteen original, hash-bound +700x600 PNGs (four distinct PNG hashes). The capture index bindings exactly +match each receipt, including candidate/run/test/window/PID/pane/frame identity. +Offline Vision used the native request settings: accurate, `en-US`, language +correction disabled, revision 3; host macOS 26.7 (25G229). Its existing-oracle +output reproduced **all eighteen per-capture dictionaries exactly**, not just +the combined failure. All four distinct original images were also viewed. +The host Vision result is replay evidence, not a guest rerun. + +| Bottom label, all nine cases | Native normalized frame `(x, y, width, height)` | Vision normalized box `(x, y, width, height)` | Exact Vision row | +| --- | --- | --- | --- | +| Notch animation | `(0.34, 0.27166666666666667, 0.14285714285714285, 0.02666666666666667)` | `(0.3342857123928572, 0.2666666665416667, 0.1514285714285714, 0.029999999999999916)` | `Notch animation` | +| Notch height on non-notch displays | `(0.34, 0.6141666666666666, 0.31, 0.02666666666666667)` | `(0.3342857103214287, 0.609999999875, 0.3171428571428571, 0.030000000000000027)` | `Notch height on non-notch displays Match menu bar height` | + +The recorded window is **700x600 native points and 700x600 pixels: 1x**, not +2x runtime evidence. Both OCR anchors start at **x=234 pixels** versus native +**x=238 points (238 pixels at 1x)**; raw +displacements are 4.000001325 and 4.000002775 pixels, respectively. Both vertical +midpoints align and both boxes and native frames fit fully inside the viewport. +The animation label is one correctly recognized observation/row, not a +misrecognized word or split-row failure. The sizing label is also recognized +exactly; its row contains the legitimate right-column value. This establishes +**leading OCR-box overhang relative to native label geometry**, not missing +product text or a claim about the glyphs' exact ink bounds. + +The ordinary normalized `0.005` left allowance covered only **3.5 pixels** at +700 pixels wide. Neither label was in the earlier Launch at login/Remember last +tab four-pixel whitelist. The sizing label's identical bottom failure had been +masked by its passing top endpoint; animation exists only at the bottom. +This additional measured label rules out a Notch-animation-specific workaround. + +### Changed bounds and adversarial contracts + +`SettingsRemovalOutputOracle.swift` removes the two-string map. The initial +remediation used a universal four-pixel limit, which incorrectly rejected the +same four-point overhang at higher capture scales. The point-unit follow-up +corrects that bound for every General retained label whose OCR anchor starts +left of its native frame: **four native points, snapped to capture pixels**. +The standalone harness's single production call passes `windowFrame.width` +alongside `image.width`. The oracle derives `pixelsPerPoint = pixelWidth / +windowWidthPoints`, requiring finite positive dimensions and the existing +capture contract's 1...4 ratio. It compares the rounded displacement in pixels +to rounded `4 * pixelsPerPoint`; rounding distances rather than absolute edges +avoids dependence on fractional native-edge phase. No hardcoded window width, +per-label whitelist or new receipt field/attestation is used. Existing immutable +capture receipts already bind window frame and image dimensions. + +That test runs before the ordinary normalized alignment fallback, so neither +a larger window nor a denser image silently changes the native-point allowance. +At 1x/2x/3x/4x, four points correspond to 4/8/12/16 pixels. Tests accept another +0.49 pixel and reject another 0.51 pixel at those integer scales; exact four +points pass and exact five points fail, including fractional-scale fixtures. +This is bounded pixel quantization of a four-point calibration, not a larger +arbitrary float tolerance or a claim that higher-scale native OCR was measured. + +Native frames/unique static-text presence, full viewport containment, vertical +`0.005` tolerance, ordinary right-edge alignment, exact label-token matching and +same-row fragment assembly remain unchanged. A space-delimited right-column +value can still follow a label; a suffixed character cannot impersonate it. +Notifications, About, Appearance, forbidden-copy matching, two-endpoint +OR-presence/AND-absence and capture/restoration schema are unchanged. + +Contracts include the exact 1x animation and sizing measurements above, the two +earlier measured labels, synthetic 4/5-point and pixel-rounding boundaries, +wrong rows/right-hand positions, vertical just-inside/outside bounds, clipped +pixels/native frames and missing text/control/frame/dimensions at 1x/2x/3x/4x. +All twelve General labels additionally cover 700/900/1024-point windows at +1x/1.25x/1.5x/2x/3x/4x with fractional native-edge positions and exact/prefixed/ +suffixed text. Existing split-row, old-control and footer-only controls remain. +Each single missing retained label leaves other labels/absence true but fails +output; Python verifies all **144** General scenario/label/integer-scale +omissions stay **FAIL / rendered_output_mismatch**, not BLOCKED or PASS. +Falsely claiming the missing label passed remains BLOCKED. Synthetic receipt +fixtures also check existing window/pixel bindings at supported and rejected +scales, without changing the capture schema. All eleven registrations, five +controls and twelve General names are unchanged. + +### Actual offline results and remaining gates + +The initial remediation-2/5 outputs, **before the point-unit follow-up**, are task-owned under +`.build/cmp-fresh-remediation2-5/`; original evidence is read-only. Swift/Xcode +used `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`, with home, +temporary files and module caches beneath that output directory. + +| Command / evidence | Actual result | +| --- | --- | +| `python3 -B -m unittest discover -v -s scripts/tests -p 'test_regression*.py'` | **74 tests passed**, no failures/errors/skips; includes all 36 single-label omission subcases. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/cmp-fresh-remediation2-5/oracle-final"` | **1,302 cases passed**: About 11, Appearance 52, Notifications 37, haptics 104, panel swipes 116, compact removal 112, plus 290 geometry cases for each General descriptor. | +| `xcodebuild -quiet build-for-testing -project experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj -scheme GuestRegressionProbe -configuration Debug -destination 'platform=macOS,arch=arm64' -derivedDataPath "$PWD/.build/cmp-fresh-remediation2-5/DerivedData" -resultBundlePath "$PWD/.build/cmp-fresh-remediation2-5/build.xcresult" -disableAutomaticPackageResolution -skipPackageUpdates CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO` | **Exit 0**, standalone unsigned harness compiled. No XCTest execution, app build, signing or launch. | +| Before/after offline Vision + oracle on the same eighteen original PNGs | **9/9 combined General outputs now contain all twelve retained labels plus absence true**. Exactly eighteen endpoint booleans change: animation in nine bottoms and non-notch sizing in nine bottoms. All recognized observations and every other result remain identical. This is not a new 33-case native PASS. | +| Read-only preservation | All **33** original receipts and **36** PNG hashes match; **29** replay input hashes unchanged. All **245** tracked product/resource/project paths match HEAD. Current host app's **141** inventory entries match the retained host/guest before/after inventories, including bytes, modes and symlinks; all **13** architecture signature records match. No fresh signing-tool invocation or metadata exception. | + +The first expanded oracle run caught a test-fixture error: a fixed `+0.3` +horizontal displacement still lay inside the wider sizing-label native frame. +The negative fixture now starts beyond that frame's actual right edge; the +oracle's right bound was not loosened. Its failed log is retained as +`oracle.log`; the passing run is `oracle-final.log`. Other retained outputs: +`Replay.swift`, `replay-{before,after}{,.json,.log}`, `python{,-final}.log`, +`build.log`, `build.xcresult`, `preservation.json` and `source-identity.json`. +This source-only change touches the oracle, Swift/Python contracts, this +scenario, the historical haptic clarification and the experiment README. + +**Fresh independent NEW verification with the changed harness is still pending.** +This author-only replay neither verifies full-panel output nor completes any +other missing native coverage or OLD qualification. The separate NEW root +`com.apple.macl` addition (**72 zero bytes**) and root ctime change remain +**BLOCKED, unwaived and untouched**, with cause not established. Prior integrity +blocks remain unchanged. No VM, host UI, remote, agent, credential, Keychain, +product/signing change or commit occurred. No merge clearance is claimed. + +### Point-unit follow-up validation (2026-10-02) + +The preceding four-point rule corrects the initial uncommitted remediation's +pixel/point inconsistency; it is not a feature change or a native PASS. +This follow-up used only the assigned worktree. All prior uncommitted work is +preserved, with the initial patch and tracked-file hashes retained under +`.build/cmp-oracle-point-units/`. The only additional harness change is the +single `windowWidthPoints: windowFrame.width` argument at the existing oracle +call. Capture receipts/schema, registrations, restoration and app source stay +unchanged; no opaque attestation is added. + +Commands ran from this worktree. Swift/Xcode used +`DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`, with home, +temporary files and module caches under the task-owned output directory. + +| Command / check | Fresh result | +| --- | --- | +| `python3 -B -m unittest discover -v -s scripts/tests -p 'test_regression*.py'` | **75 passed**, no failures/errors/skips. Includes 144 missing-label cases at 1x/2x/3x/4x and 96 synthetic scenario/window/scale combinations, with unsupported scales still BLOCKED. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/cmp-oracle-point-units/oracle"` | **16,830 oracle contract cases passed**: About 11, Appearance 52, Notifications 37, haptics 104, panel swipes 116, compact removal 112, plus 5,466 recorded-1x/synthetic-DPI geometry cases per General descriptor. Four-point offsets pass and five-point offsets fail across all twelve labels, three window widths, six scales and four native-edge phases. | +| `xcodebuild -quiet build-for-testing -project experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj -scheme GuestRegressionProbe -configuration Debug -destination 'platform=macOS,arch=arm64' -derivedDataPath "$PWD/.build/cmp-oracle-point-units/DerivedData" -resultBundlePath "$PWD/.build/cmp-oracle-point-units/build.xcresult" -disableAutomaticPackageResolution -skipPackageUpdates CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO` | **Exit 0**, standalone harness compiled unsigned. No XCTest execution, app build, signing or launch. | +| Tracked-file comparison / `git diff --check` | Only the seven scoped oracle/harness/test/doc files differ from the follow-up's starting snapshot. All **574** other tracked files are unchanged, including **243** app/test/resource/project files, other pane oracle implementations, capture contract and eleven-case registry. | + +The initial Python run correctly rejected 36 malformed wider-window fixtures: +their label frames retained the old window's normalized x/width. Only those +synthetic coordinates were renormalized to preserve the same native-point +geometry; the viewport gate was not weakened. The initial `python.log` remains, +alongside passing `python-final.log`, `oracle.log`, `build.log`, +`build.xcresult`, `prior-work.patch`, `tracked-before.json`, `preservation.json` +and `source-final.patch`. + +**Evidence remains the recorded 1x measurements, not a fresh native replay.** +Synthetic 2x/3x/4x and fractional-scale inputs prove oracle unit consistency +only. Original failed receipts remain immutable and native verification remains +pending. The separate NEW root `com.apple.macl` addition and ctime change remain +**BLOCKED, unwaived and untouched**. No VM, signing, app/source operation outside +this worktree, remote, commit or agent was used. All current changes remain +uncommitted; no actual native PASS or merge clearance is claimed. diff --git a/experiments/tart-regression/scenarios/general-haptics-removed.md b/experiments/tart-regression/scenarios/general-haptics-removed.md new file mode 100644 index 0000000000..ce08df299e --- /dev/null +++ b/experiments/tart-regression/scenarios/general-haptics-removed.md @@ -0,0 +1,169 @@ +# General: haptic feedback removed + +Ledger: **HAP-REMOVE / HAP-CONTRACT / HAP-NATIVE**. One scoped removal; branch +`chore/remove-haptics`, source base `6ea993e7f2609b4924a7887031b8914bf45c0f99`. +Parent owns integration, publication, full checks, independent review and Tart +verification. This note is not native proof or merge approval. + +## Executable scenario + +`general-haptics-removed` selects +`GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutHaptics`. +It uses the installed, exact hash-bound candidate in an unlocked English +headless Tart guest. The standalone harness does not import or build the app. +Use the existing single-display 1440x900 fixture and normal Settings dimensions; +do not resize the window/display or change preferences to make the test fit. + +Real sidebar clicks navigate About then General. Structural sidebar/form mapping +and a fresh app-owned native window ID precede native top/bottom scrolling. +Repeated endpoints must be stable, show no clipped content before the top or +after the bottom, translate uniformly and overlap by at least 64 points. Both +window-only screenshots bind run, scenario, test, candidate hash/PID, native +window ID, pane, geometry, attachment name, dimensions and PNG digest. + +Assertions require **Enable haptic feedback absent** in both the Accessibility +form and screenshot text. Twelve unconditional retained controls need visible +label geometry plus aligned OCR in at least one capture: + +- Show menu bar icon; Launch at login; Language; Show on all displays. +- Preferred display; Automatically switch displays. +- Notch height on notch displays; Notch height on non-notch displays. +- Open notch on hover; Remember last tab; Notch animation. +- Enable media gestures. + +The original haptic-removal revision required **Enable gestures**. The scoped +[panel-swipe removal](general-panel-swipes-removed.md) now replaces only that +retained label with **Enable media gestures**, preserving its stored master +value for media. This implements the owner's separate removal decision, not an +exception to a failing haptic assertion. The subsequent scoped +[compact-mode removal](general-compact-mode-removed.md) removes only **Compact +mode** from this retained set because the owner selected its deletion. All +other twelve labels and all haptic, capture and restoration requirements remain. +The historical evidence below describes the original thirteen-label set and +does not establish proof for either new removal candidate. +The current case is for the post-rename, post-compact-removal candidate, not an +older pre-rename baseline: its missing **Enable media gestures** label would be +an expected version mismatch, not evidence about haptic removal. + +Disabled labels still exist and render: presence never requires `isHittable`. +Conditional controls (hover delay, custom heights, animation speed, expanded +gesture settings) are not enabled or changed for this probe. Their source +wiring remains covered by contracts, not claimed as native interaction proof. +Missing retained output or a remaining haptic option after valid navigation and +complete scroll coverage is **FAIL / rendered_output_mismatch**. Incomplete +scroll coverage, identity, capture or restoration is **BLOCKED**, never absence. + +## Measured native-label remediation + +The original independent report at the primary checkout's ignored +`.local/vm-regression/evidence/haptics-old-independent-3507acc/report.json` +is preserved unchanged. Its raw FAIL found the haptic option, but only eleven +of thirteen retained labels passed; that is **not correct negative proof**. + +Scoped author diagnosis on run02 used the existing OLD executable SHA-256 +`9896a6ffb6025a5b69aeae65aeec512b1eeda8677ce30b1dc8c38abad58703a0`, +built from `8844ddfff2ea42cdefc04ec0d3172aa439942d37` (AI replies already +removed). No app build, install or re-sign occurred. Only the two public General +labels were queried for native class/label/value/frame metadata: + +| Label / visible endpoint | Native query evidence | Label frame in capture pixels | Vision box in capture pixels | +| --- | --- | --- | --- | +| Launch at login / top | One static text (type 48), AXValue is exact text; AXLabel/identifier empty; zero checkboxes | x=238, width=93, height=16 | x=234, width=98, height=16 | +| Remember last tab / bottom | Same static-text class/value behavior; zero checkboxes | x=238, width=114, height=16 | x=234, width=120, height=16 | + +Both labels were already found by `form.staticTexts.matching(identifier:)`; +the checkbox-title hypothesis was disproved. The oracle rejected Vision's +left edge, four pixels before the native label frame: its existing normalized +0.005 alignment allowance is only 3.5 pixels in the actual 700x600 capture. +Vertical midpoints aligned. Local bound screenshots show both exact labels. + +That remediation's General descriptor permitted **four leading OCR pixels for only these +two labels**, using actual capture width and nearest integer pixel edges to +remove Vision's subpixel serialization noise. Typed unique static-text lookup, +unaltered native label frames, full viewport containment, vertical alignment +and exact same-row text remain required. Five-pixel displacement, wrong rows, +missing labels/frames/pixels and near text still fail. No global OCR allowance, +checkbox fallback, scroll/frame float tolerance or missing-output BLOCKED gate +was added; Notifications and the other General labels kept their prior policy. +The later [compact remediation 2/5](general-compact-mode-removed.md#fresh-remediation-25-offline-general-alignment-2026-10-02) +supersedes only that two-label whitelist after measuring the same overhang on +two more labels. Its point-unit follow-up bounds all twelve current General labels +to four native points, pixel-snapped using the actual capture/window-width ratio. +The recorded evidence here is 1x: four pixels equal four points. Synthetic +higher-scale checks are not new native evidence; this does not revise these +historical results or grant signoff. +**All historical failed receipts are immutable**, including the original +independent haptic report and author diagnosis/development failures. + +Current fixture measurements: 492x548-point form, 353-point endpoint translation, +195-point overlap (**131 points above the 64-point minimum**). The owner-set +conditional preferences were not changed: hover delay and animation speed were +visible; custom heights and expanded gesture settings were not enabled. +The diagnostic closed case restored General and closed Settings. One corrected +author development check from pre-existing General produced **FAIL / +rendered_output_mismatch**, all thirteen retained assertions true and only +`hapticControlAbsent=false`. Teardown observed General already selected, scrolled +by +353 points and verified exact original content-frame equality +(`generalScrollRestored=true`), leaving General open. Fixture cleanup then closed +Settings, normally quit the task-launched app and shut down run02; both VMs stopped. + +Raw diagnosis and corrected receipts, public images, source archive identities, +build logs and app-integrity checks are retained separately under the primary +checkout's ignored `.local/vm-regression/{work,evidence}/haptics-remediation-1-diagnosis` +and `haptics-remediation-1-devcheck`. These are **author development evidence, +not independent signoff**. The full NEW registry and fresh independent OLD/NEW +comparison remain parent-owned. + +## Restoration and wrong-behavior proof + +The existing closed/General/About fixtures remain supported. The exact app PID +and bytes must remain unchanged. Close Settings only if the probe opened it; +otherwise restore the original pane and About build-number visibility. For a +pre-existing General pane, record its initial content frames before navigation, +restore the original scroll displacement with a bounded native scroll and +require exact frame equality in teardown. A failure/abort still runs restoration; +an unverified scroll restore blocks the result. No stored data is migrated or +deleted, and the obsolete `enableHaptics` preference is simply no longer read. + +### Historical haptic comparison harness + +The following nine-case comparison belongs to the pre-panel-rename haptic +removal. Use its own recorded test-source revision, such as the corrected +pre-rename harness at `3c94d451c806024d83ac6ce25cd8b2f6641634a2`, which requires +**Enable gestures**. Preserve the actual harness identity in each historical +receipt; do not relabel evidence with the current revision or rerun the current +**Enable media gestures** expectation against that older baseline. + +For that comparison, the parent must identify and record an actual OLD haptic-bearing executable, +its SHA-256 and source/build provenance; the source base alone is **not** a +candidate identity. Run the historical scenario unchanged on OLD and require **FAIL** +because the haptic option is actually found with complete valid evidence. +An environment/scroll block is not negative proof. Then run the full **nine-case** +registry on the exact NEW candidate across closed, General and About fixtures. +Record test-source identity separately from each candidate. Do not transfer +older Appearance/Notifications proofs or version-only identity to this removal. + +## Scope and limits + +Removed six product `sensoryFeedback` bindings: panel, day wheel, week strip, +activity stack, notification send and code-copy feedback. Removed the four +haptic-only state values, eleven gated triggers, General toggle/default, unused +stack Defaults import and the exclusively owned localization entry. +Notification `didSend`/`didCopy` state still drives visible confirmation. +Panel hover/click/keyboard and media gestures, calendar selection/monitors, +activity cycling, Shelf actions, notifications and retained controls remain. +Panel gestures, compact mode, lock-screen option and inherited AI/face removals +are not broadened by this change. + +Permission-free source/oracle/receipt tests cannot establish physical actuator +behavior, live media/Shelf/notification actions, or native pixels/restoration. +Independent OLD/NEW execution is parent-owned and pending. No VM, host UI, +consent, signing, credentials, stored-user-data or remote changes are needed +for authoring this scenario. + +The historical haptic remediation changed only **HAP-NATIVE** (measured General OCR alignment and +scenario documentation) and **HAP-CONTRACT** (targeted oracle/policy cases). +Product source, the nine-entry registry/eight prior cases, generic capture +schema, receipt/export boundaries, fixture preferences, exact scroll restoration +and signing/CI configuration were unchanged at that revision. The later +panel-swipe removal has its own tenth case and fresh-candidate validation. diff --git a/experiments/tart-regression/scenarios/general-panel-swipes-removed.md b/experiments/tart-regression/scenarios/general-panel-swipes-removed.md new file mode 100644 index 0000000000..f8530fb2ff --- /dev/null +++ b/experiments/tart-regression/scenarios/general-panel-swipes-removed.md @@ -0,0 +1,219 @@ +# General: panel swipes removed, media gestures retained + +Ledger: **SWIPE-REMOVE / SWIPE-CONTRACT / SWIPE-NATIVE**. Scoped authoring in +`chore/remove-panel-swipes`, base `3c94d451c806024d83ac6ce25cd8b2f6641634a2` +(the local haptics-removal stack). Changes stay uncommitted. The owner confirmed +hover/click as sufficient panel interaction; existing keyboard access remains. +No compact-mode, lock-screen, media-feature, Calendar/Shelf, or further +haptic/AI/face removal is authorized. + +## Dependency decisions and preference compatibility + +| Original symbol / consumer | Decision | +| --- | --- | +| `enableGestures`: General master, down/up attachments, horizontal-media attachment; forced true when hover disabled | Retain its persisted **`"enableGestures"`** key and `false` default under Swift name `enableMediaGestures`. Label becomes **Enable media gestures**. Only the horizontal attachment remains; delete the hover-off assignment and disabled-state coupling. | +| `enableHorizontalMediaGestures`: General child toggle and horizontal attachment | Retain unchanged key/default (`false`), child control and two-flag conjunction. Neither formerly disabled combination becomes enabled. | +| `closeGestureEnabled`: General close toggle and up attachment only | Remove declaration, control and all readers. An existing stored value is inert, not deleted. | +| `gestureSensitivity`: General slider, vertical thresholds and horizontal-media threshold | Remove only vertical consumers. Retain key/default `200`, `100...300` step-100 slider and strict media `translation > sensitivity` threshold. | +| `normalizeGestureDirection`: Advanced toggle and shared scroll monitor | Retain key/default `true`, UI and natural-scrolling normalization unchanged. | +| `gestureProgress`: vertical stretch plus horizontal-media pulse and shared rendering | Remove vertical writers; rename the still-live value to `mediaGestureProgress`. Preserve the closed-panel media pulse (`2`, then unconditional `0` after 140 ms even if the panel opens), animations and scale/opacity/width consumers, including the InlineOSD binding. Remove the negative-stretch-only scale floor. | +| `isHoveringCalendar`: Home hover writer, model field, up-handler guard | Remove this now-unused field and writer. Calendar's own two local scroll monitors, hover guards, day/week selection and click handlers remain untouched. | +| `PanGesture` / `ScrollMonitor` | Preserve drag/scroll recognition, thresholds, event-window filter, horizontal 1.5x axis dominance, normalization, phase/timeouts and cleanup. Remove only unused up/down directions and vertical projection branches. | + +No migration, startup assignment, preference-domain reset or data deletion is +added. Both media switches retain their separate stored values, including when +the old master was forced on by disabling hover. Hover changes now leave them +alone. The same four old/new master/child combinations are off/off, off/on, +on/off = inactive; on/on = active, subject to the unchanged media context. +New installs remain off/off. No accidental media re-enable or preference loss. + +Click still calls the existing guarded `doOpen()` independently of hover and +media settings. The existing Command-Shift-I shortcut still opens/closes the +selected display through its model (including its existing timed close). +Onboarding, fallback notice, sharing, hover timers and Shelf drop guards remain; +no new opening route or hover policy is invented. + +## Executable installed-app scenario + +`general-panel-swipes-removed` selects +`GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutPanelSwipes`. +It is the **tenth** registered case: one addition to the inherited nine-case +registry, with the five existing oracle/restoration controls unchanged. + +Use the actual installed, hash-bound candidate in an unlocked, English, +headless Tart guest with the existing single 1440x900 display and ordinary +Settings dimensions. No app import/build dependency, display/window resizing, +preference toggles or host UI. Real About then General sidebar clicks precede +the existing structural form mapping and two native endpoint captures. + +Assertions: + +- Twelve retained labels render with visible native label geometry and aligned + OCR in at least one endpoint, including **Enable media gestures**, hover, + animation, remembered tabs, language and display controls. The subsequent + owner-selected [compact-mode removal](general-compact-mode-removed.md) retires + only **Compact mode** from this positive set; all other properties remain. +- **Enable gestures**, **Close gesture** and the two-finger panel-open/close + instruction are absent from the Accessibility form and both endpoint pixels. + Accessibility matches the rendered instruction, without the source/catalog's + Markdown `**` markers around `Open notch on hover`. Media gesture text is + explicitly not forbidden. +- Exact run/scenario/test/candidate hash/PID/window/pane identity, + `generalCaptureVersion: 1`, stable endpoints, no offscreen omission, uniform + translation and at least 64-point overlap are required. Invalid evidence is + BLOCKED, not a pass or a product failure. + +The media master stays unconditional. Its existing conditional horizontal +toggle and sensitivity slider are retained by source contracts without changing +their visibility policy or the guest's preferences. This scenario proves the +rendered media master, not expanded configuration, preference propagation, +actual swipe playback or static transport operation. + +After valid setup/coverage, missing retained text or any removed control/copy +means **FAIL / rendered_output_mismatch**. Absence combines with AND across +captures, presence with OR. The same closed/General/About fixtures restore +window ownership, original pane, About build visibility, pointer and exact +pre-existing General scroll frames, including on failure. + +## Deliberate update to the prior General contract + +The prior haptics scenario required **Enable gestures** because it preserved +panel swipes at that revision, not because the owner required them forever. +Replace only that retained label with **Enable media gestures** in both General +descriptors; retire only its source assertions for the now-removed down/up +handlers, Calendar close guard and close preference. At that revision, all other +twelve retained labels, haptic absence, measured label-specific four-pixel OCR +allowance, capture/geometry/restoration gates and earlier negative controls +remained. +Historical haptic receipts and documentation of their original thirteen labels +remain historical evidence, not rewritten proof against this candidate. +The later CMP removal makes this scenario's current positive set twelve labels; +the original SWIPE scope, validation counts and ten-case proof requirements +remain historical. Current integration must run the eleven-case registry. +Do not run the current haptic case against a pre-rename baseline and interpret +the missing **Enable media gestures** label as a haptic regression. Historical +negative evidence uses its own pre-rename harness revision, recorded separately +from the app identity; see the [haptic comparison](general-haptics-removed.md#historical-haptic-comparison-harness). + +## Full ledger / changed-path map + +Paths below are relative to the checkout root. + +| Ledger | Path | Change | +| --- | --- | --- | +| SWIPE-REMOVE | `notchPocket/ContentView.swift` | Remove vertical attachments/handlers; preserve media gate, context, dispatch and pulse; rename shared pulse state. | +| SWIPE-REMOVE | `notchPocket/models/Constants.swift` | Retire close key; preserve master storage identity under media-only name and all shared defaults. | +| SWIPE-REMOVE | `notchPocket/components/Settings/Views/GeneralSettingsView.swift` | Remove panel controls/footer and hover coupling; retain media configuration. | +| SWIPE-REMOVE | `notchPocket/extensions/PanGesture.swift` | Remove unused vertical directions/projection only; retain horizontal infrastructure. | +| SWIPE-REMOVE | `notchPocket/models/NotchPocketViewModel.swift` | Remove Calendar-hover field used only for panel close. | +| SWIPE-REMOVE | `notchPocket/components/Notch/NotchHomeView.swift` | Remove that field's sole writer; retain Calendar and media views. | +| SWIPE-REMOVE | `notchPocket/components/OSD/Views/InlineOSD.swift` | Follow the shared media-pulse rename; retain static controls and geometry. | +| SWIPE-CONTRACT | `notchPocket/Localizable.xcstrings` | Delete two panel-only entries; relabel the master in its existing 19 locales. Preserve all unrelated entries and media strings. | +| SWIPE-CONTRACT | `scripts/tests/test_regression_probe.py` | Add removal/preservation/access-route/preference/source contracts and new receipt failures; narrowly adapt prior General expectations. | +| SWIPE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift` | Add one test selector; reuse General navigation/capture/restore and check every removed label. | +| SWIPE-NATIVE | `experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift` | Fixed panel-swipes descriptor and exact forbidden copy; media remains a positive requirement. | +| SWIPE-NATIVE | `experiments/tart-regression/capture_contract.py` | Bind new descriptor to existing two-capture identity and General restoration contract. | +| SWIPE-NATIVE / SWIPE-CONTRACT | `experiments/tart-regression/OracleContractTests.swift` | Missing/old/near/split/offscreen text, media preservation, two-endpoint combination and unchanged measured-label boundaries. | +| SWIPE-NATIVE | `experiments/tart-regression/suite.json` | Add one scenario; preserve nine prior registrations. | +| SWIPE-CONTRACT | `experiments/tart-regression/README.md` | Document tenth case, shared capture schema and scoped prior expectation change. | +| SWIPE-CONTRACT | `experiments/tart-regression/scenarios/general-haptics-removed.md` | Explain the owner-directed retained-label replacement without rewriting historical proof. | +| SWIPE-CONTRACT | `docs/regression-coverage.md` | Record new Settings coverage and remaining runtime gaps. | +| SWIPE-CONTRACT / SWIPE-NATIVE | `experiments/tart-regression/scenarios/general-panel-swipes-removed.md` | This dependency ledger, authoring contract and parent proof requirements. | + +## Initial author validation (2026-10-02, before remediation 1/5) + +**HISTORICAL pre-merge evidence:** this table and the remediation table below +record their own panel-swipe snapshots, before compact-mode integration. Their +64/65 Python and 350/354 synthetic counts are not current integration results; +see [fresh compact remediation](general-compact-mode-removed.md#fresh-remediation-15). + +All generated homes, temporary directories, module caches and build products +were directed beneath this worktree's ignored `.build/`. No installed app, +host UI, VM, remote, user preferences, Keychain, signing identity or credentials +were operated on. + +| Command / check | Historical result | +| --- | --- | +| `python3 -B -m unittest discover -s scripts/tests -p 'test_regression_probe.py'` | **64 passed**. The first run exposed an overbroad new assignment matcher treating the key declaration as a preference write; corrected to match writes, then reran all 64. Both logs retained. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/swipe-contracts/oracle"` | **350 cases passed**: About 11, Appearance 52, Notifications 35, haptics 98, panel swipes 106, and 24 measured-label boundary cases for each General descriptor. Synthetic oracle inputs, not native captures. | +| Standalone `xcodebuild -quiet build-for-testing -project experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj -scheme GuestRegressionProbe -configuration Debug -destination 'platform=macOS,arch=arm64' -derivedDataPath "$PWD/.build/swipe-harness/DerivedData" -resultBundlePath "$PWD/.build/swipe-harness/build.xcresult" CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO` | **Succeeded** without executing tests or signing. Unsigned harness products are compilation evidence only. | +| `xcrun swiftc -frontend -parse` on the seven changed product Swift files | **Passed**; syntax only, not an application build/type-check. | +| `swiftlint lint --quiet --no-cache --config .swiftlint.yml --reporter json` on those seven product files | **Exit 0**, 98 warnings; no suppressed rules or baseline cleanup. | +| Same scoped lint including the three changed harness/oracle files | **Exit 2**: three pre-existing `empty_count` errors in the native probe (current lines 245/429/472, unchanged base lines 239/423/466), plus warnings. Those experiment files are outside the root config's normal product include paths; no unrelated repair. | +| Read-only comparison to the requested base | All unrelated catalog records byte-equivalent as parsed JSON; master retains all 19 locales; nine previous registry entries identical; 37 access/Calendar/Shelf/media files byte-identical. `git diff --check` passed. | + +Logs: `.build/swipe-contracts/{python.log,python-rerun.log,oracle.log,lint.json,product-lint.json,product-parse.log}` +and `.build/swipe-harness/{build.log,build.xcresult}`. Ignored build/cache residue +is retained for the parent. No application XCTest/full build/helper/CI gate, +independent review or native runtime signoff was attempted. + +## Remediation 1/5 (2026-10-02) + +Uncommitted remediation against `30c85008d7ef817344ccc51a742b21da7ef4bf93`, +limited to **SWIPE-REMOVE / SWIPE-CONTRACT / SWIPE-NATIVE**: + +- The media pulse set progress to `2` while closed, but its timer skipped reset + if hover/keyboard opened the panel within 140 ms. Removing the vertical + handler also removed a secondary clear path, leaving scale `1.02` and opacity + `0.8`. Cleanup now resets both feedback values unconditionally in the existing + animation. No changes to pulse start, delay, actions, two-key media gate or + bound UI. A focused source contract locks this cleanup; private SwiftUI state + has no existing behavior-unit seam, and no new state abstraction was added. +- The removed footer's AX descriptor now uses rendered text. The native probe + and oracle tests share the same exact-label presence matcher, still backed by + `form.staticTexts[...].exists`, without broader queries or new setup gates. + Four synthetic footer-only cases cross `sourceTrue` with `visible`: either + Accessibility presence or visible OCR rejects absence even when neither + removed toggle is present and all thirteen retained labels pass. Raw Markdown + remains in the fixture's source string; raw catalog/source removal contracts + remain unchanged. +- Current versus historical General/haptic harness expectations are separated + explicitly. No historical receipt or negative evidence was rewritten. + +| Command / check | Historical result | +| --- | --- | +| `python3 -B -m unittest scripts.tests.test_regression_probe.PanelSwipeRemovalSourceContractTests` before the product fix | Expected RED: 7 tests, only the new unconditional-cleanup source contract failed. | +| `bash experiments/tart-regression/test-oracle.sh "$PWD/.build/swipe-remediation1-5/oracle"` before the descriptor fix | Expected RED: `PanelFooterOnly`, `sourceTrue=true, visible=false` incorrectly reported absence. The existing top-level Swift error exits 133. | +| `python3 -B -m unittest discover -s scripts/tests -p 'test_regression_probe.py'` after both fixes | **65 passed**. Source and mocked receipt/policy tests, not executed gestures. | +| Same oracle command after both fixes | **354 passed**: About 11, Appearance 52, Notifications 35, haptics 98, panel swipes 110, and 24 geometry cases for each General descriptor. Synthetic matching/OCR inputs, not live Accessibility or captures. | +| `xcrun swiftc -frontend -parse notchPocket/ContentView.swift experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift` | Passed; syntax only, not application or harness type-check/build. | +| `git diff --check` | Passed. | + +Logs and owned compiler/test residue remain under ignored +`.build/swipe-remediation1-5/`: `python-red.log`, `oracle-red.log`, +`python-green.log`, `oracle-green.log`, `swift-parse.log`. No VM, host UI, +signing, remote, commit, agent or credential operations were performed. +The initial validation table above is historical, not fresh validation of this +patch. **Candidate `03f9` from the old source is stale after the product fix.** +The parent must rebuild and record fresh candidate and harness identities, then +perform full validation and independent native verification. + +## Parent-owned proof still required + +Identify an actual OLD panel-swipe-bearing executable, SHA-256 and build/source +provenance; this source base alone is not a candidate identity. Run only this +scenario on OLD. Require complete restored evidence and a FAIL that actually +finds the removed panel master/copy. OLD lacks the newly named media master, so +that one positive-label mismatch is expected; unrelated retained labels must +still pass. A navigation/scroll/OCR block is not negative proof. + +The original panel-swipe scope required the full **ten-case** registry on NEW. +Current integration includes compact-mode removal: run the full **eleven-case** +registry on the exact NEW candidate across closed/General/About fixtures. +Record candidate and test-source identities separately, export/check both +native attachment digests, inspect selected-window pixels locally and preserve +failures. No prior haptic/AI/face receipt substitutes for fresh independent signoff. + +Separate bounded runtime checks must prove vertical scroll no longer opens or +closes the panel; hover, click and keyboard access with hover disabled and media +off; unchanged horizontal media opt-in/opt-out combinations, sensitivity, +normalization and static transport; unchanged Calendar scrolling and Shelf +actions. Include a closed-panel media pulse followed by hover/keyboard opening +before cleanup; verify scale/opacity return to normal while open. Source checks +do not execute that timing transition. These are not claims of the General +label scenario. Any fixture +preference writes require parent-owned recording/restoration, not a domain reset. + +Parent owns full app/helper/CI checks, review, independent Tart execution, +candidate signing and any approved publication. Author source/oracle tests and +standalone harness compilation are not native proof, merge or release approval. diff --git a/experiments/tart-regression/scenarios/music-idle-launcher.md b/experiments/tart-regression/scenarios/music-idle-launcher.md new file mode 100644 index 0000000000..d7195d402e --- /dev/null +++ b/experiments/tart-regression/scenarios/music-idle-launcher.md @@ -0,0 +1,188 @@ +# Idle music launcher (#53, existing PR #86) + +Registered cases: `music-idle-no-target` and `music-idle-unavailable`. +Both execute the installed, hash-pinned candidate, not the app test host or a +mock workspace. Source: `GuestRegressionProbe/IdleMusicLauncherScenario.swift`. +The two additions preserve all eleven existing registry cases; full scope is +now thirteen. Author-side harness compilation and contract tests are not native +or independent signoff. + +## Prepared guest conditions + +Use an unlocked, English, one-display Tart guest with ordinary onboarding and +required Accessibility/capture consent already completed. Never run on a host. +The exact installed candidate must already be running, with a closed notch, +visible tabs and Settings gear, no notification/share interaction, and Settings +closed or on General/About. Keep Calendar/Mirror disabled for this bounded +default-layout fixture; their conditional layouts are separate parent proof. +The guest's existing Finder must be running. It is temporarily activated as the +unrelated foreground fixture so focus theft is observable even after a preceding +suite case leaves Notch active. No Finder window/content is inspected or captured. +The original foreground app is recorded and restored. + +The original Music Source must have been explicitly selected through Settings +(`didChooseMediaController == true`, persisted `mediaController`). No current +OS Now Playing source and no remembered source +(`lastSupportedNowPlayingBundleIdentifier` and +`lastNowPlayingLauncherBundleIdentifier` absent) may exist in this clean +guest fixture. The test refuses an existing remembered preference rather than +deleting user history. Now Playing must be available/selectable for the +no-target case. Spotify must genuinely be uninstalled for the unavailable case: +the native workspace lookup is checked, not replaced. Prepare a separate clean +guest profile if those conditions cannot be met; do not reset host preferences, +impersonate Spotify, inject an app ID, change consent or fake launch success. + +## Actions and assertions + +After existing hardware/session/candidate/PID checks, navigate the actual +Settings Media pane and select Now Playing or Spotify with its Music Source +picker. Close Settings, hover the actual panel open, select Home, restore the +guest Finder foreground fixture and click the product-owned idle launcher. + +Require a hittable launcher, no player slider, retained Home/Settings header, +the selected source, and actual visible status: +`No music app selected.` or `Spotify is not installed.`. Require unchanged +foreground PID (`noFocusChangeOnFailedLaunch` in the receipt). This assertion is +specific to these failures before an OS open is dispatched, not a ban on +intentional activation when an installed app is opened successfully. A timed-out +or cancelled dispatched open can still activate the app later; UI cancellation +does not cancel an OS launch. Capture only the freshly mapped, shareable, on-screen panel +with the same native ID and candidate PID; bind the PNG to the run and receipt. +Vision must find the expected status inside its actual Accessibility text +frame, not elsewhere in the panel. Click OK using the versioned product identifier +`com.jdylanmc.notchpocket.music.v1.launch-dismiss`, not its localized caption; +require feedback dismissal and +the launcher restored. No playback commands or real media app launches occur +in these two failure journeys. + +Teardown reopens Settings if necessary and restores the original Music Source +through the same picker, then verifies its persisted value, the pre-existing +explicit-choice flag and absent remembered source. Restore original tab, +closed notch, pointer, Settings pane/scroll/build visibility/open state and +foreground app using the existing teardown contract. A failed assertion still +runs teardown. Unverified restoration is BLOCKED, never a functional pass. +Only the Music Source preference is deliberately changed; unrelated feature, +Shelf and privacy preferences are not fixtures to reset. + +## Wrong outcomes and remaining proof + +An old player-only/always-full-player candidate, missing launcher/status, +wrong failure text, retained slider, focus theft or broken OK action produces +FAIL after valid fixture setup. Missing fixture/permission/selection, changed +candidate/window or unverifiable restoration is BLOCKED. Oracle unit controls +reject wrong/absent/duplicated/off-frame text; Python receipt controls reject +missing assertions, wrong source, stale run/window and false restoration. +These synthetic controls are not an OLD/NEW native comparison. + +Parent must build/install an exact reconciled candidate, bind source provenance +and hash, and commission independent guest execution of all thirteen cases. +Use the no-target fixture only while no external test player is publishing. +Separately use an actual external guest player through OS Now Playing to prove +playing -> paused/stopped -> launcher -> explicit app open without playback -> +resume -> full player, current versus remembered source routing, and ordinary +hover/share/timer behavior. Preserve player preferences and lifecycle too. +No product-side fixture branch, AppDelegate injection or private target +override is needed. An external synthetic player is **not Spotify account +proof**; actual Spotify installation/account/playback evidence remains separate. +Launcher history now records any nonblank source observed by the actual Now +Playing controller, independently of the unchanged recognized-player fallback +preference. Empty/stopped updates retain history; earlier recognized history is +still usable when launcher history is absent. No new player backend is added. +Calendar/Mirror, Shelf contents/actions and other Settings retained behavior +also require their own fixture evidence, not this default music-only slice. + +### Public fixture automation boundary + +[`MediaFixture`](../MediaFixture/README.md) supplies a separate test-only producer +using public AppKit, AVFoundation and MediaPlayer APIs, not a product integration +or Spotify impersonation. The [suite's CI checks](../README.md#public-media-fixture-checks) +run its object compilation, Foundation/Darwin pure contracts and mocked Python +build-recipe tests after the macOS helper/oracle gates. They do not build/sign/ +install a player app, execute audio/UI, or establish OS delivery. + +The fixture does not add a registered scenario or replace the thirteen-case +suite, independent guest activation/playback assertions, or real Spotify +account/playback evidence. Fixture-generated remembered history also makes a +guest unsuitable for these no-target cases: retain a separate clean baseline, +not deleted preferences or cleared history. Use the fixture guide's actual +engine, consumer, identity and negative-control assertions for separate +parent-owned native proof; CI success alone cannot satisfy them. + +## Remediation 1: LAUNCH-INTEGRATE / LAUNCH-TEST + +Base: PR #86 head `21012dfce4e670697da500fec63e8858deb15d24`. +The owner's supplied #53 acceptance explicitly requires **paused, stopped and +no active player to collapse the opened Home music section immediately**. +Rubberduck's proposed `isPlayerIdle`-based paused retention is **rejected as an +incorrect-scope finding**, not accepted risk or a waived defect: + +- `MusicPresentationPolicy.presentation(isPlaying:)` and `MusicSectionView` + govern the opened section and deliberately select the launcher for `false`. + The debounce-based `isPlayerIdle` would retain the full player after pause, + directly violating that acceptance. +- `ContentView` separately retains closed music live activity via + `isPlaying || !isPlayerIdle` plus the live-activity preference. Its closed and + opened horizontal-gesture guards are unchanged, including + `!isPlayerIdle && isHoveringMusicArea` for the open Home player. +- `MusicPlayerView.onDisappear` still clears music-area hover when the full + player is replaced. This prevents the collapsed launcher from inheriting + the removed player's hover context; it does not remove closed live activity, + rewrite gestures, revive compact mode, or reset hover preferences. + +The real fixes use `MusicLaunchContext` for both label/icon identity and the +action target. Playing album-art clicks prefer the actual observed bundle, +including an Apple Music fallback with no history or Spotify with another +remembered publisher. Idle Now Playing accepts a current bundle only from the +actual Now Playing controller, then uses launcher/legacy history. Recognized +fallback selection and its separate history-writing criteria are unchanged. +Arbitrary publishers keep their exact target/icon lookup and truthful generic +`Open music app` label; they are never relabeled Spotify or added as backends. + +`MusicLaunchTransaction` owns a five-second UI deadline, generation checks before +dispatch and after suspension, and cancellation on context change/disappearance. +Its independent timer does not join the suspended workspace task. The manager's +shared `MusicAppLauncher` permits only one outstanding OS open, even across +timeout, source change, disappearance and a new view. Further clicks report an +already-pending request without queueing another open. The gate reopens only +when the old await actually returns. Late results cannot replace newer feedback. +The workspace bridge waits for the native completion callback, not cooperative +task cancellation, before releasing that gate. +These limits bound UI waiting and request accumulation, **not OS activation**. +Failure/timeout wording explicitly permits a late launch. + +Feedback occupies a bounded inline row, never an opaque overlay on transport. +Guidance is available through an accessibility hint as well as hover help; +resume/source changes clear obsolete feedback and the launch hold. The existing +classic slider helpers were moved verbatim into `MusicSliderView.swift` to bring +`NotchHomeView.swift` below the 500-line lint threshold; no lint gate is disabled. +The thirteen scenario registrations, fixture requirements, expected failure +text, pixel assertions and restoration requirements remain unchanged. The +failure-scoped focus receipt key is intentionally stricter; legacy ambiguous +receipts do not satisfy it. + +Remaining parent-owned evidence: fresh reconciled product build and exact-candidate +independent guest execution of all thirteen registrations, plus real OS-player +playing/paused/stopped/no-source/resume transitions, playing album-art routing, +successful activation without issuing playback, and visible non-covering feedback +with retained full-panel/Calendar/Mirror layout and ordinary hover/gesture behavior. +Hostless unit/source/oracle checks do not establish those outcomes. No Tart or +host UI execution, signing, installation, remote writes or commits are authorized +in this remediation slice. + +### Local checks (2026-10-02, uncommitted remediation) + +Evidence is retained in this worktree's ignored `.build/pr86-remediation1/`. + +| Check | Result and limits | +| --- | --- | +| `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test --package-path .build/pr86-remediation1/launch-units --disable-sandbox` | **53 XCTest cases passed**, including 10 transaction cases with a noncooperative suspended opener. This temporary hostless package links the actual launch sources and test files; its source-extracted `MediaControllerType` omits only the unrelated `Defaults.Serializable` conformance. It is not the app-hosted full suite or an OS launch test. | +| `python3 -B -m unittest discover -s scripts/tests -p test_regression_probe.py` | **83 passed**. Includes original thirteen-case registry, output/restoration contracts, failure-only focus receipts, lifecycle/inline wiring and retained closed live activity/gestures. | +| `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer bash experiments/tart-regression/test-oracle.sh "$PWD/.build/pr86-remediation1/oracles"` | **Passed**, including all 16 idle-music oracle cases and every pre-existing oracle/control. Synthetic policy evidence only. | +| `SIGN_IDENTITY='' scripts/lint.sh --quiet` | **0 errors**; 1302 inherited app-wide warnings. Strict targeted lint passed for launch helpers, extracted sliders and changed unit tests. The classic Home file is 476 lines; its file-length warning is removed without disabling a gate. Other inherited Home/manager warnings were not unrelated cleanup targets. | +| App compile via `source scripts/env.sh; xcb build` | **BUILD SUCCEEDED** with `SIGN_IDENTITY=''`, explicit `CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO`, cached `.build/pr86-native-001/SourcePackages`, `-disableAutomaticPackageResolution -skipPackageUpdates -onlyUsePackageVersionsFromResolvedFile`, and `.build/pr86-remediation1/DerivedData`. No `local.env` existed or was read, no signing step ran, and no app was launched. This unsigned compiler check is not the parent's runnable candidate. | +| Standalone `GuestRegressionProbe` `xcodebuild build-for-testing` | **TEST BUILD SUCCEEDED**, Debug/macOS arm64, `.build/pr86-remediation1/ProbeBuild`, `CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO`; not executed. | + +The extracted slider declarations were compared byte-for-byte with the base. +`suite.json` is byte-identical to that base; catalog duplicate-key validation and +`git diff --check` passed. App-hosted full XCTest, signed candidate production, +independent native execution and real-player evidence remain unrun, not waived. diff --git a/experiments/tart-regression/scenarios/notifications-ai-replies-removed.md b/experiments/tart-regression/scenarios/notifications-ai-replies-removed.md new file mode 100644 index 0000000000..dfab70d5a0 --- /dev/null +++ b/experiments/tart-regression/scenarios/notifications-ai-replies-removed.md @@ -0,0 +1,202 @@ +# Notifications without AI reply suggestions + +Owner decision: remove AI reply suggestions only; retain notifications and manual +replies. Local authoring base: `550cb9bb7ab424e359f6d7c70e48ff091ed2eca5`, stacked +above the pending idle-face removal. Integration and independent validation are +parent-owned; this note is not native signoff. + +Scenario: `notifications-ai-replies-removed`. +Selector: `GuestRegressionProbe/GuestRegressionProbe/testInstalledNotificationsWithoutAIReplies`. + +## Installed-app contract + +From General, click the actual Notifications **outline row** and observe its +selection. Map the detail form structurally: one scroll view with no outline, +beside the sidebar's outline-containing scroll view. Do not locate the form +using a notification control whose presence is under test. + +SwiftUI row labels can be static-text **AXValue** with an empty AXLabel/identifier. +Use XCTest's typed `form.staticTexts.matching(identifier:)` lookup for both +retained labels and the removed label, not a generic label-only predicate. +All sidebar clicks, including restoration, remain scoped to their outline row. + +Visit both native scroll endpoints and capture each separately. Repeat each +endpoint scroll once and require unchanged nonempty direct content geometry. +The top must have no content above the viewport; the bottom must have no content +below it. Both snapshots must have the same ordered content types and frames, +translated by one nonnegative vertical offset, with at least **64 points of +viewport overlap**. Otherwise block with incomplete scroll evidence, never infer +absence from an offscreen control. This bounded two-capture contract is not an +unbounded scroll loop and does not change notification preferences. + +After pane/geometry setup, assert: + +- **Show notifications in the notch** renders in Accessibility and detail pixels. +- **From all apps** renders in Accessibility and detail pixels, even when disabled. +- **Suggest replies with Apple Intelligence** is absent from the form's typed + static texts at both endpoints and from both detail captures. OCR also rejects + partial `Suggest replies` / `Apple Intelligence` remnants. + +Retained text presence requires unique typed lookup, a nonempty label frame +fully within the viewport, and matching actual OCR pixels aligned with that +frame. `isHittable`/enabled state is not a retained-text assertion: disabled +static text can render. Retained assertions combine with OR across the two +captures; suggestion absence combines with AND. An empty detail OCR result +cannot prove absence. None of these controls is a prerequisite gate. Missing retained output reaches +**FAIL / rendered_output_mismatch**, not an environment block. The unchanged +About same-row OCR fragment helper supplies normalization and row geometry. + +`observedPublicText` must contain exactly the three Boolean assertions +`Show notifications in the notch`, `From all apps`, `suggestionControlAbsent`. +The evaluator also requires true discovery receipts `notificationsPaneSelected`, +`notificationsFormMapped`, `notificationsScrollComplete`, plus measured offset +and overlap and verdict/output consistency. `notificationsCaptureVersion: 1` +requires exactly two ordered `captures`, named +`guest-public-notifications--top` and `...-bottom`; there is no legacy +`screenshotSHA256` for this scenario. Each includes its role/name/hash, run, +scenario/test, candidate path/executable hash/PID, native window ID, Settings marker, +pane, window/form/content/endpoint geometry, pixel dimensions, visible label +frames and exact per-capture assertions. The native window/PID/pane/frame and +content are rechecked across capture; source bytes and signatures remain +separately verified by the runner/operator. + +The shared Python contract recomputes endpoint coverage and output aggregation. +Export binds each named test attachment in the native manifest to its role, +SHA-256 and PNG dimensions; missing, extra, duplicate, stale or inconsistent +evidence is rejected. Equal image hashes are allowed only for zero translation +with full endpoint containment. The seven prior cases keep their single-capture +contracts, selectors and registry entries unchanged. + +## Fixture and restoration + +Use the existing unprivileged, unlocked, logged-in headless Tart guest, English +UI, one display, normal onboarding complete, and a visible notch Settings gear. +Keep notification mirroring **off** in the synthetic guest profile; the case +does not enable it, send a notification, access Contacts, invoke a model or send +a message. Apple Intelligence availability is irrelevant: the old app renders +its suggestion control even when disabled. + +Settings must be at least 700 x 600 and fully onscreen at the existing +**1440x900** guest display. Do not enlarge the display/window or flip +`From all apps` to force full-form fit. The previous independent attempt at +`8844ddfff2ea42cdefc04ec0d3172aa439942d37` blocked at +`notifications_full_form_not_visible`; its unchanged report remains at the +primary checkout's ignored `.local/vm-regression/evidence/ai-old-independent-8844ddf/report.json`. + +Isolated author diagnosis on the exact old guest candidate measured a +492x548-point viewport, a 191-point top-to-bottom translation and 357-point +overlap. The allow-list group extended below the viewport; the suggestion label +was at screen y=797 at the top and y=606 at the bottom. Repeated endpoint actions +left the geometry unchanged. The old gate incorrectly required all those +offscreen content frames to fit one capture. Local real top/bottom images +confirmed the retained labels and the old suggestion control, without any +preference change. This is **development diagnosis, not independent signoff**; +its original diagnostic-only BLOCKED result is retained separately. +The subsequent single author development run reached **FAIL / +rendered_output_mismatch** on OLD, with both retained assertions true and +`suggestionControlAbsent=false`. Its two real PNGs, native counts, restoration +and interpretation are retained under the primary checkout's ignored +`.local/vm-regression/evidence/ai-remediation-1-devcheck/`. This is not an +independent wrong-behavior signoff or a retry promoted to verification. +Per-app allow-list values are left untouched; their mutation behavior is not +claimed by these two retained-label assertions. + +Reuse the existing exact installed path `/Applications/notch-pocket.app`, bundle +ID, version/build, executable hash, running PID, guest/session checks, before/after +signature validation, run identity, one-native-test counts, screenshot digest, +job lifecycle, exclusive lock and LIFO teardown. No app rebuild/signing dependency +is added to the standalone harness. Closed Settings returns to General and is +closed; pre-existing General/About stays open on its original pane, including +About build visibility. Other original panes remain unsupported. Original +window size, preferences, shelf, app lifecycle and About controls are not changed. +This does not extend restoration to arbitrary panes or claim exact OS focus. + +## Independent wrong-behavior proof + +Run this **same harness scenario and assertions** against the **previous-face +candidate already installed in run02**, source +`2e28bd1920265ee30d8761ad03c0b420e3f2168b`, executable SHA-256 +`7a30c4d4939da81c165744050bc38e0a91ea699786cddd605de9c4735d6c5aa0`. +The independent worker must verify the supplied guest artifact against its +preparation provenance (`face-candidate-2e28bd1-preparation/provenance.json` in +the primary checkout's ignored evidence directory). It is **not the host +installation or the older PR97 preview** documented for Appearance; do not copy +host install evidence or substitute artifacts. Both apps may identify themselves +as **0.1.0 (272)**; version equality is not source provenance or identity. + +Expect old-app **FAIL / rendered_output_mismatch**, with +`suggestionControlAbsent=false`, the retained output present, two bound captures +and verified restoration. A BLOCKED run is not negative proof. Then run the +exact new candidate, expecting **PASS / rendered_output_verified**. Do not +weaken assertions, register old behavior as an expected new-app failure or +replace any existing control. Keep all earlier failed/blocked reports. + +The independent report must record both old/new executable hashes, app paths, +before/after signature and integrity checks, source revision and build provenance +(including the diff digest for uncommitted source), deployed harness/source +hashes, registry/runner identity, receipt/capture digests and actual dispatch +identity. The minimal launcher manifest cannot replace this provenance. +Unavailable provenance is a gap. Run the OLD candidate only for this one +wrong-behavior scenario. The worker must run the full eight-case registry on the +**NEW candidate only**, exercising the existing closed, pre-existing General +and pre-existing About fixtures without modifying the seven prior cases. + +Author development evidence is scoped to diagnosis and the old-candidate +scenario; it is not an independent report or full-suite result. Permission-free +checks cover source boundaries, the output oracle and strict receipt/export +policy, not native behavior. Fresh independent old/new comparison and the +NEW-only full registry still remain parent-owned. No manual reply delivery or +separate `canReply` false-positive classification is certified. + +## Remediation-only scope + +The current remediation above `8844ddf` changes **AI-NATIVE** harness, +Notifications oracle, shared capture contract, export/evaluation and scenario +documentation; **AI-CONTRACT** policy/oracle tests and coverage documentation. +It does not alter product source, signatures, preferences, configuration, +the eight-entry registry, or the seven prior native scenarios. Both manual +FocusState listeners remain intact. The ledger below also records the earlier +removal work; it does not authorize new AI-REMOVE changes in this remediation. + +## Removal and preservation trace + +`SmartReplyManager`, `SmartReplyAvailability` and `ReplySuggestionSet` were only +used by Notification Settings availability and the expanded reply row's generation +task/chips. `FoundationModels`, `SystemLanguageModel`, `LanguageModelSession`, +`@Generable` and `@Guide` had no other product uses. Framework loading was through +the manager's guarded import/autolinking, with **no explicit FoundationModels +framework/project link** to remove. Delete the manager's four project references. +`Foundation`, `SwiftUI`, the shared `Defaults` package and other frameworks remain; +only the now-unused `Defaults` import in NotificationLiveActivity is removed. + +Manual TextField/Send, draft load/save/clear-on-success, pull-only focus, +key-window/compose holds and teardown, timeout/error retention and distinct +sent/drafted/clipboard handoff outcomes remain. The notification source, manager, +watcher, shared/client protocols, Contacts integration and manual delivery +fallbacks are not edited. The separate `canReply` false-positive issue is +**not repaired or certified** here. Historical `smartRepliesEnabled=true` data is +ignored, not migrated/deleted. `Localizable.xcstrings` is unchanged; stale +translations remain for catalog-owner maintenance. + +| Ledger | Repository-relative path | Hunk | +| --- | --- | --- | +| AI-REMOVE | `notchPocket/managers/SmartReplyManager.swift` | Delete suggestion-only manager, availability/model types and framework import | +| AI-REMOVE | `notchPocket/components/Notch/NotificationLiveActivity.swift` | Delete suggestion state, task/chips, unused import and suggestion-specific comments; retain manual code | +| AI-REMOVE | `notchPocket/components/Settings/Views/NotificationSettingsView.swift` | Delete suggestion section and availability/footer helpers only | +| AI-REMOVE | `notchPocket/models/Constants.swift` | Delete suggestion default only | +| AI-REMOVE | `notchPocket.xcodeproj/project.pbxproj` | Delete four manager build/file/group/source references | +| AI-CONTRACT | `scripts/tests/test_regression_probe.py` | Add source-removal and retained manual/settings/source-path contracts | +| AI-CONTRACT | `README.md` | Document suggestion removal, retained manual behavior and ignored legacy preference | +| AI-CONTRACT | `docs/regression-coverage.md` | Remove obsolete generation coverage; record Settings coverage and native gaps | +| AI-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift` | Add Notifications selector/navigation, structural viewport proof and output dispatch; reuse lifecycle/restoration | +| AI-NATIVE | `experiments/tart-regression/GuestRegressionProbe/SettingsRemovalOutputOracle.swift` | Notifications descriptor/oracle, now shared with General haptic removal; retains existing same-row OCR helper | +| AI-NATIVE | `experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.xcodeproj/project.pbxproj` | Register new standalone oracle source | +| AI-NATIVE | `experiments/tart-regression/run-suite.py` | Add exact Notifications assertion/discovery validation; preserve transport/export/lock contracts | +| AI-NATIVE | `experiments/tart-regression/capture_contract.py` | Shared exact two-capture schema, endpoint/overlap/identity and aggregate-output checks | +| AI-NATIVE | `experiments/tart-regression/GuestRegressionProbe/run-guest.py` | Validate Notifications multi-capture evidence; retain legacy single-capture checks | +| AI-NATIVE | `experiments/tart-regression/suite.json` | Append one functional case; retain all seven existing cases | +| AI-NATIVE | `experiments/tart-regression/OracleContractTests.swift` | Add positive/missing/wrong/old Notifications output cases; retain prior cases | +| AI-NATIVE | `experiments/tart-regression/test-oracle.sh` | Compile new oracle in existing permission-free runner | +| AI-NATIVE | `scripts/tests/test_regression_probe.py` | Extend registry, receipt consistency, native-query and old-artifact provenance contracts | +| AI-NATIVE | `experiments/tart-regression/README.md` | Document third journey, exact old guest provenance and bounded viewport coverage | +| AI-NATIVE | `experiments/tart-regression/scenarios/notifications-ai-replies-removed.md` | Scenario, fixture, negative proof, limits and ledger | diff --git a/experiments/tart-regression/suite.json b/experiments/tart-regression/suite.json index 18e5890382..ae28705f99 100644 --- a/experiments/tart-regression/suite.json +++ b/experiments/tart-regression/suite.json @@ -54,6 +54,69 @@ "expectedVerdict": "BLOCKED", "expectedReason": "native_interaction_aborted", "notes": "scenarios/about-version.md" + }, + { + "id": "appearance-idle-face-removed", + "kind": "regression", + "scenario": "appearance-idle-face-removed", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledAppearanceWithoutIdleFace", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/appearance-idle-face-removed.md" + }, + { + "id": "notifications-ai-replies-removed", + "kind": "regression", + "scenario": "notifications-ai-replies-removed", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledNotificationsWithoutAIReplies", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/notifications-ai-replies-removed.md" + }, + { + "id": "general-haptics-removed", + "kind": "regression", + "scenario": "general-haptics-removed", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutHaptics", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/general-haptics-removed.md" + }, + { + "id": "general-panel-swipes-removed", + "kind": "regression", + "scenario": "general-panel-swipes-removed", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutPanelSwipes", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/general-panel-swipes-removed.md" + }, + { + "id": "general-compact-mode-removed", + "kind": "regression", + "scenario": "general-compact-mode-removed", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledGeneralWithoutCompactMode", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/general-compact-mode-removed.md" + }, + { + "id": "music-idle-no-target", + "kind": "regression", + "scenario": "music-idle-no-target", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledIdleMusicWithoutTarget", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/music-idle-launcher.md" + }, + { + "id": "music-idle-unavailable", + "kind": "regression", + "scenario": "music-idle-unavailable", + "test": "GuestRegressionProbe/GuestRegressionProbe/testInstalledIdleMusicUnavailableTarget", + "expectedVerdict": "PASS", + "expectedReason": "rendered_output_verified", + "notes": "scenarios/music-idle-launcher.md" } ] } diff --git a/experiments/tart-regression/test-oracle.sh b/experiments/tart-regression/test-oracle.sh index e01c8152b8..a1d1ffb6e5 100644 --- a/experiments/tart-regression/test-oracle.sh +++ b/experiments/tart-regression/test-oracle.sh @@ -11,5 +11,8 @@ mkdir -p "$1" exit 2 } xcrun swiftc "$source_root/GuestRegressionProbe/AboutOutputOracle.swift" \ + "$source_root/GuestRegressionProbe/AppearanceOutputOracle.swift" \ + "$source_root/GuestRegressionProbe/SettingsRemovalOutputOracle.swift" \ + "$source_root/GuestRegressionProbe/IdleMusicOutputOracle.swift" \ "$source_root/OracleContractTests.swift" -o "$1/oracle-contract-tests" "$1/oracle-contract-tests" diff --git a/notchPocket.xcodeproj/project.pbxproj b/notchPocket.xcodeproj/project.pbxproj index cc16e53e69..087c32dc08 100644 --- a/notchPocket.xcodeproj/project.pbxproj +++ b/notchPocket.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 530000072026100200000001 /* MusicSliderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 530000082026100200000001 /* MusicSliderView.swift */; }; + 530000052026100200000001 /* MusicLaunchTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 530000062026100200000001 /* MusicLaunchTransaction.swift */; }; + 530000012026091500000001 /* MusicAppLauncher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 530000022026091500000001 /* MusicAppLauncher.swift */; }; + 530000032026091500000001 /* MusicSectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 530000042026091500000001 /* MusicSectionView.swift */; }; CAC000062026091200000001 /* GraphCalendarPayloadDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAC000072026091200000001 /* GraphCalendarPayloadDecoder.swift */; }; CAC000042026091200000001 /* GraphCalendarCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAC000052026091200000001 /* GraphCalendarCore.swift */; }; CAC000012026091200000001 /* CalendarCoreModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAC000022026091200000001 /* CalendarCoreModels.swift */; }; @@ -128,7 +132,6 @@ 14D0321A2C68F32E0096E6A1 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 14D032192C68F32E0096E6A1 /* LaunchAtLogin */; }; 14D570B92C5E98A20011E668 /* drop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570B82C5E98A20011E668 /* drop.swift */; }; 14D570BC2C5E98EB0011E668 /* generic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570BB2C5E98EB0011E668 /* generic.swift */; }; - 14D570C02C5EA5870011E668 /* AnimatedFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570BF2C5EA5870011E668 /* AnimatedFace.swift */; }; 14D570C62C5F38210011E668 /* NotchPocketHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570C52C5F38210011E668 /* NotchPocketHeader.swift */; }; 14D570C92C5F38890011E668 /* NotchPocketViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570C82C5F38890011E668 /* NotchPocketViewModel.swift */; }; 14D570CB2C5F4B2C0011E668 /* BatteryStatusViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D570CA2C5F4B2C0011E668 /* BatteryStatusViewModel.swift */; }; @@ -161,8 +164,7 @@ AA02NSV12E7A0001 /* NotificationSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA02NSV22E7A0001 /* NotificationSettingsView.swift */; }; AA03OTP12E7A0001 /* OTPDetector.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA03OTP22E7A0001 /* OTPDetector.swift */; }; AA04LAS12E7A0001 /* LiveActivityStack.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA04LAS22E7A0001 /* LiveActivityStack.swift */; }; - AA05SRM12E7A0001 /* SmartReplyManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA05SRM22E7A0001 /* SmartReplyManager.swift */; }; - AA06CHV12E7A0001 /* CompactHomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA06CHV22E7A0001 /* CompactHomeView.swift */; }; + AA06CHV12E7A0001 /* MediaOutputSlotButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA06CHV22E7A0001 /* MediaOutputSlotButton.swift */; }; AA07ARM12E7A0001 /* AudioRouteManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA07ARM22E7A0001 /* AudioRouteManager.swift */; }; AFA82F21304B406590337862 /* ShelfContextMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = E49B58CAC648403F864E6D78 /* ShelfContextMenu.swift */; }; B10348D92C74E56000475897 /* ConditionalModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = B10348D82C74E56000475897 /* ConditionalModifier.swift */; }; @@ -235,6 +237,10 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 530000082026100200000001 /* MusicSliderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicSliderView.swift; sourceTree = ""; }; + 530000062026100200000001 /* MusicLaunchTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicLaunchTransaction.swift; sourceTree = ""; }; + 530000022026091500000001 /* MusicAppLauncher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicAppLauncher.swift; sourceTree = ""; }; + 530000042026091500000001 /* MusicSectionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicSectionView.swift; sourceTree = ""; }; CAC000072026091200000001 /* GraphCalendarPayloadDecoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GraphCalendarPayloadDecoder.swift; sourceTree = ""; }; CAC000052026091200000001 /* GraphCalendarCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GraphCalendarCore.swift; sourceTree = ""; }; CAC000022026091200000001 /* CalendarCoreModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalendarCoreModels.swift; sourceTree = ""; }; @@ -353,7 +359,6 @@ 14D031EF2C689DC00096E6A1 /* ApplicationServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ApplicationServices.framework; path = System/Library/Frameworks/ApplicationServices.framework; sourceTree = SDKROOT; }; 14D570B82C5E98A20011E668 /* drop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = drop.swift; sourceTree = ""; }; 14D570BB2C5E98EB0011E668 /* generic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = generic.swift; sourceTree = ""; }; - 14D570BF2C5EA5870011E668 /* AnimatedFace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnimatedFace.swift; sourceTree = ""; }; 14D570C52C5F38210011E668 /* NotchPocketHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchPocketHeader.swift; sourceTree = ""; }; 14D570C82C5F38890011E668 /* NotchPocketViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchPocketViewModel.swift; sourceTree = ""; }; 14D570CA2C5F4B2C0011E668 /* BatteryStatusViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BatteryStatusViewModel.swift; sourceTree = ""; }; @@ -383,8 +388,7 @@ AA02NSV22E7A0001 /* NotificationSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationSettingsView.swift; sourceTree = ""; }; AA03OTP22E7A0001 /* OTPDetector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OTPDetector.swift; sourceTree = ""; }; AA04LAS22E7A0001 /* LiveActivityStack.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityStack.swift; sourceTree = ""; }; - AA05SRM22E7A0001 /* SmartReplyManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmartReplyManager.swift; sourceTree = ""; }; - AA06CHV22E7A0001 /* CompactHomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompactHomeView.swift; sourceTree = ""; }; + AA06CHV22E7A0001 /* MediaOutputSlotButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaOutputSlotButton.swift; sourceTree = ""; }; AA07ARM22E7A0001 /* AudioRouteManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioRouteManager.swift; sourceTree = ""; }; AFAD1670A870402D88BFFE47 /* AudioOutputRouteResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioOutputRouteResolver.swift; sourceTree = ""; }; B0C26F24108F414781F79D4F /* AppleScriptControllerSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleScriptControllerSupport.swift; sourceTree = ""; }; @@ -571,6 +575,8 @@ 1153BD8D2D986B1F00979FB0 /* MediaControllerProtocol.swift */, 1153BD922D986E4300979FB0 /* AppleMusicController.swift */, 61F20E44C65E4DA1945BFF5C /* MediaAppBundleID.swift */, + 530000022026091500000001 /* MusicAppLauncher.swift */, + 530000062026100200000001 /* MusicLaunchTransaction.swift */, B0C26F24108F414781F79D4F /* AppleScriptControllerSupport.swift */, 1153BD992D98824300979FB0 /* SpotifyController.swift */, 1153BD9B2D98853B00979FB0 /* NowPlayingController.swift */, @@ -714,7 +720,6 @@ B186542F2C6F455E000B926A /* Notch */, 9A0887332C7AFF7E00C160EA /* Tabs */, B186542E2C6F453B000B926A /* Music */, - 14D570BF2C5EA5870011E668 /* AnimatedFace.swift */, 507266DA2C908E2E00A2D00D /* HoverButton.swift */, 0268933F488E47DFB58E48CF /* VisualEffectView.swift */, ); @@ -733,7 +738,6 @@ AA02CAM22E7A0001 /* ContactAvatarManager.swift */, 147163992C5D35FF0068B555 /* MusicManager.swift */, AA07ARM22E7A0001 /* AudioRouteManager.swift */, - AA05SRM22E7A0001 /* SmartReplyManager.swift */, F1F2A0A200000000000000F2 /* AudioCaptureManager.swift */, 149E0B962C737D00006418B1 /* WebcamManager.swift */, 14C08BB52C8DE42D000F8AA0 /* CalendarManager.swift */, @@ -932,6 +936,8 @@ B186542E2C6F453B000B926A /* Music */ = { isa = PBXGroup; children = ( + 530000042026091500000001 /* MusicSectionView.swift */, + 530000082026100200000001 /* MusicSliderView.swift */, 147163972C5D35B70068B555 /* MusicVisualizer.swift */, ); path = Music; @@ -941,7 +947,7 @@ isa = PBXGroup; children = ( AA01NLA22E7A0001 /* NotificationLiveActivity.swift */, - AA06CHV22E7A0001 /* CompactHomeView.swift */, + AA06CHV22E7A0001 /* MediaOutputSlotButton.swift */, AA04LAS22E7A0001 /* LiveActivityStack.swift */, 1194E8862EA6DDA7009C82D6 /* NotchPocketSkyLightWindow.swift */, 1160F8D72DD98230006FBB94 /* NotchShape.swift */, @@ -1192,7 +1198,6 @@ B1D365CE2C6A979C0047BDBC /* LiveActivityModifier.swift in Sources */, 1113ABD02E80E6BB00EC13B2 /* ThumbnailService.swift in Sources */, 11CFC65B2E097E9D00748C80 /* WelcomeView.swift in Sources */, - 14D570C02C5EA5870011E668 /* AnimatedFace.swift in Sources */, 111BE9952ECF2DF40079DD4E /* DragDetector.swift in Sources */, B1D365D02C6A9A6C0047BDBC /* SystemEventIndicatorModifier.swift in Sources */, 1194E87C2EA19E09009C82D6 /* ImageProcessingService.swift in Sources */, @@ -1233,13 +1238,16 @@ AA01SNM12E7A0001 /* SystemNotificationManager.swift in Sources */, AA01NDW12E7A0001 /* NotificationDebugWindow.swift in Sources */, AA01NLA12E7A0001 /* NotificationLiveActivity.swift in Sources */, - AA06CHV12E7A0001 /* CompactHomeView.swift in Sources */, + AA06CHV12E7A0001 /* MediaOutputSlotButton.swift in Sources */, AA04LAS12E7A0001 /* LiveActivityStack.swift in Sources */, AA02CAM12E7A0001 /* ContactAvatarManager.swift in Sources */, AA03OTP12E7A0001 /* OTPDetector.swift in Sources */, 1471639A2C5D35FF0068B555 /* MusicManager.swift in Sources */, + 530000012026091500000001 /* MusicAppLauncher.swift in Sources */, + 530000052026100200000001 /* MusicLaunchTransaction.swift in Sources */, + 530000032026091500000001 /* MusicSectionView.swift in Sources */, + 530000072026100200000001 /* MusicSliderView.swift in Sources */, AA07ARM12E7A0001 /* AudioRouteManager.swift in Sources */, - AA05SRM12E7A0001 /* SmartReplyManager.swift in Sources */, F1F2A0A100000000000000F1 /* AudioCaptureManager.swift in Sources */, B1B112932C6A577E00093D8F /* MouseTracker.swift in Sources */, B1C448962C9712C4001F0858 /* ActionBar.swift in Sources */, diff --git a/notchPocket/ContentView.swift b/notchPocket/ContentView.swift index 8e56f83f19..5dff1a8bcd 100644 --- a/notchPocket/ContentView.swift +++ b/notchPocket/ContentView.swift @@ -28,19 +28,17 @@ struct ContentView: View { @State private var activityIndex: Int = 0 @State private var hoverTask: Task? @State private var isHovering: Bool = false + @State private var musicLaunchInteractionActive = false + @State private var isHoveringMusicLaunchFeedback = false @State private var anyDropDebounceTask: Task? - @State private var gestureProgress: CGFloat = .zero + @State private var mediaGestureProgress: CGFloat = .zero @State private var horizontalMediaGestureTriggered = false @State private var horizontalMediaGestureFeedback: CGFloat = .zero @State private var isHoveringMusicArea = false - @State private var haptics: Bool = false - @Namespace var albumArtNamespace - @Default(.showNotHumanFace) var showNotHumanFace - // Use standardized animations from StandardAnimations enum private let animationSpring = StandardAnimations.interactive @@ -56,16 +54,10 @@ struct ContentView: View { return effectiveHeight / 38.0 } - /// Compact mode gets a rounder opened shape (35 vs 19) — at its smaller - /// size the standard radius reads square rather than pill-like. - private var openedInsets: (top: CGFloat, bottom: CGFloat) { - Defaults[.compactMode] ? compactCornerRadiusInsets.opened : cornerRadiusInsets.opened - } - private var topCornerRadius: CGFloat { // If the notch is open, return the opened radius. if vm.notchState == .open { - return openedInsets.top + return cornerRadiusInsets.opened.top } // For the closed notch, scale if enabled @@ -82,7 +74,7 @@ struct ContentView: View { let bottomCorner: CGFloat if vm.notchState == .open { - bottomCorner = openedInsets.bottom + bottomCorner = cornerRadiusInsets.opened.bottom } else if let scaleFactor = cornerRadiusScaleFactor { bottomCorner = max(0, baseClosedBottom * scaleFactor) } else { @@ -119,27 +111,14 @@ struct ContentView: View { /// A notification is a glance, not a workspace — it doesn't need the full /// height the home/shelf tabs are sized for, and stretching to fill it /// just surrounds two lines of text with empty black. - /// nil means "size to content". - /// - /// Compact mode must use nil: this frame bounds hit-testing as well as - /// layout, so any value shorter than the content leaves the transport - /// row outside the hover region — moving toward the buttons registered - /// as a hover-exit and closed the notch. The compact panel's height is - /// controlled by its own internal padding instead, which is the honest - /// lever anyway. - private var openNotchHeight: CGFloat? { + private var openNotchHeight: CGFloat { if notificationManager.activeNotification != nil { return 132 } - return Defaults[.compactMode] ? nil : vm.notchSize.height + return vm.notchSize.height } - /// Compact mode drops the tab bar along with the tabs it switches - /// between — there's only the player to show, so a switcher would have - /// nothing to switch to. Also what keeps the panel narrow, since the - /// header spans the full notch width. private var showsHeader: Bool { vm.notchState == .open && notificationManager.activeNotification == nil - && !Defaults[.compactMode] } /// The activity currently on top of the stack — what the chin has to be @@ -182,11 +161,6 @@ struct ContentView: View { chinWidth += 2 * inlineMusicPeekLabelWidth } } - } else if !coordinator.expandingView.show && vm.notchState == .closed - && (!musicManager.isPlaying && musicManager.isPlayerIdle) && Defaults[.showNotHumanFace] - && !vm.hideOnClosed - { - chinWidth += (2 * max(0, displayClosedNotchHeight - 12) + 20) } return chinWidth @@ -216,12 +190,7 @@ struct ContentView: View { var body: some View { @Bindable var dropInteraction = vm.dropInteraction - // Calculate scale based on gesture progress only - let gestureScale: CGFloat = { - guard gestureProgress != 0 else { return 1.0 } - let scaleFactor = 1.0 + gestureProgress * 0.01 - return max(0.6, scaleFactor) - }() + let mediaGestureScale = 1.0 + mediaGestureProgress * 0.01 ZStack(alignment: .top) { VStack(spacing: 0) { @@ -229,7 +198,7 @@ struct ContentView: View { .frame(alignment: .top) .padding( .horizontal, - vm.notchState == .open ? openedInsets.top : cornerRadiusInsets.closed.bottom + vm.notchState == .open ? cornerRadiusInsets.opened.top : cornerRadiusInsets.closed.bottom ) .padding([.horizontal, .bottom], vm.notchState == .open ? 12 : 0) .background(.black) @@ -260,30 +229,29 @@ struct ContentView: View { .conditionalModifier(true) { view in return view .animation(vm.notchState == .open ? StandardAnimations.open : StandardAnimations.close, value: vm.notchState) - .animation(.smooth, value: gestureProgress) + .animation(.smooth, value: mediaGestureProgress) } .contentShape(Rectangle()) .onHover { hovering in handleHover(hovering) } + .onPreferenceChange(MusicLaunchInteractionPreferenceKey.self) { active in + musicLaunchInteractionActive = active + } + .onPreferenceChange(MusicLaunchFeedbackHoverPreferenceKey.self) { hovering in + isHoveringMusicLaunchFeedback = hovering + } + .onChange(of: musicLaunchInteractionActive) { _, active in + if !active && !isHovering && vm.notchState == .open { + handleHover(false) + } + } .onTapGesture { if vm.notchState == .closed && !shouldDisplayNowPlayingFallbackNotice { doOpen() } } - .conditionalModifier(Defaults[.enableGestures] && !shouldDisplayNowPlayingFallbackNotice) { view in - view - .panGesture(direction: .down) { translation, phase in - handleDownGesture(translation: translation, phase: phase) - } - } - .conditionalModifier(Defaults[.closeGestureEnabled] && Defaults[.enableGestures] && !shouldDisplayNowPlayingFallbackNotice) { view in - view - .panGesture(direction: .up) { translation, phase in - handleUpGesture(translation: translation, phase: phase) - } - } - .conditionalModifier(Defaults[.enableHorizontalMediaGestures] && Defaults[.enableGestures] && !shouldDisplayNowPlayingFallbackNotice) { view in + .conditionalModifier(Defaults[.enableHorizontalMediaGestures] && Defaults[.enableMediaGestures] && !shouldDisplayNowPlayingFallbackNotice) { view in view .panGesture(direction: .left) { translation, phase in handleNextTrackGesture(translation: translation, phase: phase) @@ -293,13 +261,14 @@ struct ContentView: View { } } .onReceive(NotificationCenter.default.publisher(for: .sharingDidFinish)) { _ in - if vm.notchState == .open && !isHovering && !vm.isBatteryPopoverActive { + if vm.notchState == .open && !isHovering && !vm.isBatteryPopoverActive && !musicLaunchInteractionActive { hoverTask?.cancel() hoverTask = Task { try? await Task.sleep(for: .milliseconds(100)) guard !Task.isCancelled else { return } await MainActor.run { - if self.vm.notchState == .open && !self.isHovering && !self.vm.isBatteryPopoverActive && !SharingStateManager.shared.preventNotchClose { + if self.vm.notchState == .open && !self.isHovering && !self.vm.isBatteryPopoverActive + && !self.musicLaunchInteractionActive && !SharingStateManager.shared.preventNotchClose { self.vm.close() } } @@ -321,6 +290,10 @@ struct ContentView: View { } } .onDisappear { + hoverTask?.cancel() + hoverTask = nil + musicLaunchInteractionActive = false + isHoveringMusicLaunchFeedback = false // Balance the refcount: torn down while open (screen // lock, display-set change, window teardown) means the // open->closed onChange never fires — without this the @@ -342,20 +315,21 @@ struct ContentView: View { if activityIndex >= count { activityIndex = max(count - 1, 0) } } .onChange(of: vm.isBatteryPopoverActive) { - if !vm.isBatteryPopoverActive && !isHovering && vm.notchState == .open && !SharingStateManager.shared.preventNotchClose { + if !vm.isBatteryPopoverActive && !isHovering && vm.notchState == .open + && !musicLaunchInteractionActive && !SharingStateManager.shared.preventNotchClose { hoverTask?.cancel() hoverTask = Task { try? await Task.sleep(for: .milliseconds(100)) guard !Task.isCancelled else { return } await MainActor.run { - if !self.vm.isBatteryPopoverActive && !self.isHovering && self.vm.notchState == .open && !SharingStateManager.shared.preventNotchClose { + if !self.vm.isBatteryPopoverActive && !self.isHovering && self.vm.notchState == .open + && !self.musicLaunchInteractionActive && !SharingStateManager.shared.preventNotchClose { self.vm.close() } } } } } - .sensoryFeedback(.alignment, trigger: haptics) .contextMenu { Button("Settings") { DispatchQueue.main.async { @@ -381,11 +355,11 @@ struct ContentView: View { .ignoresSafeArea(.all) .compositingGroup() .scaleEffect( - x: gestureScale, - y: gestureScale, + x: mediaGestureScale, + y: mediaGestureScale, anchor: .top ) - .animation(.smooth, value: gestureProgress) + .animation(.smooth, value: mediaGestureProgress) .background(dragDetector) .preferredColorScheme(.dark) .environmentObject(vm) @@ -474,7 +448,7 @@ struct ContentView: View { icon: coordinator.binding(for: vm.screenUUID).icon, accent: coordinator.binding(for: vm.screenUUID).accent, hoverAnimation: $isHovering, - gestureProgress: $gestureProgress + mediaGestureProgress: $mediaGestureProgress ) .transition(.opacity) } else if !liveActivities.isEmpty && vm.notchState == .closed && !vm.hideOnClosed { @@ -487,8 +461,6 @@ struct ContentView: View { .frame(alignment: .center) } } - } else if !coordinator.expandingView.show && vm.notchState == .closed && (!musicManager.isPlaying && musicManager.isPlayerIdle) && Defaults[.showNotHumanFace] && !vm.hideOnClosed { - NotchPocketFaceAnimation() } else if showsHeader { // No tab bar over a notification: it's a glance, // not a place to switch between home and shelf — @@ -497,7 +469,7 @@ struct ContentView: View { // out around a short message. NotchPocketHeader() .frame(height: max(24, displayClosedNotchHeight)) - .opacity(gestureProgress != 0 ? 1.0 - min(abs(gestureProgress) * 0.1, 0.3) : 1.0) + .opacity(mediaGestureProgress != 0 ? 1.0 - min(abs(mediaGestureProgress) * 0.1, 0.3) : 1.0) } // New case to enable compact notch on external displays else if !vm.hasNotch { @@ -555,15 +527,6 @@ struct ContentView: View { // reply UI — the usual tabs can wait until it's dismissed. if let notification = notificationManager.activeNotification { NotificationExpandedView(notification: notification) - } else if Defaults[.compactMode] { - // Player only — no tab switching, so currentView is - // ignored here rather than offering a shelf the - // compact layout has no room (or tab bar) for. - // 336 = Atoll's 420 base less 20%, which also lands - // within a few points of their Dynamic Island width - // (340) — the tighter of their two compact sizes. - CompactHomeView(albumArtNamespace: albumArtNamespace) - .frame(width: 336) } else { switch coordinator.currentView { case .dashboard: @@ -592,7 +555,7 @@ struct ContentView: View { ) .zIndex(1) .allowsHitTesting(vm.notchState == .open) - .opacity(gestureProgress != 0 ? 1.0 - min(abs(gestureProgress) * 0.1, 0.3) : 1.0) + .opacity(mediaGestureProgress != 0 ? 1.0 - min(abs(mediaGestureProgress) * 0.1, 0.3) : 1.0) } } .onDrop(of: [.fileURL, .url, .utf8PlainText, .plainText, .data], delegate: GeneralDropTargetDelegate(isTargeted: $dropInteraction.generalDropTargeting)) @@ -643,20 +606,6 @@ struct ContentView: View { ) } - @ViewBuilder - func NotchPocketFaceAnimation() -> some View { - HStack { - Rectangle() - .fill(.black) - .frame(width: vm.closedNotchSize.width + 20) - let faceScale = min(1.0, displayClosedNotchHeight / 30.0) - AnimatedFace(height: 24.0 * faceScale, width: 30.0 * faceScale) - }.frame( - height: displayClosedNotchHeight, - alignment: .center - ) - } - /// True while the song-change peek is expanding the closed pill inline. private var showingInlineMusicPeek: Bool { coordinator.expandingView.show @@ -774,7 +723,7 @@ struct ContentView: View { width: max( 0, displayClosedNotchHeight - 12 - + gestureProgress / 2 + + mediaGestureProgress / 2 ), height: max( 0, @@ -836,10 +785,6 @@ struct ContentView: View { notificationManager.holdActive() } - if vm.notchState == .closed && Defaults[.enableHaptics] { - haptics.toggle() - } - guard vm.notchState == .closed, !shouldDisplayNowPlayingFallbackNotice, !coordinator.shouldShowSneakPeek(on: vm.screenUUID), @@ -871,7 +816,8 @@ struct ContentView: View { // Pointer left — let the notification age out again. self.notificationManager.resumeDismiss() - if self.vm.notchState == .open && !self.vm.isBatteryPopoverActive && !SharingStateManager.shared.preventNotchClose { + if self.vm.notchState == .open && !self.vm.isBatteryPopoverActive + && !self.musicLaunchInteractionActive && !SharingStateManager.shared.preventNotchClose { self.vm.close() } } @@ -879,58 +825,7 @@ struct ContentView: View { } } - // MARK: - Gesture Handling - - private func handleDownGesture(translation: CGFloat, phase: NSEvent.Phase) { - guard vm.notchState == .closed else { return } - - if phase == .ended { - withAnimation(animationSpring) { gestureProgress = .zero } - return - } - - withAnimation(animationSpring) { - gestureProgress = (translation / Defaults[.gestureSensitivity]) * 20 - } - - if translation > Defaults[.gestureSensitivity] { - if Defaults[.enableHaptics] { - haptics.toggle() - } - withAnimation(animationSpring) { - gestureProgress = .zero - } - doOpen() - } - } - - private func handleUpGesture(translation: CGFloat, phase: NSEvent.Phase) { - guard vm.notchState == .open && !vm.isHoveringCalendar else { return } - - withAnimation(animationSpring) { - gestureProgress = (translation / Defaults[.gestureSensitivity]) * -20 - } - - if phase == .ended { - withAnimation(animationSpring) { - gestureProgress = .zero - } - } - - if translation > Defaults[.gestureSensitivity] { - withAnimation(animationSpring) { - isHovering = false - } - if !SharingStateManager.shared.preventNotchClose { - gestureProgress = .zero - vm.close() - } - - if Defaults[.enableHaptics] { - haptics.toggle() - } - } - } + // MARK: - Media Gesture Handling private func handleNextTrackGesture(translation: CGFloat, phase: NSEvent.Phase) { handleHorizontalMediaGesture(translation: translation, phase: phase, feedback: -1) { @@ -950,7 +845,7 @@ struct ContentView: View { feedback: CGFloat, action: () -> Void ) { - guard isHorizontalMediaGestureContext else { + guard isHorizontalMediaGestureContext && !isHoveringMusicLaunchFeedback else { resetHorizontalMediaGesture() return } @@ -964,10 +859,6 @@ struct ContentView: View { horizontalMediaGestureTriggered = true triggerHorizontalMediaFeedback(feedback) action() - - if Defaults[.enableHaptics] { - haptics.toggle() - } } private func resetHorizontalMediaGesture() { @@ -978,7 +869,7 @@ struct ContentView: View { withAnimation(.interactiveSpring(response: 0.18, dampingFraction: 0.62)) { horizontalMediaGestureFeedback = feedback if vm.notchState == .closed { - gestureProgress = 2 + mediaGestureProgress = 2 } } @@ -986,9 +877,7 @@ struct ContentView: View { try? await Task.sleep(for: .milliseconds(140)) withAnimation(animationSpring) { horizontalMediaGestureFeedback = .zero - if vm.notchState == .closed { - gestureProgress = .zero - } + mediaGestureProgress = .zero } } } diff --git a/notchPocket/Localizable.xcstrings b/notchPocket/Localizable.xcstrings index b159d108a8..9bac18eac8 100644 --- a/notchPocket/Localizable.xcstrings +++ b/notchPocket/Localizable.xcstrings @@ -12,6 +12,9 @@ } }, "%lld shelf items" : {}, + "A music app open is still pending." : {}, + "A previous music app open request is still pending. Check Applications before trying again." : {}, + "Opens the current music app without starting playback." : {}, "Add Shelf Summary" : {}, "Close and reopen the panel after the configuration issue is resolved." : {}, "Dashboard" : {}, @@ -206,6 +209,17 @@ } } }, + "%@ is not installed." : { + "comment" : "Concise music launcher failure. The placeholder is a human-readable music app name.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ is not installed." + } + } + } + }, "%@x" : { "comment" : "Animation speed multiplier." }, @@ -5337,124 +5351,6 @@ } } }, - "Close gesture" : { - "localizations" : { - "cs" : { - "stringUnit" : { - "state" : "translated", - "value" : "Gesto zavření" - } - }, - "de" : { - "stringUnit" : { - "state" : "translated", - "value" : "Schließgeste" - } - }, - "en" : { - "stringUnit" : { - "state" : "translated", - "value" : "Close gesture" - } - }, - "en-GB" : { - "stringUnit" : { - "state" : "translated", - "value" : "Close gesture" - } - }, - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "Gesto de cerrar" - } - }, - "fr" : { - "stringUnit" : { - "state" : "translated", - "value" : "Geste de fermeture" - } - }, - "he" : { - "stringUnit" : { - "state" : "translated", - "value" : "מחווה לסגירה" - } - }, - "hu" : { - "stringUnit" : { - "state" : "translated", - "value" : "Bezárási gesztus" - } - }, - "it" : { - "stringUnit" : { - "state" : "translated", - "value" : "Gesto di chiusura" - } - }, - "ja" : { - "stringUnit" : { - "state" : "translated", - "value" : "閉じるジェスチャー" - } - }, - "ko" : { - "stringUnit" : { - "state" : "translated", - "value" : "닫기 제스처" - } - }, - "nl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Sluit gebaar" - } - }, - "pl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Gest zamknięcia" - } - }, - "pt-BR" : { - "stringUnit" : { - "state" : "translated", - "value" : "Gesto de fechar" - } - }, - "ru" : { - "stringUnit" : { - "state" : "translated", - "value" : "Жест закрытия" - } - }, - "tr" : { - "stringUnit" : { - "state" : "translated", - "value" : "El hareketlerini kapat" - } - }, - "uk" : { - "stringUnit" : { - "state" : "translated", - "value" : "Жест вимкнення" - } - }, - "zh-Hans" : { - "stringUnit" : { - "state" : "translated", - "value" : "关闭手势" - } - }, - "zh-Hant-HK" : { - "stringUnit" : { - "state" : "translated", - "value" : "關閉手勢" - } - } - } - }, "Close Notch" : { "comment" : "Accessibility action to collapse the notch, not close its window.", "localizations" : { @@ -5937,7 +5833,6 @@ } } }, - "Compact mode" : {}, "Continue" : { "localizations" : { "cs" : { @@ -8256,120 +8151,121 @@ } } }, - "Enable gestures" : { + "Enable media gestures" : { + "comment" : "Master switch for media gestures only; not panel opening or closing.", "localizations" : { "cs" : { "stringUnit" : { "state" : "translated", - "value" : "Povolit gesta" + "value" : "Povolit gesta pro média" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "Gestensteuerung aktivieren" + "value" : "Mediengesten aktivieren" } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "Enable gestures" + "value" : "Enable media gestures" } }, "en-GB" : { "stringUnit" : { "state" : "translated", - "value" : "Enable gestures" + "value" : "Enable media gestures" } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "Habilitar gestos" + "value" : "Habilitar gestos multimedia" } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "Activer les gestes" + "value" : "Activer les gestes multimédias" } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "אפשר מחוות" + "value" : "אפשר מחוות מדיה" } }, "hu" : { "stringUnit" : { "state" : "translated", - "value" : "Gesztusok engedélyezése" + "value" : "Médiagesztusok engedélyezése" } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "Abilita gesti" + "value" : "Abilita gesti multimediali" } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ジェスチャーを有効化" + "value" : "メディアジェスチャーを有効化" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "제스처 켜기" + "value" : "미디어 제스처 켜기" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "Gebaren inschakelen" + "value" : "Mediagebaren inschakelen" } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "Włącz obsługę gestów" + "value" : "Włącz gesty multimedialne" } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "Ativar gestos" + "value" : "Ativar gestos de mídia" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Включить жесты" + "value" : "Включить медиажесты" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "El hareketlerini aktifleştir" + "value" : "Medya hareketlerini etkinleştir" } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "Увімкнути жести" + "value" : "Увімкнути медіажести" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "启用手势" + "value" : "启用媒体手势" } }, "zh-Hant-HK" : { "stringUnit" : { "state" : "translated", - "value" : "啟用手勢" + "value" : "啟用媒體手勢" } } } @@ -8551,118 +8447,6 @@ } } }, - "Enable haptic feedback" : { - "localizations" : { - "de" : { - "stringUnit" : { - "state" : "translated", - "value" : "Haptisches Feedback aktivieren" - } - }, - "en" : { - "stringUnit" : { - "state" : "translated", - "value" : "Enable haptic feedback" - } - }, - "en-GB" : { - "stringUnit" : { - "state" : "translated", - "value" : "Enable haptic feedback" - } - }, - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "Activar respuesta háptica" - } - }, - "fr" : { - "stringUnit" : { - "state" : "translated", - "value" : "Activer le retour haptique" - } - }, - "he" : { - "stringUnit" : { - "state" : "translated", - "value" : "אפשר משוב רטט (האפטי)" - } - }, - "hu" : { - "stringUnit" : { - "state" : "translated", - "value" : "Haptikus visszajelzés engedélyezése" - } - }, - "it" : { - "stringUnit" : { - "state" : "translated", - "value" : "Attiva la vibrazione" - } - }, - "ja" : { - "stringUnit" : { - "state" : "translated", - "value" : "触覚フィードバックを有効にする" - } - }, - "ko" : { - "stringUnit" : { - "state" : "translated", - "value" : "햅틱 피드백 활성화" - } - }, - "nl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Haptische feedback inschakelen" - } - }, - "pl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Włącz informację zwrotną w postaci wibracji" - } - }, - "pt-BR" : { - "stringUnit" : { - "state" : "translated", - "value" : "Ativar retorno tátil" - } - }, - "ru" : { - "stringUnit" : { - "state" : "translated", - "value" : "Включить тактильный отклик" - } - }, - "tr" : { - "stringUnit" : { - "state" : "translated", - "value" : "Titreşimli geribildirimi etkinleştir" - } - }, - "uk" : { - "stringUnit" : { - "state" : "translated", - "value" : "Вібрація при наведенні на острів" - } - }, - "zh-Hans" : { - "stringUnit" : { - "state" : "translated", - "value" : "启用震动反馈" - } - }, - "zh-Hant-HK" : { - "stringUnit" : { - "state" : "translated", - "value" : "啟用震動反饋" - } - } - } - }, "Enable shelf" : { "localizations" : { "cs" : { @@ -14336,6 +14120,50 @@ } } }, + "Opening %@ was not confirmed. It may still open. Check Applications before trying again." : { + "comment" : "Music launcher failure. The placeholder is a human-readable music app name.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Opening %@ was not confirmed. It may still open. Check Applications before trying again." + } + } + } + }, + "Music app %@ is not installed. Install it or choose a different Music Source in Settings." : { + "comment" : "Music launcher failure. The placeholder is a human-readable music app name.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Music app %@ is not installed. Install it or choose a different Music Source in Settings." + } + } + } + }, + "Music app open was not confirmed." : { + "comment" : "Concise music launcher failure; the OS may still complete the open.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Music app open was not confirmed." + } + } + } + }, + "Music app is not installed." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Music app is not installed." + } + } + } + }, + "Music app open timed out." : {}, "Music Source" : { "localizations" : { "cs" : { @@ -15264,6 +15092,27 @@ } } }, + "No music app is selected. Choose a Music Source in Settings or play music once with Now Playing." : { + "comment" : "Music launcher guidance when Now Playing has no observed or remembered music app.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "No music app is selected. Choose a Music Source in Settings or play music once with Now Playing." + } + } + } + }, + "No music app selected." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "No music app selected." + } + } + } + }, "Normalize gesture direction" : { "localizations" : { "de" : { @@ -16153,8 +16002,30 @@ } } }, + "OK" : { + "comment" : "Dismiss the inline music launcher failure feedback.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "OK" + } + } + } + }, "Only these apps show a live activity in the notch. Turn on \"From all apps\" to mirror everything instead." : {}, "Open" : {}, + "Open %@" : { + "comment" : "Music launcher button label. The placeholder is the user's selected music app.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Open %@" + } + } + } + }, "Open Calendar Settings" : { "localizations" : { "cs" : { @@ -16275,6 +16146,17 @@ }, "Open in %@" : {}, "Open in Calendar" : {}, + "Open music app" : { + "comment" : "Music launcher button label when no named player has been resolved.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Open music app" + } + } + } + }, "Open Notch" : { "localizations" : { "de" : { @@ -16733,6 +16615,17 @@ } } }, + "Opens your preferred music app without starting playback." : { + "comment" : "Accessibility hint for the idle music launcher button.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Opens your preferred music app without starting playback." + } + } + } + }, "Option (⌥) Key Behavior" : { "localizations" : { "cs" : { @@ -23236,7 +23129,6 @@ } } }, - "Shows a smaller opened notch with just the music player — no tabs, calendar or mirror." : {}, "Slider color" : { "localizations" : { "cs" : { @@ -24749,6 +24641,29 @@ }, "Tap to see the next of %lld waiting" : {}, "The background helper crashed or was closed by macOS. It restarts automatically on the next OSD event." : {}, + "The music app open request timed out. It may still open. Check Applications before trying again." : {}, + "The music app open was not confirmed. It may still open. Check Applications before trying again." : { + "comment" : "Generic music launcher failure when the app has no known display name.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The music app open was not confirmed. It may still open. Check Applications before trying again." + } + } + } + }, + "The selected music app is not installed. Choose a different Music Source in Settings." : { + "comment" : "Generic unavailable music app guidance when the app has no known display name.", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The selected music app is not installed. Choose a different Music Source in Settings." + } + } + } + }, "Time to Full Charge: %@" : { "localizations" : { "de" : { @@ -25309,124 +25224,6 @@ } } }, - "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when **Open notch on hover** option is disabled" : { - "localizations" : { - "cs" : { - "stringUnit" : { - "state" : "translated", - "value" : "Posunutím dvěma prsty nahoru zavřete, dvojitým posunem dolů otevřete, když je zakázána možnost **Otevření výřezu při nápovědě**" - } - }, - "de" : { - "stringUnit" : { - "state" : "translated", - "value" : "Zwei-Finger Wischen nach oben zum Schließen der Notch, zwei-Finger wischen nach unten um die Notch zu öffnen, wenn die Option **Notch bei Mausberührung öffnen** deaktiviert ist" - } - }, - "en" : { - "stringUnit" : { - "state" : "translated", - "value" : "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when **Open notch on hover** option is disabled" - } - }, - "en-GB" : { - "stringUnit" : { - "state" : "translated", - "value" : "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when **Open notch on hover** option is disabled" - } - }, - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "Deslice con dos dedos hacia arriba para cerrar, deslice con dos dedos hacia abajo para abrir cuando la opción de **Abrir el notch al pasar el cursor** esté deshabilitada" - } - }, - "fr" : { - "stringUnit" : { - "state" : "translated", - "value" : "Glisser deux doigts vers le haut sur l'encoche pour fermer, glisser deux doigts vers le bas sur l'encoche pour l'ouvrir lorsque l'option **Ouvrir l'encoche au survolant** est désactivée" - } - }, - "he" : { - "stringUnit" : { - "state" : "translated", - "value" : "החלק שתי אצבעות למעלה על המגרעת כדי לסגור, או למטה כדי לפתוח כאשר האפשרות **פתח מגרעת בריחוף** מושבתת" - } - }, - "hu" : { - "stringUnit" : { - "state" : "translated", - "value" : "„Kétujjas felfelé legyintés a notch-on a bezáráshoz, kétujjas lefelé legyintés a notch-on a megnyitáshoz, ha a **Notch megnyitása rámutatással** opció ki van kapcsolva.”" - } - }, - "it" : { - "stringUnit" : { - "state" : "translated", - "value" : "Scorri due dita verso l'alto sulla notch per chiudere, scorri due dita verso il basso sulla tacca per aprirla quando l'opzione **Apri notch all'hover ** è disabilitata" - } - }, - "ja" : { - "stringUnit" : { - "state" : "translated", - "value" : "**ホバーでノッチを開く** オプションが無効の時は、2本指でノッチを上にスワイプして閉じ、下にスワイプして開きます。" - } - }, - "ko" : { - "stringUnit" : { - "state" : "translated", - "value" : "노치에 가져다 대서 열기 옵션이 꺼져있을 때, 노치를 두 손가락을 위로 밀어서 닫고, 두 손가락을 아래로 내려서 열기" - } - }, - "nl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Veeg met twee vingers omhoog over de inkeping om deze te sluiten, veeg met twee vingers omlaag over de inkeping om deze te openen als de optie **Inkeping openen bij aanwijzen** is uitgeschakeld" - } - }, - "pl" : { - "stringUnit" : { - "state" : "translated", - "value" : "Przesuń dwoma palcami w górę na notchu, aby zamknąć, przesuń dwoma palcami w dół na notchu, aby otworzyć, gdy opcja **Otwórz notch przy najechaniu palcem ** jest wyłączona" - } - }, - "pt-BR" : { - "stringUnit" : { - "state" : "translated", - "value" : "Role para cima com dois dedos para no notch para fechar, role para baixo com dois dedos no notch para abrir quando a opção **Abrir notch ao passar o mouse por cima** estiver desativada" - } - }, - "ru" : { - "stringUnit" : { - "state" : "translated", - "value" : "Свайп двумя пальцами вверх по вырезу — закрыть, свайп двумя пальцами вниз — открыть, если опция **Открывать вырез при наведении** отключена" - } - }, - "tr" : { - "stringUnit" : { - "state" : "translated", - "value" : "**Fareyi üzerine getirdiğinde aç** seçeneği devre dışı bırakıldığında, kapatmak için çentiği iki parmağınızla yukarı kaydırın, açmak için çentiği iki parmağınızla aşağı kaydırın." - } - }, - "uk" : { - "stringUnit" : { - "state" : "translated", - "value" : "Проведіть двома пальцями вгору по чубчику, щоб закрити його, або двома пальцями вниз, щоб відкрити, якщо вимкнено опцію «Відкривати виріз під час наведення»" - } - }, - "zh-Hans" : { - "stringUnit" : { - "state" : "translated", - "value" : "在Notch里双指向上滑动以关闭。当**悬停在Notch时打开**选项禁用时,双指向下滑动即可打开" - } - }, - "zh-Hant-HK" : { - "stringUnit" : { - "state" : "translated", - "value" : "鼠標懸停在劉海上時,雙指上滑關閉劉海,下滑開啟劉海" - } - } - } - }, "Uninstall" : { "extractionState" : "stale", "localizations" : { diff --git a/notchPocket/MediaControllers/MusicAppLauncher.swift b/notchPocket/MediaControllers/MusicAppLauncher.swift new file mode 100644 index 0000000000..251bcf7249 --- /dev/null +++ b/notchPocket/MediaControllers/MusicAppLauncher.swift @@ -0,0 +1,222 @@ +// +// MusicAppLauncher.swift +// notchPocket +// +// SPDX-License-Identifier: GPL-3.0-only +// + +import AppKit + +enum MusicSectionPresentation: Equatable { + case player + case launcher + + var showsPlaybackControls: Bool { self == .player } + var showsLauncherIcon: Bool { self == .launcher } +} + +enum MusicPresentationPolicy { + static func presentation(isPlaying: Bool) -> MusicSectionPresentation { + isPlaying ? .player : .launcher + } +} + +enum MusicLaunchTargetResolver { + static func bundleIdentifier( + preferred: MediaControllerType, + currentBundleIdentifier: String?, + rememberedNowPlayingBundleIdentifier: String? + ) -> String? { + switch preferred { + case .appleMusic: + MediaAppBundleID.appleMusic + case .spotify: + MediaAppBundleID.spotify + case .youtubeMusic: + MediaAppBundleID.youTubeMusic + case .nowPlaying: + rememberedBundleIdentifier( + observed: currentBundleIdentifier, + previous: rememberedNowPlayingBundleIdentifier + ) + } + } + + static func rememberedBundleIdentifier(observed: String?, previous: String?) -> String? { + nonemptyBundleIdentifier(observed) ?? nonemptyBundleIdentifier(previous) + } +} + +struct MusicLaunchContext: Equatable { + let isPlaying: Bool + let preferred: MediaControllerType + let effective: MediaControllerType? + let observedBundleIdentifier: String? + let rememberedBundleIdentifier: String? + + var bundleIdentifier: String? { + if isPlaying, let observed = nonemptyBundleIdentifier(observedBundleIdentifier) { + return observed + } + return MusicLaunchTargetResolver.bundleIdentifier( + preferred: preferred, + currentBundleIdentifier: effective == .nowPlaying ? observedBundleIdentifier : nil, + rememberedNowPlayingBundleIdentifier: rememberedBundleIdentifier + ) + } +} + +private func nonemptyBundleIdentifier(_ value: String?) -> String? { + guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines), + !trimmed.isEmpty else { return nil } + return trimmed +} + +@MainActor +protocol MusicAppOpening { + func applicationURL(forBundleIdentifier bundleIdentifier: String) -> URL? + func openApplication(at url: URL) async -> Bool +} + +enum MusicAppLaunchOutcome: Equatable { + case opened(bundleIdentifier: String) + case noTarget + case notInstalled(bundleIdentifier: String) + case openFailed(bundleIdentifier: String) + case timedOut + case alreadyOpening + case cancelled +} + +enum MusicAppFeedback { + static func displayName(for bundleIdentifier: String?) -> LocalizedStringResource? { + guard let bundleIdentifier = nonemptyBundleIdentifier(bundleIdentifier), + let controller = MediaControllerType(nowPlayingBundleIdentifier: bundleIdentifier) else { + return nil + } + return controller.localizedResource + } + + static func launchLabel(for bundleIdentifier: String?) -> LocalizedStringResource { + guard let name = displayName(for: bundleIdentifier) else { return "Open music app" } + return LocalizedStringResource( + "Open \(String(localized: name))", + comment: "Music launcher button label. The placeholder is the user's selected music app." + ) + } + + static func conciseMessage(for outcome: MusicAppLaunchOutcome) -> LocalizedStringResource? { + switch outcome { + case .opened, .cancelled: + return nil + case .noTarget: + return "No music app selected." + case .notInstalled(let bundleIdentifier): + guard let name = displayName(for: bundleIdentifier) else { return "Music app is not installed." } + return LocalizedStringResource( + "\(String(localized: name)) is not installed.", + comment: "Concise music launcher failure. The placeholder is a human-readable music app name." + ) + case .openFailed: + return "Music app open was not confirmed." + case .timedOut: + return "Music app open timed out." + case .alreadyOpening: + return "A music app open is still pending." + } + } + + static func message(for outcome: MusicAppLaunchOutcome) -> LocalizedStringResource? { + switch outcome { + case .opened, .cancelled: + return nil + case .noTarget: + return "No music app is selected. Choose a Music Source in Settings or play music once with Now Playing." + case .notInstalled(let bundleIdentifier): + guard let name = displayName(for: bundleIdentifier) else { + return "The selected music app is not installed. Choose a different Music Source in Settings." + } + return LocalizedStringResource( + "Music app \(String(localized: name)) is not installed. Install it or choose a different Music Source in Settings.", + comment: "Music launcher failure. The placeholder is a human-readable music app name." + ) + case .openFailed(let bundleIdentifier): + guard let name = displayName(for: bundleIdentifier) else { + return "The music app open was not confirmed. It may still open. Check Applications before trying again." + } + return LocalizedStringResource( + "Opening \(String(localized: name)) was not confirmed. It may still open. Check Applications before trying again.", + comment: "Music launcher failure. The placeholder is a human-readable music app name." + ) + case .timedOut: + return "The music app open request timed out. It may still open. Check Applications before trying again." + case .alreadyOpening: + return "A previous music app open request is still pending. Check Applications before trying again." + } + } +} + +@MainActor +final class MusicAppLauncher { + private let workspace: any MusicAppOpening + private(set) var isOpening = false + + init(workspace: any MusicAppOpening) { + self.workspace = workspace + } + + func launch(bundleIdentifier: String?) async -> MusicAppLaunchOutcome { + guard !Task.isCancelled else { return .cancelled } + guard let bundleIdentifier = nonemptyBundleIdentifier(bundleIdentifier) else { + Log.music.error("Cannot open music app: no preferred or observed target") + return .noTarget + } + guard !isOpening else { + Log.music.error("Music app open still pending; refusing another OS request") + return .alreadyOpening + } + guard let url = workspace.applicationURL(forBundleIdentifier: bundleIdentifier) else { + Log.music.error("Music app is not installed: \(bundleIdentifier)") + return .notInstalled(bundleIdentifier: bundleIdentifier) + } + guard !Task.isCancelled else { return .cancelled } + isOpening = true + defer { isOpening = false } + let opened = await workspace.openApplication(at: url) + guard !Task.isCancelled else { return .cancelled } + guard opened else { + Log.music.error("Music app open was not confirmed: \(bundleIdentifier)") + return .openFailed(bundleIdentifier: bundleIdentifier) + } + Log.music.debug("Opened music app: \(bundleIdentifier)") + return .opened(bundleIdentifier: bundleIdentifier) + } +} + +@MainActor +struct WorkspaceMusicAppOpening: MusicAppOpening { + func applicationURL(forBundleIdentifier bundleIdentifier: String) -> URL? { + NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) + } + + func openApplication(at url: URL) async -> Bool { + let configuration = NSWorkspace.OpenConfiguration() + configuration.activates = true + configuration.createsNewApplicationInstance = false + // Only the native completion releases the gate; Task cancellation cannot + // tell us whether an already-dispatched OS open is still pending. + return await withCheckedContinuation { continuation in + NSWorkspace.shared.openApplication(at: url, configuration: configuration) { application, error in + if let error { + Log.music.error("NSWorkspace did not confirm music app open: \(error)") + continuation.resume(returning: false) + } else if application != nil { + continuation.resume(returning: true) + } else { + Log.music.error("NSWorkspace completed music app open without an application or error") + continuation.resume(returning: false) + } + } + } + } +} diff --git a/notchPocket/MediaControllers/MusicLaunchTransaction.swift b/notchPocket/MediaControllers/MusicLaunchTransaction.swift new file mode 100644 index 0000000000..96b6e2e492 --- /dev/null +++ b/notchPocket/MediaControllers/MusicLaunchTransaction.swift @@ -0,0 +1,94 @@ +// +// MusicLaunchTransaction.swift +// notchPocket +// +// SPDX-License-Identifier: GPL-3.0-only +// + +import Combine +import Foundation + +@MainActor +final class MusicLaunchTransaction: ObservableObject { + @Published private(set) var isLaunching = false + @Published private(set) var failure: MusicAppLaunchOutcome? + + private let launcher: MusicAppLauncher + private let timeout: Duration + private var generation = UUID() + private var requestTask: Task? + private var deadlineTask: Task? + + init(launcher: MusicAppLauncher, timeout: Duration = .seconds(5)) { + self.launcher = launcher + self.timeout = timeout + } + + deinit { + requestTask?.cancel() + deadlineTask?.cancel() + } + + func start(context: MusicLaunchContext, currentContext: @escaping @MainActor () -> MusicLaunchContext) { + guard !isLaunching else { return } + cancel() + let request = generation + isLaunching = true + requestTask = Task { @MainActor [weak self, launcher] in + guard !Task.isCancelled, + self?.isCurrent(request, context: context, currentContext: currentContext) == true else { return } + let outcome = await launcher.launch(bundleIdentifier: context.bundleIdentifier) + guard !Task.isCancelled, + self?.isCurrent(request, context: context, currentContext: currentContext) == true else { return } + self?.finish(outcome) + } + // No task group: an uncooperative workspace completion must not delay the UI deadline. + deadlineTask = Task { @MainActor [weak self, timeout] in + do { + try await Task.sleep(for: timeout) + } catch is CancellationError { + return + } catch { + Log.music.error("Music launch deadline failed: \(error)") + } + guard !Task.isCancelled, + self?.isCurrent(request, context: context, currentContext: currentContext) == true else { return } + Log.music.error("Music app open timed out; OS request may still complete") + self?.finish(.timedOut) + } + } + + func cancel() { + generation = UUID() + requestTask?.cancel() + deadlineTask?.cancel() + requestTask = nil + deadlineTask = nil + isLaunching = false + failure = nil + } + + func dismissFailure() { + failure = nil + } + + private func isCurrent( + _ request: UUID, + context: MusicLaunchContext, + currentContext: () -> MusicLaunchContext + ) -> Bool { + guard generation == request else { return false } + guard context == currentContext() else { + cancel() + return false + } + return true + } + + private func finish(_ outcome: MusicAppLaunchOutcome) { + // Cancellation releases UI ownership, not the OS open. The shared launcher + // retains its single-operation gate until that await actually returns. + cancel() + failure = MusicAppFeedback.message(for: outcome) == nil ? nil : outcome + } +} diff --git a/notchPocket/components/AnimatedFace.swift b/notchPocket/components/AnimatedFace.swift deleted file mode 100644 index 5d0ec97c20..0000000000 --- a/notchPocket/components/AnimatedFace.swift +++ /dev/null @@ -1,100 +0,0 @@ -// -// AnimatedFace.swift -// -// Created by Harsh Vardhan Goswami on 04/08/24. -// - -import SwiftUI - -struct AnimatedFace: View { - @State private var isBlinking = false - @State private var blinkTask: Task? = nil - var height: CGFloat = 24 - var width: CGFloat = 30 - - private var eyeSpacing: CGFloat { 4 * (height / 24.0) } - private var eyeSize: CGSize { CGSize(width: 4 * (height / 24.0), height: 4 * (height / 24.0)) } - private var blinkHeight: CGFloat { 1 * (height / 24.0) } - private var noseSize: CGSize { CGSize(width: 3 * (height / 24.0), height: 4 * (height / 24.0)) } - private var mouthSize: CGSize { CGSize(width: 14 * (height / 24.0), height: 10 * (height / 24.0)) } - - var body: some View { - VStack(spacing: eyeSpacing) { - HStack(spacing: eyeSpacing) { - Eye(isBlinking: isBlinking, size: eyeSize, blinkHeight: blinkHeight) - Eye(isBlinking: isBlinking, size: eyeSize, blinkHeight: blinkHeight) - } - VStack(spacing: 2 * (height / 24.0)) { - RoundedRectangle(cornerRadius: 2 * (height / 24.0)) - .fill(Color.white) - .frame(width: noseSize.width, height: noseSize.height) - Mouth(size: mouthSize) - } - } - .frame(width: width, height: height) - .onAppear(perform: startBlinking) - .onDisappear(perform: stopBlinking) - } - - func startBlinking() { - guard blinkTask == nil else { return } - blinkTask = Task { - while !(Task.isCancelled) { - try? await Task.sleep(for: .seconds(3)) - if Task.isCancelled { break } - await MainActor.run { - isBlinking = true - } - try? await Task.sleep(for: .milliseconds(100)) - if Task.isCancelled { break } - await MainActor.run { - isBlinking = false - } - } - await MainActor.run { blinkTask = nil } - } - } - - func stopBlinking() { - blinkTask?.cancel() - blinkTask = nil - } -} - -struct Eye: View { - let isBlinking: Bool - let size: CGSize - let blinkHeight: CGFloat - - var body: some View { - RoundedRectangle(cornerRadius: size.height / 2) - .fill(Color.white) - .frame(width: size.width, height: isBlinking ? blinkHeight : size.height) - .frame(maxWidth: 15 * (size.height / 4.0), maxHeight: 15 * (size.height / 4.0)) - } -} - -struct Mouth: View { - let size: CGSize - var body: some View { - Canvas { context, _ in - let width = size.width - let height = size.height - var path = Path() - path.move(to: CGPoint(x: 0, y: height / 2)) - path.addQuadCurve(to: CGPoint(x: width, y: height / 2), control: CGPoint(x: width / 2, y: height)) - context.stroke(path, with: .color(.white), lineWidth: max(1, 2 * (size.height / 10.0))) - } - .frame(width: size.width, height: size.height) - } -} - -struct MinimalFaceFeatures_Previews: PreviewProvider { - static var previews: some View { - ZStack { - Color.black - AnimatedFace(height: 24, width: 30) - } - .previewLayout(.fixed(width: 60, height: 60)) // Adjusted preview size for better visibility - } -} diff --git a/notchPocket/components/Calendar/NotchPocketCalendar.swift b/notchPocket/components/Calendar/NotchPocketCalendar.swift index e8927d185b..01193c95c5 100644 --- a/notchPocket/components/Calendar/NotchPocketCalendar.swift +++ b/notchPocket/components/Calendar/NotchPocketCalendar.swift @@ -23,7 +23,6 @@ struct WheelPicker: View { @EnvironmentObject var vm: NotchPocketViewModel @Binding var selectedDate: Date @State private var scrollPosition: Int? - @State private var haptics: Bool = false @State private var byClick: Bool = false @State private var scrollAccumulator: CGFloat = 0 @State private var isHovering: Bool = false @@ -53,9 +52,6 @@ struct WheelPicker: View { withAnimation { scrollPosition = index } - if Defaults[.enableHaptics] { - haptics.toggle() - } } } } @@ -67,7 +63,6 @@ struct WheelPicker: View { .scrollPosition(id: $scrollPosition, anchor: .center) .scrollTargetBehavior(.viewAligned) // Ensures scroll view snaps the centered view .safeAreaPadding(.horizontal) - .sensoryFeedback(.alignment, trigger: haptics) .onContinuousHover { phase in switch phase { case .active(_): @@ -137,9 +132,6 @@ struct WheelPicker: View { } let newDate = dateForItemIndex(index: newIndex, spacerNum: spacerNum) selectedDate = newDate - if Defaults[.enableHaptics] { - haptics.toggle() - } } } } @@ -193,9 +185,6 @@ struct WheelPicker: View { let date = dateForItemIndex(index: newIndex, spacerNum: spacerNum) if !Calendar.current.isDate(date, inSameDayAs: selectedDate) { selectedDate = date - if Defaults[.enableHaptics] { - haptics.toggle() - } } } @@ -246,7 +235,6 @@ struct WeekStripPicker: View { @Default(.weekStartDay) private var weekStartDay @State private var displayedWeekStart: Date = Date() @State private var slideForward: Bool = true - @State private var haptics: Bool = false @State private var scrollAccumulator: CGFloat = 0 @State private var isHovering: Bool = false @State private var scrollMonitor: Any? @@ -278,7 +266,6 @@ struct WeekStripPicker: View { .frame(height: 50) .clipped() // keep the week-flip slide inside the calendar column (no bleed into music) .padding(.horizontal, 2) - .sensoryFeedback(.alignment, trigger: haptics) .onContinuousHover { phase in switch phase { case .active: @@ -369,9 +356,6 @@ struct WeekStripPicker: View { } selectedDate = newDate } - if Defaults[.enableHaptics] { - haptics.toggle() - } } /// Chevrons page the visible week and carry the selection along (same weekday column). @@ -383,18 +367,12 @@ struct WeekStripPicker: View { displayedWeekStart = newStart selectedDate = newSelection } - if Defaults[.enableHaptics] { - haptics.toggle() - } } private func selectDate(_ date: Date) { withAnimation { selectedDate = date } - if Defaults[.enableHaptics] { - haptics.toggle() - } } private func startOfWeek(for date: Date) -> Date { diff --git a/notchPocket/components/LiveActivities/NotchPocketBattery.swift b/notchPocket/components/LiveActivities/NotchPocketBattery.swift index 7c7ef48031..aae3a21523 100644 --- a/notchPocket/components/LiveActivities/NotchPocketBattery.swift +++ b/notchPocket/components/LiveActivities/NotchPocketBattery.swift @@ -44,7 +44,7 @@ struct BatteryView: View { /// /// These were previously absolute: the fill height was /// `(batteryWidth - 2.75) - 18`, which only lands correctly at the - /// default 30pt — at compact mode's 24pt it collapses to ~3pt, a sliver + /// default 30pt — at 24pt it collapses to ~3pt, a sliver /// floating inside the outline. Expressing them relative to a reference /// width keeps the 30pt case numerically identical to before while /// making every other size correct. diff --git a/notchPocket/components/Music/MusicSectionView.swift b/notchPocket/components/Music/MusicSectionView.swift new file mode 100644 index 0000000000..8184ccc39a --- /dev/null +++ b/notchPocket/components/Music/MusicSectionView.swift @@ -0,0 +1,146 @@ +// +// MusicSectionView.swift +// notchPocket +// +// SPDX-License-Identifier: GPL-3.0-only +// + +import Defaults +import SwiftUI + +@MainActor +func musicAppLaunchIcon(for bundleIdentifier: String?) -> Image { + if let bundleIdentifier, + let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) { + return Image(nsImage: NSWorkspace.shared.icon(forFile: url.path)) + } + return Image(systemName: "music.note") +} + +struct MusicLaunchInteractionPreferenceKey: PreferenceKey { + static let defaultValue = false + + static func reduce(value: inout Bool, nextValue: () -> Bool) { + value = value || nextValue() + } +} + +struct MusicLaunchFeedbackHoverPreferenceKey: PreferenceKey { + static let defaultValue = false + + static func reduce(value: inout Bool, nextValue: () -> Bool) { + value = value || nextValue() + } +} + +@MainActor +struct MusicSectionView: View { + @ObservedObject private var musicManager = MusicManager.shared + @Default(.lastNowPlayingLauncherBundleIdentifier) private var rememberedBundleIdentifier + @Default(.lastSupportedNowPlayingBundleIdentifier) private var legacyRememberedBundleIdentifier + @StateObject private var launch = MusicLaunchTransaction(launcher: MusicManager.shared.musicAppLauncher) + @State private var isHoveringFeedback = false + + private let playingContent: (@escaping () -> Void) -> PlayingContent + + init(@ViewBuilder playingContent: @escaping (@escaping () -> Void) -> PlayingContent) { + self.playingContent = playingContent + } + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + if MusicPresentationPolicy.presentation(isPlaying: musicManager.isPlaying).showsPlaybackControls { + playingContent(openMusicApp) + } else { + launcherButton + } + if let failure = launch.failure { + failureFeedback(failure) + .onHover { isHoveringFeedback = $0 } + .onDisappear { isHoveringFeedback = false } + } + } + .preference(key: MusicLaunchInteractionPreferenceKey.self, value: launch.isLaunching) + .preference( + key: MusicLaunchFeedbackHoverPreferenceKey.self, + value: launch.failure != nil && isHoveringFeedback + ) + .onChange(of: launchContext) { _, _ in + clearLaunch() + } + .onDisappear(perform: clearLaunch) + } + + private var launchContext: MusicLaunchContext { + // Defaults wrappers invalidate the view when history changes without a playback update. + MusicLaunchContext( + isPlaying: musicManager.isPlaying, + preferred: musicManager.preferredMediaController, + effective: musicManager.effectiveMediaController, + observedBundleIdentifier: musicManager.bundleIdentifier, + rememberedBundleIdentifier: rememberedBundleIdentifier ?? legacyRememberedBundleIdentifier + ) + } + + private var launcherButton: some View { + Button(action: openMusicApp) { + launcherIcon + .resizable() + .scaledToFit() + .frame(width: 32, height: 32) + .padding(4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(launch.isLaunching) + .accessibilityLabel(Text(MusicAppFeedback.launchLabel(for: launchContext.bundleIdentifier))) + .accessibilityHint("Opens your preferred music app without starting playback.") + .accessibilityIdentifier("com.jdylanmc.notchpocket.music.v1.idle-launcher") + .help(Text(MusicAppFeedback.launchLabel(for: launchContext.bundleIdentifier))) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var launcherIcon: Image { + musicAppLaunchIcon(for: launchContext.bundleIdentifier) + } + + @ViewBuilder + private func failureFeedback(_ outcome: MusicAppLaunchOutcome) -> some View { + if let message = MusicAppFeedback.conciseMessage(for: outcome), + let guidance = MusicAppFeedback.message(for: outcome) { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + .accessibilityHidden(true) + Text(message) + .font(.caption.weight(.semibold)) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityHint(Text(guidance)) + .accessibilityIdentifier("com.jdylanmc.notchpocket.music.v1.launch-status") + Button("OK") { + launch.dismissFailure() + isHoveringFeedback = false + } + .buttonStyle(.plain) + .font(.caption.weight(.semibold)) + .frame(minWidth: 24, minHeight: 24) + .contentShape(Rectangle()) + .accessibilityIdentifier("com.jdylanmc.notchpocket.music.v1.launch-dismiss") + } + .frame(height: 32) + .help(Text(guidance)) + .accessibilityElement(children: .contain) + } + } + + private func clearLaunch() { + launch.cancel() + isHoveringFeedback = false + } + + private func openMusicApp() { + let manager = musicManager + launch.start(context: launchContext, currentContext: { manager.musicLaunchContext }) + } +} diff --git a/notchPocket/components/Music/MusicSliderView.swift b/notchPocket/components/Music/MusicSliderView.swift new file mode 100644 index 0000000000..dc212db5b8 --- /dev/null +++ b/notchPocket/components/Music/MusicSliderView.swift @@ -0,0 +1,197 @@ +// +// MusicSliderView.swift +// notchPocket +// +// Created by Hugo Persson on 2024-08-18. +// Modified by Harsh Vardhan Goswami & Richard Kunkli & Mustafa Ramadan +// + +import Defaults +import SwiftUI + +struct MusicSliderView: View { + @Binding var sliderValue: Double + @Binding var duration: Double + @Binding var lastDragged: Date + var color: NSColor + @Binding var dragging: Bool + let currentDate: Date + let timestampDate: Date + let elapsedTime: Double + let playbackRate: Double + let isPlaying: Bool + var onValueChange: (Double) -> Void + + // Layout options, ported from Atoll (GPL-3.0, itself a Notch Pocket + // fork). Defaults retain the standard stacked/duration layout. + var labelLayout: TimeLabelLayout = .stacked + var trailingLabel: TrailingLabel = .duration + var restingTrackHeight: CGFloat = 5 + var draggingTrackHeight: CGFloat = 9 + + enum TimeLabelLayout { + /// Times on a row beneath the track. + case stacked + /// Times flanking the track on the same row. + case inline + } + + enum TrailingLabel { + case duration + /// Counts down: "-2:56". + case remaining + } + + var body: some View { + Group { + switch labelLayout { + case .stacked: stackedContent + case .inline: inlineContent + } + } + .onChange(of: currentDate) { + guard !dragging, timestampDate.timeIntervalSince(lastDragged) > -1 else { return } + sliderValue = MusicManager.shared.estimatedPlaybackPosition(at: currentDate) + } + } + + private var stackedContent: some View { + VStack { + sliderCore + .frame(height: sliderFrameHeight, alignment: .center) + + HStack { + Text(timeString(from: sliderValue)) + Spacer() + Text(trailingTimeText) + } + .fontWeight(.medium) + .foregroundColor(timeLabelColor) + .font(.caption) + } + } + + private var inlineContent: some View { + HStack(spacing: 6) { + Text(timeString(from: sliderValue)) + .font(inlineLabelFont) + .foregroundColor(timeLabelColor) + .frame(width: 36, alignment: .leading) + + sliderCore + .frame(height: sliderFrameHeight) + .frame(maxWidth: .infinity) + + Text(trailingTimeText) + .font(inlineLabelFont) + .foregroundColor(timeLabelColor) + .frame(width: 42, alignment: .trailing) + } + } + + private var sliderCore: some View { + CustomSlider( + value: $sliderValue, + range: 0...duration, + color: Defaults[.sliderColor] == SliderColorEnum.albumArt + ? Color(nsColor: color).ensureMinimumBrightness(factor: 0.8) + : Defaults[.sliderColor] == SliderColorEnum.accent ? .effectiveAccent : .white, + dragging: $dragging, + lastDragged: $lastDragged, + onValueChange: onValueChange, + restingTrackHeight: restingTrackHeight, + draggingTrackHeight: draggingTrackHeight + ) + } + + private var timeLabelColor: Color { + Defaults[.playerColorTinting] + ? Color(nsColor: color).ensureMinimumBrightness(factor: 0.6) : .gray + } + + private var trailingTimeText: String { + switch trailingLabel { + case .duration: + return timeString(from: duration) + case .remaining: + return "-" + timeString(from: max(duration - sliderValue, 0)) + } + } + + /// Monospaced digits so the label doesn't jitter as the numbers tick. + private var inlineLabelFont: Font { + .system(size: 11, weight: .medium).monospacedDigit() + } + + private var sliderFrameHeight: CGFloat { + max(restingTrackHeight, draggingTrackHeight) + 1 + } + + func timeString(from seconds: Double) -> String { + guard seconds.isFinite else { return "--:--" } + let totalMinutes = Int(seconds) / 60 + let remainingSeconds = Int(seconds) % 60 + let hours = totalMinutes / 60 + let minutes = totalMinutes % 60 + + if hours > 0 { + return String(format: "%d:%02d:%02d", hours, minutes, remainingSeconds) + } else { + return String(format: "%d:%02d", minutes, remainingSeconds) + } + } +} + +struct CustomSlider: View { + @Binding var value: Double + var range: ClosedRange + var color: Color = .white + @Binding var dragging: Bool + @Binding var lastDragged: Date + var onValueChange: ((Double) -> Void)? + var onDragChange: ((Double) -> Void)? + /// Defaults retain the standard layout's 5/9 track heights. + var restingTrackHeight: CGFloat = 5 + var draggingTrackHeight: CGFloat = 9 + + var body: some View { + GeometryReader { geometry in + let width = geometry.size.width + let height = CGFloat(dragging ? draggingTrackHeight : restingTrackHeight) + let rangeSpan = range.upperBound - range.lowerBound + + let progress = rangeSpan == .zero ? 0 : (value - range.lowerBound) / rangeSpan + let filledTrackWidth = min(max(progress, 0), 1) * width + + ZStack(alignment: .leading) { + Rectangle() + .fill(.gray.opacity(0.3)) + .frame(height: height) + + Rectangle() + .fill(color) + .frame(width: filledTrackWidth, height: height) + } + .cornerRadius(height / 2) + .frame(height: max(restingTrackHeight, draggingTrackHeight) + 1) + .contentShape(Rectangle()) + .gesture( + DragGesture(minimumDistance: 0) + .onChanged { gesture in + withAnimation { + dragging = true + } + let newValue = range.lowerBound + Double(gesture.location.x / width) * rangeSpan + value = min(max(newValue, range.lowerBound), range.upperBound) + onDragChange?(value) + } + .onEnded { _ in + onValueChange?(value) + dragging = false + lastDragged = Date() + } + ) + .animation(.spring(response: 0.35, dampingFraction: 0.7), value: dragging) + } + } +} diff --git a/notchPocket/components/Notch/CompactHomeView.swift b/notchPocket/components/Notch/CompactHomeView.swift deleted file mode 100644 index 6ad0a35800..0000000000 --- a/notchPocket/components/Notch/CompactHomeView.swift +++ /dev/null @@ -1,411 +0,0 @@ -// -// CompactHomeView.swift -// notchPocket -// -// A smaller open-notch layout: just the now-playing essentials — art, -// title, scrubber, transport — with no tab bar, calendar or mirror. -// -// Layout and proportions follow Atoll's MinimalisticMusicPlayerView -// (https://github.com/Ebullioscopic/Atoll, GPL-3.0, itself a Notch Pocket -// fork): 50pt album art, 12/10pt title and artist, a fixed-width -// visualizer block on the right sized to match the trailing time label so -// the bars centre over it, an inline progress row with a counting-down -// remaining time, and a 10pt-spaced transport row. -// -// Built on this project's own MusicSliderView / HoverButton / -// MarqueeText rather than porting Atoll's ~1500-line view wholesale, so -// seeking behaves identically in both layouts instead of drifting apart. -// The transport row is a fixed five here rather than the musicControlSlots -// preference — that preference exists to configure the full layout, and -// its default would leave compact mode without shuffle or media output. -// - -import Defaults -import SwiftUI - -struct CompactHomeView: View { - @EnvironmentObject var vm: NotchPocketViewModel - @ObservedObject var musicManager = MusicManager.shared - @ObservedObject var batteryModel = BatteryStatusViewModel.shared - let albumArtNamespace: Namespace.ID - - @State private var sliderValue: Double = 0 - @State private var dragging: Bool = false - @State private var lastDragged: Date = .distantPast - @State private var showingOutputPicker = false - @ObservedObject private var routeManager = AudioRouteManager.shared - - @Default(.coloredSpectrogram) private var coloredSpectrogram - @Default(.playerColorTinting) private var playerColorTinting - - private let albumArtWidth: CGFloat = 45 - private let headerSpacing: CGFloat = 10 - /// Matches the trailing time label's width in the row below, so the - /// visualizer's bars sit centred over "-0:00" rather than drifting. - private let vizBlockWidth: CGFloat = 42 - private let vizBarWidth: CGFloat = 24 - - // No idle branch, deliberately. The standard layout has none either — - // it renders whatever MusicManager last cached, so a paused or stopped - // track keeps its art, title and scrub position. A "Nothing Playing" - // placeholder here made compact mode lose state the full layout keeps. - var body: some View { - VStack(spacing: 0) { - header - .frame(height: albumArtWidth) - - progressRow - .padding(.top, 4) - - transport - .padding(.top, 1) - } - .padding(.horizontal, 12) - // Atoll's 15/3 formula assumes the player is the whole panel; here - // a notch-clearance spacer sits above it, so these are trimmed to - // land the panel at the intended overall height. - .padding(.top, 4) - .padding(.bottom, 1) - .frame(maxWidth: .infinity) - .buttonStyle(PlainButtonStyle()) - } - - // MARK: - Header - - private var header: some View { - GeometryReader { geo in - let textWidth = max( - 0, - geo.size.width - albumArtWidth - headerSpacing - (vizBlockWidth + headerSpacing) - ) - - HStack(alignment: .center, spacing: headerSpacing) { - compactAlbumArt - - VStack(alignment: .leading, spacing: 1) { - MarqueeText( - musicManager.songTitle, - font: .system(size: 12, weight: .semibold), - color: .white, - frameWidth: textWidth - ) - - Text(musicManager.artistName) - .font(.system(size: 10)) - .foregroundStyle( - playerColorTinting - ? Color(nsColor: musicManager.avgColor).ensureMinimumBrightness(factor: 0.6) - : .gray - ) - .lineLimit(1) - } - .frame(width: textWidth, alignment: .leading) - - ZStack { - MusicVisualizer( - isPlaying: musicManager.isPlaying, - tintColor: coloredSpectrogram - ? Color(nsColor: musicManager.avgColor).ensureMinimumBrightness(factor: 0.6) - : .gray - ) - .frame(width: vizBarWidth, height: 16) - } - .frame(width: vizBlockWidth) - } - } - .overlay(alignment: .topTrailing) { - // Compact mode hides NotchPocketHeader (it spans the full notch - // width), which took the battery with it. Overlaid rather than - // placed in the HStack so it doesn't steal width from the title. - if Defaults[.showBatteryIndicator] { - NotchPocketBatteryView( - batteryWidth: 24, - isCharging: batteryModel.isCharging, - isInLowPowerMode: batteryModel.isInLowPowerMode, - isPluggedIn: batteryModel.isPluggedIn, - levelBattery: batteryModel.levelBattery, - maxCapacity: batteryModel.maxCapacity, - timeToFullCharge: batteryModel.timeToFullCharge, - timeToDischarge: batteryModel.timeToDischarge, - maxAdapterWatts: batteryModel.maxAdapterWatts, - isForNotification: false - ) - .offset(y: -14) - } - } - } - - // MARK: - Progress - - private var progressRow: some View { - // See NotchHomeView.musicSlider — 0.5s ticks are imperceptible here. - TimelineView(.animation(minimumInterval: musicManager.playbackRate > 0 ? 0.5 : nil)) { timeline in - MusicSliderView( - sliderValue: $sliderValue, - duration: $musicManager.songDuration, - lastDragged: $lastDragged, - color: musicManager.avgColor, - dragging: $dragging, - currentDate: timeline.date, - timestampDate: musicManager.timestampDate, - elapsedTime: musicManager.elapsedTime, - playbackRate: musicManager.playbackRate, - isPlaying: musicManager.isPlaying, - onValueChange: { MusicManager.shared.seek(to: $0) }, - labelLayout: .inline, - trailingLabel: .remaining, - restingTrackHeight: 7, - draggingTrackHeight: 11 - ) - } - .onAppear { sliderValue = musicManager.elapsedTime } - } - - // MARK: - Transport - - private var transport: some View { - HStack(spacing: 10) { - ForEach(Array(displayedSlots.enumerated()), id: \.offset) { _, slot in - slotView(for: slot) - } - } - .frame(maxWidth: .infinity, alignment: .center) - .frame(height: playPauseSize) - } - - /// Atoll's control dimensions: 36pt secondary buttons with 18pt glyphs, - /// a 54pt play/pause with a 26pt glyph. HoverButton's 30/40 is what made - /// this row read undersized against the rest of the panel. - private let controlSize: CGFloat = 32 - private let playPauseSize: CGFloat = 48 - - private func compactControl( - icon: String, - size: CGFloat, - glyph: CGFloat, - tint: Color = .white, - action: @escaping () -> Void - ) -> some View { - CompactControlButton( - icon: icon, - frameSize: size, - glyphSize: glyph, - tint: tint, - action: action - ) - } - - /// Fixed five rather than the musicControlSlots preference, so compact - /// mode always shows the full transport regardless of how the standard - /// layout is configured. - private var displayedSlots: [MusicControlButton] { - [.shuffle, .previous, .playPause, .next, .mediaOutput] - } - - @ViewBuilder - private func slotView(for slot: MusicControlButton) -> some View { - switch slot { - case .shuffle: - compactControl( - icon: "shuffle", - size: controlSize, - glyph: 16, - tint: musicManager.isShuffled ? .red : .white - ) { MusicManager.shared.toggleShuffle() } - case .previous: - compactControl(icon: "backward.fill", size: controlSize, glyph: 16) { - MusicManager.shared.previousTrack() - } - case .playPause: - compactControl( - icon: musicManager.isPlaying ? "pause.fill" : "play.fill", - size: playPauseSize, - glyph: 23 - ) { MusicManager.shared.togglePlay() } - case .next: - compactControl(icon: "forward.fill", size: controlSize, glyph: 16) { - MusicManager.shared.nextTrack() - } - case .repeatMode: - compactControl(icon: repeatIcon, size: controlSize, glyph: 16, tint: repeatIconColor) { - MusicManager.shared.toggleRepeat() - } - case .mediaOutput: - mediaOutputButton - case .none: - EmptyView() - default: - // Slots that only make sense in the full layout are skipped - // rather than rendered half-working in a player-only view. - EmptyView() - } - } - - /// Shows where audio is going and switches it, via a popover device - /// picker. - private var mediaOutputButton: some View { - compactControl(icon: routeSymbol, size: controlSize, glyph: 16) { - // Enumerate on open rather than polling: devices come and go - // (AirPods connecting, a display waking) and a list built at - // launch would be stale by the time anyone opened it. - routeManager.refreshDevices() - showingOutputPicker.toggle() - } - .popover(isPresented: $showingOutputPicker, arrowEdge: .bottom) { - AudioOutputPicker( - routeManager: routeManager, - onSelect: { showingOutputPicker = false } - ) - } - } - - private var compactAlbumArt: some View { - ZStack(alignment: .bottomTrailing) { - Image(nsImage: musicManager.albumArt) - .resizable() - .aspectRatio(contentMode: .fill) - .frame(width: albumArtWidth, height: albumArtWidth) - .clipShape(RoundedRectangle(cornerRadius: 10)) - - // Badge scaled to this art. AlbumArtView's is a fixed 30pt with - // a +10/+10 offset, sized for the 120pt art in the full layout — - // on 50pt art it spills outside the corner. - if !musicManager.usingAppIconForArtwork { - appIcon(for: musicManager.bundleIdentifier ?? MediaAppBundleID.appleMusic) - .resizable() - .aspectRatio(contentMode: .fit) - .frame(width: 18, height: 18) - .offset(x: 5, y: 5) - } - } - .frame(width: albumArtWidth, height: albumArtWidth) - } - - /// Prefer the live device's own icon; fall back to the resolver's - /// classification before the first enumeration has run. - private var routeSymbol: String { - routeManager.activeDevice?.iconName ?? AudioOutputRouteResolver.shared.outputRouteSymbol() - } - - private var repeatIcon: String { - musicManager.repeatMode == .one ? "repeat.1" : "repeat" - } - - private var repeatIconColor: Color { - musicManager.repeatMode == .off ? .primary : .red - } - -} - -/// Output device list for the compact player's media-output button. -struct AudioOutputPicker: View { - @ObservedObject var routeManager: AudioRouteManager - let onSelect: () -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 0) { - Text("Output") - .font(.system(size: 11, weight: .semibold)) - .foregroundStyle(.secondary) - .padding(.horizontal, 12) - .padding(.top, 10) - .padding(.bottom, 6) - - if routeManager.devices.isEmpty { - // Enumeration is async, so an empty list on first open is - // normal rather than an error worth alarming anyone about. - Text("Looking for devices…") - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .padding(.horizontal, 12) - .padding(.bottom, 10) - } else { - ForEach(routeManager.devices) { device in - Button { - routeManager.select(device) - onSelect() - } label: { - HStack(spacing: 8) { - Image(systemName: device.iconName) - .frame(width: 18) - Text(device.name) - .font(.system(size: 12)) - .lineLimit(1) - Spacer(minLength: 12) - if device.id == routeManager.activeDeviceID { - Image(systemName: "checkmark") - .font(.system(size: 10, weight: .bold)) - } - } - .contentShape(Rectangle()) - .padding(.horizontal, 12) - .padding(.vertical, 6) - } - .buttonStyle(.plain) - } - .padding(.bottom, 6) - } - } - .frame(minWidth: 220) - } -} - -/// Transport button matching Atoll's MinimalisticSquircircleButton: a -/// squircle that fills faintly on hover, sized independently of its glyph -/// so a 54pt play/pause and a 36pt skip share the same visual language. -/// -/// Not HoverButton — that's fixed at 30/40pt with a capsule fill, which -/// reads undersized against this layout's 50pt artwork. -private struct CompactControlButton: View { - let icon: String - let frameSize: CGFloat - let glyphSize: CGFloat - let tint: Color - let action: () -> Void - - @State private var isHovering = false - - var body: some View { - Button(action: action) { - RoundedRectangle(cornerRadius: frameSize * 0.4, style: .continuous) - .fill(isHovering ? Color.white.opacity(0.12) : .clear) - .frame(width: frameSize, height: frameSize) - .overlay { - Image(systemName: icon) - .font(.system(size: glyphSize, weight: .medium)) - .foregroundStyle(tint) - .contentTransition(.symbolEffect(.replace)) - } - .contentShape(RoundedRectangle(cornerRadius: frameSize * 0.4, style: .continuous)) - } - .buttonStyle(.plain) - .onHover { hovering in - withAnimation(.easeOut(duration: 0.18)) { isHovering = hovering } - } - } -} - -/// Audio-output slot for the standard layout's control row. -/// -/// Separate from CompactHomeView's inline version only because that one -/// uses the compact button sizing; the picker and behaviour are shared. -struct MediaOutputSlotButton: View { - @ObservedObject private var routeManager = AudioRouteManager.shared - @State private var showingPicker = false - - var body: some View { - HoverButton(icon: routeSymbol, scale: .medium) { - routeManager.refreshDevices() - showingPicker.toggle() - } - .popover(isPresented: $showingPicker, arrowEdge: .bottom) { - AudioOutputPicker(routeManager: routeManager) { - showingPicker = false - } - } - } - - private var routeSymbol: String { - routeManager.activeDevice?.iconName ?? AudioOutputRouteResolver.shared.outputRouteSymbol() - } -} diff --git a/notchPocket/components/Notch/LiveActivityStack.swift b/notchPocket/components/Notch/LiveActivityStack.swift index 7eb5c7b4e8..73b96f4708 100644 --- a/notchPocket/components/Notch/LiveActivityStack.swift +++ b/notchPocket/components/Notch/LiveActivityStack.swift @@ -11,7 +11,6 @@ // display for a beat and then hands it back on its own. // -import Defaults import SwiftUI /// One entry in the closed-notch stack. @@ -45,7 +44,6 @@ struct LiveActivityStack: View { @ViewBuilder let content: (LiveActivityItem) -> Content @State private var dragOffset: CGFloat = 0 - @State private var haptics: Bool = false private var clampedIndex: Int { min(max(index, 0), max(items.count - 1, 0)) } @@ -88,14 +86,12 @@ struct LiveActivityStack: View { move(by: value.translation.width < 0 ? 1 : -1) } ) - .sensoryFeedback(.alignment, trigger: haptics) } private func move(by delta: Int) { let next = clampedIndex + delta guard items.indices.contains(next) else { return } withAnimation(.smooth(duration: 0.3)) { index = next } - if Defaults[.enableHaptics] { haptics.toggle() } } } diff --git a/notchPocket/components/Notch/MediaOutputSlotButton.swift b/notchPocket/components/Notch/MediaOutputSlotButton.swift new file mode 100644 index 0000000000..b96797cb9b --- /dev/null +++ b/notchPocket/components/Notch/MediaOutputSlotButton.swift @@ -0,0 +1,83 @@ +// +// MediaOutputSlotButton.swift +// notchPocket +// +// Shared media-output controls retained from CompactHomeView. +// + +import SwiftUI + +/// Output device list for the player's media-output button. +struct AudioOutputPicker: View { + @ObservedObject var routeManager: AudioRouteManager + let onSelect: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text("Output") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 12) + .padding(.top, 10) + .padding(.bottom, 6) + + if routeManager.devices.isEmpty { + // Enumeration is async, so an empty list on first open is + // normal rather than an error worth alarming anyone about. + Text("Looking for devices…") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .padding(.horizontal, 12) + .padding(.bottom, 10) + } else { + ForEach(routeManager.devices) { device in + Button { + routeManager.select(device) + onSelect() + } label: { + HStack(spacing: 8) { + Image(systemName: device.iconName) + .frame(width: 18) + Text(device.name) + .font(.system(size: 12)) + .lineLimit(1) + Spacer(minLength: 12) + if device.id == routeManager.activeDeviceID { + Image(systemName: "checkmark") + .font(.system(size: 10, weight: .bold)) + } + } + .contentShape(Rectangle()) + .padding(.horizontal, 12) + .padding(.vertical, 6) + } + .buttonStyle(.plain) + } + .padding(.bottom, 6) + } + } + .frame(minWidth: 220) + } +} + +/// Audio-output slot for the standard layout's control row. +struct MediaOutputSlotButton: View { + @ObservedObject private var routeManager = AudioRouteManager.shared + @State private var showingPicker = false + + var body: some View { + HoverButton(icon: routeSymbol, scale: .medium) { + routeManager.refreshDevices() + showingPicker.toggle() + } + .popover(isPresented: $showingPicker, arrowEdge: .bottom) { + AudioOutputPicker(routeManager: routeManager) { + showingPicker = false + } + } + } + + private var routeSymbol: String { + routeManager.activeDevice?.iconName ?? AudioOutputRouteResolver.shared.outputRouteSymbol() + } +} diff --git a/notchPocket/components/Notch/NotchHomeView.swift b/notchPocket/components/Notch/NotchHomeView.swift index b9f33437b1..0d356eb741 100644 --- a/notchPocket/components/Notch/NotchHomeView.swift +++ b/notchPocket/components/Notch/NotchHomeView.swift @@ -17,10 +17,13 @@ struct MusicPlayerView: View { let albumArtNamespace: Namespace.ID let horizontalMediaGestureFeedback: CGFloat @Binding var isHoveringMusicArea: Bool + let openMusicApp: () -> Void var body: some View { HStack { - AlbumArtView(vm: vm, albumArtNamespace: albumArtNamespace).frame(width: 120).padding(.all, 5 * (vm.notchSize.height / 190)) + AlbumArtView(vm: vm, albumArtNamespace: albumArtNamespace, openMusicApp: openMusicApp) + .frame(width: 120) + .padding(.all, 5 * (vm.notchSize.height / 190)) MusicControlsView(horizontalMediaGestureFeedback: horizontalMediaGestureFeedback) .compositingGroup() } @@ -38,6 +41,7 @@ struct AlbumArtView: View { @ObservedObject var musicManager = MusicManager.shared @ObservedObject var vm: NotchPocketViewModel let albumArtNamespace: Namespace.ID + let openMusicApp: () -> Void var body: some View { ZStack(alignment: .bottomTrailing) { @@ -64,15 +68,15 @@ struct AlbumArtView: View { private var albumArtButton: some View { ZStack { - Button { - musicManager.openMusicApp() - } label: { + Button(action: openMusicApp) { ZStack(alignment:.bottomTrailing) { albumArtImage appIconOverlay } } .buttonStyle(PlainButtonStyle()) + .accessibilityLabel(Text(MusicAppFeedback.launchLabel(for: musicManager.musicLaunchContext.bundleIdentifier))) + .accessibilityHint("Opens the current music app without starting playback.") .scaleEffect(musicManager.isPlaying ? 1 : 0.85) albumArtDarkOverlay @@ -103,7 +107,7 @@ struct AlbumArtView: View { @ViewBuilder private var appIconOverlay: some View { if vm.notchState == .open && !musicManager.usingAppIconForArtwork { - appIcon(for: musicManager.bundleIdentifier ?? MediaAppBundleID.appleMusic) + musicAppLaunchIcon(for: musicManager.musicLaunchContext.bundleIdentifier) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 30, height: 30) @@ -442,18 +446,18 @@ struct NotchHomeView: View { private var mainContent: some View { HStack(alignment: .top, spacing: (shouldShowCamera && Defaults[.showCalendar]) ? 10 : 15) { - MusicPlayerView( - albumArtNamespace: albumArtNamespace, - horizontalMediaGestureFeedback: horizontalMediaGestureFeedback, - isHoveringMusicArea: $isHoveringMusicArea - ) + MusicSectionView { openMusicApp in + MusicPlayerView( + albumArtNamespace: albumArtNamespace, + horizontalMediaGestureFeedback: horizontalMediaGestureFeedback, + isHoveringMusicArea: $isHoveringMusicArea, + openMusicApp: openMusicApp + ) + } if Defaults[.showCalendar] { CalendarView() .frame(width: shouldShowCamera ? 170 : 215) - .onHover { isHovering in - vm.isHoveringCalendar = isHovering - } .environmentObject(vm) .transition(.opacity) } @@ -470,193 +474,3 @@ struct NotchHomeView: View { .blur(radius: vm.notchState == .closed ? 30 : 0) } } - -struct MusicSliderView: View { - @Binding var sliderValue: Double - @Binding var duration: Double - @Binding var lastDragged: Date - var color: NSColor - @Binding var dragging: Bool - let currentDate: Date - let timestampDate: Date - let elapsedTime: Double - let playbackRate: Double - let isPlaying: Bool - var onValueChange: (Double) -> Void - - // Layout options, ported from Atoll (GPL-3.0, itself a Notch Pocket - // fork) so the compact layout can put the times either side of the - // track. Defaults reproduce the previous stacked/duration look exactly, - // so the standard layout is untouched. - var labelLayout: TimeLabelLayout = .stacked - var trailingLabel: TrailingLabel = .duration - var restingTrackHeight: CGFloat = 5 - var draggingTrackHeight: CGFloat = 9 - - enum TimeLabelLayout { - /// Times on a row beneath the track. - case stacked - /// Times flanking the track on the same row. - case inline - } - - enum TrailingLabel { - case duration - /// Counts down: "-2:56". - case remaining - } - - var body: some View { - Group { - switch labelLayout { - case .stacked: stackedContent - case .inline: inlineContent - } - } - .onChange(of: currentDate) { - guard !dragging, timestampDate.timeIntervalSince(lastDragged) > -1 else { return } - sliderValue = MusicManager.shared.estimatedPlaybackPosition(at: currentDate) - } - } - - private var stackedContent: some View { - VStack { - sliderCore - .frame(height: sliderFrameHeight, alignment: .center) - - HStack { - Text(timeString(from: sliderValue)) - Spacer() - Text(trailingTimeText) - } - .fontWeight(.medium) - .foregroundColor(timeLabelColor) - .font(.caption) - } - } - - private var inlineContent: some View { - HStack(spacing: 6) { - Text(timeString(from: sliderValue)) - .font(inlineLabelFont) - .foregroundColor(timeLabelColor) - .frame(width: 36, alignment: .leading) - - sliderCore - .frame(height: sliderFrameHeight) - .frame(maxWidth: .infinity) - - Text(trailingTimeText) - .font(inlineLabelFont) - .foregroundColor(timeLabelColor) - .frame(width: 42, alignment: .trailing) - } - } - - private var sliderCore: some View { - CustomSlider( - value: $sliderValue, - range: 0...duration, - color: Defaults[.sliderColor] == SliderColorEnum.albumArt - ? Color(nsColor: color).ensureMinimumBrightness(factor: 0.8) - : Defaults[.sliderColor] == SliderColorEnum.accent ? .effectiveAccent : .white, - dragging: $dragging, - lastDragged: $lastDragged, - onValueChange: onValueChange, - restingTrackHeight: restingTrackHeight, - draggingTrackHeight: draggingTrackHeight - ) - } - - private var timeLabelColor: Color { - Defaults[.playerColorTinting] - ? Color(nsColor: color).ensureMinimumBrightness(factor: 0.6) : .gray - } - - private var trailingTimeText: String { - switch trailingLabel { - case .duration: - return timeString(from: duration) - case .remaining: - return "-" + timeString(from: max(duration - sliderValue, 0)) - } - } - - /// Monospaced digits so the label doesn't jitter as the numbers tick. - private var inlineLabelFont: Font { - .system(size: 11, weight: .medium).monospacedDigit() - } - - private var sliderFrameHeight: CGFloat { - max(restingTrackHeight, draggingTrackHeight) + 1 - } - - func timeString(from seconds: Double) -> String { - guard seconds.isFinite else { return "--:--" } - let totalMinutes = Int(seconds) / 60 - let remainingSeconds = Int(seconds) % 60 - let hours = totalMinutes / 60 - let minutes = totalMinutes % 60 - - if hours > 0 { - return String(format: "%d:%02d:%02d", hours, minutes, remainingSeconds) - } else { - return String(format: "%d:%02d", minutes, remainingSeconds) - } - } -} - -struct CustomSlider: View { - @Binding var value: Double - var range: ClosedRange - var color: Color = .white - @Binding var dragging: Bool - @Binding var lastDragged: Date - var onValueChange: ((Double) -> Void)? - var onDragChange: ((Double) -> Void)? - /// Defaults match the previous hard-coded 5/9 so the standard layout is - /// unchanged; the compact layout passes a chunkier track. - var restingTrackHeight: CGFloat = 5 - var draggingTrackHeight: CGFloat = 9 - - var body: some View { - GeometryReader { geometry in - let width = geometry.size.width - let height = CGFloat(dragging ? draggingTrackHeight : restingTrackHeight) - let rangeSpan = range.upperBound - range.lowerBound - - let progress = rangeSpan == .zero ? 0 : (value - range.lowerBound) / rangeSpan - let filledTrackWidth = min(max(progress, 0), 1) * width - - ZStack(alignment: .leading) { - Rectangle() - .fill(.gray.opacity(0.3)) - .frame(height: height) - - Rectangle() - .fill(color) - .frame(width: filledTrackWidth, height: height) - } - .cornerRadius(height / 2) - .frame(height: max(restingTrackHeight, draggingTrackHeight) + 1) - .contentShape(Rectangle()) - .gesture( - DragGesture(minimumDistance: 0) - .onChanged { gesture in - withAnimation { - dragging = true - } - let newValue = range.lowerBound + Double(gesture.location.x / width) * rangeSpan - value = min(max(newValue, range.lowerBound), range.upperBound) - onDragChange?(value) - } - .onEnded { _ in - onValueChange?(value) - dragging = false - lastDragged = Date() - } - ) - .animation(.spring(response: 0.35, dampingFraction: 0.7), value: dragging) - } - } -} diff --git a/notchPocket/components/Notch/NotificationLiveActivity.swift b/notchPocket/components/Notch/NotificationLiveActivity.swift index cfb6d7b385..4def30b3fc 100644 --- a/notchPocket/components/Notch/NotificationLiveActivity.swift +++ b/notchPocket/components/Notch/NotificationLiveActivity.swift @@ -13,7 +13,6 @@ // primitives. // -import Defaults import SwiftUI /// Closed notch: app icon on the left, a status dot on the right that @@ -114,7 +113,6 @@ struct NotificationExpandedView: View { @State private var didHandOff = false @FocusState private var replyFocused: Bool @State private var hostWindow: NotchPocketSkyLightWindow? - @State private var suggestions: [String] = [] @State private var isComposing = false /// User-visible delivery failure — the draft is kept, the notch stays /// open, and the user can retry or handle the message themselves. @@ -163,7 +161,7 @@ struct NotificationExpandedView: View { // Deliberately no auto-focus: mounting this view (hover, arrival, // cycle) used to grab key-window status and pre-focus the field, // which read as focus hijacking. Focus is pull-only — tapping the - // field or a suggestion chip sets replyFocused explicitly. + // field requests reply focus. } // The single teardown point for both the key-window grant and the // compose hold. Focus changes are too noisy to release on (see @@ -187,9 +185,8 @@ struct NotificationExpandedView: View { guard focused else { // Deliberately does NOT release key status or the compose // hold. Focus flips constantly for reasons that have - // nothing to do with the user being done: the suggestion - // chips arriving restructure the view above the field and - // drop focus, and clicking Send blurs on mouse-down. + // nothing to do with the user being done: clicking Send + // blurs on mouse-down. // Releasing on each of those resigned key status // mid-typing and closed the notch out from under clicks. // Both are released in onDisappear instead, which is the @@ -398,9 +395,6 @@ struct NotificationExpandedView: View { private var replyRow: some View { VStack(alignment: .leading, spacing: 6) { - if !suggestions.isEmpty { - suggestionChips - } replyField if let sendError { Text(sendError) @@ -410,39 +404,6 @@ struct NotificationExpandedView: View { .transition(.opacity) } } - .task(id: notification.id) { - guard Defaults[.smartRepliesEnabled], let body = notification.body else { return } - suggestions = await SmartReplyManager.suggestReplies(sender: notification.sender, body: body) - } - } - - /// Tapping a chip fills the field rather than sending immediately — an - /// AI-drafted reply should get a glance before it goes out under your - /// name, not fire on a single tap. - private var suggestionChips: some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { - // Keyed by position, not by the string itself: two identical - // suggestions would collide as ForEach ids and render - // undefined. SmartReplyManager already dedupes, but the - // view shouldn't depend on model output being distinct. - ForEach(Array(suggestions.enumerated()), id: \.offset) { _, suggestion in - Button { - replyText = suggestion - replyFocused = true - } label: { - Text(suggestion) - .font(.system(size: 12)) - .foregroundStyle(.primary) - .lineLimit(1) - .padding(.horizontal, 10) - .padding(.vertical, 5) - .background(.white.opacity(0.1), in: Capsule()) - } - .buttonStyle(ScaleDownButtonStyle()) - } - } - } } private var replyField: some View { @@ -477,9 +438,8 @@ struct NotificationExpandedView: View { /// panel a bare tap gesture needs a clean mouse-down/up pair in a window /// whose key status isn't changing — but clicking here blurs the text /// field, which flips key status mid-click and ate the tap. Enter - /// (onSubmit) worked the whole time, and the suggestion chips (already - /// Buttons) worked, which is what pointed at the gesture rather than at - /// send() itself. Buttons track the press properly across that change. + /// (onSubmit) worked the whole time. Buttons track the press properly + /// across that change. private var sendButton: some View { Button(action: send) { ZStack { @@ -514,7 +474,6 @@ struct NotificationExpandedView: View { .animation(.smooth(duration: 0.25), value: isSending) .animation(.smooth(duration: 0.25), value: didSend) .animation(.smooth(duration: 0.25), value: didHandOff) - .sensoryFeedback(.success, trigger: didSend) } private var fillStyle: Color { @@ -735,7 +694,6 @@ private struct CodeCopyButton: View { } .buttonStyle(ScaleDownButtonStyle()) .animation(.smooth(duration: 0.25), value: didCopy) - .sensoryFeedback(.success, trigger: didCopy) } private func copy() { diff --git a/notchPocket/components/OSD/Views/InlineOSD.swift b/notchPocket/components/OSD/Views/InlineOSD.swift index 1ac6e2c89a..4fbc830d73 100644 --- a/notchPocket/components/OSD/Views/InlineOSD.swift +++ b/notchPocket/components/OSD/Views/InlineOSD.swift @@ -15,7 +15,7 @@ struct InlineOSD: View { @Binding var icon: String @Binding var accent: Color? @Binding var hoverAnimation: Bool - @Binding var gestureProgress: CGFloat + @Binding var mediaGestureProgress: CGFloat var body: some View { HStack { HStack(spacing: 5) { @@ -28,7 +28,7 @@ struct InlineOSD: View { .allowsTightening(true) .contentTransition(.numericText()) } - .frame(width: 100 - (hoverAnimation ? 0 : 12) + gestureProgress / 2, height: vm.notchSize.height - (hoverAnimation ? 0 : 12), alignment: .leading) + .frame(width: 100 - (hoverAnimation ? 0 : 12) + mediaGestureProgress / 2, height: vm.notchSize.height - (hoverAnimation ? 0 : 12), alignment: .leading) Rectangle() .fill(.black) @@ -74,7 +74,7 @@ struct InlineOSD: View { } } .padding(.trailing, 4) - .frame(width: 100 - (hoverAnimation ? 0 : 12) + gestureProgress / 2, height: vm.closedNotchSize.height - (hoverAnimation ? 0 : 12), alignment: .center) + .frame(width: 100 - (hoverAnimation ? 0 : 12) + mediaGestureProgress / 2, height: vm.closedNotchSize.height - (hoverAnimation ? 0 : 12), alignment: .center) } .frame(height: vm.closedNotchSize.height + (hoverAnimation ? 8 : 0), alignment: .center) } @@ -96,7 +96,7 @@ struct InlineOSD: View { } #Preview { - InlineOSD(type: .constant(.brightness), value: .constant(0.4), icon: .constant(""), accent: .constant(nil), hoverAnimation: .constant(false), gestureProgress: .constant(0)) + InlineOSD(type: .constant(.brightness), value: .constant(0.4), icon: .constant(""), accent: .constant(nil), hoverAnimation: .constant(false), mediaGestureProgress: .constant(0)) .padding(.horizontal, 8) .background(Color.black) .padding() diff --git a/notchPocket/components/Settings/Views/AppearanceSettingsView.swift b/notchPocket/components/Settings/Views/AppearanceSettingsView.swift index 55581a3c87..cec1241370 100644 --- a/notchPocket/components/Settings/Views/AppearanceSettingsView.swift +++ b/notchPocket/components/Settings/Views/AppearanceSettingsView.swift @@ -67,15 +67,6 @@ struct AppearanceSettingsView: View { } header: { Text("Media") } - Section { - Defaults.Toggle(key: .showNotHumanFace) { - Text("Show cool face animation while inactive") - } - } header: { - HStack { - Text("Additional features") - } - } } .accentColor(.effectiveAccent) .navigationTitle("Appearance") diff --git a/notchPocket/components/Settings/Views/GeneralSettingsView.swift b/notchPocket/components/Settings/Views/GeneralSettingsView.swift index 6cbc497ee1..1f8ff5b2ba 100644 --- a/notchPocket/components/Settings/Views/GeneralSettingsView.swift +++ b/notchPocket/components/Settings/Views/GeneralSettingsView.swift @@ -28,7 +28,7 @@ struct GeneralSettings: View { @Default(.notchHeightMode) var notchHeightMode @Default(.showOnAllDisplays) var showOnAllDisplays @Default(.automaticallySwitchDisplay) var automaticallySwitchDisplay - @Default(.enableGestures) var enableGestures + @Default(.enableMediaGestures) var enableMediaGestures @Default(.openNotchOnHover) var openNotchOnHover @Default(.enableOpeningAnimation) var enableOpeningAnimation @Default(.animationSpeedMultiplier) var animationSpeedMultiplier @@ -170,7 +170,7 @@ struct GeneralSettings: View { NotchBehaviour() - gestureControls() + mediaGestureControls() } .toolbar { Button("Quit app") { @@ -180,11 +180,6 @@ struct GeneralSettings: View { } .accentColor(.effectiveAccent) .navigationTitle("General") - .onChange(of: openNotchOnHover) { - if !openNotchOnHover { - enableGestures = true - } - } .alert("Restart to apply language", isPresented: $showLanguageRestartAlert) { Button("Later", role: .cancel) {} Button("Restart Now") { @@ -196,19 +191,15 @@ struct GeneralSettings: View { } @ViewBuilder - func gestureControls() -> some View { + func mediaGestureControls() -> some View { Section { - Defaults.Toggle(key: .enableGestures) { - Text("Enable gestures") + Defaults.Toggle(key: .enableMediaGestures) { + Text("Enable media gestures") } - .disabled(!openNotchOnHover) - if enableGestures { + if enableMediaGestures { Defaults.Toggle(key: .enableHorizontalMediaGestures) { Text("Change media with horizontal gestures") } - Defaults.Toggle(key: .closeGestureEnabled) { - Text("Close gesture") - } Slider(value: $gestureSensitivity, in: 100...300, step: 100) { HStack { Text("Gesture sensitivity") @@ -226,13 +217,6 @@ struct GeneralSettings: View { Text("Gesture control") customBadge(text: "Beta") } - } footer: { - Text( - "Two-finger swipe up on notch to close, two-finger swipe down on notch to open when **Open notch on hover** option is disabled" - ) - .multilineTextAlignment(.trailing) - .foregroundStyle(.secondary) - .font(.caption) } } @@ -242,9 +226,6 @@ struct GeneralSettings: View { Defaults.Toggle(key: .openNotchOnHover) { Text("Open notch on hover") } - Defaults.Toggle(key: .enableHaptics) { - Text("Enable haptic feedback") - } Toggle("Remember last tab", isOn: $coordinator.openLastTabByDefault) if openNotchOnHover { Slider(value: $minimumHoverDuration, in: 0...1, step: 0.1) { @@ -289,15 +270,5 @@ struct GeneralSettings: View { } header: { Text("Notch behavior") } - - Section { - Defaults.Toggle(key: .compactMode) { - Text("Compact mode") - } - } footer: { - Text("Shows a smaller opened notch with just the music player — no tabs, calendar or mirror.") - .font(.caption) - .foregroundStyle(.secondary) - } } } diff --git a/notchPocket/components/Settings/Views/NotificationSettingsView.swift b/notchPocket/components/Settings/Views/NotificationSettingsView.swift index ebdbee0196..86d48f88da 100644 --- a/notchPocket/components/Settings/Views/NotificationSettingsView.swift +++ b/notchPocket/components/Settings/Views/NotificationSettingsView.swift @@ -67,38 +67,11 @@ struct NotificationSettingsView: View { } } .disabled(!notificationLiveActivity) - - Section { - Defaults.Toggle(key: .smartRepliesEnabled) { - Text("Suggest replies with Apple Intelligence") - } - .disabled(!notificationLiveActivity || !smartRepliesAvailable) - } footer: { - Text(smartReplyFooter) - .font(.caption) - .foregroundStyle(.secondary) - } } .formStyle(.grouped) .navigationTitle("Notifications") } - private var smartRepliesAvailable: Bool { - if case .available = SmartReplyManager.availability { return true } - return false - } - - private var smartReplyFooter: String { - // Drafts run entirely on-device via Apple's on-device model — no - // network calls, nothing leaves the Mac. - switch SmartReplyManager.availability { - case .available: - return "Drafts a few short reply options for messages, entirely on-device. Nothing is sent over the network." - case .unavailable(let reason): - return reason - } - } - @ViewBuilder private func appRow(_ app: KnownNotificationApp) -> some View { HStack { diff --git a/notchPocket/extensions/PanGesture.swift b/notchPocket/extensions/PanGesture.swift index 46ebdcb4bd..3d5af71e90 100644 --- a/notchPocket/extensions/PanGesture.swift +++ b/notchPocket/extensions/PanGesture.swift @@ -10,13 +10,12 @@ import SwiftUI import Defaults enum PanDirection { - case left, right, up, down + case left, right - var isHorizontal: Bool { self == .left || self == .right } - var sign: CGFloat { (self == .right || self == .down) ? 1 : -1 } + var sign: CGFloat { self == .right ? 1 : -1 } - func signed(from translation: CGSize) -> CGFloat { (isHorizontal ? translation.width : translation.height) * sign } - func signed(deltaX: CGFloat, deltaY: CGFloat) -> CGFloat { (isHorizontal ? deltaX : deltaY) * sign } + func signed(from translation: CGSize) -> CGFloat { translation.width * sign } + func signed(deltaX: CGFloat) -> CGFloat { deltaX * sign } } extension View { @@ -120,12 +119,12 @@ private struct ScrollMonitor: NSViewRepresentable { return } - // Only consider scroll events that are primarily along the configured axis. + // Only consider scroll events that are primarily horizontal. let absDX = abs(event.scrollingDeltaX) let absDY = abs(event.scrollingDeltaY) // Require the movement along the gesture axis to be at least 1.5x the orthogonal axis. let axisDominanceFactor: CGFloat = 1.5 - let isAxisDominant: Bool = direction.isHorizontal ? (absDX >= axisDominanceFactor * absDY) : (absDY >= axisDominanceFactor * absDX) + let isAxisDominant: Bool = absDX >= axisDominanceFactor * absDY guard isAxisDominant else { return } // Determine whether to normalize system deltas to device (physical) direction. @@ -134,8 +133,7 @@ private struct ScrollMonitor: NSViewRepresentable { // Scale non-precise (mouse wheel) scrolling deltas so they feel similar to // trackpad gestures. let rawDelta = direction.signed( - deltaX: event.scrollingDeltaX * deviceDirectionMultiplier, - deltaY: event.scrollingDeltaY * deviceDirectionMultiplier + deltaX: event.scrollingDeltaX * deviceDirectionMultiplier ) let scale: CGFloat = event.hasPreciseScrollingDeltas ? 1 : 8 let delta = rawDelta * scale diff --git a/notchPocket/managers/AudioRouteManager.swift b/notchPocket/managers/AudioRouteManager.swift index ddce8f2c81..c769f5bdf6 100644 --- a/notchPocket/managers/AudioRouteManager.swift +++ b/notchPocket/managers/AudioRouteManager.swift @@ -3,7 +3,7 @@ // notchPocket // // Lists the Mac's audio output devices and switches the system default -// between them, for the compact player's media-output button. +// between them, for the player's media-output button. // // Adapted from Atoll's AudioRouteManager // (https://github.com/Ebullioscopic/Atoll, GPL-3.0, itself a Notch Pocket diff --git a/notchPocket/managers/MusicManager.swift b/notchPocket/managers/MusicManager.swift index 02bd24170e..3f5d24904d 100644 --- a/notchPocket/managers/MusicManager.swift +++ b/notchPocket/managers/MusicManager.swift @@ -58,6 +58,7 @@ struct NowPlayingFallbackNotice: Identifiable, Equatable { final class MusicManager: ObservableObject { // MARK: - Properties static let shared = MusicManager() + let musicAppLauncher = MusicAppLauncher(workspace: WorkspaceMusicAppOpening()) private static let noticeDuration: Duration = .seconds(6) private static let runtimeRecoveryDelay: Duration = .seconds(1) @@ -468,6 +469,16 @@ final class MusicManager: ObservableObject { private func updateFromPlaybackState(_ state: PlaybackState) { guard state.lastUpdated != .distantPast else { return } + if effectiveMediaController == .nowPlaying { + let remembered = Defaults[.lastNowPlayingLauncherBundleIdentifier] + let observed = MusicLaunchTargetResolver.rememberedBundleIdentifier( + observed: state.bundleIdentifier, previous: remembered + ) + if observed != remembered { + Defaults[.lastNowPlayingLauncherBundleIdentifier] = observed + } + } + if effectiveMediaController == .nowPlaying, MediaControllerType(nowPlayingBundleIdentifier: state.bundleIdentifier) != nil, Defaults[.lastSupportedNowPlayingBundleIdentifier] != state.bundleIdentifier { @@ -788,25 +799,19 @@ final class MusicManager: ObservableObject { } } } - func openMusicApp() { - guard let bundleID = bundleIdentifier else { - Log.music.error("Error: appBundleIdentifier is nil") - return - } + var musicLaunchContext: MusicLaunchContext { + MusicLaunchContext( + isPlaying: isPlaying, + preferred: preferredMediaController, + effective: effectiveMediaController, + observedBundleIdentifier: bundleIdentifier, + rememberedBundleIdentifier: Defaults[.lastNowPlayingLauncherBundleIdentifier] + ?? Defaults[.lastSupportedNowPlayingBundleIdentifier] + ) + } - let workspace = NSWorkspace.shared - if let appURL = workspace.urlForApplication(withBundleIdentifier: bundleID) { - let configuration = NSWorkspace.OpenConfiguration() - workspace.openApplication(at: appURL, configuration: configuration) { (app, error) in - if let error = error { - Log.music.error("Failed to launch app with bundle ID: \(bundleID), error: \(error)") - } else { - Log.music.debug("Launched app with bundle ID: \(bundleID)") - } - } - } else { - Log.music.error("Failed to find app with bundle ID: \(bundleID)") - } + func openMusicApp() async -> MusicAppLaunchOutcome { + await musicAppLauncher.launch(bundleIdentifier: musicLaunchContext.bundleIdentifier) } func forceUpdate() { diff --git a/notchPocket/managers/SmartReplyManager.swift b/notchPocket/managers/SmartReplyManager.swift deleted file mode 100644 index 427e86df1f..0000000000 --- a/notchPocket/managers/SmartReplyManager.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// SmartReplyManager.swift -// notchPocket -// -// Draft reply suggestions using Apple's on-device Foundation Models — -// entirely local, no network calls, same model that powers Apple -// Intelligence system-wide. -// -// Every touchpoint here is macOS 26+ and Apple-Intelligence-enabled only. -// This project's deployment target is macOS 14, so nothing outside an -// `@available`/`#available` guard may reference FoundationModels — Swift's -// autolinking weak-links the framework based on those annotations, which is -// what lets the app still launch on older macOS versions at all. Skipping a -// guard wouldn't just lose this feature, it would risk the whole app -// failing to launch below macOS 26. -// - -import Foundation - -#if canImport(FoundationModels) -import FoundationModels -#endif - -enum SmartReplyAvailability: Equatable { - case available - case unavailable(reason: String) -} - -enum SmartReplyManager { - static var availability: SmartReplyAvailability { - #if canImport(FoundationModels) - guard #available(macOS 26.0, *) else { - return .unavailable(reason: "Requires macOS 26 or later.") - } - switch SystemLanguageModel.default.availability { - case .available: - return .available - case .unavailable(let reason): - return .unavailable(reason: describeUnavailable(reason)) - } - #else - return .unavailable(reason: "Requires macOS 26 or later.") - #endif - } - - #if canImport(FoundationModels) - @available(macOS 26.0, *) - private static func describeUnavailable(_ reason: SystemLanguageModel.Availability.UnavailableReason) -> String { - switch reason { - case .deviceNotEligible: - return "This Mac doesn't support Apple Intelligence." - case .appleIntelligenceNotEnabled: - return "Turn on Apple Intelligence in System Settings → Apple Intelligence & Siri." - case .modelNotReady: - return "The on-device model is still downloading." - @unknown default: - return "Apple Intelligence isn't available right now." - } - } - #endif - - /// Up to three short reply drafts for the given message, or an empty - /// array on any unavailability/failure — callers show nothing rather - /// than an error state for what's an optional nicety, not a feature the - /// UI depends on. - static func suggestReplies(sender: String?, body: String) async -> [String] { - #if canImport(FoundationModels) - guard #available(macOS 26.0, *), - case .available = SystemLanguageModel.default.availability, - !body.isEmpty - else { return [] } - - do { - let session = LanguageModelSession(instructions: """ - You draft extremely short, casual reply suggestions to an \ - incoming message, in the voice of the person replying, not \ - the sender. Match the tone and language of the message. \ - Never invent facts, plans, times, or commitments the message \ - doesn't mention. Each reply must be under 8 words. - """) - let prompt = "From: \(sender ?? "someone")\nMessage: \(body)\n\nSuggest 3 short possible replies." - let result = try await session.respond(to: prompt, generating: ReplySuggestionSet.self) - - // The model repeats itself sometimes ("Got it!" twice), which is - // both useless as a second chip and a duplicate SwiftUI ForEach - // id. Dedupe case-insensitively, keeping first-seen order. - var seen = Set() - return result.content.replies - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty && seen.insert($0.lowercased()).inserted } - .prefix(3) - .map { $0 } - } catch { - return [] - } - #else - return [] - #endif - } -} - -#if canImport(FoundationModels) -@available(macOS 26.0, *) -@Generable -struct ReplySuggestionSet: Equatable { - @Guide(description: "2 to 3 short, casual reply suggestions, each under 8 words") - let replies: [String] -} -#endif diff --git a/notchPocket/models/Constants.swift b/notchPocket/models/Constants.swift index 5a98222f9b..daca21fe98 100644 --- a/notchPocket/models/Constants.swift +++ b/notchPocket/models/Constants.swift @@ -228,7 +228,6 @@ extension Defaults.Keys { static let minimumHoverDuration = Key("minimumHoverDuration", default: 0.3) static let enableOpeningAnimation = Key("enableOpeningAnimation", default: true) static let animationSpeedMultiplier = Key("animationSpeedMultiplier", default: 1.0) - static let enableHaptics = Key("enableHaptics", default: false) static let openNotchOnHover = Key("openNotchOnHover", default: true) static let extendHoverArea = Key("extendHoverArea", default: false) static let notchHeightMode = Key( @@ -256,7 +255,6 @@ extension Defaults.Keys { static let enableShadow = Key("enableShadow", default: true) static let cornerRadiusScaling = Key("cornerRadiusScaling", default: true) - static let showNotHumanFace = Key("showNotHumanFace", default: false) static let tileShowLabels = Key("tileShowLabels", default: false) static let showCalendar = Key("showCalendar", default: false) static let hideCompletedReminders = Key("hideCompletedReminders", default: true) @@ -266,13 +264,10 @@ extension Defaults.Keys { ) static let playerColorTinting = Key("playerColorTinting", default: true) - // MARK: Gestures - // Off by default in this fork: the notch opens on hover and closes on - // hover-out, so the gesture layer is a second way to do what pointing - // already does. - static let enableGestures = Key("enableGestures", default: false) + // MARK: Media gestures + // Keep the former master key so removing panel swipes cannot re-enable media gestures. + static let enableMediaGestures = Key("enableGestures", default: false) static let enableHorizontalMediaGestures = Key("enableHorizontalMediaGestures", default: false) - static let closeGestureEnabled = Key("closeGestureEnabled", default: false) static let gestureSensitivity = Key("gestureSensitivity", default: 200.0) // MARK: Media playback @@ -313,10 +308,6 @@ extension Defaults.Keys { static let inlineOSD = Key("inlineOSD", default: false) // MARK: Layout - /// Swaps the opened notch for a smaller, player-only layout: no tab - /// bar, calendar or mirror. Off by default so existing users keep the - /// layout they already have. - static let compactMode = Key("compactMode", default: false) static let dashboardConfigurationData = Key("dashboardConfigurationData", default: nil) // MARK: Notifications @@ -338,10 +329,6 @@ extension Defaults.Keys { "com.anthropic.claudefordesktop" ] ) - /// Off by default: a new capability, even though it runs entirely - /// on-device with no network calls. Only takes effect on macOS 26+ with - /// Apple Intelligence enabled — see SmartReplyManager. - static let smartRepliesEnabled = Key("smartRepliesEnabled", default: false) static let enableGradient = Key("enableGradient", default: false) static let systemEventIndicatorShadow = Key("systemEventIndicatorShadow", default: false) @@ -385,6 +372,10 @@ extension Defaults.Keys { "lastSupportedNowPlayingBundleIdentifier", default: nil ) + static let lastNowPlayingLauncherBundleIdentifier = Key( + "lastNowPlayingLauncherBundleIdentifier", + default: nil + ) // MARK: Advanced Settings static let useCustomAccentColor = Key("useCustomAccentColor", default: false) diff --git a/notchPocket/models/NotchPocketViewModel.swift b/notchPocket/models/NotchPocketViewModel.swift index af861a205c..b3143d4e17 100644 --- a/notchPocket/models/NotchPocketViewModel.swift +++ b/notchPocket/models/NotchPocketViewModel.swift @@ -24,7 +24,6 @@ final class NotchPocketViewModel: NSObject, ObservableObject { @Published var hideOnClosed: Bool = true @Published var edgeAutoOpenActive: Bool = false - @Published var isHoveringCalendar: Bool = false @Published var isBatteryPopoverActive: Bool = false @Published var screenUUID: String? diff --git a/notchPocket/sizing/matters.swift b/notchPocket/sizing/matters.swift index 06e1e7aba6..1b6d56fe4f 100644 --- a/notchPocket/sizing/matters.swift +++ b/notchPocket/sizing/matters.swift @@ -14,13 +14,6 @@ let openNotchSize: CGSize = .init(width: 640, height: 190) let windowSize: CGSize = .init(width: openNotchSize.width, height: openNotchSize.height + shadowPadding) let cornerRadiusInsets: (opened: (top: CGFloat, bottom: CGFloat), closed: (top: CGFloat, bottom: CGFloat)) = (opened: (top: 19, bottom: 24), closed: (top: 6, bottom: 14)) -/// Compact mode uses a much rounder opened shape than the standard layout -/// — matching Atoll's minimalisticCornerRadiusInsets (35/35 against the -/// standard 19/24). At compact's smaller size the standard radius reads -/// square; the rounder corners are what make it look like a pill rather -/// than a shrunken panel. -let compactCornerRadiusInsets: (opened: (top: CGFloat, bottom: CGFloat), closed: (top: CGFloat, bottom: CGFloat)) = (opened: (top: 35, bottom: 35), closed: cornerRadiusInsets.closed) - // Horizontal gap between closed-state live-activity content (album art / waveform) // and the physical notch edge. Without this margin the hardware bezel clips the // adjacent content since the spacer rect used to be narrower than the physical notch. diff --git a/notchPocketTests/MusicAppFeedbackTests.swift b/notchPocketTests/MusicAppFeedbackTests.swift new file mode 100644 index 0000000000..b1f3904703 --- /dev/null +++ b/notchPocketTests/MusicAppFeedbackTests.swift @@ -0,0 +1,163 @@ +// +// MusicAppFeedbackTests.swift +// notchPocketTests +// + +import Foundation +import XCTest + +@testable import notchPocket + +final class MusicAppFeedbackTests: XCTestCase { + private let unknownBundleIdentifier = "com.example.unknown-player" + + private func render(_ resource: LocalizedStringResource?) -> String? { + resource.map { String(localized: $0) } + } + + // MARK: - displayName + + func testKnownBundleIdentifiersUseExistingLocalizedNames() { + XCTAssertEqual( + render(MusicAppFeedback.displayName(for: MediaAppBundleID.spotify)), + MediaControllerType.spotify.localizedString + ) + XCTAssertEqual( + render(MusicAppFeedback.displayName(for: MediaAppBundleID.appleMusic)), + MediaControllerType.appleMusic.localizedString + ) + XCTAssertEqual( + render(MusicAppFeedback.displayName(for: MediaAppBundleID.youTubeMusic)), + MediaControllerType.youtubeMusic.localizedString + ) + } + + func testKnownAppsHaveDistinctDisplayNames() { + let names = [ + MediaAppBundleID.spotify, + MediaAppBundleID.appleMusic, + MediaAppBundleID.youTubeMusic + ].compactMap { render(MusicAppFeedback.displayName(for: $0)) } + + XCTAssertEqual(names.count, 3) + XCTAssertEqual(Set(names).count, 3) + } + + func testDisplayNameTrimsBundleIdentifier() { + XCTAssertEqual( + render(MusicAppFeedback.displayName(for: " \(MediaAppBundleID.spotify) \n")), + MediaControllerType.spotify.localizedString + ) + } + + func testDisplayNameIsNilForMissingOrBlankIdentifier() { + XCTAssertNil(MusicAppFeedback.displayName(for: nil)) + XCTAssertNil(MusicAppFeedback.displayName(for: "")) + XCTAssertNil(MusicAppFeedback.displayName(for: " \t\n")) + } + + func testDisplayNameIsNilForUnknownIdentifier() { + XCTAssertNil(MusicAppFeedback.displayName(for: unknownBundleIdentifier)) + } + + // MARK: - message + + func testSuccessfulLaunchProducesNoMessage() { + let outcome = MusicAppLaunchOutcome.opened(bundleIdentifier: MediaAppBundleID.spotify) + + XCTAssertNil(MusicAppFeedback.message(for: outcome)) + } + + func testCancellationIsNotAnErrorAndDoesNotClaimOSCancellation() { + XCTAssertNil(MusicAppFeedback.message(for: .cancelled)) + XCTAssertNil(MusicAppFeedback.conciseMessage(for: .cancelled)) + } + + func testUnconfirmedRequestsNeverClaimNothingLaunched() { + for outcome in [MusicAppLaunchOutcome.timedOut, .alreadyOpening, + .openFailed(bundleIdentifier: MediaAppBundleID.spotify)] { + let message = render(MusicAppFeedback.message(for: outcome)) + XCTAssertNotNil(message) + XCTAssertTrue(message?.contains("Check Applications before trying again.") == true) + XCTAssertFalse(message?.contains("could not be opened") == true) + XCTAssertNotNil(MusicAppFeedback.conciseMessage(for: outcome)) + } + XCTAssertTrue(render(MusicAppFeedback.message(for: .timedOut))?.contains("may still open") == true) + } + + func testArbitraryPublishersHaveTruthfulGenericLabelsAndFeedbackNotSpotify() { + for source in ["org.videolan.vlc", "com.google.Chrome", "org.example.ExternalPlayer"] { + XCTAssertEqual(render(MusicAppFeedback.launchLabel(for: source)), "Open music app") + XCTAssertNil(MusicAppFeedback.displayName(for: source)) + for outcome in [MusicAppLaunchOutcome.notInstalled(bundleIdentifier: source), + .openFailed(bundleIdentifier: source)] { + let message = render(MusicAppFeedback.message(for: outcome)) + XCTAssertNotNil(message) + XCTAssertFalse(message?.contains("Spotify") == true) + XCTAssertFalse(message?.contains(source) == true) + } + } + } + + func testEveryFailureOutcomeProducesAMessage() { + let failures: [MusicAppLaunchOutcome] = [ + .noTarget, + .notInstalled(bundleIdentifier: MediaAppBundleID.spotify), + .openFailed(bundleIdentifier: MediaAppBundleID.spotify), + .notInstalled(bundleIdentifier: unknownBundleIdentifier), + .openFailed(bundleIdentifier: unknownBundleIdentifier), + .timedOut, + .alreadyOpening + ] + + for failure in failures { + let message = render(MusicAppFeedback.message(for: failure)) + + XCTAssertNotNil(message, "\(failure) must explain itself to the user") + XCTAssertFalse(message?.isEmpty ?? true, "\(failure) must not render an empty message") + } + } + + func testNoTargetMessageGuidesWithoutNamingAnApp() { + let message = render(MusicAppFeedback.message(for: .noTarget)) + + XCTAssertNotNil(message) + XCTAssertFalse(message?.contains("com.") ?? true) + } + + func testNotInstalledMessageNamesAKnownApp() { + let outcome = MusicAppLaunchOutcome.notInstalled(bundleIdentifier: MediaAppBundleID.spotify) + let message = render(MusicAppFeedback.message(for: outcome)) + + XCTAssertNotNil(message) + XCTAssertTrue(message?.contains(MediaControllerType.spotify.localizedString) ?? false) + XCTAssertFalse(message?.contains(MediaAppBundleID.spotify) ?? true) + } + + func testOpenFailureMessageNamesAKnownApp() { + let outcome = MusicAppLaunchOutcome.openFailed(bundleIdentifier: MediaAppBundleID.appleMusic) + let message = render(MusicAppFeedback.message(for: outcome)) + + XCTAssertNotNil(message) + XCTAssertTrue(message?.contains(MediaControllerType.appleMusic.localizedString) ?? false) + XCTAssertFalse(message?.contains(MediaAppBundleID.appleMusic) ?? true) + } + + func testUnknownBundleIdentifiersNeverReachUserFacingMessages() { + let outcomes: [MusicAppLaunchOutcome] = [ + .notInstalled(bundleIdentifier: unknownBundleIdentifier), + .openFailed(bundleIdentifier: unknownBundleIdentifier) + ] + + for outcome in outcomes { + guard let message = render(MusicAppFeedback.message(for: outcome)) else { + XCTFail("\(outcome) must still explain the failure") + continue + } + + XCTAssertFalse(message.contains(unknownBundleIdentifier)) + XCTAssertFalse(message.contains("com."), "raw identifiers must not leak: \(message)") + XCTAssertTrue(message.contains(" "), "generic wording must be a sentence: \(message)") + } + } +} diff --git a/notchPocketTests/MusicAppLauncherTests.swift b/notchPocketTests/MusicAppLauncherTests.swift new file mode 100644 index 0000000000..b3ab4413c3 --- /dev/null +++ b/notchPocketTests/MusicAppLauncherTests.swift @@ -0,0 +1,133 @@ +// +// MusicAppLauncherTests.swift +// notchPocketTests +// + +import XCTest + +@testable import notchPocket + +@MainActor +private final class MusicAppOpeningSpy: MusicAppOpening { + enum Operation: Equatable { + case lookup(bundleIdentifier: String) + case open(url: URL) + } + + private(set) var operations: [Operation] = [] + var installedApplications: [String: URL] = [:] + var openSucceeds = true + + func applicationURL(forBundleIdentifier bundleIdentifier: String) -> URL? { + operations.append(.lookup(bundleIdentifier: bundleIdentifier)) + return installedApplications[bundleIdentifier] + } + + func openApplication(at url: URL) async -> Bool { + operations.append(.open(url: url)) + return openSucceeds + } +} + +@MainActor +final class MusicAppLauncherTests: XCTestCase { + private let spotifyURL = URL(fileURLWithPath: "/Applications/Spotify.app") + + private func makeSpy(installed: Bool = true, openSucceeds: Bool = true) -> MusicAppOpeningSpy { + let spy = MusicAppOpeningSpy() + if installed { + spy.installedApplications[MediaAppBundleID.spotify] = spotifyURL + } + spy.openSucceeds = openSucceeds + return spy + } + + func testMissingTargetReportsNoTargetWithoutTouchingWorkspace() async { + let spy = makeSpy() + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: nil) + + XCTAssertEqual(outcome, .noTarget) + XCTAssertTrue(spy.operations.isEmpty) + } + + func testBlankTargetReportsNoTargetWithoutTouchingWorkspace() async { + let spy = makeSpy() + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: " \n") + + XCTAssertEqual(outcome, .noTarget) + XCTAssertTrue(spy.operations.isEmpty) + } + + func testUninstalledTargetReportsNotInstalledWithoutOpening() async { + let spy = makeSpy(installed: false) + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: MediaAppBundleID.spotify) + + XCTAssertEqual(outcome, .notInstalled(bundleIdentifier: MediaAppBundleID.spotify)) + XCTAssertEqual(spy.operations, [.lookup(bundleIdentifier: MediaAppBundleID.spotify)]) + } + + func testInstalledTargetOpensApplicationAndReportsSuccess() async { + let spy = makeSpy() + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: MediaAppBundleID.spotify) + + XCTAssertEqual(outcome, .opened(bundleIdentifier: MediaAppBundleID.spotify)) + XCTAssertEqual( + spy.operations, + [.lookup(bundleIdentifier: MediaAppBundleID.spotify), .open(url: spotifyURL)] + ) + } + + func testFailedOpenReportsOpenFailedForThatTarget() async { + let spy = makeSpy(openSucceeds: false) + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: MediaAppBundleID.spotify) + + XCTAssertEqual(outcome, .openFailed(bundleIdentifier: MediaAppBundleID.spotify)) + XCTAssertEqual( + spy.operations, + [.lookup(bundleIdentifier: MediaAppBundleID.spotify), .open(url: spotifyURL)] + ) + } + + func testTargetIsTrimmedBeforeLookupAndReporting() async { + let spy = makeSpy() + let launcher = MusicAppLauncher(workspace: spy) + + let outcome = await launcher.launch(bundleIdentifier: " \(MediaAppBundleID.spotify) \n") + + XCTAssertEqual(outcome, .opened(bundleIdentifier: MediaAppBundleID.spotify)) + XCTAssertEqual( + spy.operations, + [.lookup(bundleIdentifier: MediaAppBundleID.spotify), .open(url: spotifyURL)] + ) + } + + func testLaunchOnlyOpensTheAppOnceAndInvokesNoOtherOperation() async { + let spy = makeSpy() + let launcher = MusicAppLauncher(workspace: spy) + + _ = await launcher.launch(bundleIdentifier: MediaAppBundleID.spotify) + + let openCount = spy.operations.filter { operation in + if case .open = operation { return true } + return false + }.count + let lookupCount = spy.operations.filter { operation in + if case .lookup = operation { return true } + return false + }.count + + XCTAssertEqual(openCount, 1) + XCTAssertEqual(lookupCount, 1) + XCTAssertEqual(spy.operations.count, 2) + } +} diff --git a/notchPocketTests/MusicLaunchTargetResolverTests.swift b/notchPocketTests/MusicLaunchTargetResolverTests.swift new file mode 100644 index 0000000000..8dbde901d5 --- /dev/null +++ b/notchPocketTests/MusicLaunchTargetResolverTests.swift @@ -0,0 +1,169 @@ +// +// MusicLaunchTargetResolverTests.swift +// notchPocketTests +// + +import XCTest + +@testable import notchPocket + +final class MusicLaunchTargetResolverTests: XCTestCase { + func testPlayingAppleMusicFallbackOpensObservedSourceWithoutNowPlayingHistory() { + let context = MusicLaunchContext( + isPlaying: true, preferred: .nowPlaying, effective: .appleMusic, + observedBundleIdentifier: MediaAppBundleID.appleMusic, rememberedBundleIdentifier: nil + ) + XCTAssertEqual(context.bundleIdentifier, MediaAppBundleID.appleMusic) + } + + func testPlayingSpotifyFallbackIgnoresOtherRememberedPublisher() { + let context = MusicLaunchContext( + isPlaying: true, preferred: .nowPlaying, effective: .spotify, + observedBundleIdentifier: MediaAppBundleID.spotify, rememberedBundleIdentifier: "org.videolan.vlc" + ) + XCTAssertEqual(context.bundleIdentifier, MediaAppBundleID.spotify) + } + + func testIdleFallbackDoesNotMasqueradeAsTrueNowPlayingPublisher() { + for remembered in [nil, "org.videolan.vlc"] { + let context = MusicLaunchContext( + isPlaying: false, preferred: .nowPlaying, effective: .appleMusic, + observedBundleIdentifier: MediaAppBundleID.appleMusic, rememberedBundleIdentifier: remembered + ) + XCTAssertEqual(context.bundleIdentifier, remembered) + } + } + + func testIdleDirectPreferenceWinsButPlayingObservedSourceWins() { + for playing in [false, true] { + let context = MusicLaunchContext( + isPlaying: playing, preferred: .spotify, effective: .spotify, + observedBundleIdentifier: MediaAppBundleID.appleMusic, rememberedBundleIdentifier: "org.videolan.vlc" + ) + XCTAssertEqual(context.bundleIdentifier, playing ? MediaAppBundleID.appleMusic : MediaAppBundleID.spotify) + } + } + + func testTrueNowPlayingUsesCurrentArbitraryPublisherBeforeHistory() { + for source in ["org.videolan.vlc", "com.google.Chrome", "org.example.ExternalPlayer"] { + for playing in [false, true] { + let context = MusicLaunchContext( + isPlaying: playing, preferred: .nowPlaying, effective: .nowPlaying, + observedBundleIdentifier: source, rememberedBundleIdentifier: MediaAppBundleID.spotify + ) + XCTAssertEqual(context.bundleIdentifier, source) + XCTAssertEqual(String(localized: MusicAppFeedback.launchLabel(for: context.bundleIdentifier)), "Open music app") + } + } + } + + private func resolve( + _ preferred: MediaControllerType, + current: String? = nil, + remembered: String? = nil + ) -> String? { + MusicLaunchTargetResolver.bundleIdentifier( + preferred: preferred, + currentBundleIdentifier: current, + rememberedNowPlayingBundleIdentifier: remembered + ) + } + + func testSpotifyResolvesToSpotifyBundleIdentifier() { + XCTAssertEqual(resolve(.spotify), MediaAppBundleID.spotify) + } + + func testAppleMusicResolvesToAppleMusicBundleIdentifier() { + XCTAssertEqual(resolve(.appleMusic), MediaAppBundleID.appleMusic) + } + + func testYouTubeMusicResolvesToYouTubeMusicBundleIdentifier() { + XCTAssertEqual(resolve(.youtubeMusic), MediaAppBundleID.youTubeMusic) + } + + func testDirectControllerIgnoresObservedBundleIdentifiers() { + let resolved = resolve( + .spotify, + current: MediaAppBundleID.appleMusic, + remembered: MediaAppBundleID.youTubeMusic + ) + + XCTAssertEqual(resolved, MediaAppBundleID.spotify) + } + + func testNowPlayingPrefersCurrentBundleIdentifier() { + let resolved = resolve( + .nowPlaying, + current: MediaAppBundleID.spotify, + remembered: MediaAppBundleID.appleMusic + ) + + XCTAssertEqual(resolved, MediaAppBundleID.spotify) + } + + func testNowPlayingFallsBackToRememberedBundleIdentifierWhenCurrentIsMissing() { + XCTAssertEqual( + resolve(.nowPlaying, current: nil, remembered: MediaAppBundleID.spotify), + MediaAppBundleID.spotify + ) + } + + func testNowPlayingTreatsBlankCurrentBundleIdentifierAsAbsent() { + XCTAssertEqual( + resolve(.nowPlaying, current: " \n", remembered: MediaAppBundleID.spotify), + MediaAppBundleID.spotify + ) + } + + func testNowPlayingWithoutAnyObservedTargetResolvesToNil() { + XCTAssertNil(resolve(.nowPlaying, current: nil, remembered: nil)) + } + + func testNowPlayingWithBlankObservedTargetsResolvesToNil() { + XCTAssertNil(resolve(.nowPlaying, current: " ", remembered: "\t")) + } + + func testNowPlayingDoesNotFallBackToAppleMusic() { + let resolved = resolve(.nowPlaying, current: nil, remembered: nil) + + XCTAssertNotEqual(resolved, MediaAppBundleID.appleMusic) + XCTAssertNil(resolved) + } + + func testNowPlayingPreservesAnExternalPlayersBundleIdentifier() { + XCTAssertEqual(resolve(.nowPlaying, current: "org.example.external-player"), "org.example.external-player") + XCTAssertEqual(resolve(.nowPlaying, remembered: "org.example.remembered-player"), "org.example.remembered-player") + } + + func testRememberedLauncherTargetSurvivesClearedAndBlankNowPlayingUpdates() { + var remembered: String? + for observed in [" org.example.external-player ", "", " \n"] { + remembered = MusicLaunchTargetResolver.rememberedBundleIdentifier(observed: observed, previous: remembered) + XCTAssertEqual(remembered, "org.example.external-player") + } + XCTAssertEqual( + MusicLaunchTargetResolver.rememberedBundleIdentifier(observed: nil, previous: remembered), + "org.example.external-player" + ) + } + + func testNewNowPlayingSourceReplacesRememberedLauncherTarget() { + XCTAssertEqual( + MusicLaunchTargetResolver.rememberedBundleIdentifier( + observed: "org.example.new-player", previous: MediaAppBundleID.spotify + ), + "org.example.new-player" + ) + } + + func testNowPlayingTrimsResolvedBundleIdentifier() { + XCTAssertEqual( + resolve(.nowPlaying, current: " \(MediaAppBundleID.spotify) \n", remembered: nil), + MediaAppBundleID.spotify + ) + XCTAssertEqual( + resolve(.nowPlaying, current: nil, remembered: " \(MediaAppBundleID.appleMusic) "), + MediaAppBundleID.appleMusic + ) + } +} diff --git a/notchPocketTests/MusicLaunchTransactionTests.swift b/notchPocketTests/MusicLaunchTransactionTests.swift new file mode 100644 index 0000000000..5d77f82889 --- /dev/null +++ b/notchPocketTests/MusicLaunchTransactionTests.swift @@ -0,0 +1,256 @@ +// +// MusicLaunchTransactionTests.swift +// notchPocketTests +// + +import Combine +import XCTest + +@testable import notchPocket + +@MainActor +private final class SuspendedMusicAppOpening: MusicAppOpening { + private(set) var openCount = 0 + private(set) var lookupCount = 0 + var onOpen: (() -> Void)? + var onLookup: (() -> Void)? + private var continuation: CheckedContinuation? + + func applicationURL(forBundleIdentifier bundleIdentifier: String) -> URL? { + lookupCount += 1 + onLookup?() + return URL(fileURLWithPath: "/Applications/Test Player.app") + } + + func openApplication(at url: URL) async -> Bool { + openCount += 1 + return await withCheckedContinuation { continuation in + self.continuation = continuation + onOpen?() + } + } + + func complete(_ opened: Bool) { + let pending = continuation + continuation = nil + pending?.resume(returning: opened) + } +} + +@MainActor +final class MusicLaunchTransactionTests: XCTestCase { + private func context( + playing: Bool = false, + preferred: MediaControllerType = .nowPlaying, + effective: MediaControllerType = .nowPlaying, + observed: String = MediaAppBundleID.spotify, + remembered: String? = nil + ) -> MusicLaunchContext { + MusicLaunchContext( + isPlaying: playing, preferred: preferred, effective: effective, + observedBundleIdentifier: observed, rememberedBundleIdentifier: remembered + ) + } + + private func start( + _ transaction: MusicLaunchTransaction, + workspace: SuspendedMusicAppOpening, + current: MusicLaunchContext + ) async { + let dispatched = expectation(description: "one workspace request dispatched") + workspace.onOpen = { dispatched.fulfill() } + transaction.start(context: current, currentContext: { current }) + await fulfillment(of: [dispatched], timeout: 1) + workspace.onOpen = nil + } + + private func drain(_ launcher: MusicAppLauncher) async { + // Bounded even on a broken implementation; never await the suspended OS task. + for _ in 0..<100 where launcher.isOpening { + await Task.yield() + } + XCTAssertFalse(launcher.isOpening, "completed OS request must release the shared gate") + } + + func testTimeoutReleasesUIWhileNoncooperativeOSRequestStaysSingle() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher, timeout: .milliseconds(50)) + let current = context() + let expired = expectation(description: "UI deadline returns without OS completion") + let subscription = transaction.$failure.sink { if $0 == .timedOut { expired.fulfill() } } + await start(transaction, workspace: workspace, current: current) + XCTAssertTrue(transaction.isLaunching) + await fulfillment(of: [expired], timeout: 1) + subscription.cancel() + + XCTAssertFalse(transaction.isLaunching) + XCTAssertEqual(transaction.failure, .timedOut) + XCTAssertTrue(launcher.isOpening) + for _ in 0..<20 { + let outcome = await launcher.launch(bundleIdentifier: MediaAppBundleID.appleMusic) + XCTAssertEqual(outcome, .alreadyOpening) + } + XCTAssertEqual(workspace.openCount, 1) + XCTAssertEqual(workspace.lookupCount, 1) + workspace.complete(false) + await drain(launcher) + XCTAssertEqual(transaction.failure, .timedOut, "late failure must not replace timeout") + } + + func testPlaybackResumeCancelsHoldAndSuppressesLateFailure() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + var current = context() + let dispatched = expectation(description: "dispatched before resume") + workspace.onOpen = { dispatched.fulfill() } + transaction.start(context: current, currentContext: { current }) + await fulfillment(of: [dispatched], timeout: 1) + + current = context(playing: true) + transaction.cancel() // The view's context-change handler. + XCTAssertFalse(transaction.isLaunching) + XCTAssertNil(transaction.failure) + workspace.complete(false) + await drain(launcher) + XCTAssertNil(transaction.failure) + } + + func testSourceChangeIsCheckedAfterAwaitEvenBeforeViewNotification() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + var current = context(playing: true) + let dispatched = expectation(description: "dispatched before source change") + workspace.onOpen = { dispatched.fulfill() } + transaction.start(context: current, currentContext: { current }) + await fulfillment(of: [dispatched], timeout: 1) + + current = context(playing: true, observed: "org.videolan.vlc") + workspace.complete(false) + await drain(launcher) + XCTAssertFalse(transaction.isLaunching) + XCTAssertNil(transaction.failure) + } + + func testCancelBeforeDispatchDoesNotEvenLookUpApplication() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + let current = context() + transaction.start(context: current, currentContext: { current }) + transaction.cancel() + await Task.yield() + XCTAssertEqual(workspace.lookupCount, 0) + XCTAssertEqual(workspace.openCount, 0) + XCTAssertFalse(transaction.isLaunching) + } + + func testDisappearanceSuppressesTheDeadlineAndReleasesUIWithoutOSCompletion() async throws { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher, timeout: .milliseconds(20)) + await start(transaction, workspace: workspace, current: context()) + transaction.cancel() + try await Task.sleep(for: .milliseconds(50)) + XCTAssertFalse(transaction.isLaunching) + XCTAssertNil(transaction.failure) + XCTAssertTrue(launcher.isOpening, "UI cancellation must not pretend the OS request ended") + workspace.complete(false) + await drain(launcher) + XCTAssertNil(transaction.failure) + } + + func testChangedContextBeforeDispatchCancelsWithoutOSWork() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + let cancelled = expectation(description: "stale context releases hold") + var current = context() + transaction.start(context: current, currentContext: { current }) + let subscription = transaction.$isLaunching.dropFirst().sink { if !$0 { cancelled.fulfill() } } + current = context(preferred: .appleMusic, effective: .appleMusic) + await fulfillment(of: [cancelled], timeout: 1) + subscription.cancel() + XCTAssertEqual(workspace.lookupCount, 0) + XCTAssertEqual(workspace.openCount, 0) + XCTAssertNil(transaction.failure) + } + + func testDisappearReappearCannotAccumulateRequestsOrOverwriteNewFeedback() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let original = MusicLaunchTransaction(launcher: launcher) + let current = context() + await start(original, workspace: workspace, current: current) + original.cancel() // Disappearance releases UI, not the outstanding OS request. + XCTAssertFalse(original.isLaunching) + + let replacement = MusicLaunchTransaction(launcher: launcher) + let refused = expectation(description: "new view reports still-pending OS operation") + let subscription = replacement.$failure.sink { if $0 == .alreadyOpening { refused.fulfill() } } + replacement.start(context: current, currentContext: { current }) + await fulfillment(of: [refused], timeout: 1) + subscription.cancel() + XCTAssertFalse(replacement.isLaunching) + XCTAssertEqual(workspace.openCount, 1) + workspace.complete(true) + await drain(launcher) + XCTAssertNil(original.failure) + XCTAssertEqual(replacement.failure, .alreadyOpening, "old success cannot clear newer feedback") + + await start(replacement, workspace: workspace, current: current) + XCTAssertEqual(workspace.openCount, 2, "retry is allowed only after the old operation returns") + workspace.complete(true) + await drain(launcher) + XCTAssertFalse(replacement.isLaunching) + XCTAssertNil(replacement.failure) + } + + func testRepeatedClicksAreCoalescedAndPlayingFailureIsPublished() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + let current = context(playing: true) + await start(transaction, workspace: workspace, current: current) + for _ in 0..<20 { transaction.start(context: current, currentContext: { current }) } + XCTAssertEqual(workspace.openCount, 1) + workspace.complete(false) + await drain(launcher) + XCTAssertFalse(transaction.isLaunching) + XCTAssertEqual(transaction.failure, .openFailed(bundleIdentifier: MediaAppBundleID.spotify)) + transaction.dismissFailure() + XCTAssertNil(transaction.failure) + } + + func testStateChangeClearsAlreadyVisibleFeedback() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + await start(transaction, workspace: workspace, current: context()) + workspace.complete(false) + await drain(launcher) + XCTAssertNotNil(transaction.failure) + transaction.cancel() + XCTAssertNil(transaction.failure) + XCTAssertFalse(transaction.isLaunching) + } + + func testCancellationDuringLookupPreventsDispatch() async { + let workspace = SuspendedMusicAppOpening() + let launcher = MusicAppLauncher(workspace: workspace) + let transaction = MusicLaunchTransaction(launcher: launcher) + let lookedUp = expectation(description: "lookup cancels transaction before OS dispatch") + workspace.onLookup = { + transaction.cancel() + lookedUp.fulfill() + } + let current = context() + transaction.start(context: current, currentContext: { current }) + await fulfillment(of: [lookedUp], timeout: 1) + XCTAssertEqual(workspace.openCount, 0) + XCTAssertFalse(transaction.isLaunching) + XCTAssertNil(transaction.failure) + } +} diff --git a/notchPocketTests/MusicPresentationPolicyTests.swift b/notchPocketTests/MusicPresentationPolicyTests.swift new file mode 100644 index 0000000000..3fd135232b --- /dev/null +++ b/notchPocketTests/MusicPresentationPolicyTests.swift @@ -0,0 +1,35 @@ +// +// MusicPresentationPolicyTests.swift +// notchPocketTests +// + +import XCTest + +@testable import notchPocket + +final class MusicPresentationPolicyTests: XCTestCase { + func testPlayingUsesPlayerPresentationWithControls() { + let presentation = MusicPresentationPolicy.presentation(isPlaying: true) + + XCTAssertEqual(presentation, .player) + XCTAssertTrue(presentation.showsPlaybackControls) + XCTAssertFalse(presentation.showsLauncherIcon) + } + + func testNotPlayingCollapsesToLauncherWithoutControls() { + let presentation = MusicPresentationPolicy.presentation(isPlaying: false) + + XCTAssertEqual(presentation, .launcher) + XCTAssertFalse(presentation.showsPlaybackControls) + XCTAssertTrue(presentation.showsLauncherIcon) + } + + func testPauseStopAndResumeDoNotLatchLauncherPresentation() { + let states = [false, true, false, false, true] + + XCTAssertEqual( + states.map { MusicPresentationPolicy.presentation(isPlaying: $0) }, + [.launcher, .player, .launcher, .launcher, .player] + ) + } +} diff --git a/scripts/distribution.py b/scripts/distribution.py index 17ec0b3830..8f784ab527 100644 --- a/scripts/distribution.py +++ b/scripts/distribution.py @@ -83,12 +83,15 @@ def run_command(command, *, env, phase, timeout): return result -def validate_inputs(identity, team, build_value): +def validate_inputs(identity, team, build_value, *, certificate_sha1=None): if not re.fullmatch(r"[A-Z0-9]{10}", team): raise DistributionError("invalid_input", "Supply an explicit ten-character Apple team ID.") if (not re.fullmatch(r"Developer ID Application: [^\x00-\x1f\x7f]+ \([A-Z0-9]{10}\)", identity) or not identity.endswith(" (" + team + ")")): raise DistributionError("invalid_input", "Supply the full Developer ID Application name for this team.") + if certificate_sha1 is not None and not re.fullmatch(r"[0-9a-fA-F]{40}", certificate_sha1): + raise DistributionError("invalid_input", "Supply --certificate-sha1 as exactly 40 hexadecimal characters " + "without separators.") build = Path(build_value) if not build.is_absolute() or ".." in build.parts: raise DistributionError("invalid_input", "Build path must be absolute without '..'.") @@ -253,20 +256,22 @@ def bundle_layout(app, code): return expected -def requirement(team, identifier=None): +def requirement(team, identifier=None, *, certificate_sha1=None): # The leading '=' makes -R an inline requirement, not a filename. value = ('=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists' ' and certificate leaf[field.1.2.840.113635.100.6.1.13] exists' ' and certificate leaf[subject.OU] = "' + team + '"') if identifier is not None: value += ' and identifier "' + identifier + '"' + if certificate_sha1 is not None: + value += ' and certificate leaf = H"' + certificate_sha1 + '"' return value -def verify_bundles(app, tools, env, team, run, *, deep=True): +def verify_bundles(app, tools, env, team, run, *, deep=True, certificate_sha1=None): for bundle, identifier in ((app, APP_ID), (app / HELPER, HELPER_ID)): run([tools["codesign"], "--verify", *(["--deep"] if deep else []), "--strict", "--all-architectures", - "-R", requirement(team, identifier), str(bundle)], + "-R", requirement(team, identifier, certificate_sha1=certificate_sha1), str(bundle)], env=env, phase="signature_failed", timeout=120) @@ -321,10 +326,10 @@ def check_entitlements(actual, expected): raise DistributionError("signature_failed", "Signed entitlements differ from the declared contract.") -def verify_binary(binary, expected, identity, team, tools, env, run): +def verify_binary(binary, expected, identity, team, tools, env, run, *, certificate_sha1=None): identifier, entitlements = expected run([tools["codesign"], "--verify", "--strict", "--all-architectures", - "-R", requirement(team, identifier), str(binary)], + "-R", requirement(team, identifier, certificate_sha1=certificate_sha1), str(binary)], env=env, phase="signature_failed", timeout=120) evidence = [] for arch, fields, actual in signature_details(binary, tools, env, run): @@ -389,8 +394,11 @@ def sign_resource(app, identity, tools, env, run): return RESOURCE_IDENTIFIER -def build_distribution(identity, team, build_value, run=run_command): - build = validate_inputs(identity, team, build_value) +def build_distribution(identity, team, build_value, run=run_command, *, certificate_sha1=None): + build = validate_inputs(identity, team, build_value, certificate_sha1=certificate_sha1) + if certificate_sha1 is not None: + certificate_sha1 = certificate_sha1.upper() + selector = certificate_sha1 if certificate_sha1 is not None else identity env = environment() tools = find_tools(env, run) try: @@ -401,29 +409,31 @@ def build_distribution(identity, team, build_value, run=run_command): scratch = build / "Scratch" scratch.mkdir(mode=0o700) env["TMPDIR"] = str(scratch) + "/" - run(build_command(build, identity, team, tools), env=env, phase="build_failed", timeout=3600) + run(build_command(build, selector, team, tools), env=env, phase="build_failed", timeout=3600) app = build / "Products/Release" / APP_NAME code = code_inventory(app) expected = bundle_layout(app, code) - verify_bundles(app, tools, env, team, run, deep=False) + verify_bundles(app, tools, env, team, run, deep=False, certificate_sha1=certificate_sha1) for binary in code: if binary != app / RESOURCE_CODE: - verify_binary(binary, expected.get(binary, (None, {})), identity, team, tools, env, run) - resource_identifier = sign_resource(app, identity, tools, env, run) + verify_binary(binary, expected.get(binary, (None, {})), identity, team, tools, env, run, + certificate_sha1=certificate_sha1) + resource_identifier = sign_resource(app, selector, tools, env, run) expected[app / RESOURCE_CODE] = (resource_identifier, {}) - verify_bundles(app, tools, env, team, run) + verify_bundles(app, tools, env, team, run, certificate_sha1=certificate_sha1) if code_inventory(app) != code: raise DistributionError("invalid_output", "Code inventory changed during signing.") evidence = [ {"path": str(binary.relative_to(app)), "signatures": verify_binary(binary, expected.get(binary, (None, {})), - identity, team, tools, env, run)} + identity, team, tools, env, run, certificate_sha1=certificate_sha1)} for binary in code ] return {"ok": True, "status": "signed", "distribution": "local-only", "notarization": "NOT YET NOTARIZED", "gatekeeper_assessed": False, "app": str(app), "build_dir": str(build), "configuration": "Release", "version": VERSION, "team": team, "developer_dir": env["DEVELOPER_DIR"], + **({"certificate_sha1": certificate_sha1} if certificate_sha1 is not None else {}), "app_identifier": APP_ID, "helper_identifier": HELPER_ID, "code": evidence} except DistributionError as exc: exc.details["retained_build_dir"] = str(build) @@ -438,17 +448,20 @@ def build_distribution(identity, team, build_value, run=run_command): class Parser(argparse.ArgumentParser): def error(self, message): - raise DistributionError("invalid_arguments", "Use --identity, --team and --build-dir; see --help.") + raise DistributionError("invalid_arguments", "Use --identity, --team and --build-dir, " + "with optional --certificate-sha1 VALUE; see --help.") def main(argv=None): parser = Parser(description=__doc__, epilog="NOT YET NOTARIZED. Does not package, install, launch or publish.") parser.add_argument("--identity", required=True, help="Full Developer ID Application certificate common name") parser.add_argument("--team", required=True, help="Explicit ten-character Apple team ID") + parser.add_argument("--certificate-sha1", help="Optional exact public certificate SHA-1 (40 hex characters); " + "disambiguates certificates with the same common name") parser.add_argument("--build-dir", required=True, help="New absolute directory beneath this checkout's .build/") try: args = parser.parse_args(argv) - result = build_distribution(args.identity, args.team, args.build_dir) + result = build_distribution(args.identity, args.team, args.build_dir, certificate_sha1=args.certificate_sha1) except DistributionError as exc: print(json.dumps({"ok": False, "error": exc.code, "message": str(exc), **exc.details}), file=sys.stderr) return EXIT_CODES[exc.code] diff --git a/scripts/tests/test_distribution.py b/scripts/tests/test_distribution.py index f111177829..2a250294ba 100644 --- a/scripts/tests/test_distribution.py +++ b/scripts/tests/test_distribution.py @@ -7,6 +7,7 @@ import os from pathlib import Path import plistlib +import re import signal import subprocess import tempfile @@ -20,6 +21,8 @@ SPEC.loader.exec_module(distribution) IDENTITY = "Developer ID Application: Contract Fixture (ABCDE12345)" TEAM = "ABCDE12345" +CERTIFICATE_SHA1 = "0123456789ABCDEF0123456789ABCDEF01234567" +OTHER_CERTIFICATE_SHA1 = "89ABCDEF0123456789ABCDEF0123456789ABCDEF" TOOLS = {"xcodebuild": "/fixture/Xcode.app/Contents/Developer/usr/bin/xcodebuild", "codesign": "/usr/bin/codesign", "lipo": "/usr/bin/lipo"} APP_BINARY = Path("Contents/MacOS/notch-pocket") @@ -105,6 +108,30 @@ def test_explicit_identity_team_and_fresh_owned_build_path(self): self.assertEqual(distribution.validate_inputs(IDENTITY, TEAM, str(self.build)), self.build) self.assertFalse(self.build.exists()) + def test_optional_certificate_sha1_accepts_exact_hex_in_either_case(self): + for certificate_sha1 in (None, CERTIFICATE_SHA1, CERTIFICATE_SHA1.lower()): + with self.subTest(certificate_sha1=certificate_sha1): + self.assertEqual(distribution.validate_inputs( + IDENTITY, TEAM, str(self.build), certificate_sha1=certificate_sha1), self.build) + self.assertFalse(self.build.exists()) + + def test_invalid_certificate_sha1_fails_before_tools_or_build_directory_creation(self): + for certificate_sha1 in ( + "", "-", "0" * 39, "0" * 41, "G" * 40, "0x" + CERTIFICATE_SHA1, + " " + CERTIFICATE_SHA1, CERTIFICATE_SHA1 + "\n", + ":".join(["01"] * 20), "0" * 40, '0" and anchor trusted', + ): + with self.subTest(certificate_sha1=certificate_sha1), \ + mock.patch.object(distribution, "find_tools") as tools: + run = mock.Mock() + error = self.assert_error( + "invalid_input", distribution.build_distribution, IDENTITY, TEAM, str(self.build), + run=run, certificate_sha1=certificate_sha1) + self.assertIn("--certificate-sha1", str(error)) + tools.assert_not_called() + run.assert_not_called() + self.assertFalse(self.build.exists()) + def test_missing_adhoc_development_partial_and_mismatched_identity_rejected(self): for identity, team in ( ("", TEAM), ("-", TEAM), ("Developer ID Application", TEAM), @@ -112,8 +139,21 @@ def test_missing_adhoc_development_partial_and_mismatched_identity_rejected(self (IDENTITY, ""), (IDENTITY, "wrong"), (IDENTITY, "ZZZZZ12345"), ("Developer ID Application: Fixture\n (ABCDE12345)", TEAM), ): - with self.subTest(identity=identity, team=team): - self.assert_error("invalid_input", distribution.validate_inputs, identity, team, str(self.build)) + for certificate_sha1 in (None, CERTIFICATE_SHA1): + with self.subTest(identity=identity, team=team, certificate_sha1=certificate_sha1): + self.assert_error("invalid_input", distribution.validate_inputs, identity, team, str(self.build), + certificate_sha1=certificate_sha1) + + def test_certificate_requirement_extends_chain_team_and_identifier_without_replacing_them(self): + base = ('=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists' + ' and certificate leaf[field.1.2.840.113635.100.6.1.13] exists' + ' and certificate leaf[subject.OU] = "' + TEAM + '"') + for identifier in (None, distribution.APP_ID, distribution.HELPER_ID, distribution.RESOURCE_IDENTIFIER): + with self.subTest(identifier=identifier): + expected = base + (' and identifier "' + identifier + '"' if identifier is not None else "") + self.assertEqual(distribution.requirement(TEAM, identifier), expected) + self.assertEqual(distribution.requirement(TEAM, identifier, certificate_sha1=CERTIFICATE_SHA1), + expected + ' and certificate leaf = H"' + CERTIFICATE_SHA1 + '"') def test_existing_paths_are_not_overwritten(self): for directory in (False, True): @@ -251,6 +291,8 @@ def setUp(self): self.resource_architectures = b"x86_64 arm64\n" self.invalid_final_resource_architectures = set() self.changes = {} + self.certificate_changes = {} + self.final_certificate_changes = {} self.entitlement_changes = {} self.fail = None self.build_mutation = None @@ -283,6 +325,13 @@ def fake_run(self, command, *, env, phase, timeout): if resource_input and (arch != "arm64" or "--all-architectures" in command): raise distribution.DistributionError("signature_failed", "Unsigned x86_64 slice.", tool_exit=1) verified_architectures = {arch} if arch and "--all-architectures" not in command else {"x86_64", "arm64"} + if "-R" in command: + inline = command[command.index("-R") + 1] + requested = re.search(r' and certificate leaf = H"([0-9A-F]{40})"', inline) + certificates = self.final_certificate_changes if self.resource_signed else self.certificate_changes + if requested and any(certificates.get((relative, item), CERTIFICATE_SHA1) != requested.group(1) + for item in verified_architectures): + raise distribution.DistributionError("signature_failed", "Certificate leaf mismatch.", tool_exit=29) if (relative == distribution.RESOURCE_CODE and self.resource_signed and verified_architectures & self.invalid_final_resource_architectures): raise distribution.DistributionError("signature_failed", "Invalid final resource signature.", tool_exit=17) @@ -325,8 +374,9 @@ def fake_run(self, command, *, env, phase, timeout): fields.update(self.changes.get((relative, arch), {})) return b"", "\n".join(key + "=" + value for key, value in fields.items() if value is not None).encode() - def build_candidate(self): - return distribution.build_distribution(IDENTITY, TEAM, str(self.build), run=self.fake_run) + def build_candidate(self, certificate_sha1=None): + return distribution.build_distribution( + IDENTITY, TEAM, str(self.build), run=self.fake_run, certificate_sha1=certificate_sha1) def test_complete_nested_multiarchitecture_build_then_planned_resource_sign_and_outer_seal(self): source_bytes = self.resource_source.read_bytes() @@ -337,6 +387,7 @@ def test_complete_nested_multiarchitecture_build_then_planned_resource_sign_and_ self.assertEqual(result["app"], str(self.app)) self.assertEqual(result["configuration"], "Release") self.assertEqual(result["version"], "0.1.0") + self.assertNotIn("certificate_sha1", result) self.assertEqual(len(result["code"]), 4) self.assertEqual({item["path"] for item in result["code"]}, {str(path) for path in (APP_BINARY, HELPER_BINARY, FRAMEWORK_BINARY, distribution.RESOURCE_CODE)}) @@ -380,21 +431,94 @@ def test_complete_nested_multiarchitecture_build_then_planned_resource_sign_and_ self.assertIn("1.2.840.113635.100.6.1.13", inline) self.assertIn(TEAM, inline) self.assertIn("--all-architectures", command) + self.assertNotIn("certificate leaf = H", inline) self.assert_error("output_exists", self.build_candidate) + def test_explicit_certificate_reaches_xcode_both_signs_and_all_verification_requirements(self): + result = self.build_candidate(CERTIFICATE_SHA1.lower()) + self.assertTrue(result["ok"]) + self.assertEqual(result["certificate_sha1"], CERTIFICATE_SHA1) + self.assertEqual(result["team"], TEAM) + self.assertEqual(result["notarization"], "NOT YET NOTARIZED") + commands = [call[0] for call in self.calls] + build = commands[0] + self.assertEqual([part for part in build if part.startswith("CODE_SIGN_IDENTITY")], + ["CODE_SIGN_IDENTITY=" + CERTIFICATE_SHA1]) + self.assertIn("DEVELOPMENT_TEAM=" + TEAM, build) + signs = [command for command in commands if "--sign" in command] + self.assertEqual([command[-1] for command in signs], [str(self.app / distribution.RESOURCE_CODE), str(self.app)]) + for command in signs: + self.assertEqual(command[command.index("--sign") + 1], CERTIFICATE_SHA1) + self.assertIn("--timestamp", command) + self.assertIn("runtime", command) + self.assertNotIn("--deep", command) + checks = [command for command in commands if "-R" in command] + self.assertEqual(len(checks), 11) + self.assertEqual({command[-1] for command in checks}, { + str(self.app / path) for path in + (Path(), distribution.HELPER, APP_BINARY, HELPER_BINARY, FRAMEWORK_BINARY, distribution.RESOURCE_CODE) + }) + for command in checks: + self.assertIn(' and certificate leaf = H"' + CERTIFICATE_SHA1 + '"', command[command.index("-R") + 1]) + self.assertIn("--all-architectures", command) + self.assertIn("--strict", command) + + def test_wrong_xcode_certificate_with_matching_name_and_team_blocks_resource_signing(self): + self.certificate_changes[(FRAMEWORK_BINARY, "arm64")] = OTHER_CERTIFICATE_SHA1 + error = self.assert_error("signature_failed", self.build_candidate, CERTIFICATE_SHA1) + self.assertEqual(error.details["tool_exit"], 29) + self.assertEqual(error.details["retained_build_dir"], str(self.build)) + self.assertFalse(any("--sign" in call[0] for call in self.calls)) + + def test_wrong_final_certificate_on_any_bundle_binary_or_slice_refuses_success_without_retry(self): + for index, path in enumerate(( + Path(), distribution.HELPER, APP_BINARY, HELPER_BINARY, FRAMEWORK_BINARY, distribution.RESOURCE_CODE, + )): + for arch in ("x86_64", "arm64"): + with self.subTest(path=path, arch=arch): + self.build = self.root / ".build" / ("final-certificate-" + str(index) + "-" + arch) + self.app = self.build / "Products/Release/notch-pocket.app" + self.calls.clear() + self.resource_signed = False + self.final_certificate_changes = {(path, arch): OTHER_CERTIFICATE_SHA1} + error = self.assert_error("signature_failed", self.build_candidate, CERTIFICATE_SHA1) + self.assertEqual(error.details["tool_exit"], 29) + self.assertEqual(error.details["retained_build_dir"], str(self.build)) + self.assertEqual(len([call for call in self.calls if "--sign" in call[0]]), 2) + self.assertEqual(self.calls[-1][0][-1], str(self.app / path)) + self.assertIn("--all-architectures", self.calls[-1][0]) + + def test_matching_leaf_does_not_replace_final_name_team_or_entitlement_checks(self): + for index, (fields, entitlements) in enumerate(( + ({"Authority": "Developer ID Application: Another Fixture (ABCDE12345)"}, {}), + ({"TeamIdentifier": "ZZZZZ12345"}, {}), + ({}, {"get-task-allow": False}), + )): + with self.subTest(fields=fields, entitlements=entitlements): + self.build = self.root / ".build" / ("matching-leaf-" + str(index)) + self.app = self.build / "Products/Release/notch-pocket.app" + self.calls.clear() + self.resource_signed = False + self.changes = {(distribution.RESOURCE_CODE, "arm64"): fields} + self.entitlement_changes = {(distribution.RESOURCE_CODE, "arm64"): entitlements} + error = self.assert_error("signature_failed", self.build_candidate, CERTIFICATE_SHA1) + self.assertEqual(error.details["retained_build_dir"], str(self.build)) + self.assertEqual(len([call for call in self.calls if "--sign" in call[0]]), 2) + def test_ad_hoc_wrong_signer_team_flags_or_missing_timestamp_on_any_slice_fails(self): bad_fields = [ {"Signature": "adhoc"}, {"Authority": "Apple Development: Wrong"}, {"TeamIdentifier": "ZZZZZ12345"}, {"Timestamp": None}, {"Timestamp": "none"}, {"CodeDirectory v": "20500 flags=0x0(none)"}, {"Identifier": "wrong"}, ] - for index, fields in enumerate(bad_fields): - with self.subTest(fields=fields): - self.build = self.root / ".build" / ("negative-" + str(index)) - self.app = self.build / "Products/Release/notch-pocket.app" - self.changes = {(HELPER_BINARY, "x86_64"): fields} - self.assert_error("signature_failed", self.build_candidate) - self.assertFalse(self.resource_signed) + for certificate_sha1 in (None, CERTIFICATE_SHA1): + for index, fields in enumerate(bad_fields): + with self.subTest(fields=fields, certificate_sha1=certificate_sha1): + self.build = self.root / ".build" / ("negative-" + str(certificate_sha1) + "-" + str(index)) + self.app = self.build / "Products/Release/notch-pocket.app" + self.changes = {(HELPER_BINARY, "x86_64"): fields} + self.assert_error("signature_failed", self.build_candidate, certificate_sha1) + self.assertFalse(self.resource_signed) def test_exact_entitlements_and_no_debug_including_false(self): for actual in ({"get-task-allow": False}, {"com.apple.security.get-task-allow": True}, @@ -544,6 +668,15 @@ def test_build_failure_retains_owned_path_and_code_without_success(self): self.assertEqual(error.details["retained_build_dir"], str(self.build)) self.assertTrue(self.build.is_dir()) + def test_unavailable_explicit_certificate_build_failure_never_falls_back_to_name(self): + self.fail = lambda command: self.raise_build_failure() + error = self.assert_error("build_failed", self.build_candidate, CERTIFICATE_SHA1) + self.assertEqual(error.details["tool_exit"], 65) + self.assertEqual(error.details["retained_build_dir"], str(self.build)) + self.assertEqual(len(self.calls), 1) + self.assertIn("CODE_SIGN_IDENTITY=" + CERTIFICATE_SHA1, self.calls[0][0]) + self.assertNotIn("CODE_SIGN_IDENTITY=" + IDENTITY, self.calls[0][0]) + @staticmethod def raise_build_failure(): raise distribution.DistributionError("build_failed", "xcodebuild failed.", tool_exit=65) @@ -657,7 +790,13 @@ def test_json_failure_is_not_success_or_a_native_log_dump(self): self.assertNotIn(IDENTITY, errors.getvalue()) def test_required_cli_inputs_and_unknown_flags_never_execute(self): - for args in ([], ["--identity", IDENTITY], ["--private-token", "do-not-echo"]): + required = ["--identity", IDENTITY, "--team", TEAM, "--build-dir", str(self.build)] + for args in ( + [], ["--identity", IDENTITY], ["--private-token", "do-not-echo"], + required + ["--certificate-sha1"], + ["--certificate-sha1", CERTIFICATE_SHA1, "--team", TEAM, "--build-dir", str(self.build)], + ["--certificate-sha1", CERTIFICATE_SHA1, "--identity", IDENTITY, "--build-dir", str(self.build)], + ): output, errors = io.StringIO(), io.StringIO() with self.subTest(args=args), mock.patch.object(distribution, "build_distribution") as build, \ contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): @@ -666,6 +805,36 @@ def test_required_cli_inputs_and_unknown_flags_never_execute(self): self.assertEqual(output.getvalue(), "") self.assertNotIn("do-not-echo", errors.getvalue()) + def test_cli_forwards_optional_certificate_and_keeps_full_name_compatibility(self): + for certificate_sha1 in (None, CERTIFICATE_SHA1.lower()): + args = ["--identity", IDENTITY, "--team", TEAM, "--build-dir", str(self.build)] + if certificate_sha1 is not None: + args += ["--certificate-sha1", certificate_sha1] + output, errors = io.StringIO(), io.StringIO() + with self.subTest(certificate_sha1=certificate_sha1), \ + mock.patch.object(distribution, "build_distribution", return_value={"ok": True}) as build, \ + contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): + self.assertEqual(distribution.main(args), 0) + build.assert_called_once_with(IDENTITY, TEAM, str(self.build), certificate_sha1=certificate_sha1) + self.assertTrue(json.loads(output.getvalue())["ok"]) + self.assertEqual(errors.getvalue(), "") + + def test_cli_invalid_certificate_reports_input_error_without_echo_or_native_calls(self): + output, errors = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): + status = distribution.main([ + "--identity", IDENTITY, "--team", TEAM, "--build-dir", str(self.build), + "--certificate-sha1", "do-not-echo", + ]) + self.assertEqual(status, 3) + self.assertEqual(json.loads(errors.getvalue())["error"], "invalid_input") + self.assertIn("--certificate-sha1", json.loads(errors.getvalue())["message"]) + self.assertNotIn("do-not-echo", errors.getvalue()) + self.assertNotIn(IDENTITY, errors.getvalue()) + self.assertEqual(output.getvalue(), "") + self.assertEqual(self.calls, []) + self.assertFalse(self.build.exists()) + class SubprocessTests(unittest.TestCase): def test_pipe_error_stops_and_reaps_owned_child_before_propagating(self): diff --git a/scripts/tests/test_regression_probe.py b/scripts/tests/test_regression_probe.py index dd7a56b686..435d061f62 100644 --- a/scripts/tests/test_regression_probe.py +++ b/scripts/tests/test_regression_probe.py @@ -1,10 +1,14 @@ import contextlib +import copy +import hashlib import importlib.util import io import json from pathlib import Path import plistlib +import re import subprocess +import struct import tempfile from types import SimpleNamespace import unittest @@ -149,10 +153,610 @@ def framework(self, passed=True): return {"totalTestCount": 1, "passedTests": int(passed), "failedTests": int(not passed), "skippedTests": 0, "expectedFailures": 0} - def test_real_registry_has_valid_notes_and_one_functional_journey(self): + def notifications_receipt(self, scale=1): + case = next(c for c in SUITE.load_registry(ROOT / "experiments/tart-regression/suite.json") + if c["id"] == "notifications-ai-replies-removed") + observations = dict.fromkeys(["Show notifications in the notch", "From all apps", "suggestionControlAbsent"], True) + receipt = dict(self.receipt(scenario=case["scenario"]), testIdentifier=case["test"], + runID="10000000-0000-4000-8000-000000000001", notificationsCaptureVersion=1, + observedPublicText=observations, discovery={ + "notificationsPaneSelected": True, "notificationsFormMapped": True, + "notificationsScrollComplete": True, "notificationsScrollOffsetPoints": 180, + "notificationsOverlapPoints": 368, + }) + del receipt["screenshotSHA256"] + receipt["captures"] = [] + for index, role in enumerate(["top", "bottom"]): + frame = {"x": 598, "y": 147 - index * 180, "width": 452, "height": 680} + receipt["captures"].append({ + "role": role, "name": f'guest-public-notifications-{receipt["runID"]}-{role}', + "sha256": ("b" if index == 0 else "c") * 64, "runID": receipt["runID"], + "scenario": case["scenario"], "testIdentifier": case["test"], "candidateSHA256": "a" * 64, + "candidatePID": 123, "appPath": "/Applications/notch-pocket.app", + "windowID": 456, "windowMarker": "NotchPocketSettingsWindow", + "pane": "Notifications", "windowFrame": {"x": 370, "y": 75, "width": 700, "height": 600}, + "formFrame": {"x": 578, "y": 127, "width": 492, "height": 548}, + "contentFrames": [frame], "endpointFrames": [dict(frame)], "contentTypes": [3], + "labelFrames": {label: {"x": 0.34, "y": 0.8 - n * 0.2, "width": 0.3, "height": 0.03} + for n, label in enumerate(["Show notifications in the notch", "From all apps"])} if index == 0 else {}, + "observedPublicText": dict(observations) if index == 0 else { + "Show notifications in the notch": False, "From all apps": False, "suggestionControlAbsent": True, + }, + "pixelWidth": int(700 * scale), "pixelHeight": int(600 * scale), + }) + return case, receipt + + def test_real_registry_preserves_journeys_and_controls_and_adds_idle_launcher(self): cases = SUITE.load_registry(ROOT / "experiments/tart-regression/suite.json") - self.assertEqual([c["id"] for c in cases if c["kind"] == "regression"], ["about-version"]) - self.assertEqual(len(cases), 6) + self.assertEqual([c["id"] for c in cases if c["kind"] == "regression"], + ["about-version", "appearance-idle-face-removed", "notifications-ai-replies-removed", + "general-haptics-removed", "general-panel-swipes-removed", "general-compact-mode-removed", + "music-idle-no-target", "music-idle-unavailable"]) + self.assertEqual([(c["id"], c["scenario"], c["expectedVerdict"], c["expectedReason"]) + for c in cases if c["kind"] == "control"], [ + ("about-wrong-output", "visual-fail", "FAIL", "rendered_output_mismatch"), + ("about-stale-evidence", "stale-evidence", "BLOCKED", "capture_identity_mismatch"), + ("about-missing-reveal", "visual-no-reveal", "FAIL", "rendered_output_mismatch"), + ("abort-after-settings-open", "native-abort-after-open", "BLOCKED", "native_interaction_aborted"), + ("abort-after-about-selection", "native-abort-after-about", "BLOCKED", "native_interaction_aborted"), + ]) + self.assertEqual(len(cases), 13) + + def music_receipt(self, scenario="music-idle-no-target"): + case = next(c for c in SUITE.load_registry(ROOT / "experiments/tart-regression/suite.json") + if c["id"] == scenario) + source = SUITE.IDLE_MUSIC_SCENARIOS[scenario][0] + receipt = dict(self.receipt(scenario=scenario), testIdentifier=case["test"], + runID="10000000-0000-4000-8000-000000000001", + observedPublicText=dict.fromkeys([ + "selectedSourceVerified", "idleLauncherVisible", "transportAbsent", "headerPreserved", + "launchStatusVisible", "noFocusChangeOnFailedLaunch", "statusPixels", "statusDismissed", "launcherRestored", + ], True), discovery={ + "musicSource": source, "musicSourceRestored": True, "musicPreferencesRestored": True, + "musicPanelRestored": True, "musicWindowID": 10, "musicCandidatePID": 123, + "musicWindowMarker": "com.jdylanmc.notchpocket.notch.v1.window.10", + "musicCaptureRunID": "10000000-0000-4000-8000-000000000001", + }) + return case, receipt + + def test_music_requires_real_output_and_restoration_evidence(self): + for scenario in SUITE.IDLE_MUSIC_SCENARIOS: + case, receipt = self.music_receipt(scenario) + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64), + ("PASS", "rendered_output_verified")) + PROBE.idle_music_assertions(receipt) + for field in receipt["observedPublicText"]: + missing = copy.deepcopy(receipt) + del missing["observedPublicText"][field] + self.assertEqual(SUITE.evaluate(case, missing, self.framework(), 0, "a" * 64)[0], "BLOCKED") + wrong = copy.deepcopy(receipt) + wrong["observedPublicText"][field] = False + self.assertEqual(SUITE.evaluate(case, wrong, self.framework(), 0, "a" * 64)[0], "BLOCKED") + wrong.update(verdict="FAIL", reason="rendered_output_mismatch", xcodeExit=65, suiteExit=10) + self.assertEqual(SUITE.evaluate(case, wrong, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + for field in receipt["discovery"]: + missing = copy.deepcopy(receipt) + del missing["discovery"][field] + self.assertEqual(SUITE.evaluate(case, missing, self.framework(), 0, "a" * 64)[0], "BLOCKED") + + def test_music_rejects_stale_wrong_target_and_changed_native_identity(self): + case, receipt = self.music_receipt() + for change in [{"musicSource": "Spotify"}, {"musicCaptureRunID": "other"}, + {"musicWindowID": 12}, {"musicWindowID": True}, {"musicCandidatePID": 0}, + {"musicPreferencesRestored": False}, {"musicPanelRestored": False}]: + wrong = copy.deepcopy(receipt) + wrong["discovery"].update(change) + self.assertEqual(SUITE.evaluate(case, wrong, self.framework(), 0, "a" * 64)[0], "BLOCKED") + + def test_music_focus_receipt_is_failure_scoped_not_a_success_activation_ban(self): + case, receipt = self.music_receipt() + for replacement in ["noFocusChange", "targetActivatedOnSuccess"]: + wrong = copy.deepcopy(receipt) + del wrong["observedPublicText"]["noFocusChangeOnFailedLaunch"] + wrong["observedPublicText"][replacement] = True + self.assertEqual(SUITE.evaluate(case, wrong, self.framework(), 0, "a" * 64)[0], "BLOCKED") + wrong = copy.deepcopy(receipt) + wrong["observedPublicText"]["noFocusChangeOnFailedLaunch"] = False + wrong.update(verdict="FAIL", reason="rendered_output_mismatch", xcodeExit=65, suiteExit=10) + self.assertEqual(SUITE.evaluate(case, wrong, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + + def general_receipt(self, scenario="general-haptics-removed", scale=1): + _, receipt = self.notifications_receipt(scale) + case = next(c for c in SUITE.load_registry(ROOT / "experiments/tart-regression/suite.json") + if c["id"] == scenario) + descriptor = SUITE.SCENARIOS[case["scenario"]] + labels = sorted(descriptor["labels"]) + receipt.pop("notificationsCaptureVersion") + receipt.update(scenario=case["scenario"], testIdentifier=case["test"], + generalCaptureVersion=1, originalPane="General") + receipt["discovery"] = {key.replace("notifications", "general"): value + for key, value in receipt["discovery"].items()} + receipt["discovery"].update(generalNavigationObserved=True, generalScrollRestored=True) + receipt["observedPublicText"] = dict.fromkeys(labels + [descriptor["absence"]], True) + for index, capture in enumerate(receipt["captures"]): + capture.update(name=capture["name"].replace("notifications", "general"), + scenario=case["scenario"], testIdentifier=case["test"], pane="General") + visible = labels[:7] if index == 0 else labels[7:] + capture["labelFrames"] = { + label: {"x": 0.34, "y": 0.8 - n * 0.08, "width": 0.6, "height": 0.03} + for n, label in enumerate(visible) + } + capture["observedPublicText"] = {label: label in visible for label in labels} + capture["observedPublicText"][descriptor["absence"]] = True + return case, receipt + + def test_panel_swipes_requires_media_output_and_absence_at_both_endpoints(self): + case, receipt = self.general_receipt("general-panel-swipes-removed") + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64), + ("PASS", "rendered_output_verified")) + self.assertEqual(PROBE.settings_captures(receipt), receipt["captures"]) + self.assertIn("Enable media gestures", receipt["observedPublicText"]) + self.assertNotIn("Enable gestures", receipt["observedPublicText"]) + for label in receipt["observedPublicText"]: + for endpoint in range(2): + failed = copy.deepcopy(receipt) + failed.update(verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65) + failed["observedPublicText"][label] = False + if label == "panelGestureControlsAbsent": + failed["captures"][endpoint]["observedPublicText"][label] = False + else: + for capture in failed["captures"]: + capture["observedPublicText"][label] = False + with self.subTest(label=label, endpoint=endpoint): + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + inconsistent = dict(failed, verdict="PASS", suiteExit=0, xcodeExit=0) + self.assertEqual(SUITE.evaluate(case, inconsistent, self.framework(), 0, "a" * 64)[0], + "BLOCKED") + + def test_compact_removal_requires_every_retained_label_and_absence_at_both_endpoints(self): + case, receipt = self.general_receipt("general-compact-mode-removed") + labels = { + "Show menu bar icon", "Launch at login", "Language", "Show on all displays", + "Preferred display", "Automatically switch displays", "Notch height on notch displays", + "Notch height on non-notch displays", "Open notch on hover", "Remember last tab", + "Notch animation", "Enable media gestures", + } + for scenario in ["general-haptics-removed", "general-panel-swipes-removed", case["scenario"]]: + self.assertEqual(SUITE.SCENARIOS[scenario]["labels"], labels) + self.assertEqual(set(receipt["observedPublicText"]), labels | {"compactModeControlAbsent"}) + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64), + ("PASS", "rendered_output_verified")) + self.assertEqual(PROBE.settings_captures(receipt), receipt["captures"]) + for label in receipt["observedPublicText"]: + for endpoint in range(2): + failed = copy.deepcopy(receipt) + failed.update(verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65) + failed["observedPublicText"][label] = False + if label == "compactModeControlAbsent": + failed["captures"][endpoint]["observedPublicText"][label] = False + else: + for capture in failed["captures"]: + capture["observedPublicText"][label] = False + with self.subTest(label=label, endpoint=endpoint): + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + inconsistent = dict(failed, verdict="PASS", suiteExit=0, xcodeExit=0) + self.assertEqual(SUITE.evaluate(case, inconsistent, self.framework(), 0, "a" * 64)[0], + "BLOCKED") + + def test_compact_removal_rejects_borrowed_incomplete_or_unrestored_evidence(self): + case, receipt = self.general_receipt("general-compact-mode-removed") + for scenario in ["general-haptics-removed", "general-panel-swipes-removed"]: + _, other = self.general_receipt(scenario) + for field in ["captures", "testIdentifier", "observedPublicText"]: + with self.subTest(scenario=scenario, field=field): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **{field: other[field]}), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + for change in [ + {"generalCaptureVersion": True}, {"generalCaptureVersion": 2}, + {"screenshotSHA256": "b" * 64}, {"captures": receipt["captures"][:1]}, + {"captures": list(reversed(receipt["captures"]))}, {"originalPane": "Other"}, + {"cleanup": "blocked"}, + ]: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), self.framework(), 0, "a" * 64)[0], + "BLOCKED") + for guard in receipt["discovery"]: + altered = copy.deepcopy(receipt) + altered["discovery"].pop(guard) + with self.subTest(guard=guard): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for endpoint in range(2): + for field in receipt["captures"][endpoint]: + altered = copy.deepcopy(receipt) + altered["captures"][endpoint].pop(field) + with self.subTest(endpoint=endpoint, field=field): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for pane in ["closed", "About"]: + altered = copy.deepcopy(receipt) + altered["originalPane"] = pane + altered["discovery"].pop("generalScrollRestored") + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "PASS") + + def test_panel_swipes_rejects_borrowed_general_evidence_and_missing_restoration(self): + case, receipt = self.general_receipt("general-panel-swipes-removed") + _, haptics = self.general_receipt() + for change in [ + {"captures": haptics["captures"]}, {"testIdentifier": haptics["testIdentifier"]}, + {"observedPublicText": haptics["observedPublicText"]}, {"generalCaptureVersion": 2}, + {"captures": receipt["captures"][:1]}, {"screenshotSHA256": "b" * 64}, + {"cleanup": "blocked"}, {"originalPane": "Other"}, + ]: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), self.framework(), 0, "a" * 64)[0], + "BLOCKED") + for guard in receipt["discovery"]: + altered = copy.deepcopy(receipt) + altered["discovery"].pop(guard) + with self.subTest(guard=guard): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for pane in ["closed", "About"]: + altered = copy.deepcopy(receipt) + altered["originalPane"] = pane + altered["discovery"].pop("generalScrollRestored") + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "PASS") + + def test_general_requires_retained_output_absence_navigation_and_restoration(self): + case, receipt = self.general_receipt() + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64), + ("PASS", "rendered_output_verified")) + self.assertEqual(PROBE.settings_captures(receipt), receipt["captures"]) + for key in receipt["observedPublicText"]: + failed = copy.deepcopy(receipt) + failed.update(verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65) + failed["observedPublicText"][key] = False + for capture in failed["captures"]: + capture["observedPublicText"][key] = False + with self.subTest(missing_or_removed=key): + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + inconsistent = dict(failed, verdict="PASS", suiteExit=0, xcodeExit=0) + self.assertEqual(SUITE.evaluate(case, inconsistent, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for field in receipt["discovery"]: + altered = copy.deepcopy(receipt) + altered["discovery"].pop(field) + with self.subTest(missing_guard=field): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for pane in ["closed", "About"]: + altered = copy.deepcopy(receipt) + altered["originalPane"] = pane + altered["discovery"].pop("generalScrollRestored") + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "PASS") + blocked = dict(receipt, verdict="BLOCKED", reason="general_scroll_coverage_incomplete", suiteExit=20, xcodeExit=65) + self.assertEqual(SUITE.evaluate(case, blocked, self.framework(False), 20, "a" * 64), + ("BLOCKED", "general_scroll_coverage_incomplete")) + + def test_general_rejects_stale_cross_scenario_or_incomplete_endpoint_evidence(self): + case, receipt = self.general_receipt() + for change in [ + {"generalCaptureVersion": True}, {"generalCaptureVersion": 2}, {"notificationsCaptureVersion": 1}, + {"screenshotSHA256": "b" * 64}, {"captures": []}, {"captures": receipt["captures"][:1]}, + {"captures": receipt["captures"] * 2}, {"captures": list(reversed(receipt["captures"]))}, + {"originalPane": "Other"}, {"testIdentifier": self.case["test"]}, + {"captures": self.notifications_receipt()[1]["captures"]}, {"cleanup": "blocked"}, + ]: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), self.framework(), 0, "a" * 64)[0], "BLOCKED") + for index in range(2): + for field in receipt["captures"][index]: + altered = copy.deepcopy(receipt) + altered["captures"][index].pop(field) + with self.subTest(endpoint=index, missing=field): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for change in [ + {"candidateSHA256": "d" * 64}, {"candidatePID": 999}, {"windowID": 999}, + {"runID": "20000000-0000-4000-8000-000000000001"}, {"pane": "Notifications"}, + {"name": "wrong"}, {"pixelWidth": 701}, {"labelFrames": {}}, + {"contentTypes": [True]}, {"endpointFrames": []}, {"sha256": "wrong"}, + ]: + altered = copy.deepcopy(receipt) + altered["captures"][index].update(change) + with self.subTest(endpoint=index, change=change): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for delta in [-1, 0, 484, 485, 500]: + altered = copy.deepcopy(receipt) + tail = altered["captures"][1] + tail["contentFrames"][0]["y"] = 147 - delta + tail["endpointFrames"] = copy.deepcopy(tail["contentFrames"]) + altered["discovery"].update(generalScrollOffsetPoints=delta, generalOverlapPoints=548-delta) + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], + "PASS" if delta == 484 else "BLOCKED") + for index in range(2): + failed = copy.deepcopy(receipt) + failed.update(verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65) + failed["captures"][index]["observedPublicText"]["hapticControlAbsent"] = False + failed["observedPublicText"]["hapticControlAbsent"] = False + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64)[0], "FAIL") + + def test_general_missing_measured_labels_remains_output_failure_not_block(self): + for scenario in ["general-haptics-removed", "general-panel-swipes-removed", "general-compact-mode-removed"]: + for scale in [1, 2, 3, 4]: + case, receipt = self.general_receipt(scenario, scale) + for label in SUITE.SCENARIOS[scenario]["labels"]: + with self.subTest(scenario=scenario, scale=scale, missing=label): + failed = copy.deepcopy(receipt) + failed.update(verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65) + failed["observedPublicText"][label] = False + for capture in failed["captures"]: + capture["labelFrames"].pop(label, None) + capture["observedPublicText"][label] = False + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + self.assertEqual(PROBE.settings_captures(failed), failed["captures"]) + lying = copy.deepcopy(failed) + lying["observedPublicText"][label] = True + self.assertEqual(SUITE.evaluate(case, lying, self.framework(False), 10, "a" * 64)[0], "BLOCKED") + + def test_capture_scale_uses_existing_frame_and_dimensions_without_new_receipt_fields(self): + """Synthetic geometry contracts, not additional native capture evidence.""" + for scenario in ["notifications-ai-replies-removed", "general-haptics-removed", + "general-panel-swipes-removed", "general-compact-mode-removed"]: + for points in [700, 900, 1024]: + for scale in [0.75, 1, 1.25, 1.5, 2, 3, 4, 4.25]: + case, receipt = (self.notifications_receipt(scale) if scenario.startswith("notifications") + else self.general_receipt(scenario, scale)) + for capture in receipt["captures"]: + normalization = capture["windowFrame"]["width"] / points + for frame in capture["labelFrames"].values(): + frame["x"] *= normalization + frame["width"] *= normalization + capture["windowFrame"]["width"] = points + capture["pixelWidth"] = int(points * scale) + with self.subTest(scenario=scenario, points=points, scale=scale): + expected = "PASS" if 1 <= scale <= 4 else "BLOCKED" + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64)[0], expected) + if expected == "PASS": + self.assertEqual(PROBE.settings_captures(receipt), receipt["captures"]) + + def test_notifications_requires_complete_consistent_output_and_viewport_proof(self): + case, receipt = self.notifications_receipt() + observations, discovery = receipt["observedPublicText"], receipt["discovery"] + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64), + ("PASS", "rendered_output_verified")) + for field in observations: + with self.subTest(missing=field): + incomplete = {key: value for key, value in observations.items() if key != field} + self.assertEqual(SUITE.evaluate(case, dict(receipt, observedPublicText=incomplete), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + with self.subTest(wrong=field): + failed = dict(receipt, verdict="FAIL", reason="rendered_output_mismatch", + suiteExit=10, xcodeExit=65, observedPublicText=dict(observations, **{field: False})) + failed["captures"] = copy.deepcopy(receipt["captures"]) + failed["captures"][0]["observedPublicText"][field] = False + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + self.assertEqual(SUITE.evaluate(case, dict(receipt, observedPublicText=failed["observedPublicText"]), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + for field in discovery: + for value in [False, None, 1]: + with self.subTest(guard=field, value=value): + self.assertEqual(SUITE.evaluate(case, dict(receipt, discovery=dict(discovery, **{field: value})), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + for change in [{"observedPublicText": None}, {"observedPublicText": {}}, + {"observedPublicText": dict(observations, suggestionControlAbsent=1)}, + {"observedPublicText": dict(observations, unexpected=True)}, + {"discovery": None}, {"discovery": {}}, + {"cleanup": "blocked"}, {"expectedCandidateSHA256": "c" * 64}, + {"screenshotSHA256": None}, {"testIdentifier": self.case["test"]}]: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + blocked = dict(receipt, verdict="BLOCKED", reason="notifications_scroll_coverage_incomplete", + suiteExit=20, xcodeExit=65, observedPublicText={}) + self.assertEqual(SUITE.evaluate(case, blocked, self.framework(False), 20, "a" * 64), + ("BLOCKED", "notifications_scroll_coverage_incomplete")) + + def test_notifications_rejects_missing_duplicate_extra_or_stale_capture_evidence(self): + case, receipt = self.notifications_receipt() + changes = [ + {"captures": None}, {"captures": []}, {"captures": receipt["captures"][:1]}, + {"captures": receipt["captures"] * 2}, {"captures": [receipt["captures"][0]] * 2}, + {"captures": list(reversed(receipt["captures"]))}, {"notificationsCaptureVersion": True}, + {"notificationsCaptureVersion": 2}, {"runID": "not-a-run"}, {"screenshotSHA256": "b" * 64}, + ] + for change in changes: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), self.framework(), 0, "a" * 64)[0], "BLOCKED") + for field in receipt["captures"][0]: + altered = copy.deepcopy(receipt) + del altered["captures"][0][field] + with self.subTest(missing=field): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for change in [ + {"unexpected": 1}, {"role": "top"}, {"runID": "20000000-0000-4000-8000-000000000001"}, + {"candidateSHA256": "d" * 64}, {"candidatePID": 124}, {"windowID": 457}, {"appPath": "/other.app"}, + {"name": receipt["captures"][0]["name"]}, {"sha256": "b" * 64}, {"sha256": "invalid"}, + {"pane": "General"}, {"windowMarker": "other"}, {"scenario": "visual-pass"}, + {"testIdentifier": self.case["test"]}, {"pixelWidth": 701}, {"pixelHeight": True}, + {"observedPublicText": {}}, {"observedPublicText": {"suggestionControlAbsent": True}}, + {"contentFrames": []}, {"contentTypes": [True]}, {"endpointFrames": []}, + {"formFrame": {"x": 0, "y": 0, "width": 492, "height": 548}}, + ]: + altered = copy.deepcopy(receipt) + altered["captures"][1].update(change) + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + + def test_notifications_rejects_gaps_stalled_endpoints_geometry_and_unbound_labels(self): + case, receipt = self.notifications_receipt() + for delta in [0, 500, -1]: + altered = copy.deepcopy(receipt) + tail = altered["captures"][1] + tail["contentFrames"][0]["y"] = 147 - delta + tail["endpointFrames"] = copy.deepcopy(tail["contentFrames"]) + altered["discovery"].update(notificationsScrollOffsetPoints=delta, notificationsOverlapPoints=548-delta) + with self.subTest(offset=delta): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for field, value in [("height", float("nan")), ("y", float("inf")), ("width", -1), ("x", True), + ("x", 0), ("y", 126)]: + altered = copy.deepcopy(receipt) + top = altered["captures"][0] + top["contentFrames"][0][field] = value + top["endpointFrames"] = copy.deepcopy(top["contentFrames"]) + with self.subTest(field=field, value=value): + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + for labels in [{}, {"unknown": {"x": 0.4, "y": 0.5, "width": 0.2, "height": 0.03}}, + {"From all apps": {"x": 0.4, "y": 1.1, "width": 0.2, "height": 0.03}}]: + altered = copy.deepcopy(receipt) + altered["captures"][0]["labelFrames"] = labels + self.assertEqual(SUITE.evaluate(case, altered, self.framework(), 0, "a" * 64)[0], "BLOCKED") + # A truly short form can have zero motion, but both endpoints must fit. + fitted = copy.deepcopy(receipt) + for capture in fitted["captures"]: + capture["contentFrames"] = [{"x": 598, "y": 147, "width": 452, "height": 400}] + capture["endpointFrames"] = copy.deepcopy(capture["contentFrames"]) + fitted["captures"][1]["sha256"] = fitted["captures"][0]["sha256"] + fitted["discovery"].update(notificationsScrollOffsetPoints=0, notificationsOverlapPoints=548) + self.assertEqual(SUITE.evaluate(case, fitted, self.framework(), 0, "a" * 64)[0], "PASS") + + def test_notifications_export_requires_each_named_hashed_capture_and_no_extras(self): + _, receipt = self.notifications_receipt() + self.check_settings_export(receipt) + + def test_general_export_requires_each_named_hashed_capture_and_no_extras(self): + _, receipt = self.general_receipt() + self.check_settings_export(receipt) + + def check_settings_export(self, receipt): + destination = self.root / "captures" + destination.mkdir() + attachments = [] + for index, capture in enumerate(receipt["captures"]): + # Header bytes are policy fixtures, never native screenshots or signoff. + data = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" + struct.pack(">II", 700, 600) + bytes([index]) + filename = f"capture-{index}.png" + (destination / filename).write_bytes(data) + capture["sha256"] = hashlib.sha256(data).hexdigest() + attachments.append({"exportedFileName": filename, + "suggestedHumanReadableName": capture["name"] + "_0_fixture.png"}) + manifest = [{"testIdentifier": "GuestRegressionProbe/" + SUITE.SCENARIOS[receipt["scenario"]]["test"] + "()", + "attachments": attachments}] + manifest_path = destination / "manifest.json" + manifest_path.write_text(json.dumps(manifest)) + with patch.object(SUITE.subprocess, "run"): + result = SUITE.export_capture(self.root / "run", destination, receipt) + self.assertEqual([item["role"] for item in result], ["top", "bottom"]) + for altered in [[], [None], [{}], [manifest[0], manifest[0]], + [dict(manifest[0], testIdentifier="Other/test()")], + [dict(manifest[0], attachments=attachments[:1])], + [dict(manifest[0], attachments=attachments * 2)], + [dict(manifest[0], attachments=[attachments[0], attachments[0]])], + [dict(manifest[0], attachments=[attachments[0], dict(attachments[1], exportedFileName="../outside.png")])], + [dict(manifest[0], attachments=[attachments[0], dict(attachments[1], exportedFileName="capture-0.png")])], + [dict(manifest[0], attachments=[attachments[0], dict(attachments[1], suggestedHumanReadableName="other.png")])]]: + with self.subTest(manifest=altered): + manifest_path.write_text(json.dumps(altered)) + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + manifest_path.write_text(json.dumps(manifest)) + extra = destination / "extra.png" + extra.write_bytes(b"extra") + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + extra.unlink() + image = destination / "capture-1.png" + data = image.read_bytes() + image.unlink() + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + image.write_bytes(data + b"drift") + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + wrong_size = data[:16] + struct.pack(">II", 1, 1) + data[24:] + image.write_bytes(wrong_size) + receipt["captures"][1]["sha256"] = hashlib.sha256(wrong_size).hexdigest() + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + + def test_legacy_capture_contract_rejects_multi_capture_substitution(self): + for extra in [{"captures": []}, {"notificationsCaptureVersion": 1}, {"generalCaptureVersion": 1}]: + receipt = dict(self.receipt(), **extra) + self.assertEqual(SUITE.evaluate(self.case, receipt, self.framework(), 0, "a" * 64)[0], "BLOCKED") + destination = self.root / "legacy" + destination.mkdir() + image = destination / "single.png" + image.write_bytes(b"legacy-contract-fixture") + receipt = dict(self.receipt(), screenshotSHA256=hashlib.sha256(image.read_bytes()).hexdigest()) + with patch.object(SUITE.subprocess, "run"): + self.assertEqual(SUITE.export_capture(self.root / "run", destination, receipt), str(image)) + (destination / "extra.png").write_bytes(b"extra") + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) + + def test_appearance_requires_complete_consistent_observable_assertions(self): + case = next(c for c in SUITE.load_registry(ROOT / "experiments/tart-regression/suite.json") + if c["id"] == "appearance-idle-face-removed") + observations = dict.fromkeys([ + "Always show tabs", "Show settings icon in notch", "Colored spectrogram", + "Real-time audio waveform", "Player tinting", "Enable blur effect behind album art", + "Slider color", "faceControlAbsent", "additionalFeaturesAbsent", + ], True) + discovery = dict.fromkeys([ + "appearancePaneSelected", "appearanceFormMapped", "appearanceFullFormVisible", + "appearanceSectionHeaderClassVerified", + ], True) + receipt = dict(self.receipt(scenario=case["scenario"]), testIdentifier=case["test"], + observedPublicText=observations, discovery=discovery) + self.assertEqual(SUITE.evaluate(case, receipt, self.framework(), 0, "a" * 64)[0], "PASS") + for field in observations: + with self.subTest(missing=field): + incomplete = {key: value for key, value in observations.items() if key != field} + self.assertEqual(SUITE.evaluate(case, dict(receipt, observedPublicText=incomplete), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + with self.subTest(wrong=field): + failed = dict(receipt, verdict="FAIL", reason="rendered_output_mismatch", + suiteExit=10, xcodeExit=65, observedPublicText=dict(observations, **{field: False})) + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64)[0], "FAIL") + self.assertEqual(SUITE.evaluate(case, dict(receipt, observedPublicText=failed["observedPublicText"]), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + for field in discovery: + for value in [False, None, 1]: + with self.subTest(guard=field, value=value): + self.assertEqual(SUITE.evaluate(case, dict(receipt, discovery=dict(discovery, **{field: value})), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + missing_controls = dict(observations, **{"Colored spectrogram": False, "Slider color": False}) + failed = dict(receipt, verdict="FAIL", reason="rendered_output_mismatch", suiteExit=10, xcodeExit=65, + observedPublicText=missing_controls) + self.assertEqual(SUITE.evaluate(case, failed, self.framework(False), 10, "a" * 64), + ("FAIL", "rendered_output_mismatch")) + for change in [{"observedPublicText": None}, {"observedPublicText": {}}, + {"observedPublicText": dict(observations, faceControlAbsent=1)}, + {"observedPublicText": dict(observations, unexpected=True)}, + {"discovery": None}, {"discovery": {}}, {"discovery": {"appearancePaneSelected": False}}]: + with self.subTest(change=change): + self.assertEqual(SUITE.evaluate(case, dict(receipt, **change), + self.framework(), 0, "a" * 64)[0], "BLOCKED") + + def test_music_capture_export_binds_native_test_and_run_attachment(self): + _, receipt = self.music_receipt() + destination = self.root / "music" + destination.mkdir() + image = destination / "music.png" + image.write_bytes(b"synthetic-capture-contract-only") + receipt["screenshotSHA256"] = hashlib.sha256(image.read_bytes()).hexdigest() + attachment = { + "exportedFileName": image.name, + "suggestedHumanReadableName": "guest-public-music-" + receipt["runID"] + "_1.png", + } + manifest = [{"testIdentifier": "GuestRegressionProbe/testInstalledIdleMusicWithoutTarget()", + "attachments": [attachment]}] + manifest_path = destination / "manifest.json" + manifest_path.write_text(json.dumps(manifest)) + with patch.object(SUITE.subprocess, "run"): + self.assertEqual(SUITE.export_capture(self.root / "run", destination, receipt), str(image)) + for wrong in [ + [], [None], [dict(manifest[0], testIdentifier="other")], + [dict(manifest[0], attachments=[])], [dict(manifest[0], attachments=[None])], + [dict(manifest[0], attachments=[dict(attachment, suggestedHumanReadableName=None)])], + [dict(manifest[0], attachments=[dict(attachment, suggestedHumanReadableName="stale_1.png")])], + [dict(manifest[0], attachments=[dict(attachment, exportedFileName="other.png")])], + ]: + manifest_path.write_text(json.dumps(wrong)) + with self.assertRaises(ValueError): + SUITE.export_capture(self.root / "run", destination, receipt) def test_default_full_suite_includes_registered_controls(self): cases = SUITE.load_registry(self.registry) @@ -381,6 +985,763 @@ def test_timeout_during_cleanup_is_reported(self): self.assertEqual(result["lookupError"], "TimeoutExpired") +class IdleLauncherSourceContractTests(unittest.TestCase): + """Wiring boundaries only; native playback and focus require the guest.""" + + def test_launcher_does_not_restore_removed_layout_or_replace_shared_media(self): + root = ROOT / "notchPocket" + content = (root / "ContentView.swift").read_text() + home = (root / "components/Notch/NotchHomeView.swift").read_text() + project = (ROOT / "notchPocket.xcodeproj/project.pbxproj").read_text() + self.assertIn("MusicSectionView { openMusicApp in", home) + self.assertIn("MusicPlayerView(", home) + self.assertIn("MediaOutputSlotButton()", home) + self.assertIn("CalendarView()", home) + self.assertIn("WebcamView(webcamManager:", home) + self.assertNotIn("CompactMusicHover", project + content) + self.assertFalse((root / "components/Notch/CompactMusicHoverTrackingView.swift").exists()) + self.assertFalse((ROOT / "notchPocketTests/CompactMusicHoverPolicyTests.swift").exists()) + self.assertIn(".onPreferenceChange(MusicLaunchInteractionPreferenceKey.self)", content) + self.assertIn(".onPreferenceChange(MusicLaunchFeedbackHoverPreferenceKey.self)", content) + self.assertIn("guard isHorizontalMediaGestureContext && !isHoveringMusicLaunchFeedback", content) + self.assertEqual(content.count("!self.musicLaunchInteractionActive && !SharingStateManager.shared.preventNotchClose"), 3) + + def test_native_scenarios_use_product_identifiers_and_real_source_selection(self): + root = ROOT / "experiments/tart-regression/GuestRegressionProbe" + native = (root / "IdleMusicLauncherScenario.swift").read_text() + view = (ROOT / "notchPocket/components/Music/MusicSectionView.swift").read_text() + for identifier in ["com.jdylanmc.notchpocket.music.v1.idle-launcher", + "com.jdylanmc.notchpocket.music.v1.launch-status", + "com.jdylanmc.notchpocket.music.v1.launch-dismiss"]: + self.assertIn(identifier, native) + self.assertIn('.accessibilityIdentifier("' + identifier + '")', view) + for action in ["launcher.click()", "dismiss.click()", "panel.screenshot()", "option.click()", + "CFPreferencesAppSynchronize", "NSWorkspace.shared.urlForApplication", + "IdleMusicOutputOracle.statusVisible", "musicPreferencesRestored"]: + self.assertIn(action, native) + self.assertNotIn("@testable import notchPocket", native) + self.assertNotIn("CFPreferencesSet", native) + self.assertNotIn("launchEnvironment", native) + self.assertNotIn("NSApp.activate", view) + self.assertNotIn('panel.buttons["OK"]', native) + self.assertIn(".accessibilityHint(Text(guidance))", view) + self.assertRegex(view, r"\.onChange\(of: launchContext\).+?in\s+clearLaunch\(\)") + self.assertIn(".onDisappear(perform: clearLaunch)", view) + self.assertIn("launch.cancel()", view) + self.assertIn("value: launch.isLaunching", view) + self.assertIn(".disabled(launch.isLaunching)", view) + self.assertNotIn(".overlay(", view, "feedback must not cover active transports") + self.assertNotIn(".background(.black)", view) + self.assertIn(".frame(height: 32)", view) + + def test_paused_launcher_is_distinct_from_retained_live_activity_and_gestures(self): + root = ROOT / "notchPocket" + view = (root / "components/Music/MusicSectionView.swift").read_text() + policy = (root / "MediaControllers/MusicAppLauncher.swift").read_text() + content = (root / "ContentView.swift").read_text() + self.assertIn("MusicPresentationPolicy.presentation(isPlaying: musicManager.isPlaying)", view) + self.assertNotIn("isPlayerIdle", view) + self.assertIn("isPlaying ? .player : .launcher", policy) + self.assertIn("coordinator.musicLiveActivityEnabled && (musicManager.isPlaying || !musicManager.isPlayerIdle)", content) + self.assertIn("coordinator.currentView == .home && !musicManager.isPlayerIdle && isHoveringMusicArea", content) + + def test_launcher_history_does_not_change_controller_fallback(self): + manager = (ROOT / "notchPocket/managers/MusicManager.swift").read_text() + fallback = manager.split("private func resolvedNowPlayingFallback()", 1)[1].split( + "func ensureNowPlayingAvailabilityChecked()", 1)[0] + self.assertIn("lastSupportedNowPlayingBundleIdentifier", fallback) + self.assertNotIn("lastNowPlayingLauncherBundleIdentifier", fallback) + updates = manager.split("private func updateFromPlaybackState", 1)[1] + self.assertRegex(updates, r"if effectiveMediaController == \.nowPlaying \{\s+" + r"let remembered = Defaults\[\.lastNowPlayingLauncherBundleIdentifier\]") + self.assertIn("MusicLaunchTargetResolver.rememberedBundleIdentifier(", updates) + launcher = manager.split("var musicLaunchContext:", 1)[1].split("func forceUpdate()", 1)[0] + self.assertIn("Defaults[.lastNowPlayingLauncherBundleIdentifier]", launcher) + self.assertIn("?? Defaults[.lastSupportedNowPlayingBundleIdentifier]", launcher) + self.assertIn("isPlaying: isPlaying", launcher) + self.assertIn("effective: effectiveMediaController", launcher) + self.assertIn("observedBundleIdentifier: bundleIdentifier", launcher) + self.assertIn("await musicAppLauncher.launch(bundleIdentifier: musicLaunchContext.bundleIdentifier)", launcher) + self.assertIn("let musicAppLauncher = MusicAppLauncher(workspace: WorkspaceMusicAppOpening())", manager) + policy = (ROOT / "notchPocket/MediaControllers/MusicAppLauncher.swift").read_text() + self.assertIn("if isPlaying, let observed = nonemptyBundleIdentifier(observedBundleIdentifier)", policy) + self.assertIn("currentBundleIdentifier: effective == .nowPlaying ? observedBundleIdentifier : nil", policy) + view = (ROOT / "notchPocket/components/Music/MusicSectionView.swift").read_text() + self.assertIn("launch.start(context: launchContext, currentContext: { manager.musicLaunchContext })", view) + self.assertIn("MusicAppFeedback.launchLabel(for: launchContext.bundleIdentifier)", view) + self.assertIn("musicAppLaunchIcon(for: launchContext.bundleIdentifier)", view) + self.assertIn("urlForApplication(withBundleIdentifier: bundleIdentifier)", view) + home = (ROOT / "notchPocket/components/Notch/NotchHomeView.swift").read_text() + self.assertIn("musicAppLaunchIcon(for: musicManager.musicLaunchContext.bundleIdentifier)", home) + self.assertIn("MusicAppFeedback.launchLabel(for: musicManager.musicLaunchContext.bundleIdentifier)", home) + self.assertIn("configuration.activates = true", policy, + "successful user-requested opens intentionally activate the target") + self.assertIn("configuration.createsNewApplicationInstance = false", policy) + self.assertIn("return await withCheckedContinuation", policy) + self.assertNotIn("try await NSWorkspace.shared.openApplication", policy) + self.assertNotRegex(launcher, r"togglePlay|\.play\(|\.pause\(") + + +class CompactModeRemovalSourceContractTests(unittest.TestCase): + """Removal and preservation boundaries, not installed full-panel output proof.""" + + def test_legacy_compact_preference_has_no_reader_writer_or_migration(self): + sources = [source for folder in ["notchPocket", "notchPocketXPCHelper", "Shared"] + for source in (ROOT / folder).rglob("*.swift")] + self.assertTrue(sources) + for source in sources: + with self.subTest(path=str(source.relative_to(ROOT))): + self.assertNotRegex(source.read_text(), + r"\bcompactMode\b|\bcompactCornerRadiusInsets\b" + r"|struct CompactHomeView\b|struct CompactControlButton\b") + self.assertFalse((ROOT / "notchPocket/components/Notch/CompactHomeView.swift").exists()) + project = (ROOT / "notchPocket.xcodeproj/project.pbxproj").read_text() + self.assertNotIn("CompactHomeView", project) + self.assertIn("path = MediaOutputSlotButton.swift;", project) + self.assertEqual(project.count("MediaOutputSlotButton.swift in Sources"), 2) + + def test_full_panel_shape_height_header_and_all_routes_ignore_legacy_flag(self): + content = (ROOT / "notchPocket/ContentView.swift").read_text() + self.assertNotIn("openedInsets", content) + self.assertRegex(content, r"\.padding\(\s*\.horizontal,\s*" + r"vm\.notchState == \.open \? cornerRadiusInsets\.opened\.top" + r" : cornerRadiusInsets\.closed\.bottom\s*\)") + self.assertIn("return cornerRadiusInsets.opened.top", content) + self.assertIn("bottomCorner = cornerRadiusInsets.opened.bottom", content) + height = content.split("private var openNotchHeight: CGFloat {", 1)[1].split("\n }", 1)[0] + self.assertEqual(height.strip(), "if notificationManager.activeNotification != nil { return 132 }\n" + " return vm.notchSize.height") + header = content.split("private var showsHeader: Bool {", 1)[1].split("\n }", 1)[0] + self.assertEqual(header.strip(), "vm.notchState == .open\n" + " && notificationManager.activeNotification == nil") + self.assertIn("} else if showsHeader {", content) + self.assertIn("NotchPocketHeader()", content) + self.assertIn("NotificationExpandedView(notification: notification)\n" + " } else {\n switch coordinator.currentView {", content) + for route, view in [("dashboard", "DashboardView"), ("home", "NotchHomeView"), ("shelf", "ShelfView")]: + self.assertRegex(content, rf"case \.{route}:\s+{view}\(") + self.assertNotIn(".frame(width: 336)", content) + + def test_shared_media_output_transport_and_small_icons_remain(self): + output = (ROOT / "notchPocket/components/Notch/MediaOutputSlotButton.swift").read_text() + for fragment in [ + "struct AudioOutputPicker: View", "struct MediaOutputSlotButton: View", + "HoverButton(icon: routeSymbol, scale: .medium)", "routeManager.refreshDevices()", + "showingPicker.toggle()", ".popover(isPresented: $showingPicker, arrowEdge: .bottom)", + "AudioOutputPicker(routeManager: routeManager)", "showingPicker = false", + "ForEach(routeManager.devices)", "routeManager.select(device)", "onSelect()", + "device.id == routeManager.activeDeviceID", + "routeManager.activeDevice?.iconName ?? AudioOutputRouteResolver.shared.outputRouteSymbol()", + ]: + self.assertIn(fragment, output) + home = (ROOT / "notchPocket/components/Notch/NotchHomeView.swift").read_text() + home += (ROOT / "notchPocket/components/Music/MusicSliderView.swift").read_text() + for fragment in [ + "MusicManager.shared.seek(to: newValue)", "MusicManager.shared.toggleShuffle()", + "MusicManager.shared.previousTrack()", "MusicManager.shared.togglePlay()", + "MusicManager.shared.nextTrack()", "MusicManager.shared.toggleRepeat()", + "MediaOutputSlotButton()", "VolumeControlView()", "FavoriteControlButton()", + "MusicManager.shared.skip(seconds: -15)", "MusicManager.shared.skip(seconds: 15)", + "@Default(.musicControlSlots)", "@Default(.musicControlSlotLimit)", + "MusicManager.shared.estimatedPlaybackPosition(at: currentDate)", + "musicAppLaunchIcon(for: musicManager.musicLaunchContext.bundleIdentifier)", + ".frame(width: 30, height: 30)", "struct MusicSliderView: View", "struct CustomSlider: View", + ]: + self.assertIn(fragment, home) + + def test_calendar_mirror_header_navigation_and_defaults_are_preserved(self): + home = (ROOT / "notchPocket/components/Notch/NotchHomeView.swift").read_text() + for fragment in ["Defaults[.showMirror] && webcamManager.cameraAvailable && vm.isCameraExpanded", + "if Defaults[.showCalendar] {", "CalendarView()", "if shouldShowCamera {", + "WebcamView(webcamManager: webcamManager)", "MusicPlayerView("]: + self.assertIn(fragment, home) + header = (ROOT / "notchPocket/components/Notch/NotchPocketHeader.swift").read_text() + for fragment in ["TabSelectionView()", 'label: "Dashboard"', 'label: "Home"', + "if Defaults[.showMirror] {", "vm.toggleCameraPreview()", + "if Defaults[.settingsIconInNotch] {", "NotchPocketBatteryView(", + "exposesCompactTabAccessibility"]: + self.assertIn(fragment, header) + constants = (ROOT / "notchPocket/models/Constants.swift").read_text() + for fragment in ['showCalendar = Key("showCalendar", default: false)', + 'showMirror = Key("showMirror", default: false)', + 'notchPocketShelf = Key("notchPocketShelf", default: true)', + 'dashboardConfigurationData = Key("dashboardConfigurationData", default: nil)']: + self.assertIn("static let " + fragment, constants) + coordinator = (ROOT / "notchPocket/NotchPocketViewCoordinator.swift").read_text() + self.assertIn('@AppStorage("alwaysShowTabs") var alwaysShowTabs: Bool = true', coordinator) + self.assertIn('@AppStorage("openLastTabByDefault") var openLastTabByDefault: Bool = false', coordinator) + + def test_closed_notched_and_external_display_geometry_stays_distinct(self): + sizing = (ROOT / "notchPocket/sizing/matters.swift").read_text() + for fragment in [ + "let openNotchSize: CGSize = .init(width: 640, height: 190)", + "(opened: (top: 19, bottom: 24), closed: (top: 6, bottom: 14))", + "let liveActivityEdgeMargin: CGFloat = 8", + "func getClosedNotchSize(screenUUID: String? = nil)", "screen.auxiliaryTopLeftArea?.width", + "screen.auxiliaryTopRightArea?.width", + "screen.safeAreaInsets.top > 0 ? Defaults[.notchHeight] : Defaults[.nonNotchHeight]", + "closed: CGSize(width: 20, height: 20)", + ]: + self.assertIn(fragment, sizing) + content = (ROOT / "notchPocket/ContentView.swift").read_text() + for fragment in [ + "let baseClosedTop = cornerRadiusInsets.closed.top", + "let baseClosedBottom = cornerRadiusInsets.closed.bottom", + "let effectiveHeight = displayClosedNotchHeight", "effectiveHeight / 38.0", + "else if !vm.hasNotch {", + "Rectangle().fill(.clear).frame(width: vm.closedNotchSize.width - 20, height: 11)", + "let baseArtSize = displayClosedNotchHeight - 12", "liveActivityEdgeMargin", + ]: + self.assertIn(fragment, content) + + def test_catalog_removes_only_owned_mode_copy_not_shared_media_labels(self): + def unique(pairs): + self.assertEqual(len(dict(pairs)), len(pairs), "Duplicate localization key") + return dict(pairs) + strings = json.loads((ROOT / "notchPocket/Localizable.xcstrings").read_text(), + object_pairs_hook=unique)["strings"] + for key in ["Compact mode", + "Shows a smaller opened notch with just the music player — no tabs, calendar or mirror."]: + self.assertNotIn(key, strings) + for key in ["Output", "Looking for devices…", "Calendar", "Mirror", "Show calendar", + "Enable mirror", "Enable media gestures", "Notch height on notch displays", + "Notch height on non-notch displays", "Remember last tab"]: + self.assertTrue(key in strings, f"Missing retained localization: {key}") + + def test_native_case_uses_existing_capture_and_restore_without_new_authority(self): + root = ROOT / "experiments/tart-regression/GuestRegressionProbe" + native = (root / "GuestRegressionProbe.swift").read_text() + self.assertIn('runInstalledSettingsOutput(testName: "testInstalledGeneralWithoutCompactMode",\n' + ' modes: ["general-compact-mode-removed"])', native) + oracle = (root / "SettingsRemovalOutputOracle.swift").read_text() + for fragment in ['case compactMode = "general-compact-mode-removed"', + '"compactModeControlAbsent"', '"compact mode"', '"shows a smaller opened notch"']: + self.assertIn(fragment, oracle) + retained = oracle.split("var retainedLabels: [String] {", 1)[1].split("var removedLabels", 1)[0] + self.assertNotIn('"Compact mode"', retained) + self.assertIn("case .general, .panelSwipes, .compactMode:", retained) + self.assertEqual(re.findall(r'"([^"]+)"', retained.split( + "case .general, .panelSwipes, .compactMode:", 1)[1]), [ + "Show menu bar icon", "Launch at login", "Language", "Show on all displays", + "Preferred display", "Automatically switch displays", + "Notch height on notch displays", "Notch height on non-notch displays", + "Open notch on hover", "Remember last tab", "Notch animation", "Enable media gestures", + ]) + self.assertIn("scenario.removedLabelsAbsent { form.staticTexts[$0].exists }", native) + self.assertRegex(oracle, r"func removedLabelsAbsent\(isPresent: \(String\) -> Bool\) -> Bool \{\s*" + r"removedLabels\.allSatisfy \{ !isPresent\(\$0\) \}\s*\}") + self.assertIn("SettingsRemovalOutputOracle.combine(outputs, scenario: scenario)", native) + self.assertIn('state.discovery["generalScrollRestored"] = restored == original', native) + self.assertEqual(native.count("VNImageRequestHandler"), 2) + self.assertNotIn("import notchPocket", native) + + +class PanelSwipeRemovalSourceContractTests(unittest.TestCase): + """Source boundaries and preference wiring, not installed-app gesture proof.""" + + def test_vertical_panel_handlers_state_and_defaults_have_no_product_consumers(self): + sources = list((ROOT / "notchPocket").rglob("*.swift")) + self.assertTrue(sources) + for source in sources: + with self.subTest(path=str(source.relative_to(ROOT))): + self.assertNotRegex(source.read_text(), + r"closeGestureEnabled|handleDownGesture|handleUpGesture|isHoveringCalendar" + r"|\bgestureProgress\b|panGesture\(direction: \.(up|down)\)") + pan = (ROOT / "notchPocket/extensions/PanGesture.swift").read_text() + directions = pan.split("enum PanDirection {", 1)[1].split("extension View", 1)[0] + self.assertIn("case left, right", directions) + self.assertNotRegex(directions, r"\b(up|down|isHorizontal|deltaY|height)\b") + + def test_persisted_media_keys_defaults_and_two_flag_gate_are_unchanged(self): + constants = (ROOT / "notchPocket/models/Constants.swift").read_text() + for declaration in [ + 'enableMediaGestures = Key("enableGestures", default: false)', + 'enableHorizontalMediaGestures = Key("enableHorizontalMediaGestures", default: false)', + 'gestureSensitivity = Key("gestureSensitivity", default: 200.0)', + 'normalizeGestureDirection = Key("normalizeGestureDirection", default: true)', + ]: + self.assertIn("static let " + declaration, constants) + content = (ROOT / "notchPocket/ContentView.swift").read_text() + self.assertEqual(content.count("Defaults[.enableMediaGestures]"), 1) + self.assertIn( + ".conditionalModifier(Defaults[.enableHorizontalMediaGestures] && Defaults[.enableMediaGestures]" + " && !shouldDisplayNowPlayingFallbackNotice)", content) + settings = (ROOT / "notchPocket/components/Settings/Views/GeneralSettingsView.swift").read_text() + for fragment in [ + "@Default(.enableMediaGestures) var enableMediaGestures", + "Defaults.Toggle(key: .enableMediaGestures)", 'Text("Enable media gestures")', + "if enableMediaGestures {", "Defaults.Toggle(key: .enableHorizontalMediaGestures)", + 'Text("Change media with horizontal gestures")', + "Slider(value: $gestureSensitivity, in: 100...300, step: 100)", 'Text("Gesture sensitivity")', + ]: + self.assertIn(fragment, settings) + for source in (ROOT / "notchPocket").rglob("*.swift"): + self.assertIsNone(re.search( + r"(?m)(?:Defaults\[\.(?:enableMediaGestures|enableHorizontalMediaGestures)\]" + r"|^\s*(?:self\.)?enableMediaGestures)\s*=(?!=)", source.read_text()), + f"Unexpected automatic media preference write: {source.relative_to(ROOT)}") + advanced = (ROOT / "notchPocket/components/Settings/Views/AdvancedSettingsView.swift").read_text() + self.assertIn("Defaults.Toggle(key: .normalizeGestureDirection)", advanced) + + def test_hover_disabled_does_not_enable_media_or_block_click_and_keyboard(self): + settings = (ROOT / "notchPocket/components/Settings/Views/GeneralSettingsView.swift").read_text() + self.assertNotIn(".onChange(of: openNotchOnHover)", settings) + self.assertNotIn(".disabled(!openNotchOnHover)", settings) + content = (ROOT / "notchPocket/ContentView.swift").read_text() + click = content.split(".onTapGesture {", 1)[1].split(".conditionalModifier(", 1)[0] + self.assertIn("if vm.notchState == .closed && !shouldDisplayNowPlayingFallbackNotice", click) + self.assertIn("doOpen()", click) + app = (ROOT / "notchPocket/NotchPocketApp.swift").read_text() + shortcut = app.split("KeyboardShortcuts.onKeyDown(for: .toggleNotchOpen)", 1)[1].split( + "// Sync notch height", 1)[0] + self.assertIn("didOpen = viewModel.open()", shortcut) + self.assertIn("viewModel.close()", shortcut) + self.assertIn("viewModel?.close()", shortcut) + self.assertIn("if Defaults[.showOnAllDisplays]", shortcut) + model = (ROOT / "notchPocket/models/NotchPocketViewModel.swift").read_text() + opening = model.split("func open() -> Bool {", 1)[1].split("func close()", 1)[0] + self.assertIn("guard !coordinator.firstLaunch, notchState != .open else { return false }", opening) + self.assertIn("self.notchState = .open", opening) + for route in [click, shortcut, opening]: + self.assertNotRegex(route, r"openNotchOnHover|enableMediaGestures|enableHorizontalMediaGestures") + hover = content.split("private func handleHover(", 1)[1].split("// MARK: - Media", 1)[0] + for fragment in ["Defaults[.openNotchOnHover]", "Defaults[.minimumHoverDuration]", "self.doOpen()", + "self.vm.close()", "Task.isCancelled", "!SharingStateManager.shared.preventNotchClose"]: + self.assertIn(fragment, hover) + + def test_horizontal_media_recognition_feedback_and_static_controls_remain(self): + content = (ROOT / "notchPocket/ContentView.swift").read_text() + media = content.split("// MARK: - Media Gesture Handling", 1)[1].split("struct FullScreenDropDelegate", 1)[0] + for fragment in [ + "musicManager.nextTrack()", "musicManager.previousTrack()", + "guard isHorizontalMediaGestureContext", "guard phase != .ended", + "guard !horizontalMediaGestureTriggered else { return }", + "guard translation > Defaults[.gestureSensitivity] else { return }", + "horizontalMediaGestureTriggered = false", "horizontalMediaGestureFeedback = feedback", + "mediaGestureProgress = 2", "mediaGestureProgress = .zero", + "guard !vm.hideOnClosed", "coordinator.musicLiveActivityEnabled", + "coordinator.currentView == .home && !musicManager.isPlayerIdle && isHoveringMusicArea", + ]: + self.assertIn(fragment, media) + self.assertNotRegex(media, r"\b(doOpen|open|close)\(\)") + self.assertEqual(re.findall(r"\.panGesture\(direction: \.(\w+)\)", content), ["left", "right"]) + pan = (ROOT / "notchPocket/extensions/PanGesture.swift").read_text() + for fragment in [ + "translation.width * sign", "deltaX * sign", "self == .right ? 1 : -1", + "DragGesture(minimumDistance: 0)", "NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel])", + "event.window === view?.window", "NSEvent.removeMonitor(lm)", + "let axisDominanceFactor: CGFloat = 1.5", "absDX >= axisDominanceFactor * absDY", + "Defaults[.normalizeGestureDirection] ? (event.isDirectionInvertedFromDevice ? 1 : -1) : 1", + "event.hasPreciseScrollingDeltas ? 1 : 8", "accumulated += delta", + "Task.sleep(for: .milliseconds(300))", "event.phase == .ended || event.momentumPhase == .ended", + ]: + self.assertIn(fragment, pan) + home = (ROOT / "notchPocket/components/Notch/NotchHomeView.swift").read_text() + for fragment in ["MusicPlayerView(", "CalendarView()", "horizontalMediaGestureFeedback", + "isHoveringMusicArea: $isHoveringMusicArea"]: + self.assertIn(fragment, home) + for fragment in ["ShelfStateViewModel.shared.load(providers)", "ShelfView(", "NotchHomeView("]: + self.assertIn(fragment, content) + + def test_media_pulse_cleanup_is_unconditional_after_delay(self): + content = (ROOT / "notchPocket/ContentView.swift").read_text() + feedback = content.split("private func triggerHorizontalMediaFeedback(", 1)[1].split( + "private var isHorizontalMediaGestureContext:", 1)[0] + start, cleanup = feedback.split("Task { @MainActor in", 1) + self.assertIn("withAnimation(.interactiveSpring(response: 0.18, dampingFraction: 0.62))", start) + self.assertRegex(start, r"horizontalMediaGestureFeedback = feedback\s+" + r"if vm\.notchState == \.closed \{\s+mediaGestureProgress = 2\s+\}") + # Source contract only: opening before the timer must not gate either reset. + self.assertRegex(cleanup, r"^\s*try\? await Task\.sleep\(for: \.milliseconds\(140\)\)\s+" + r"withAnimation\(animationSpring\) \{\s+" + r"horizontalMediaGestureFeedback = \.zero\s+" + r"mediaGestureProgress = \.zero\s+\}\s+\}\s+\}\s*$") + + def test_catalog_removes_only_panel_copy_and_retains_media_configuration(self): + def unique(pairs): + self.assertEqual(len(dict(pairs)), len(pairs), "Duplicate localization key") + return dict(pairs) + catalog = json.loads((ROOT / "notchPocket/Localizable.xcstrings").read_text(), object_pairs_hook=unique) + strings = catalog["strings"] + self.assertNotIn("Close gesture", strings) + self.assertNotIn("Enable gestures", strings) + self.assertFalse(any(key.startswith("Two-finger swipe up on notch") for key in strings)) + for key in ["Enable media gestures", "Change media with horizontal gestures", "Gesture sensitivity", + "Normalize gesture direction", "Gesture control", "Open notch on hover"]: + self.assertIn(key, strings) + self.assertEqual(set(strings["Enable media gestures"]["localizations"]), + {"cs", "de", "en", "en-GB", "es", "fr", "he", "hu", "it", "ja", "ko", + "nl", "pl", "pt-BR", "ru", "tr", "uk", "zh-Hans", "zh-Hant-HK"}) + + def test_new_native_case_keeps_removed_output_out_of_setup_guards(self): + root = ROOT / "experiments/tart-regression/GuestRegressionProbe" + native = (root / "GuestRegressionProbe.swift").read_text() + self.assertIn("func testInstalledGeneralWithoutPanelSwipes()", native) + self.assertIn('modes: ["general-panel-swipes-removed"]', native) + self.assertIn('if scenario.pane == "General"', native) + output = native.split("var controls: [String: Bool]", 1)[1].split("let capture =", 1)[0] + self.assertIn("scenario.removedLabelsAbsent { form.staticTexts[$0].exists }", output) + self.assertNotIn("require(", output) + self.assertNotIn("isHittable", output) + oracle = (root / "SettingsRemovalOutputOracle.swift").read_text() + self.assertIn("removedLabels.allSatisfy { !isPresent($0) }", oracle) + for label in ["Enable gestures", "Close gesture", "Enable media gestures", "panelGestureControlsAbsent"]: + self.assertIn('"' + label + '"', oracle) + + +class HapticRemovalSourceContractTests(unittest.TestCase): + """Source wiring contracts, not physical trackpad or live interaction proof.""" + + def test_product_has_no_haptic_actuator_setting_or_consumer(self): + sources = [source for folder in ["notchPocket", "notchPocketXPCHelper", "Shared"] + for source in (ROOT / folder).rglob("*") + if source.suffix in {".swift", ".m", ".mm", ".h", ".c", ".cpp"}] + self.assertTrue(sources) + for source in sources: + with self.subTest(path=str(source.relative_to(ROOT))): + self.assertNotRegex(source.read_text(), + r"(?i)haptic|sensoryFeedback|FeedbackGenerator|kSystemSoundID_Vibrate") + self.assertNotRegex((ROOT / "notchPocket.xcodeproj/project.pbxproj").read_text(), r"(?i)haptic") + catalog = json.loads((ROOT / "notchPocket/Localizable.xcstrings").read_text()) + self.assertNotIn("Enable haptic feedback", catalog["strings"]) + for key in ["Open notch on hover", "Notch animation", "Enable media gestures"]: + self.assertIn(key, catalog["strings"]) + + def test_panel_hover_click_keyboard_media_and_shelf_handlers_remain(self): + content = (ROOT / "notchPocket/ContentView.swift").read_text() + for fragment in [ + ".onHover { hovering in\n handleHover(hovering)", + ".onTapGesture {", "if vm.notchState == .closed && !shouldDisplayNowPlayingFallbackNotice", + 'SettingsWindowController.shared.showWindow()', '.keyboardShortcut(KeyEquivalent(","), modifiers: .command)', + "notificationManager.holdActive()", "self.notificationManager.resumeDismiss()", + "Defaults[.minimumHoverDuration]", "Defaults[.openNotchOnHover]", "Task.isCancelled", + "handleNextTrackGesture(translation: translation, phase: phase)", + "handlePreviousTrackGesture(translation: translation, phase: phase)", + "if !SharingStateManager.shared.preventNotchClose", "vm.close()", "didOpen = vm.open()", + "guard !horizontalMediaGestureTriggered else { return }", + "guard translation > Defaults[.gestureSensitivity] else { return }", + "horizontalMediaGestureTriggered = true\n triggerHorizontalMediaFeedback(feedback)\n action()", + "musicManager.nextTrack()", "musicManager.previousTrack()", + "horizontalMediaGestureFeedback = feedback", "horizontalMediaGestureFeedback = .zero", + "dropInteraction.dropEvent = true\n ShelfStateViewModel.shared.load(providers)", + "if doOpen() {\n coordinator.currentView = .shelf", + "ShelfView(", "NotchHomeView(", "DashboardView(", + ]: + self.assertIn(fragment, content) + + def test_calendar_selection_scroll_monitors_and_activity_cycling_remain(self): + calendar = (ROOT / "notchPocket/components/Calendar/NotchPocketCalendar.swift").read_text() + for fragment in [ + "selectedDate = date\n byClick = true", + "scrollPosition = index", ".scrollPosition(id: $scrollPosition, anchor: .center)", + "navigateDateByScrollWheel(deltaY: event.deltaY)", "navigateByScrollWheel(deltaY: event.deltaY)", + "handleScrollChange(newValue: newValue, config: config)", "guard isHovering else { return event }", + "scrollPosition = newIndex", "selectedDate = newDate", "stepSelection(by: direction)", + "displayedWeekStart = newStart\n selectedDate = newSelection", + "pageWeek(by: direction)", "selectDate(date)", "Button(action: onClick)", + "await calendarManager.updateCurrentDate(selectedDate)", + ]: + self.assertIn(fragment, calendar) + self.assertEqual(calendar.count("NSEvent.addLocalMonitorForEvents(matching: .scrollWheel)"), 2) + self.assertEqual(calendar.count("NSEvent.removeMonitor(monitor)"), 2) + stack = (ROOT / "notchPocket/components/Notch/LiveActivityStack.swift").read_text() + for fragment in [ + "DragGesture(minimumDistance: 14)", "abs(value.translation.width) > 24", + "move(by: value.translation.width < 0 ? 1 : -1)", + "guard items.indices.contains(next) else { return }", + "withAnimation(.smooth(duration: 0.3)) { index = next }", + ]: + self.assertIn(fragment, stack) + + def test_notification_send_copy_and_visible_confirmation_remain(self): + view = (ROOT / "notchPocket/components/Notch/NotificationLiveActivity.swift").read_text() + for fragment in [ + "Button(action: send)", ".onSubmit(send)", ".disabled(!canSend)", "guard canSend else { return }", + "let outcome = await manager.reply(to: notification, text: text)", "didSend = outcome == .sent", + ".animation(.smooth(duration: 0.25), value: didSend)", 'Image(systemName: "checkmark")', + "Button(action: copy)", "NSPasteboard.general.clearContents()", + "NSPasteboard.general.setString(code, forType: .string)", + "didCopy = true", "didCopy = false", 'Text(didCopy ? "Copied" : "Copy")', + ".animation(.smooth(duration: 0.25), value: didCopy)", + ]: + self.assertIn(fragment, view) + + def test_general_controls_and_unrelated_options_are_not_removed(self): + # SWIPE/CMP owner intent retires panel swipes and compact mode, not the media master. + settings = (ROOT / "notchPocket/components/Settings/Views/GeneralSettingsView.swift").read_text() + for label in SUITE.SCENARIOS["general-haptics-removed"]["labels"]: + self.assertIn('"' + label + '"', settings) + for fragment in ["if openNotchOnHover", 'Text("Hover delay")', "if enableMediaGestures", + ".enableHorizontalMediaGestures", "$gestureSensitivity", + "$animationSpeedMultiplier", "appLanguage.applyAppleLanguagesOverride()"]: + self.assertIn(fragment, settings) + constants = (ROOT / "notchPocket/models/Constants.swift").read_text() + for key in ["enableMediaGestures", "enableHorizontalMediaGestures", + "showOnLockScreen", "notchPocketShelf", "openNotchOnHover", "enableOpeningAnimation"]: + self.assertIn("static let " + key + " = ", constants) + + def test_general_native_case_uses_fixed_descriptors_and_verified_scroll_restoration(self): + root = ROOT / "experiments/tart-regression/GuestRegressionProbe" + oracle = (root / "SettingsRemovalOutputOracle.swift").read_text() + for label in SUITE.SCENARIOS["general-haptics-removed"]["labels"]: + self.assertIn('"' + label + '"', oracle) + native = (root / "GuestRegressionProbe.swift").read_text() + for fragment in [ + "func testInstalledGeneralWithoutHaptics()", 'modes: ["general-haptics-removed"]', + 'state.discovery["generalNavigationObserved"] = true', + 'let originalForm = try settingsForm(settings, scenario: .general)', + 'state.originalGeneralScroll = frames', + 'state.discovery["generalScrollRestored"] = restored == original', + "guard restored == original else", "state.cleanup = \"blocked\"", + "SettingsRemovalOutputOracle.combine(outputs, scenario: scenario)", + ]: + self.assertIn(fragment, native) + self.assertEqual(native.count("VNImageRequestHandler"), 2) + self.assertNotIn("import notchPocket", native) + inspect = native.split("private func inspectScrollableSettings(", 1)[1].split( + "private func inspectAppearance(", 1)[0] + self.assertLess(inspect.index("state.originalGeneralScroll = frames"), inspect.index("about.click()")) + self.assertLess(inspect.index("pane.click()"), inspect.index("let form = try settingsForm(")) + restore = native.split("private func restore(", 1)[1].split("private func finish(", 1)[0] + self.assertIn("let form = try settingsForm(settings, scenario: .general)", restore) + project = (root / "GuestRegressionProbe.xcodeproj/project.pbxproj").read_text() + self.assertIn("path = SettingsRemovalOutputOracle.swift;", project) + self.assertIn("dependencies = ();", project) + + def test_measured_general_labels_keep_static_text_query_and_dpi_invariant_point_allowance(self): + root = ROOT / "experiments/tart-regression/GuestRegressionProbe" + oracle = (root / "SettingsRemovalOutputOracle.swift").read_text() + self.assertIn('if scenario.pane == "General", anchor.x < frame.minX', oracle) + self.assertIn("windowWidthPoints: CGFloat", oracle) + self.assertIn("windowWidthPoints.isFinite, windowWidthPoints > 0", oracle) + self.assertIn("let pixelsPerPoint = CGFloat(pixelWidth) / windowWidthPoints", oracle) + self.assertIn("guard (1...4).contains(pixelsPerPoint)", oracle) + self.assertIn("((frame.minX - anchor.x) * CGFloat(pixelWidth)).rounded()", oracle) + self.assertIn("let maximumLeadingPixels = (4 * pixelsPerPoint).rounded()", oracle) + self.assertIn("leadingPixels >= 0 && leadingPixels <= maximumLeadingPixels", oracle) + self.assertNotIn("700", oracle) + self.assertNotIn("leadingOCRPaddingPixels", oracle) + self.assertLess(oracle.index('if scenario.pane == "General"'), + oracle.index("return alignment.contains(anchor)")) + self.assertIn("anchor.y >= alignment.minY, anchor.y <= alignment.maxY", oracle) + self.assertIn('row == label || row.hasPrefix(label + " ")', oracle) + native = (root / "GuestRegressionProbe.swift").read_text() + output = native.split("var controls: [String: Bool]", 1)[1].split("let capture =", 1)[0] + self.assertIn("form.staticTexts.matching(identifier: label)", output) + self.assertIn("matches.count == 1", output) + self.assertNotIn("checkBoxes", output) + self.assertNotIn("descendants(matching: .any)", output) + self.assertEqual(native.count("SettingsRemovalOutputOracle.evaluate("), 1) + call = native.split("SettingsRemovalOutputOracle.evaluate(", 1)[1].split("\n )", 1)[0] + self.assertIn("pixelWidth: image.width", call) + self.assertIn("windowWidthPoints: windowFrame.width", call) + self.assertIn("let windowFrame = settings.frame", native) + self.assertIn('"windowFrame": rect(windowFrame)', native) + self.assertIn('"pixelWidth": image.width, "pixelHeight": image.height', native) + + +class AIReplyRemovalSourceContractTests(unittest.TestCase): + """Removal/preservation source contracts, not live banner or send evidence.""" + + def test_generation_default_and_framework_have_no_remaining_product_reader(self): + sources = [source for folder in ["notchPocket", "notchPocketXPCHelper", "Shared"] + for source in (ROOT / folder).rglob("*.swift")] + self.assertTrue(sources) + for source in sources: + with self.subTest(path=str(source.relative_to(ROOT))): + self.assertNotRegex(source.read_text(), + r"SmartReply|smartRepliesEnabled|suggestReplies|suggestionChips" + r"|ReplySuggestionSet|FoundationModels|LanguageModelSession|SystemLanguageModel") + self.assertFalse((ROOT / "notchPocket/managers/SmartReplyManager.swift").exists()) + project = (ROOT / "notchPocket.xcodeproj/project.pbxproj").read_text() + for removed in ["SmartReply", "AA05SRM", "FoundationModels"]: + self.assertNotIn(removed, project) + + def test_notifications_settings_and_allow_list_remain_without_suggestions(self): + settings = (ROOT / "notchPocket/components/Settings/Views/NotificationSettingsView.swift").read_text() + for fragment in [ + "Defaults.Toggle(key: .notificationLiveActivity)", 'Text("Show notifications in the notch")', + "Defaults.Toggle(key: .notificationsFromAllApps)", 'Text("From all apps")', + "if !notificationsFromAllApps", "ForEach(knownNotificationApps)", "appRow(app)", + "allowedApps.contains(app.bundleID)", "allowedApps.insert(app.bundleID)", + "allowedApps.remove(app.bundleID)", ".disabled(!notificationLiveActivity)", + '.navigationTitle("Notifications")', + ]: + self.assertIn(fragment, settings) + for label in ["Messages", "FaceTime", "Mail", "Outlook", "Microsoft Teams", "WhatsApp", + "Telegram", "Telegram Desktop", "Discord", "Claude"]: + self.assertIn('name: "' + label + '"', settings) + self.assertNotIn("Suggest replies", settings) + self.assertNotIn("Apple Intelligence", settings) + constants = (ROOT / "notchPocket/models/Constants.swift").read_text() + for key in ["notificationLiveActivity", "notificationsFromAllApps"]: + self.assertIn('static let ' + key + ' = Key("' + key + '", default: false)', constants) + self.assertIn('static let notificationAllowedApps = Key>(', constants) + navigation = (ROOT / "notchPocket/components/Settings/SettingsView.swift").read_text() + self.assertIn("case .notifications:\n NotificationSettingsView()", navigation) + + def test_manual_composer_focus_draft_error_and_handoff_paths_remain(self): + view = (ROOT / "notchPocket/components/Notch/NotificationLiveActivity.swift").read_text() + self.assertNotIn("suggestions", view) + reply_row = view.split("private var replyRow: some View {", 1)[1].split("private var replyField:", 1)[0] + self.assertIn("replyField", reply_row) + self.assertIn("if let sendError", reply_row) + self.assertNotIn(".task", reply_row) + for fragment in [ + 'TextField("Reply", text: $replyText, axis: .horizontal)', + ".focused($replyFocused)", ".onSubmit(send)", "Button(action: send)", + ".onChange(of: hostWindow)", ".onChange(of: replyFocused)", + ".disabled(isSending || didSend || didHandOff)", ".disabled(!canSend)", + "replyText = manager.draft(for: notification.id)", "manager.setDraft(text, for: notification.id)", + "hostWindow?.wantsKeyForTextInput = false", "hostWindow?.wantsKeyForTextInput = true", + "manager.holdActive()", "manager.holdWhileTyping()", "manager.resumeDismiss()", + "manager.isComposingReply = true", "manager.isComposingReply = false", + "SharingStateManager.shared.beginInteraction()", "SharingStateManager.shared.endInteraction()", + "let outcome = await manager.reply(to: notification, text: text)", + "didSend = outcome == .sent", "didHandOff = outcome == .handedOffToApp || outcome == .draftedInApp", + "manager.clearDraft(for: notification.id)", "manager.dismissActive(token: notification.id)", + "case .reply:\n replyRow", "else if notification.canReply", + "Task { await manager.open(notification) }", + ]: + self.assertIn(fragment, view) + failure = view.split("if outcome == .failed {", 1)[1].split('replyText = ""', 1)[0] + self.assertIn("sendError = String(localized:", failure) + self.assertIn("Your draft is still here", failure) + self.assertIn("return", failure) + self.assertNotIn("clearDraft", failure) + on_appear = view.split(".onAppear {", 2)[-1].split(".onDisappear {", 1)[0] + self.assertNotIn("replyFocused = true", on_appear) + + def test_notification_source_drafts_timeouts_and_delivery_fallbacks_are_retained(self): + manager = (ROOT / "notchPocket/managers/SystemNotificationManager.swift").read_text() + for fragment in [ + "forName: .systemNotificationDidAppear", "forName: .systemNotificationDidDisappear", + "XPCHelperClient.shared.startNotificationWatching()", "XPCHelperClient.shared.stopNotificationWatching()", + "private var replyDrafts: [String: String] = [:]", + 'func draft(for id: String) -> String { replyDrafts[id] ?? "" }', + "replyDrafts[id] = text", "replyDrafts.removeValue(forKey: id)", + "if isComposingReply, activeNotification != nil", "func cycleToNextQueued()", + "func holdWhileTyping()", "func holdActive()", "func resumeDismiss(after delay: TimeInterval = 3)", + "private let bannerReplyTimeout: TimeInterval = 2.0", + "private let imessageScriptTimeout: TimeInterval = 4.0", + "await XPCHelperClient.shared.replyToNotification(token: notification.id, text: text)", + "if bannerDelivered == nil", "await XPCHelperClient.shared.sendIMessage(text, toChatNamed: chatName)", + "ContactAvatarManager.shared.phoneNumber(forContactNamed: sender)", + 'URL(string: "whatsapp://send?phone=\\(phone)&text=\\(encoded)")', + "NSPasteboard.general.setString(text, forType: .string)", "await open(notification)", + "return .sent", "return .failed", "return .draftedInApp", "return .handedOffToApp", + ]: + self.assertIn(fragment, manager) + timeout = manager.split("if bannerDelivered == nil {", 1)[1].split("\n }", 1)[0] + self.assertIn("return .failed", timeout) + self.assertNotIn("sendIMessage", timeout) + self.assertTrue((ROOT / "notchPocketXPCHelper/NotificationWatcher.swift").is_file()) + self.assertTrue((ROOT / "Shared/NotchPocketXPCHelperProtocol.swift").is_file()) + + def test_native_queries_use_typed_values_and_never_gate_on_expected_output(self): + native = (ROOT / "experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift").read_text() + notifications = native.split("private func inspectScrollableSettings(", 1)[1].split( + "private func inspectAppearance(", 1)[0] + for fragment in [ + '.containing(.staticText, identifier: scenario.pane)', 'row.staticTexts[scenario.pane]', + "form.staticTexts.matching(identifier: label)", + "scenario.removedLabelsAbsent { form.staticTexts[$0].exists }", + "formFrame.contains(matches.firstMatch.frame)", "first.map(\\.frame) == confirmed.map(\\.frame)", + "overlap >= 64", r"\(prefix)_scroll_coverage_incomplete", + "frames.allSatisfy { $0.minY >= formFrame.minY }", + "frames.allSatisfy { $0.maxY <= formFrame.maxY }", + "CGWindowListCopyWindowInfo", r"\(prefix)_capture_content_changed", + "let form = try settingsForm(settings, scenario: scenario)", + ]: + self.assertIn(fragment, notifications) + self.assertIn("sidebars.count == 1 && forms.count == 1", native) + output = notifications.split("var controls: [String: Bool]", 1)[1].split("let capture =", 1)[0] + self.assertNotIn("require(", output) + self.assertNotIn("isHittable", output) + self.assertNotIn("notifications_full_form_not_visible", notifications) + for label in ["Show notifications in the notch", "From all apps", "Suggest replies with Apple Intelligence"]: + self.assertNotIn('"' + label + '"', notifications) + self.assertIn('addTeardownBlock { @MainActor in self.restore(state) }', native) + self.assertIn('let control = row.staticTexts[targetPane]', native) + + def test_negative_control_records_prior_artifact_not_an_assumed_base_build(self): + note = (ROOT / "experiments/tart-regression/scenarios/notifications-ai-replies-removed.md").read_text() + self.assertIn("2e28bd1920265ee30d8761ad03c0b420e3f2168b", note) + self.assertIn("7a30c4d4939da81c165744050bc38e0a91ea699786cddd605de9c4735d6c5aa0", note) + self.assertNotIn("32331e682ed6fb6bba460019c1a949dee39e32ce92decafda48312ef0ce3aaaf", note) + self.assertNotIn("4fff039f5a62249c7ac84466c5cb0c124b2c9a06", note) + self.assertIn("550cb9bb7ab424e359f6d7c70e48ff091ed2eca5", note) + self.assertIn("full eight-case registry", note) + self.assertIn("NEW candidate only", note) + self.assertIn("not negative proof", note) + + +class IdleFaceRemovalSourceContractTests(unittest.TestCase): + """Source boundary contracts, not compiled-app or native behavior proof.""" + + def test_no_default_observer_or_render_path_can_read_the_legacy_true_setting(self): + sources = list((ROOT / "notchPocket").rglob("*.swift")) + self.assertTrue(sources) + for source in sources: + with self.subTest(path=str(source.relative_to(ROOT))): + self.assertNotRegex(source.read_text(), + r"showNotHumanFace|NotchPocketFaceAnimation|AnimatedFace|MinimalFaceFeatures_Previews") + + def test_face_only_implementation_and_project_membership_are_removed(self): + self.assertFalse((ROOT / "notchPocket/components/AnimatedFace.swift").exists()) + project = (ROOT / "notchPocket.xcodeproj/project.pbxproj").read_text() + self.assertNotIn("AnimatedFace", project) + appearance = (ROOT / "notchPocket/components/Settings/Views/AppearanceSettingsView.swift").read_text() + self.assertNotIn("Show cool face animation while inactive", appearance) + self.assertNotIn("Additional features", appearance) + lint = (ROOT / ".swiftlint.yml").read_text() + self.assertNotIn("NotchPocketFaceAnimation", lint) + + def test_appearance_navigation_does_not_guard_on_controls_under_test(self): + native = (ROOT / "experiments/tart-regression/GuestRegressionProbe/GuestRegressionProbe.swift").read_text() + appearance = native.split("private func inspectAppearance(", 1)[1].split( + "private func runInstalledSettingsOutput(", 1)[0] + for label in ["Colored spectrogram", "Slider color"]: + self.assertNotIn('"' + label + '"', appearance) + for fragment in [ + "let control = row.staticTexts[targetPane]", + "let appearance = row.staticTexts[\"Appearance\"]", + "form.staticTexts.matching(identifier: $0)", + 'header("General").count == 1 && header("Media").count == 1', + 'header("Additional features").count == 0', + "snapshot.frame.contains($0.frame)", "headFrames == tailFrames", + ]: + self.assertIn(fragment, native) + self.assertNotIn("appearance_content_unavailable", appearance) + self.assertNotIn("appearance_tail_unavailable", appearance) + + def test_old_preview_provenance_is_not_inferred_from_version_or_branch_base(self): + scenario = (ROOT / "experiments/tart-regression/scenarios/appearance-idle-face-removed.md").read_text() + self.assertIn("4fff039f5a62249c7ac84466c5cb0c124b2c9a06", scenario) + self.assertIn("32331e682ed6fb6bba460019c1a949dee39e32ce92decafda48312ef0ce3aaaf", scenario) + self.assertIn("Both candidates", scenario) + self.assertIn("source provenance", scenario) + self.assertNotIn("identified pre-removal app from base", scenario) + + def test_retained_appearance_and_full_panel_paths_remain(self): + appearance = (ROOT / "notchPocket/components/Settings/Views/AppearanceSettingsView.swift").read_text() + for fragment in [ + 'Toggle("Always show tabs", isOn: $coordinator.alwaysShowTabs)', + ".settingsIconInNotch", ".coloredSpectrogram", ".realtimeAudioWaveform", + ".playerColorTinting", ".lightingEffect", 'Picker("Slider color", selection: $sliderColor)', + ]: + self.assertIn(fragment, appearance) + content = (ROOT / "notchPocket/ContentView.swift").read_text() + for fragment in ["MusicLiveActivity()", "NotchPocketHeader()", "NotchHomeView(", + "ShelfView(", "DashboardView(", "NotificationExpandedView(", + "case .music:", "case .shelf:", "case .home:", "case .dashboard:"]: + self.assertIn(fragment, content) + constants = (ROOT / "notchPocket/models/Constants.swift").read_text() + for key in ["notchPocketShelf", "useCustomAccentColor", "customAccentColorData", + "enableShadow", "animationSpeedMultiplier", "enableHorizontalMediaGestures"]: + self.assertIn("static let " + key + " =", constants) + + class RegressionSkillContractTests(unittest.TestCase): def test_owned_skills_and_confirmed_intents_are_discoverable(self): for name in ["regression-test", "regression-suite", "setup-regression-suite"]: