From fb017552380ab3027c4bc73c77d5722fe934a970 Mon Sep 17 00:00:00 2001 From: heyaim <223061694+heyaim@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:39:33 -0600 Subject: [PATCH] Fix composer control overlap at large text sizes At accessibility XXXL, the composer icons outgrew their fixed 36-point frames, causing attachment/send accessibility-bounds overlap in the 280-point Matrix iOS simulator fixture. All six frames used by the attachment, send and microphone controls in ContentComposerView now use a .title2-relative @ScaledMetric with a 36-point default, so their allocations follow the icons' scaling. Automatic regression tests cover iOS composer interactions, selected-language layouts and photo-picker callbacks, plus macOS controls. --- .github/workflows/swift-tests.yml | 45 +- Package.swift | 12 +- bitchat.xcodeproj/project.pbxproj | 387 ++++++++++++++++++ .../xcschemes/Composer Layout.xcscheme | 31 ++ bitchat/Services/UnifiedPeerService.swift | 6 +- bitchat/ViewModels/ChatViewModel.swift | 12 +- .../ChatViewModelBootstrapper.swift | 41 +- .../ViewModels/GeoChannelCoordinator.swift | 12 +- bitchat/Views/ContentComposerView.swift | 20 +- bitchat/_ComposerTestHost/BitchatApp.swift | 42 ++ bitchat/_ComposerTestHost/FrameProbes.swift | 22 + .../ComposerMacTests/MacButtonTests.swift | 202 +++++++++ bitchatTests/ComposerSupport/Models.swift | 160 ++++++++ bitchatTests/Mocks/MockIdentityManager.swift | 2 + bitchatTests/Mocks/MockKeychain.swift | 2 + bitchatTests/Mocks/MockTransport.swift | 2 + .../ComposerLayoutFixture.swift | 146 +++++++ .../ComposerLayoutUITests.swift | 373 +++++++++++++++++ composerLayoutTests/NetworkIsolation.c | 61 +++ composerLayoutTests/README.md | 172 ++++++++ composerLayoutTests/check_invariants.py | 173 ++++++++ composerLayoutTests/run-macos.py | 138 +++++++ composerLayoutTests/run.py | 192 +++++++++ composerLayoutTests/runner_support.py | 95 +++++ composerLayoutTests/test_invariants.py | 116 ++++++ composerLayoutTests/test_runners.py | 148 +++++++ 26 files changed, 2580 insertions(+), 32 deletions(-) create mode 100644 bitchat.xcodeproj/xcshareddata/xcschemes/Composer Layout.xcscheme create mode 100644 bitchat/_ComposerTestHost/BitchatApp.swift create mode 100644 bitchat/_ComposerTestHost/FrameProbes.swift create mode 100644 bitchatTests/ComposerMacTests/MacButtonTests.swift create mode 100644 bitchatTests/ComposerSupport/Models.swift create mode 100644 composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift create mode 100644 composerLayoutTests/ComposerLayoutUITests/ComposerLayoutUITests.swift create mode 100644 composerLayoutTests/NetworkIsolation.c create mode 100644 composerLayoutTests/README.md create mode 100644 composerLayoutTests/check_invariants.py create mode 100644 composerLayoutTests/run-macos.py create mode 100644 composerLayoutTests/run.py create mode 100644 composerLayoutTests/runner_support.py create mode 100644 composerLayoutTests/test_invariants.py create mode 100644 composerLayoutTests/test_runners.py diff --git a/.github/workflows/swift-tests.yml b/.github/workflows/swift-tests.yml index e64683de..15b7fa50 100644 --- a/.github/workflows/swift-tests.yml +++ b/.github/workflows/swift-tests.yml @@ -15,7 +15,7 @@ jobs: # The long steps carry tighter individual bounds (5-minute test watchdog, # 6-minute benchmark step, 10-minute floor gate that may re-run the # benchmarks up to twice on a noisy runner); this is the backstop. - timeout-minutes: 25 + timeout-minutes: 40 strategy: fail-fast: false # Don't cancel other matrix jobs when one fails @@ -133,6 +133,23 @@ jobs: timeout-minutes: 10 run: ./scripts/check-perf-floors.sh perf-output.log + + - name: Check composer test infrastructure + if: matrix.name == 'app' + run: | + python3 -m unittest discover -s composerLayoutTests -p 'test_*.py' -v + python3 composerLayoutTests/check_invariants.py --source . + + # Run native composer UI events serially after coverage and benchmarks. + # Resolved packages are copied into a separate composer configuration cache. + - name: Run macOS composer button tests + if: matrix.name == 'app' + timeout-minutes: 15 + run: | + python3 composerLayoutTests/run-macos.py \ + --output "$RUNNER_TEMP/composer-macos" \ + --scratch-path "$GITHUB_WORKSPACE/.build" + # SPM tests do not link the shipping app targets. This job covers the # iOS-conditional paths and both universal Release link configurations. ios-build: @@ -157,6 +174,7 @@ jobs: -configuration Release \ -sdk iphonesimulator \ -destination 'generic/platform=iOS Simulator' \ + -derivedDataPath "$RUNNER_TEMP/composer-shipping-ios" \ ARCHS='arm64 x86_64' \ ONLY_ACTIVE_ARCH=NO \ CODE_SIGNING_ALLOWED=NO \ @@ -169,11 +187,18 @@ jobs: -scheme "bitchat (macOS)" \ -configuration Release \ -destination 'generic/platform=macOS' \ + -derivedDataPath "$RUNNER_TEMP/composer-shipping-macos" \ ARCHS='arm64 x86_64' \ ONLY_ACTIVE_ARCH=NO \ CODE_SIGNING_ALLOWED=NO \ build + - name: Check shipping excludes composer test infrastructure + run: | + python3 composerLayoutTests/check_invariants.py --source . \ + --shipping-derived "$RUNNER_TEMP/composer-shipping-ios" \ + --shipping-derived "$RUNNER_TEMP/composer-shipping-macos" + # The SwiftPM matrix runs on macOS and cannot execute UIKit/CoreBluetooth # conditional tests. Build the shared iOS test target and run it on the first # available iPhone simulator from the runner image instead of hard-coding a @@ -184,7 +209,7 @@ jobs: ios-tests: name: Run iOS simulator tests runs-on: macos-latest - timeout-minutes: 20 + timeout-minutes: 65 steps: - name: Checkout code @@ -199,7 +224,7 @@ jobs: id: destination run: | set -uo pipefail - destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -showdestinations 2>/dev/null || true) + destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -clonedSourcePackagesDirPath "$RUNNER_TEMP/composer-packages" -showdestinations 2>/dev/null || true) destination_id=$(awk -F'id:' ' /platform:iOS Simulator/ && /name:iPhone/ \ && !/error/ && !/unavailable/ && !found { @@ -254,6 +279,7 @@ jobs: echo "id=$destination_id" >> "$GITHUB_OUTPUT" - name: Run iOS tests + timeout-minutes: 20 run: | set -o pipefail xcodebuild -project bitchat.xcodeproj \ @@ -261,9 +287,22 @@ jobs: -sdk iphonesimulator \ -destination "platform=iOS Simulator,id=${{ steps.destination.outputs.id }}" \ -parallel-testing-enabled NO \ + -clonedSourcePackagesDirPath "$RUNNER_TEMP/composer-packages" \ CODE_SIGNING_ALLOWED=NO \ test + # Use the selected simulator type/runtime for an owned clean device; reuse packages. + # The runner rejects missing/skipped cases and propagates test failures. + - name: Run composer layout and photo-picker tests + timeout-minutes: 40 + env: + SIMULATOR_UUID: ${{ steps.destination.outputs.id }} + run: | + python3 composerLayoutTests/run.py \ + --output "$RUNNER_TEMP/composer-layout" \ + --simulator "$SIMULATOR_UUID" \ + --packages "$RUNNER_TEMP/composer-packages" + # Blocking since the backlog reached zero (all violations fixed; rules the # codebase deliberately breaks are disabled in .swiftlint.yml). --strict # promotes warnings to errors so new violations fail the job. Runs in a diff --git a/Package.swift b/Package.swift index f5e5146f..745843a2 100644 --- a/Package.swift +++ b/Package.swift @@ -1,7 +1,12 @@ // swift-tools-version: 5.9 +import Foundation import PackageDescription +// The serial composer runner selects the declared inert host. Normal builds +// exclude its entry point and frame probes, and omit the composer test folders. +let composerTestHost = ProcessInfo.processInfo.environment["COMPOSER_TEST_HOST"] == "1" + let package = Package( name: "bitchat", defaultLocalization: "en", @@ -42,10 +47,11 @@ let package = Package( // Globe picker geometry, bundled by the Xcode app targets and read // from Bundle.main; the SwiftPM build only runs tests. "Resources/Globe" - ], + ] + (composerTestHost ? ["BitchatApp.swift"] : ["_ComposerTestHost"]), resources: [ .process("Localizable.xcstrings") - ] + ], + swiftSettings: composerTestHost ? [.define("COMPOSER_TEST_HOST")] : [] ), .testTarget( name: "bitchatTests", @@ -60,7 +66,7 @@ let package = Package( // CI perf gate data (read by scripts/check-perf-floors.sh), // not a test resource. "Performance/perf-floors.json" - ], + ] + (composerTestHost ? [] : ["ComposerSupport", "ComposerMacTests"]), resources: [ .process("Localization"), // Only the vector fixture: declaring the whole "Noise" diff --git a/bitchat.xcodeproj/project.pbxproj b/bitchat.xcodeproj/project.pbxproj index bcf11381..baf552a0 100644 --- a/bitchat.xcodeproj/project.pbxproj +++ b/bitchat.xcodeproj/project.pbxproj @@ -18,6 +18,54 @@ A6E3EA812E7706A80032EA8A /* Tor in Frameworks */ = {isa = PBXBuildFile; productRef = A6E3EA802E7706A80032EA8A /* Tor */; }; E0A1B2C3D4E5F6012345678D /* relays/online_relays_gps.csv in Resources */ = {isa = PBXBuildFile; fileRef = E0A1B2C3D4E5F6012345678A /* relays/online_relays_gps.csv */; }; E0A1B2C3D4E5F6012345678E /* relays/online_relays_gps.csv in Resources */ = {isa = PBXBuildFile; fileRef = E0A1B2C3D4E5F6012345678A /* relays/online_relays_gps.csv */; }; + 0FD4A61C59153C14A7E41F99 /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = 0E031A6E35CC942D8998CAAB; + }; + 704AE3894D3872BD06BFD5DE /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = C7E25ADA1B2E5D6FAC0E6B7B; + }; + A1584175E603B034F59EEBE8 /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = 3EDD4711E8FF79150AA1F463; + }; + C5A83E309071A1B25F4A7B46 /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = 4557AAEAF8277C07CF9648F9; + }; + 2EB562838CAFF2C214C4A189 /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = 9568547CCECD17A7F35B21C9; + }; + 44DE06A7899F0A80FB446311 /* PBXBuildFile */ = { + isa = PBXBuildFile; + fileRef = B9D1E848D0F09986D6BDF447; + }; + 03D7BEB420EFFDB87EF450FD /* PBXBuildFile */ = { + isa = PBXBuildFile; + productRef = A6E3E56F2E77036A0032EA8A; + }; + 01F06966C2E1F698E0F4E7BD /* PBXBuildFile */ = { + isa = PBXBuildFile; + productRef = 4EB6BA1B8464F1EA38F4E286; + }; + 9529347D1824DB0C0CD93BCD /* PBXBuildFile */ = { + isa = PBXBuildFile; + productRef = A6E3EA7E2E7706720032EA8A; + }; + 8DC675D15220FD342892A8B2 /* PBXBuildFile */ = { + isa = PBXBuildFile; + productRef = A6BCF9472F80953E001CF9B9; + }; + C24F2C16BB66381A86F79579 /* PBXBuildFile */ = { + fileRef = 49CC0C4E8EA444D12CE9AE33; + isa = PBXBuildFile; + }; + E5DDAD1A300237EA659306EA /* PBXBuildFile */ = { + fileRef = 4719F0588C7C709762CEC0A1; + isa = PBXBuildFile; + }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -42,6 +90,13 @@ remoteGlobalIDString = 0576A29205865664C0937536; remoteInfo = bitchat_macOS; }; + 29F4623BA5DFCA2CF4012F08 /* PBXContainerItemProxy */ = { + containerPortal = 475D96681D0EA0AE57A4E06E; + isa = PBXContainerItemProxy; + proxyType = 1; + remoteGlobalIDString = F65577E1D5BDF44B0CC114F2; + remoteInfo = ComposerLayoutHost; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -64,6 +119,70 @@ A6F183FC2E948783006A9046 /* tor-nolzma.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = "tor-nolzma.xcframework"; path = "localPackages/Tor/Frameworks/tor-nolzma.xcframework"; sourceTree = ""; }; C0DB1DE27F0AAB5092663E8E /* bitchatTests_iOS.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = bitchatTests_iOS.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; E0A1B2C3D4E5F6012345678A /* relays/online_relays_gps.csv */ = {isa = PBXFileReference; lastKnownFileType = text; path = relays/online_relays_gps.csv; sourceTree = ""; }; + BBA3A27A331606CFD602F2F3 /* ComposerLayoutHost.app */ = { + isa = PBXFileReference; + explicitFileType = wrapper.application; + includeInIndex = 0; + path = ComposerLayoutHost.app; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 0E031A6E35CC942D8998CAAB /* composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift; + sourceTree = SOURCE_ROOT; + }; + C7E25ADA1B2E5D6FAC0E6B7B /* bitchatTests/ComposerSupport/Models.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = bitchatTests/ComposerSupport/Models.swift; + sourceTree = SOURCE_ROOT; + }; + 3EDD4711E8FF79150AA1F463 /* composerLayoutTests/NetworkIsolation.c */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.c.c; + path = composerLayoutTests/NetworkIsolation.c; + sourceTree = SOURCE_ROOT; + }; + 4557AAEAF8277C07CF9648F9 /* bitchatTests/Mocks/MockKeychain.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = bitchatTests/Mocks/MockKeychain.swift; + sourceTree = SOURCE_ROOT; + }; + 9568547CCECD17A7F35B21C9 /* bitchatTests/Mocks/MockIdentityManager.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = bitchatTests/Mocks/MockIdentityManager.swift; + sourceTree = SOURCE_ROOT; + }; + B9D1E848D0F09986D6BDF447 /* bitchatTests/Mocks/MockTransport.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = bitchatTests/Mocks/MockTransport.swift; + sourceTree = SOURCE_ROOT; + }; + 4719F0588C7C709762CEC0A1 /* ComposerLayoutUITests.swift */ = { + includeInIndex = 1; + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = ComposerLayoutUITests.swift; + sourceTree = ""; + }; + 49CC0C4E8EA444D12CE9AE33 /* Foundation.framework */ = { + isa = PBXFileReference; + lastKnownFileType = wrapper.framework; + name = Foundation.framework; + path = System/Library/Frameworks/Foundation.framework; + sourceTree = SDKROOT; + }; + 52BF462027D179E22A8016EA /* ComposerLayoutUITests.xctest */ = { + explicitFileType = wrapper.cfbundle; + includeInIndex = 0; + isa = PBXFileReference; + path = ComposerLayoutUITests.xctest; + sourceTree = BUILT_PRODUCTS_DIR; + }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ @@ -78,6 +197,8 @@ A6E32D1C2E762EA70032EA8A /* Exceptions for "bitchat" folder in "bitchat_iOS" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( + _ComposerTestHost/BitchatApp.swift, + _ComposerTestHost/FrameProbes.swift, Info.plist, ); target = AF077EA0474EDEDE2C72716C /* bitchat_iOS */; @@ -85,6 +206,8 @@ A6E32D1D2E762EA70032EA8A /* Exceptions for "bitchat" folder in "bitchat_macOS" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( + _ComposerTestHost/BitchatApp.swift, + _ComposerTestHost/FrameProbes.swift, Info.plist, LaunchScreen.storyboard, ); @@ -100,6 +223,8 @@ C5E027A52ECCDFD700BD6012 /* Exceptions for "bitchatTests" folder in "bitchatTests_macOS" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( + ComposerMacTests/MacButtonTests.swift, + ComposerSupport/Models.swift, Info.plist, Localization/PrimaryLocalizationKeys.json, README.md, @@ -109,18 +234,29 @@ C5E027A82ECCDFE200BD6012 /* Exceptions for "bitchatTests" folder in "bitchatTests_iOS" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( + ComposerMacTests/MacButtonTests.swift, + ComposerSupport/Models.swift, Info.plist, Localization/PrimaryLocalizationKeys.json, README.md, ); target = 6CB97DF2EA57234CB3E563B8 /* bitchatTests_iOS */; }; + F4D6D685ACB53521D888A8CA /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + BitchatApp.swift, + ); + target = F65577E1D5BDF44B0CC114F2; + }; /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ A6E32C972E762EA70032EA8A /* bitchat */ = { isa = PBXFileSystemSynchronizedRootGroup; exceptions = ( + F4D6D685ACB53521D888A8CA, A6E32D1B2E762EA70032EA8A /* Exceptions for "bitchat" folder in "bitchatShareExtension" target */, A6E32D1C2E762EA70032EA8A /* Exceptions for "bitchat" folder in "bitchat_iOS" target */, A6E32D1D2E762EA70032EA8A /* Exceptions for "bitchat" folder in "bitchat_macOS" target */, @@ -171,12 +307,31 @@ A6BCF9482F80953E001CF9B9 /* BitFoundation in Frameworks */, ); }; + 0CA636AF6AD4692FF9F554B9 /* PBXFrameworksBuildPhase */ = { + isa = PBXFrameworksBuildPhase; + files = ( + 03D7BEB420EFFDB87EF450FD, + 01F06966C2E1F698E0F4E7BD, + 9529347D1824DB0C0CD93BCD, + 8DC675D15220FD342892A8B2, + ); + }; + B8A938D2ED42FD359E6328D7 /* PBXFrameworksBuildPhase */ = { + buildActionMask = 2147483647; + files = ( + C24F2C16BB66381A86F79579, + ); + isa = PBXFrameworksBuildPhase; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 18198ED912AAF495D8AF7763 = { isa = PBXGroup; children = ( + 44305818FCC51418B841EDAC, + 592EAA93ECCC78828EFE5E3E, A6E32C972E762EA70032EA8A /* bitchat */, E0A1B2C3D4E5F6012345678A /* relays/online_relays_gps.csv */, A6E32D212E762EAB0032EA8A /* bitchatShareExtension */, @@ -190,6 +345,8 @@ 9F37F9F2C353B58AC809E93B /* Products */ = { isa = PBXGroup; children = ( + BBA3A27A331606CFD602F2F3, + 52BF462027D179E22A8016EA, 96D0D41CA19EE5A772AA8434 /* bitchat.app */, 8F3A7C058C2C8E1A06C8CF8B /* bitchat.app */, 61F92EBA29C47C0FCC482F1F /* bitchatShareExtension.appex */, @@ -207,6 +364,28 @@ name = Frameworks; sourceTree = ""; }; + 592EAA93ECCC78828EFE5E3E /* ComposerLayoutUITests */ = { + children = ( + 4719F0588C7C709762CEC0A1, + ); + isa = PBXGroup; + name = ComposerLayoutUITests; + path = composerLayoutTests/ComposerLayoutUITests; + sourceTree = ""; + }; + 44305818FCC51418B841EDAC /* Composer Test Support */ = { + isa = PBXGroup; + children = ( + 0E031A6E35CC942D8998CAAB, + C7E25ADA1B2E5D6FAC0E6B7B, + 3EDD4711E8FF79150AA1F463, + 4557AAEAF8277C07CF9648F9, + 9568547CCECD17A7F35B21C9, + B9D1E848D0F09986D6BDF447, + ); + name = "Composer Test Support"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -319,6 +498,50 @@ productReference = 96D0D41CA19EE5A772AA8434 /* bitchat.app */; productType = "com.apple.product-type.application"; }; + F65577E1D5BDF44B0CC114F2 /* ComposerLayoutHost */ = { + isa = PBXNativeTarget; + buildConfigurationList = 787803C0514BE47521F990F6; + buildPhases = ( + 332CE32F0337F80ADC04D86A, + 004B96E941C3E8D88136608F, + 0CA636AF6AD4692FF9F554B9, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A6E32C972E762EA70032EA8A, + ); + name = ComposerLayoutHost; + packageProductDependencies = ( + 4EB6BA1B8464F1EA38F4E286, + A6E3E56F2E77036A0032EA8A, + A6E3EA7E2E7706720032EA8A, + A6BCF9472F80953E001CF9B9, + ); + productName = ComposerLayoutHost; + productReference = BBA3A27A331606CFD602F2F3; + productType = "com.apple.product-type.application"; + }; + E811F30D87EDB22592FB266C /* ComposerLayoutUITests */ = { + buildConfigurationList = 2C45D2A775A3939BE73AE20D; + buildPhases = ( + 4EA274B470AC5BA59C442462, + B8A938D2ED42FD359E6328D7, + 5C4DA50EF358A683465A00BA, + ); + buildRules = ( + ); + dependencies = ( + 27620291E1D248BC8328DA70, + ); + isa = PBXNativeTarget; + name = ComposerLayoutUITests; + productName = ComposerLayoutUITests; + productReference = 52BF462027D179E22A8016EA; + productType = "com.apple.product-type.bundle.ui-testing"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -362,6 +585,8 @@ projectDirPath = ""; projectRoot = ""; targets = ( + F65577E1D5BDF44B0CC114F2, + E811F30D87EDB22592FB266C, 57CA17A36A2532A6CFF367BB /* bitchatShareExtension */, 6CB97DF2EA57234CB3E563B8 /* bitchatTests_iOS */, 47FF23248747DD7CB666CB91 /* bitchatTests_macOS */, @@ -399,6 +624,19 @@ E0A1B2C3D4E5F6012345678E /* relays/online_relays_gps.csv in Resources */, ); }; + 004B96E941C3E8D88136608F /* PBXResourcesBuildPhase */ = { + isa = PBXResourcesBuildPhase; + files = ( + E0A1B2C3D4E5F6012345678E, + ); + }; + 5C4DA50EF358A683465A00BA /* PBXResourcesBuildPhase */ = { + buildActionMask = 2147483647; + files = ( + ); + isa = PBXResourcesBuildPhase; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -427,6 +665,27 @@ files = ( ); }; + 332CE32F0337F80ADC04D86A /* PBXSourcesBuildPhase */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0FD4A61C59153C14A7E41F99, + 704AE3894D3872BD06BFD5DE, + A1584175E603B034F59EEBE8, + C5A83E309071A1B25F4A7B46, + 2EB562838CAFF2C214C4A189, + 44DE06A7899F0A80FB446311, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4EA274B470AC5BA59C442462 /* PBXSourcesBuildPhase */ = { + buildActionMask = 2147483647; + files = ( + E5DDAD1A300237EA659306EA, + ); + isa = PBXSourcesBuildPhase; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -445,6 +704,12 @@ target = AF077EA0474EDEDE2C72716C /* bitchat_iOS */; targetProxy = 96415D4F989854F908EAD303 /* PBXContainerItemProxy */; }; + 27620291E1D248BC8328DA70 /* ComposerLayoutHost */ = { + isa = PBXTargetDependency; + name = ComposerLayoutHost; + target = F65577E1D5BDF44B0CC114F2; + targetProxy = 29F4623BA5DFCA2CF4012F08; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ @@ -861,6 +1126,111 @@ }; name = Debug; }; + F0F4729775306C17EFAE4310 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = ""; + SUPPORTED_PLATFORMS = iphonesimulator; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.social-networking"; + PRODUCT_BUNDLE_IDENTIFIER = local.composerlayout.host; + INFOPLIST_KEY_CFBundleDisplayName = bitchat; + DEVELOPMENT_ASSET_PATHS = bitchat/_PreviewHelpers; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_MACCATALYST = NO; + TARGETED_DEVICE_FAMILY = 1; + CODE_SIGN_STYLE = "$(CODE_SIGN_STYLE)"; + CODE_SIGNING_ALLOWED = NO; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIconDebug; + SDKROOT = iphoneos; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + SWIFT_VERSION = "$(SWIFT_VERSION)"; + PRODUCT_NAME = ComposerLayoutHost; + CODE_SIGNING_REQUIRED = NO; + IPHONEOS_DEPLOYMENT_TARGET = "$(IPHONEOS_DEPLOYMENT_TARGET)"; + ENABLE_PREVIEWS = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + INFOPLIST_FILE = bitchat/Info.plist; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + PRODUCT_MODULE_NAME = bitchat; + APP_GROUP_ID = group.local.composerlayout.host; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) COMPOSER_TEST_HOST"; + SKIP_INSTALL = YES; + }; + baseConfigurationReferenceRelativePath = Debug.xcconfig; + name = Debug; + baseConfigurationReferenceAnchor = A6E367C92E76469E0032EA8A; + }; + A2380C9BBF6AE66E935DB853 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = ""; + SUPPORTED_PLATFORMS = iphonesimulator; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.social-networking"; + PRODUCT_BUNDLE_IDENTIFIER = local.composerlayout.host; + INFOPLIST_KEY_CFBundleDisplayName = bitchat; + DEVELOPMENT_ASSET_PATHS = bitchat/_PreviewHelpers; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_MACCATALYST = NO; + TARGETED_DEVICE_FAMILY = 1; + CODE_SIGN_STYLE = "$(CODE_SIGN_STYLE)"; + CODE_SIGNING_ALLOWED = NO; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + SDKROOT = iphoneos; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + SWIFT_VERSION = "$(SWIFT_VERSION)"; + PRODUCT_NAME = ComposerLayoutHost; + CODE_SIGNING_REQUIRED = NO; + IPHONEOS_DEPLOYMENT_TARGET = "$(IPHONEOS_DEPLOYMENT_TARGET)"; + ENABLE_PREVIEWS = YES; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + INFOPLIST_FILE = bitchat/Info.plist; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + PRODUCT_MODULE_NAME = bitchat; + APP_GROUP_ID = group.local.composerlayout.host; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) COMPOSER_TEST_HOST"; + SKIP_INSTALL = YES; + }; + baseConfigurationReferenceRelativePath = Release.xcconfig; + name = Release; + baseConfigurationReferenceAnchor = A6E367C92E76469E0032EA8A; + }; + 5D81D204EEA1DB5D410F8E84 /* Debug */ = { + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGNING_ALLOWED = NO; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + PRODUCT_BUNDLE_IDENTIFIER = local.composerlayout.ComposerLayoutUITests; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = ComposerLayoutHost; + SUPPORTED_PLATFORMS = iphonesimulator; + }; + isa = XCBuildConfiguration; + name = Debug; + }; + BEF31AA2576A5065892A6695 /* Release */ = { + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGNING_ALLOWED = NO; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + PRODUCT_BUNDLE_IDENTIFIER = local.composerlayout.ComposerLayoutUITests; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = ComposerLayoutHost; + VALIDATE_PRODUCT = YES; + SUPPORTED_PLATFORMS = iphonesimulator; + }; + isa = XCBuildConfiguration; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -912,6 +1282,23 @@ ); defaultConfigurationName = Debug; }; + 787803C0514BE47521F990F6 /* XCConfigurationList */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F0F4729775306C17EFAE4310, + A2380C9BBF6AE66E935DB853, + ); + defaultConfigurationName = Debug; + }; + 2C45D2A775A3939BE73AE20D /* XCConfigurationList */ = { + buildConfigurations = ( + BEF31AA2576A5065892A6695, + 5D81D204EEA1DB5D410F8E84, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + isa = XCConfigurationList; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/bitchat.xcodeproj/xcshareddata/xcschemes/Composer Layout.xcscheme b/bitchat.xcodeproj/xcshareddata/xcschemes/Composer Layout.xcscheme new file mode 100644 index 00000000..2fbc24dd --- /dev/null +++ b/bitchat.xcodeproj/xcshareddata/xcschemes/Composer Layout.xcscheme @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bitchat/Services/UnifiedPeerService.swift b/bitchat/Services/UnifiedPeerService.swift index b52de90a..489c5632 100644 --- a/bitchat/Services/UnifiedPeerService.swift +++ b/bitchat/Services/UnifiedPeerService.swift @@ -31,7 +31,7 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { private let idBridge: NostrIdentityBridge private let identityManager: SecureIdentityStateManagerProtocol weak var messageRouter: MessageRouter? - private let favoritesService = FavoritesPersistenceService.shared + private let favoritesService: FavoritesPersistenceService private var cancellables = Set() // MARK: - Initialization @@ -39,11 +39,13 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { init( meshService: Transport, idBridge: NostrIdentityBridge, - identityManager: SecureIdentityStateManagerProtocol + identityManager: SecureIdentityStateManagerProtocol, + favoritesService: FavoritesPersistenceService? = nil ) { self.meshService = meshService self.idBridge = idBridge self.identityManager = identityManager + self.favoritesService = favoritesService ?? .shared // Subscribe to changes from both services setupSubscriptions() diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 36742d29..0f6a87b9 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -327,7 +327,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage let locationManager: LocationChannelManager var nostrRelayManager: NostrRelayManager? - private let userDefaults = UserDefaults.standard + private let userDefaults: UserDefaults let keychain: KeychainManagerProtocol private let panicRecoveryOperations: PanicRecoveryOperations private let panicNetworkLifecycle: PanicNetworkLifecycle @@ -1163,8 +1163,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage sfMetrics: StoreAndForwardMetrics? = nil, panicMediaWipe: (() throws -> Void)? = nil, panicRecoveryOperations: PanicRecoveryOperations? = nil, - panicNetworkLifecycle: PanicNetworkLifecycle = .noop + panicNetworkLifecycle: PanicNetworkLifecycle = .noop, + dependencies: ChatViewModelDependencies? = nil ) { + let dependencies = dependencies ?? ChatViewModelDependencies() let conversations = conversations ?? ConversationStore() let peerIdentityStore = peerIdentityStore ?? PeerIdentityStore() let locationPresenceStore = locationPresenceStore ?? LocationPresenceStore() @@ -1174,10 +1176,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage identityManager: identityManager, meshService: transport, outboxStore: outboxStore, - sfMetrics: sfMetrics + sfMetrics: sfMetrics, + dependencies: dependencies ) self.keychain = keychain + self.userDefaults = dependencies.userDefaults self.panicRecoveryOperations = panicRecoveryOperations ?? .ephemeral(wipeMedia: panicMediaWipe ?? {}) self.panicNetworkLifecycle = panicNetworkLifecycle @@ -1239,7 +1243,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage } if networkActivationAllowed { - ChatViewModelBootstrapper(viewModel: self).configure() + ChatViewModelBootstrapper(viewModel: self, dependencies: dependencies).configure() } } diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 14de9c9b..2c9d11cc 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -3,6 +3,22 @@ import BitLogger import Combine import Foundation +/// Dependencies resolved before the model's service graph is constructed. +/// Callers can mount the model with inert services without bypassing its wiring. +@MainActor +struct ChatViewModelDependencies { + var nostrTransport: NostrTransport.Dependencies? + var makeDeduplicationService: () -> MessageDeduplicationService = { + MessageDeduplicationService(nostrEventStore: NostrProcessedEventStore()) + } + var relayManager: () -> NostrRelayManager? = { .shared } + var makeGeoCoordinator: (LocationChannelManager, any GeoChannelContext) -> GeoChannelCoordinator = { + GeoChannelCoordinator(locationManager: $0, context: $1) + } + var favoritesService: FavoritesPersistenceService? + var userDefaults: UserDefaults = .standard +} + struct ChatViewModelServiceBundle { let commandProcessor: CommandProcessor let messageRouter: MessageRouter @@ -19,16 +35,20 @@ struct ChatViewModelServiceBundle { identityManager: SecureIdentityStateManagerProtocol, meshService: Transport, outboxStore: MessageOutboxStore? = nil, - sfMetrics: StoreAndForwardMetrics? = nil + sfMetrics: StoreAndForwardMetrics? = nil, + dependencies: ChatViewModelDependencies ) { let commandProcessor = CommandProcessor(identityManager: identityManager) let privateChatManager = PrivateChatManager(meshService: meshService) let unifiedPeerService = UnifiedPeerService( meshService: meshService, idBridge: idBridge, - identityManager: identityManager + identityManager: identityManager, + favoritesService: dependencies.favoritesService + ) + let nostrTransport = NostrTransport( + keychain: keychain, idBridge: idBridge, dependencies: dependencies.nostrTransport ) - let nostrTransport = NostrTransport(keychain: keychain, idBridge: idBridge) nostrTransport.senderPeerID = meshService.myPeerID let messageRouter = MessageRouter( transports: [meshService, nostrTransport], @@ -41,11 +61,11 @@ struct ChatViewModelServiceBundle { self.privateChatManager = privateChatManager self.unifiedPeerService = unifiedPeerService self.autocompleteService = AutocompleteService() - // Persist processed gift-wrap event IDs: NIP-59 randomizes their + // The live dependency persists processed gift-wrap event IDs: NIP-59 randomizes their // timestamps, so the 24h-lookback DM subscriptions redeliver the same // events on every launch and only a cross-launch record stops the // reprocessing (re-sent DELIVERED bursts, phantom-ack noise). - self.deduplicationService = MessageDeduplicationService(nostrEventStore: NostrProcessedEventStore()) + self.deduplicationService = dependencies.makeDeduplicationService() self.publicMessagePipeline = PublicMessagePipeline() } } @@ -53,9 +73,11 @@ struct ChatViewModelServiceBundle { @MainActor final class ChatViewModelBootstrapper { private unowned let viewModel: ChatViewModel + private let dependencies: ChatViewModelDependencies - init(viewModel: ChatViewModel) { + init(viewModel: ChatViewModel, dependencies: ChatViewModelDependencies? = nil) { self.viewModel = viewModel + self.dependencies = dependencies ?? ChatViewModelDependencies() } static func loadPersistedReadReceipts(userDefaults: UserDefaults = .standard) -> Set { @@ -205,7 +227,7 @@ private extension ChatViewModelBootstrapper { viewModel.updateBluetoothState(radio.getCurrentBluetoothState()) } - viewModel.nostrRelayManager = NostrRelayManager.shared + viewModel.nostrRelayManager = dependencies.relayManager() viewModel.messageRouter.flushAllOutbox() Task { @MainActor [weak viewModel] in @@ -324,10 +346,7 @@ private extension ChatViewModelBootstrapper { } func configureGeoChannels() { - viewModel.geoChannelCoordinator = GeoChannelCoordinator( - locationManager: viewModel.locationManager, - context: viewModel - ) + viewModel.geoChannelCoordinator = dependencies.makeGeoCoordinator(viewModel.locationManager, viewModel) } /// Wires the gateway-mode policy layer (`GatewayService`) to the mesh diff --git a/bitchat/ViewModels/GeoChannelCoordinator.swift b/bitchat/ViewModels/GeoChannelCoordinator.swift index 64a8db5d..1436b77e 100644 --- a/bitchat/ViewModels/GeoChannelCoordinator.swift +++ b/bitchat/ViewModels/GeoChannelCoordinator.swift @@ -32,7 +32,7 @@ extension ChatViewModel: GeoChannelContext {} final class GeoChannelCoordinator { private let locationManager: LocationChannelManager private let bookmarksStore: GeohashBookmarksStore - private let torManager: TorManager + private let isForeground: () -> Bool private weak var context: (any GeoChannelContext)? @@ -53,6 +53,7 @@ final class GeoChannelCoordinator { locationManager: LocationChannelManager? = nil, bookmarksStore: GeohashBookmarksStore? = nil, torManager: TorManager? = nil, + isForeground: (() -> Bool)? = nil, notesRevealed: AnyPublisher? = nil, locationNotesEnabled: Bool? = nil, locationNotesSettings: AnyPublisher? = nil, @@ -61,7 +62,12 @@ final class GeoChannelCoordinator { let resolvedLocationManager = locationManager ?? Self.defaultLocationManager() self.locationManager = resolvedLocationManager self.bookmarksStore = bookmarksStore ?? GeohashBookmarksStore.shared - self.torManager = torManager ?? Self.defaultTorManager() + if let isForeground { + self.isForeground = isForeground + } else { + let resolvedTorManager = torManager ?? Self.defaultTorManager() + self.isForeground = { resolvedTorManager.isForeground() } + } self.permissionState = resolvedLocationManager.permissionState self.locationNotesEnabled = locationNotesEnabled ?? LocationNotesSettings.enabled self.notesRevealedPublisher = notesRevealed @@ -172,7 +178,7 @@ final class GeoChannelCoordinator { context?.endGeohashSampling() return } - if torManager.isForeground() { + if isForeground() { context?.beginGeohashSampling(for: union) } else { context?.endGeohashSampling() diff --git a/bitchat/Views/ContentComposerView.swift b/bitchat/Views/ContentComposerView.swift index b7deab21..f5ad3edb 100644 --- a/bitchat/Views/ContentComposerView.swift +++ b/bitchat/Views/ContentComposerView.swift @@ -28,6 +28,8 @@ struct ContentComposerView: View { @Binding var showMacImagePicker: Bool #endif + @ScaledMetric(relativeTo: .title2) private var composerActionSize: CGFloat = 36 + var body: some View { VStack(alignment: .leading, spacing: 6) { if conversationUIModel.showAutocomplete && !conversationUIModel.autocompleteSuggestions.isEmpty { @@ -132,9 +134,15 @@ struct ContentComposerView: View { if conversationUIModel.canSendMediaInCurrentContext { attachmentButton + #if COMPOSER_TEST_HOST && os(macOS) + .localComposerProbeFrame("attachment") + #endif } sendOrMicButton + #if COMPOSER_TEST_HOST && os(macOS) + .localComposerProbeFrame("action") + #endif } } } @@ -261,7 +269,7 @@ private extension ContentComposerView { Image(systemName: "camera.circle.fill") .font(.bitchatSystem(size: 24)) .foregroundColor(composerAccentColor) - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) .contentShape(Circle()) .onTapGesture { imagePickerSourceType = .photoLibrary @@ -289,7 +297,7 @@ private extension ContentComposerView { Image(systemName: "photo.circle.fill") .font(.bitchatSystem(size: 24)) .foregroundColor(composerAccentColor) - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) } .buttonStyle(.plain) .accessibilityLabel( @@ -310,10 +318,10 @@ private extension ContentComposerView { .opacity(hasText ? 1 : 0) .allowsHitTesting(hasText) } - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) } else { sendButtonView(enabled: hasText) - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) } } @@ -339,7 +347,7 @@ private extension ContentComposerView { .font(.bitchatSystem(size: 24)) .foregroundColor(micColor) .modifier(PulsingOpacityModifier(active: busyTalker != nil && !voiceRecordingVM.state.isActive)) - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) .contentShape(Circle()) .overlay( Color.clear @@ -389,7 +397,7 @@ private extension ContentComposerView { Image(systemName: "arrow.up.circle.fill") .font(.bitchatSystem(size: 24)) .foregroundColor(enabled ? activeColor : Color.gray) - .frame(width: 36, height: 36) + .frame(width: composerActionSize, height: composerActionSize) } .buttonStyle(.plain) .disabled(!enabled) diff --git a/bitchat/_ComposerTestHost/BitchatApp.swift b/bitchat/_ComposerTestHost/BitchatApp.swift new file mode 100644 index 00000000..64c5908a --- /dev/null +++ b/bitchat/_ComposerTestHost/BitchatApp.swift @@ -0,0 +1,42 @@ +// +// BitchatApp.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import SwiftUI + +#if os(iOS) + @_silgen_name("composer_test_isolation_status") + private func composerTestIsolationStatus() -> Int32 +#endif + +@main +struct BitchatApp: App { + static let bundleID = Bundle.main.bundleIdentifier ?? "local.composerlayout" + static let groupID = "group.\(bundleID)" + init() { + #if os(iOS) + precondition(composerTestIsolationStatus() == 1, "Composer app-process network guard is required") + #endif + } + + var body: some Scene { + WindowGroup { + #if os(iOS) + ComposerLayoutFixture() + #else + Color.black + #endif + } + } +} + +// Shared AppRuntime source assigns this reference, but the composer host does +// not construct that runtime or install a notification delegate. +final class NotificationDelegate { + static let shared = NotificationDelegate() + weak var runtime: AppRuntime? +} diff --git a/bitchat/_ComposerTestHost/FrameProbes.swift b/bitchat/_ComposerTestHost/FrameProbes.swift new file mode 100644 index 00000000..4f28ffe1 --- /dev/null +++ b/bitchat/_ComposerTestHost/FrameProbes.swift @@ -0,0 +1,22 @@ +#if COMPOSER_TEST_HOST && os(macOS) +import SwiftUI + +// Compiled only into the inert composer host, never the shipping app. +struct LocalComposerProbeFrames: PreferenceKey { + static var defaultValue: [String: CGRect] = [:] + static func reduce(value: inout [String: CGRect], nextValue: () -> [String: CGRect]) { + value.merge(nextValue(), uniquingKeysWith: { _, new in new }) + } +} + +extension View { + func localComposerProbeFrame(_ name: String) -> some View { + background(GeometryReader { geometry in + Color.clear.preference( + key: LocalComposerProbeFrames.self, + value: [name: geometry.frame(in: .named("LocalComposerProbe"))] + ) + }.allowsHitTesting(false)) + } +} +#endif diff --git a/bitchatTests/ComposerMacTests/MacButtonTests.swift b/bitchatTests/ComposerMacTests/MacButtonTests.swift new file mode 100644 index 00000000..ef9a38f3 --- /dev/null +++ b/bitchatTests/ComposerMacTests/MacButtonTests.swift @@ -0,0 +1,202 @@ +#if os(macOS) +import AppKit +import BitFoundation +import SwiftUI +import XCTest +@testable import bitchat + +// Mounted production composer with synthetic models and native in-process events. +// The declared test host enables non-hit-testing frame probes at compile time. +// Attachment checks the binding; it does not open NSOpenPanel. This does not +// exercise physical input, VoiceOver, or microphone/camera capture. + + +@MainActor +private final class MacButtonState: ObservableObject { + @Published var text = "hello" + @Published var picker = false + var pickerRequests = 0 + var sent: [String] = [] + var frames: [String: CGRect] = [:] + var timer: Timer? + let voice = VoiceRecordingViewModel() + + init() { + // A mistaken hit on the empty-draft microphone cannot request permission. + voice.sessionProvider = { MacButtonCapture() } + } +} + +@MainActor +private final class MacButtonCapture: VoiceCaptureSession { + var isLive: Bool { false } + func requestPermission() async -> Bool { true } + func start() async throws {} + func finish() async -> URL? { nil } + func cancel() async {} + func panicCancelSynchronously() {} +} + +@MainActor +private struct MacButtonFixture: View { + @ObservedObject var state: MacButtonState + @FocusState private var focused: Bool + + var body: some View { + ContentComposerView( + messageText: $state.text, + isTextFieldFocused: $focused, + voiceRecordingVM: state.voice, + autocompleteDebounceTimer: Binding( + get: { state.timer }, set: { state.timer = $0 } + ), + onSendMessage: { + state.sent.append(state.text) + state.text = "" + }, + showMacImagePicker: Binding( + get: { state.picker }, + set: { + state.picker = $0 + if $0 { state.pickerRequests += 1 } + } + ) + ) + } +} + +final class MacButtonTests: XCTestCase { + @MainActor func testMatrixNarrowButtons() throws { + try checkButtons(glass: false, large: false, width: 280) + } + + @MainActor func testGlassNarrowButtons() throws { + try checkButtons(glass: true, large: false, width: 280) + } + + @MainActor func testMatrixLargeButtons() throws { + try checkButtons(glass: false, large: true, width: 390) + } + + @MainActor func testGlassLargeButtons() throws { + try checkButtons(glass: true, large: true, width: 390) + } + + @MainActor private func pump(_ seconds: TimeInterval = 0.05) { + RunLoop.main.run(until: Date().addingTimeInterval(seconds)) + } + + @MainActor private func waitFor(_ predicate: () -> Bool, message: String) throws { + let deadline = Date().addingTimeInterval(2) + while !predicate() && Date() < deadline { pump() } + XCTAssertTrue(predicate(), message) + guard predicate() else { throw ProbeError.condition(message) } + } + + private enum ProbeError: Error { + case condition(String) + } + + @MainActor private func checkButtons(glass: Bool, large: Bool, width: CGFloat) throws { + continueAfterFailure = false + _ = NSApplication.shared + let state = MacButtonState() + let viewModel = makeLayoutViewModel().viewModel + let models = makeLayoutFeatureModels(for: viewModel) + let height: CGFloat = 180 + let root = installLayoutEnvironment(MacButtonFixture(state: state), featureModels: models) + .environment(\.appTheme, glass ? .liquidGlass : .matrix) + .environment(\.dynamicTypeSize, large ? .accessibility5 : .large) + .frame(width: width, height: height, alignment: .top) + .coordinateSpace(name: "LocalComposerProbe") + .onPreferenceChange(LocalComposerProbeFrames.self) { state.frames = $0 } + let host = NSHostingView(rootView: root) + let window = NSWindow( + contentRect: NSRect(x: 100, y: 100, width: width, height: height), + styleMask: [.titled], backing: .buffered, defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = host + window.makeKeyAndOrderFront(nil) + defer { + state.timer?.invalidate() + window.orderOut(nil) + window.close() + } + host.layoutSubtreeIfNeeded() + try waitFor({ state.frames["attachment"] != nil && state.frames["action"] != nil }, + message: "Mounted full composer must report both control frames") + + func measuredFrame(_ key: String) throws -> CGRect { + let rect = try XCTUnwrap(state.frames[key], "Missing measured frame: \(key)") + XCTAssertFalse(rect.isEmpty) + XCTAssertFalse(rect.isInfinite) + XCTAssertFalse(rect.isNull) + XCTAssertGreaterThanOrEqual(rect.minX, -1) + XCTAssertGreaterThanOrEqual(rect.minY, -1) + XCTAssertLessThanOrEqual(rect.maxX, width + 1) + XCTAssertLessThanOrEqual(rect.maxY, height + 1) + return rect + } + + func click(_ key: String) throws { + let rect = try measuredFrame(key) + // SwiftUI's named coordinate space is top-left based. NSHostingView + // flipping determines the corresponding native view-space point. + let y = host.isFlipped ? rect.midY : host.bounds.height - rect.midY + let point = host.convert(NSPoint(x: rect.midX, y: y), to: nil) + let stamp = ProcessInfo.processInfo.systemUptime + let down = try XCTUnwrap(NSEvent.mouseEvent( + with: .leftMouseDown, location: point, modifierFlags: [], timestamp: stamp, + windowNumber: window.windowNumber, context: nil, eventNumber: 1, + clickCount: 1, pressure: 1 + )) + let up = try XCTUnwrap(NSEvent.mouseEvent( + with: .leftMouseUp, location: point, modifierFlags: [], timestamp: stamp + 0.01, + windowNumber: window.windowNumber, context: nil, eventNumber: 2, + clickCount: 1, pressure: 0 + )) + // Deliver both events directly; this XCTest host does not run the + // usual application event dispatcher. The runner bounds tracking hangs. + window.sendEvent(down) + window.sendEvent(up) + print("MAC_NATIVE_CLICK key=\(key) rect=\(rect) hostFlipped=\(host.isFlipped) windowPoint=\(point) keyWindow=\(window.isKeyWindow) applicationActive=\(NSApp.isActive) directPair=true") + pump(0.15) + } + + let attachment = try measuredFrame("attachment") + let action = try measuredFrame("action") + XCTAssertFalse(attachment.intersects(action), "Measured composer control frames must not overlap") + print("MAC_BUTTON_FRAMES glass=\(glass) large=\(large) width=\(width) attachment=\(attachment) action=\(action)") + XCTAssertEqual(state.sent, []) + try click("attachment") + try waitFor({ state.pickerRequests == 1 }, message: "Native attachment click must set the real picker binding") + XCTAssertTrue(state.picker) + XCTAssertEqual(state.sent, [], "Attachment must not send the draft") + + state.picker = false + try click("action") + try waitFor({ state.sent == ["hello"] }, message: "Native send click must invoke the real send callback exactly once") + XCTAssertEqual(state.text, "") + XCTAssertEqual(state.pickerRequests, 1, "Send must not activate attachment") + + viewModel.activeChannel = .location(GeohashChannel(level: .block, geohash: "s000000")) + try waitFor({ !models.conversationUIModel.canSendMediaInCurrentContext && state.frames["attachment"] == nil }, + message: "No-media context must remove attachment before probing disabled send") + XCTAssertEqual(state.text, "") + try click("action") + pump(0.2) + XCTAssertEqual(state.sent, ["hello"], "Empty no-media send must not invoke its callback") + XCTAssertEqual(state.text, "") + + state.text = "again" + pump(0.15) + try click("action") + try waitFor({ state.sent == ["hello", "again"] }, + message: "The same no-media send control must work after the draft becomes nonempty") + XCTAssertEqual(state.text, "") + XCTAssertEqual(state.pickerRequests, 1) + print("MAC_FULL_ROW_BUTTON_PASS glass=\(glass) large=\(large) width=\(width): in-process native attachment/send/disabled-send events with non-hit-testing frame probes; no physical input or VoiceOver claim") + } +} +#endif diff --git a/bitchatTests/ComposerSupport/Models.swift b/bitchatTests/ComposerSupport/Models.swift new file mode 100644 index 00000000..381aa7b6 --- /dev/null +++ b/bitchatTests/ComposerSupport/Models.swift @@ -0,0 +1,160 @@ +import BitFoundation +import Combine +import CoreLocation +import Foundation +import SwiftUI +#if SWIFT_PACKAGE +@testable import bitchat +#endif + +@MainActor +func makeLayoutViewModel() -> ( + viewModel: ChatViewModel, transport: MockTransport, identityManager: MockIdentityManager +) { + let keychain = MockKeychain() + let keychainHelper = MockKeychainHelper() + let idBridge = NostrIdentityBridge(keychain: keychainHelper) + let identityManager = MockIdentityManager(keychain) + let transport = MockTransport() + let locationManager = makeLayoutLocationManager() + let defaults = makeLayoutDefaults() + var connectivityBindings = 0 + var deduplicationCreations = 0 + var geoCoordinatorCreations = 0 + var dependencies = ChatViewModelDependencies() + dependencies.nostrTransport = NostrTransport.Dependencies( + notificationCenter: NotificationCenter(), + loadFavorites: { [:] }, + favoriteStatusForNoiseKey: { _ in nil }, + favoriteStatusForPeerID: { _ in nil }, + currentIdentity: { nil }, + registerPendingGiftWrap: { _ in preconditionFailure("Composer fixture attempted a gift wrap") }, + sendEvent: { _ in preconditionFailure("Composer fixture attempted a relay send") }, + scheduleAfter: { _, _ in preconditionFailure("Composer fixture attempted to schedule an ack") }, + relayConnectivity: { + connectivityBindings += 1 + return Just(false).eraseToAnyPublisher() + } + ) + dependencies.makeDeduplicationService = { + deduplicationCreations += 1 + return MessageDeduplicationService() + } + dependencies.relayManager = { nil } + dependencies.favoritesService = FavoritesPersistenceService(keychain: keychain) + dependencies.userDefaults = defaults + dependencies.makeGeoCoordinator = { manager, context in + geoCoordinatorCreations += 1 + return GeoChannelCoordinator( + locationManager: manager, + bookmarksStore: manager, + isForeground: { false }, + notesRevealed: Just(false).eraseToAnyPublisher(), + locationNotesEnabled: false, + locationNotesSettings: Empty(completeImmediately: false).eraseToAnyPublisher(), + context: context + ) + } + + let viewModel = ChatViewModel( + keychain: keychain, + idBridge: idBridge, + identityManager: identityManager, + transport: transport, + locationManager: locationManager, + readReceiptsDefaults: defaults, + dependencies: dependencies + ) + + precondition(connectivityBindings == 1 && deduplicationCreations == 1 && geoCoordinatorCreations == 1, + "Composer fixture must use the injected service dependencies") + precondition(viewModel.nostrRelayManager == nil, "Composer fixture must not acquire the live relay manager") + precondition(transport.delegate === viewModel, "Composer fixture must retain production transport wiring") + precondition(viewModel.privateChatManager.messageRouter === viewModel.messageRouter, + "Composer fixture must retain production routing wiring") + return (viewModel, transport, identityManager) +} + +@MainActor +struct LayoutFeatureModels { + let locationChannelsModel: LocationChannelsModel + let privateConversationModel: PrivateConversationModel + let conversationUIModel: ConversationUIModel +} + +private func makeLayoutDefaults() -> UserDefaults { + let suiteName = "ComposerLayoutTests.\(UUID().uuidString)" + guard let storage = UserDefaults(suiteName: suiteName) else { + preconditionFailure("Could not create isolated composer defaults") + } + storage.removePersistentDomain(forName: suiteName) + return storage +} + +@MainActor +func makeLayoutLocationManager() -> LocationChannelManager { + LocationChannelManager( + storage: makeLayoutDefaults(), + locationManager: LayoutLocationAdapter(), + geocoder: LayoutGeocoder(), + shouldInitializeCoreLocation: false + ) +} + +private final class LayoutLocationAdapter: LocationStateManaging { + weak var delegate: CLLocationManagerDelegate? + var desiredAccuracy: CLLocationAccuracy = 0 + var distanceFilter: CLLocationDistance = 0 + var authorizationStatus: CLAuthorizationStatus { .denied } + func requestWhenInUseAuthorization() { + preconditionFailure("Composer fixture attempted location authorization") + } + func requestLocation() { preconditionFailure("Composer fixture attempted location lookup") } + func startUpdatingLocation() { preconditionFailure("Composer fixture attempted location updates") } + func stopUpdatingLocation() {} +} + +private final class LayoutGeocoder: LocationStateGeocoding { + func cancelGeocode() {} + func reverseGeocodeLocation( + _ location: CLLocation, + completionHandler: @escaping ([CLPlacemark]?, Error?) -> Void + ) { + preconditionFailure("Composer fixture attempted geocoding") + } +} + +@MainActor +func makeLayoutFeatureModels( + for viewModel: ChatViewModel, displayLocationManager: LocationChannelManager? = nil +) -> LayoutFeatureModels { + let locationManager = viewModel.locationManager + let conversations = viewModel.conversations + let locationChannelsModel = LocationChannelsModel(manager: displayLocationManager ?? locationManager) + let privateConversationModel = PrivateConversationModel( + chatViewModel: viewModel, + conversations: conversations, + locationChannelsModel: locationChannelsModel + ) + let conversationUIModel = ConversationUIModel( + chatViewModel: viewModel, + privateConversationModel: privateConversationModel, + conversations: conversations + ) + return LayoutFeatureModels( + locationChannelsModel: locationChannelsModel, + privateConversationModel: privateConversationModel, + conversationUIModel: conversationUIModel + ) +} + +@MainActor +func installLayoutEnvironment( + _ view: V, + featureModels: LayoutFeatureModels +) -> some View { + view + .environmentObject(featureModels.locationChannelsModel) + .environmentObject(featureModels.privateConversationModel) + .environmentObject(featureModels.conversationUIModel) +} diff --git a/bitchatTests/Mocks/MockIdentityManager.swift b/bitchatTests/Mocks/MockIdentityManager.swift index 930d57ff..d49f8a05 100644 --- a/bitchatTests/Mocks/MockIdentityManager.swift +++ b/bitchatTests/Mocks/MockIdentityManager.swift @@ -8,7 +8,9 @@ import Foundation import BitFoundation +#if !COMPOSER_TEST_HOST @testable import bitchat +#endif final class MockIdentityManager: SecureIdentityStateManagerProtocol { private var blockedFingerprints: Set = [] diff --git a/bitchatTests/Mocks/MockKeychain.swift b/bitchatTests/Mocks/MockKeychain.swift index d5e99f1d..62ca0d0f 100644 --- a/bitchatTests/Mocks/MockKeychain.swift +++ b/bitchatTests/Mocks/MockKeychain.swift @@ -8,7 +8,9 @@ import Foundation import BitFoundation +#if !COMPOSER_TEST_HOST @testable import bitchat +#endif final class MockKeychain: KeychainManagerProtocol { private var storage: [String: Data] = [:] diff --git a/bitchatTests/Mocks/MockTransport.swift b/bitchatTests/Mocks/MockTransport.swift index 9587e86f..de119a09 100644 --- a/bitchatTests/Mocks/MockTransport.swift +++ b/bitchatTests/Mocks/MockTransport.swift @@ -10,7 +10,9 @@ import Foundation import Combine import CoreBluetooth import BitFoundation +#if !COMPOSER_TEST_HOST @testable import bitchat +#endif /// Mock Transport implementation for testing ChatViewModel in isolation. /// Records all method calls and allows test code to verify interactions. diff --git a/composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift b/composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift new file mode 100644 index 00000000..2f0184a3 --- /dev/null +++ b/composerLayoutTests/ComposerLayoutFixture/ComposerLayoutFixture.swift @@ -0,0 +1,146 @@ +#if os(iOS) + import Photos + import SwiftUI + @MainActor + struct ComposerLayoutFixture: View { + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @Environment(\.layoutDirection) private var layoutDirection + @State private var composerFrame = CGRect.zero + @State private var text = "hello" + @State private var selection = "not selected" + @State private var timer: Timer? + @State private var picker = false + @State private var source = UIImagePickerController.SourceType.camera + @State private var sent = "" + @FocusState private var focused: Bool + @StateObject private var voice: VoiceRecordingViewModel + private let viewModel: ChatViewModel + private let models: LayoutFeatureModels + private let actualPicker = ProcessInfo.processInfo.environment["ACTUAL_PICKER"] == "1" + init() { + _text = State(initialValue: ProcessInfo.processInfo.environment["LAYOUT_DRAFT"] ?? "hello") + let recording = VoiceRecordingViewModel() + recording.sessionProvider = { LayoutCapture() } + _voice = StateObject(wrappedValue: recording) + let vm = makeLayoutViewModel().viewModel + viewModel = vm + // The displayed channel can change without invoking relay subscriptions. + // Media availability is controlled separately by this fixture's view model. + models = makeLayoutFeatureModels(for: vm, displayLocationManager: makeLayoutLocationManager()) + } + private var dynamicTypeName: String { + if dynamicTypeSize == .large { return "large" } + if dynamicTypeSize == .accessibility5 { return "accessibility5" } + return "unexpected \(String(describing: dynamicTypeSize))" + } + private var composerBoundsValue: String { + // String(Double) is locale-independent; SwiftUI interpolation localizes + // decimal separators and would make the machine-readable report ambiguous. + [composerFrame.minX, composerFrame.minY, composerFrame.width, composerFrame.height] + .map { String(Double($0)) }.joined(separator: ",") + } + var body: some View { + VStack { + Group { + Text("Language: " + (Bundle.main.preferredLocalizations.first ?? "unknown") + + " Direction: " + (layoutDirection == .rightToLeft ? "rtl" : "ltr")) + .accessibilityIdentifier("languageDirection") + Text("Dynamic Type: " + dynamicTypeName) + .accessibilityIdentifier("dynamicType") + Text("Composer bounds") + .accessibilityIdentifier("composerBounds") + .accessibilityValue(composerBoundsValue) + if actualPicker { + Text("Photo permission: \(PHPhotoLibrary.authorizationStatus(for: .readWrite).rawValue)") + Text(selection).accessibilityIdentifier("selection") + Text("Draft: " + text).accessibilityIdentifier("draft") + } + Text("Sent: " + sent).accessibilityIdentifier("sent") + Text( + picker ? (source == .camera ? "camera requested" : "library requested") : "no picker") + Button("Empty draft") { text = "" } + Button("Fill draft") { + text = "hello" + picker = false + } + Button("No media context") { + let channel = ChannelID.location(GeohashChannel(level: .block, geohash: "s000000")) + viewModel.activeChannel = channel + models.locationChannelsModel.select(channel) + } + Button("Start synthetic recording") { + voice.start(shouldShow: true) + } + Text( + voice.state.isActive + ? "capture active" + : (voice.state.alertMessage.isEmpty ? "capture inactive" : "capture error")) + }.font(.system(size: 12)) + Spacer() + installLayoutEnvironment( + ContentComposerView( + messageText: $text, isTextFieldFocused: $focused, + voiceRecordingVM: voice, autocompleteDebounceTimer: $timer, + onSendMessage: { + sent = text + text = "" + }, showImagePicker: $picker, imagePickerSourceType: $source), featureModels: models + ) + .frame(width: ProcessInfo.processInfo.environment["NARROW"] == "1" ? 280 : 390) + .background(GeometryReader { geometry in + Color.clear + .onAppear { composerFrame = geometry.frame(in: .global) } + .onChange(of: geometry.frame(in: .global)) { composerFrame = $0 } + }) + }.fullScreenCover(isPresented: Binding( + get: { actualPicker && picker }, + set: { picker = $0 } + )) { + ImagePickerView(sourceType: .photoLibrary) { image in + selection = image.map { + "selected \(Int($0.size.width))x\(Int($0.size.height)) " + + (matchesFixturePhoto($0) ? "fixture pattern matched" : "wrong image content") + } ?? "cancelled" + picker = false + }.ignoresSafeArea() + }.environment( + \.appTheme, ProcessInfo.processInfo.environment["GLASS"] == "1" ? .liquidGlass : .matrix) + } + } + private func matchesFixturePhoto(_ image: UIImage) -> Bool { + guard image.size == CGSize(width: 96, height: 64), let cgImage = image.cgImage, + let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return false } + let width = 96 + let height = 64 + var pixels = [UInt8](repeating: 0, count: width * height * 4) + let decoded = pixels.withUnsafeMutableBytes { buffer -> Bool in + guard let context = CGContext( + data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, + bytesPerRow: width * 4, space: colorSpace, + bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue + ) else { return false } + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) + return true + } + guard decoded else { return false } + // Sample quadrant centers after decoding; encoded bytes can change in Photos. + let samples = [ + (24, 16, [230, 20, 170]), (72, 16, [20, 180, 230]), + (24, 48, [240, 200, 20]), (72, 48, [30, 190, 70]) + ] + return samples.allSatisfy { x, y, expected in + let offset = (y * width + x) * 4 + return (0..<3).allSatisfy { abs(Int(pixels[offset + $0]) - expected[$0]) <= 12 } + && pixels[offset + 3] >= 250 + } + } + @MainActor + final class LayoutCapture: VoiceCaptureSession { + var isLive: Bool { false } + func requestPermission() async -> Bool { true } + func start() async throws {} + func finish() async -> URL? { nil } + func cancel() async {} + func panicCancelSynchronously() {} + } +#endif diff --git a/composerLayoutTests/ComposerLayoutUITests/ComposerLayoutUITests.swift b/composerLayoutTests/ComposerLayoutUITests/ComposerLayoutUITests.swift new file mode 100644 index 00000000..3ed9ebbc --- /dev/null +++ b/composerLayoutTests/ComposerLayoutUITests/ComposerLayoutUITests.swift @@ -0,0 +1,373 @@ +import XCTest + +final class ComposerLayoutUITests: XCTestCase { + private var activeApp: XCUIApplication? + + override func record(_ issue: XCTIssue) { + if let app = activeApp, app.state == .runningForeground { + let hierarchy = XCTAttachment(string: app.debugDescription) + hierarchy.name = "App accessibility hierarchy at failure" + hierarchy.lifetime = .keepAlways + add(hierarchy) + let screenshot = XCTAttachment(screenshot: app.screenshot()) + screenshot.lifetime = .keepAlways + add(screenshot) + } + super.record(issue) + } + + override func tearDown() { + activeApp?.terminate() + activeApp = nil + super.tearDown() + } + + func testActualPhotoPickerMatrixOrdinary() { checkActualPhotoPicker(glass: false, large: false) } + func testActualPhotoPickerMatrixLarge() { checkActualPhotoPicker(glass: false, large: true) } + func testActualPhotoPickerGlassOrdinary() { checkActualPhotoPicker(glass: true, large: false) } + func testActualPhotoPickerGlassLarge() { checkActualPhotoPicker(glass: true, large: true) } + private func checkActualPhotoPicker(glass: Bool, large: Bool) { + continueAfterFailure = false + let app = XCUIApplication() + activeApp = app + app.launchEnvironment = ["CI": "1", "ACTUAL_PICKER": "1", "GLASS": glass ? "1" : "0", "NARROW": "1"] + app.launchArguments = [ + "-AppleLanguages", "(en)", "-AppleLocale", "en_US", "-UIPreferredContentSizeCategoryName", + large ? "UICTContentSizeCategoryAccessibilityXXXL" : "UICTContentSizeCategoryL" + ] + app.launch() + assertDynamicType(app, large: large) + XCTAssertFalse(app.alerts.firstMatch.exists) + XCTAssertFalse(XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch.exists) + let camera = app.buttons["attach photo"] + XCTAssertTrue(camera.waitForExistence(timeout: 8)) + camera.tap() + let cancel = pickerCancel(in: app) + XCTAssertTrue( + cancel.waitForExistence(timeout: 8), "Actual picker must present without a permission workflow") + XCTAssertFalse(app.alerts.firstMatch.exists) + XCTAssertFalse(XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch.exists) + cancel.tap() + XCTAssertTrue(app.staticTexts["cancelled"].waitForExistence(timeout: 3)) + XCTAssertTrue(app.staticTexts["Draft: hello"].exists) + camera.tap() + XCTAssertTrue(cancel.waitForExistence(timeout: 8)) + // This is the system picker's informational banner, not a permission + // alert. At accessibility XXXL it fills the viewport above the photos. + let notice = pickerNotice(in: app) + if notice.exists { + let close = notice.buttons["Close"].firstMatch + XCTAssertTrue(close.exists) + close.tap() + } + XCTAssertFalse(app.alerts.firstMatch.exists) + XCTAssertFalse(XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch.exists) + let photos = pickerPhotos(in: app) + let photo = photos.firstMatch + XCTAssertTrue(photo.waitForExistence(timeout: 5), "Seeded synthetic photo must be visible") + for candidate in photos.allElementsBoundByIndex { + print("PICKER_IMAGE label=\(candidate.label) frame=\(candidate.frame)") + } + XCTAssertGreaterThan(photo.frame.width, 0) + XCTAssertGreaterThan(photo.frame.height, 0) + XCTAssertTrue(app.frame.contains(photo.frame), "Seeded thumbnail must be on screen") + // The system picker exposes a virtual accessibility thumbnail; deliver a + // real coordinate tap at its measured center rather than an AX press. + photo.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() + XCTAssertTrue( + app.staticTexts["selected 96x64 fixture pattern matched"].waitForExistence(timeout: 8), + "Production picker delegate must return the seeded dimensions and decoded quadrant colors") + XCTAssertFalse(cancel.exists) + XCTAssertTrue( + app.staticTexts["Photo permission: 0"].exists, + "Selecting one photo must not require full library authorization") + XCTAssertTrue(app.staticTexts["Draft: hello"].exists) + app.buttons["send message"].tap() + XCTAssertTrue(app.staticTexts["Sent: hello"].waitForExistence(timeout: 3)) + let shot = XCTAttachment(screenshot: app.screenshot()) + shot.lifetime = .keepAlways + add(shot) + } + + func testAccessibilityXXXL() { check(large: true, glass: false, narrow: true) } + func testAccessibilityXXXLWide() { check(large: true, glass: false, narrow: false) } + func testGlassAccessibilityXXXLWide() { check(large: true, glass: true, narrow: false) } + func testOrdinaryNarrow() { check(large: false, glass: false, narrow: true) } + func testGlassOrdinary() { check(large: false, glass: true, narrow: false) } + func testGlassAccessibilityXXXL() { check(large: true, glass: true, narrow: true) } + func testOrdinary() { check(large: false, glass: false, narrow: false) } + func testGlassOrdinaryNarrow() { check(large: false, glass: true, narrow: true) } + func testMicrophoneGestureUsesSyntheticCapture() { + continueAfterFailure = false + let app = XCUIApplication() + activeApp = app + app.launchEnvironment["CI"] = "1" + app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] + app.launch() + XCTAssertTrue(app.buttons["Empty draft"].waitForExistence(timeout: 10)) + app.buttons["Empty draft"].tap() + // Exercise the real gesture before any synthetic-start button is used. + app.buttons["record voice note"].press(forDuration: 1) + // The inert backend returns no file; this error establishes that the real gesture finished capture. + XCTAssertTrue(app.staticTexts["capture error"].waitForExistence(timeout: 3)) + XCTAssertFalse(app.alerts.firstMatch.exists) + XCTAssertFalse(XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch.exists) + app.terminate() + app.launch() + XCTAssertTrue(app.buttons["Empty draft"].waitForExistence(timeout: 10)) + app.buttons["Empty draft"].tap() + app.buttons["Start synthetic recording"].tap() + XCTAssertTrue(app.staticTexts["capture active"].waitForExistence(timeout: 3)) + app.buttons["cancel"].tap() + XCTAssertTrue(app.staticTexts["capture inactive"].waitForExistence(timeout: 3)) + } + func testNarrowLargeTextEditing() { checkTyping(glass: false) } + func testNarrowGlassLargeTextEditing() { checkTyping(glass: true) } + private func checkTyping(glass: Bool) { + continueAfterFailure = false + let app = XCUIApplication() + activeApp = app + app.launchEnvironment = ["CI": "1", "NARROW": "1", "GLASS": glass ? "1" : "0"] + app.launchArguments = [ + "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL" + ] + app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] + app.launch() + assertDynamicType(app, large: true) + let field = app.textFields.firstMatch + XCTAssertTrue(field.waitForExistence(timeout: 10)) + let shot = XCTAttachment(screenshot: app.screenshot()) + shot.lifetime = .keepAlways + add(shot) + XCTAssertGreaterThan(field.frame.width, 0) + assertContained([field], in: app) + app.buttons["Empty draft"].tap() + field.tap() + field.typeText("hello!") + XCTAssertEqual(field.value as? String, "hello!") + app.buttons["send message"].tap() + XCTAssertTrue(app.staticTexts["Sent: hello!"].waitForExistence(timeout: 3)) + } + // English system-picker selectors are centralized so an OS change produces + // one diagnostic failure rather than silently selecting a different element. + private func pickerCancel(in app: XCUIApplication) -> XCUIElement { + app.buttons["Cancel"].firstMatch + } + private func pickerNotice(in app: XCUIApplication) -> XCUIElement { + app.otherElements.matching(NSPredicate(format: "label BEGINSWITH 'Private Access to Photos,'")).firstMatch + } + private func pickerPhotos(in app: XCUIApplication) -> XCUIElementQuery { + app.images.matching(NSPredicate(format: "label BEGINSWITH 'Photo' OR label BEGINSWITH 'Image'")) + } + func testArabicMatrixOrdinary() { checkLocalized(language: "ar", glass: false, large: false) } + func testArabicMatrixLarge() { checkLocalized(language: "ar", glass: false, large: true) } + func testArabicGlassOrdinary() { checkLocalized(language: "ar", glass: true, large: false) } + func testArabicGlassLarge() { checkLocalized(language: "ar", glass: true, large: true) } + func testHebrewMatrixOrdinary() { checkLocalized(language: "he", glass: false, large: false) } + func testHebrewMatrixLarge() { checkLocalized(language: "he", glass: false, large: true) } + func testHebrewGlassOrdinary() { checkLocalized(language: "he", glass: true, large: false) } + func testHebrewGlassLarge() { checkLocalized(language: "he", glass: true, large: true) } + func testGermanMatrixOrdinary() { checkLocalized(language: "de", glass: false, large: false) } + func testGermanMatrixLarge() { checkLocalized(language: "de", glass: false, large: true) } + func testGermanGlassOrdinary() { checkLocalized(language: "de", glass: true, large: false) } + func testGermanGlassLarge() { checkLocalized(language: "de", glass: true, large: true) } + // Literal expected strings are independent checks of the shipped catalog, + // not labels read back from the fixture under test. + private func checkLocalized(language: String, glass: Bool, large: Bool) { + continueAfterFailure = false + let labels: [String] + let draft: String + switch language { + case "ar": + labels = ["إرفاق صورة", "إرسال رسالة", "تسجيل ملاحظة صوتية", "رسالة #mesh — عام، قريب", "رسالة #s000000 — عام"] + draft = "مرحبا ABC 123" + case "he": + labels = ["צירוף תמונה", "שלח הודעה", "הקלטת הערה קולית", "הודעה ל-#mesh — ציבורי, קרוב", "הודעה ל-#s000000 — ציבורי"] + draft = "שלום ABC 123" + case "de": + labels = ["foto anhängen", "nachricht senden", "sprachnachricht aufnehmen", "nachricht an #mesh — öffentlich, in der nähe", "nachricht an #s000000 — öffentlich"] + draft = "Grüße ABC 123" + default: XCTFail("Unsupported layout language"); return + } + let rtl = language != "de" + // Expect the identifier to be direction-isolated in the RTL placeholder. + let channelTarget = rtl ? "\u{2068}s000000\u{2069}" : "s000000" + let expectedChannel = labels[4].replacingOccurrences(of: "s000000", with: channelTarget) + let app = XCUIApplication() + activeApp = app + app.launchEnvironment = ["CI": "1", "NARROW": "1", "GLASS": glass ? "1" : "0", "LAYOUT_DRAFT": draft] + app.launchArguments = ["-AppleLanguages", "(\(language))", "-AppleLocale", language, + "-UIPreferredContentSizeCategoryName", + large ? "UICTContentSizeCategoryAccessibilityXXXL" : "UICTContentSizeCategoryL"] + app.launch() + assertDynamicType(app, large: large) + XCTAssertTrue(app.staticTexts["Language: \(language) Direction: \(rtl ? "rtl" : "ltr")"].exists, + "Actual bundle language and SwiftUI layout direction must match the requested locale") + let field = app.textFields.firstMatch + let camera = app.buttons[labels[0]] + let send = app.buttons[labels[1]] + let mic = app.buttons[labels[2]] + XCTAssertTrue(camera.waitForExistence(timeout: 5)) + XCTAssertTrue(send.exists) + XCTAssertEqual(field.value as? String, draft) + assertLocalizedRow(field: field, camera: camera, action: send, app: app, rtl: rtl, large: large) + camera.tap() + XCTAssertTrue(app.staticTexts["library requested"].waitForExistence(timeout: 3)) + send.tap() + XCTAssertTrue(app.staticTexts["Sent: " + draft].waitForExistence(timeout: 3)) + XCTAssertTrue(mic.exists) + XCTAssertEqual(field.placeholderValue, labels[3], "Localized mesh placeholder must actually load") + assertLocalizedRow(field: field, camera: camera, action: mic, app: app, rtl: rtl, large: large) + // Exercise editable text in the localized environment without depending on + // availability of individual non-Latin keys in the simulator keyboard. + field.tap() + field.typeText("123") + XCTAssertEqual(field.value as? String, "123") + XCTAssertTrue(send.exists) + send.tap() + XCTAssertTrue(app.staticTexts["Sent: 123"].waitForExistence(timeout: 3)) + app.buttons["No media context"].tap() + XCTAssertFalse(camera.exists) + XCTAssertTrue(send.exists) + XCTAssertFalse(send.isEnabled) + let channelPlaceholder = XCTNSPredicateExpectation( + predicate: NSPredicate(format: "placeholderValue == %@", expectedChannel), object: field) + let placeholderResult = XCTWaiter.wait(for: [channelPlaceholder], timeout: 3) + print("CHANNEL_PLACEHOLDER actual=\(String(reflecting: field.placeholderValue)) expected=\(String(reflecting: expectedChannel))") + XCTAssertEqual(placeholderResult, .completed, "Localized channel placeholder must actually load") + assertContained([field, send], in: app) + app.buttons["Fill draft"].tap() + XCTAssertTrue(send.isEnabled) + XCTAssertFalse(field.frame.intersects(send.frame), "Text field and send-only control must not overlap") + assertContained([field, send], in: app) + if rtl { XCTAssertLessThanOrEqual(send.frame.maxX, field.frame.minX + 1) } + else { XCTAssertLessThanOrEqual(field.frame.maxX, send.frame.minX + 1) } + send.tap() + XCTAssertTrue(app.staticTexts["Sent: hello"].waitForExistence(timeout: 3)) + let shot = XCTAttachment(screenshot: app.screenshot()) + shot.lifetime = .keepAlways + add(shot) + } + private func assertLocalizedRow( + field: XCUIElement, camera: XCUIElement, action: XCUIElement, + app: XCUIApplication, rtl: Bool, large: Bool + ) { + print("LOCALIZED_ROW rtl=\(rtl) field=\(field.frame) attachment=\(camera.frame) action=\(action.frame)") + XCTAssertFalse(camera.frame.intersects(action.frame), "Attachment and action controls must not overlap") + XCTAssertFalse(field.frame.intersects(camera.frame), "Text field and attachment must not overlap") + XCTAssertFalse(field.frame.intersects(action.frame), "Text field and action must not overlap") + assertVisibleBounds(camera, large: large) + assertVisibleBounds(action, large: large) + assertContained([field, camera, action], in: app) + if rtl { + XCTAssertLessThanOrEqual(action.frame.maxX, camera.frame.minX + 1, "RTL actions must mirror LTR ordering") + XCTAssertLessThanOrEqual(camera.frame.maxX, field.frame.minX + 1) + } else { + XCTAssertLessThanOrEqual(field.frame.maxX, camera.frame.minX + 1) + XCTAssertLessThanOrEqual(camera.frame.maxX, action.frame.minX + 1) + } + } + private func assertDynamicType(_ app: XCUIApplication, large: Bool) { + let expected = "Dynamic Type: " + (large ? "accessibility5" : "large") + XCTAssertTrue(app.staticTexts[expected].waitForExistence(timeout: 10), "Fixture must receive the requested Dynamic Type environment") + } + private func assertContained(_ controls: [XCUIElement], in app: XCUIApplication) { + let bounds = app.staticTexts["composerBounds"] + // The element is normally already present. Avoid a polling wait for each + // control, but retain a bounded fallback when the fixture is not ready. + XCTAssertTrue(bounds.exists || bounds.waitForExistence(timeout: 3)) + let components = (bounds.value as? String ?? "").split(separator: ",").compactMap { Double($0) } + guard components.count == 4 else { + XCTFail("Missing measured composer frame: \(String(describing: bounds.value))") + return + } + let frame = CGRect(x: components[0], y: components[1], width: components[2], height: components[3]) + XCTAssertGreaterThan(frame.width, 0) + XCTAssertGreaterThan(frame.height, 0) + let screen = app.frame + // Read fresh geometry for each assertion group; never cache across UI transitions. + for control in controls { + let controlFrame = control.frame + XCTAssertTrue(frame.insetBy(dx: -1, dy: -1).contains(controlFrame), + "Control accessibility bounds \(controlFrame) must stay inside measured composer \(frame)") + XCTAssertTrue(screen.contains(controlFrame), "Control accessibility bounds must remain on screen") + } + } + private func assertVisibleBounds(_ control: XCUIElement, large: Bool) { + if large { + XCTAssertGreaterThan(control.frame.width, 36) + XCTAssertGreaterThan(control.frame.height, 36) + } else { + // Accessibility can expose the icon rather than the full SwiftUI allocation. + XCTAssertGreaterThan(control.frame.width, 0) + XCTAssertGreaterThan(control.frame.height, 0) + XCTAssertLessThanOrEqual(control.frame.width, 37) + XCTAssertLessThanOrEqual(control.frame.height, 37) + } + } + private func check(large: Bool, glass: Bool, narrow: Bool) { + continueAfterFailure = false + let app = XCUIApplication() + activeApp = app + app.launchEnvironment = ["CI": "1", "GLASS": glass ? "1" : "0", "NARROW": narrow ? "1" : "0"] + app.launchArguments = [ + "-UIPreferredContentSizeCategoryName", + large ? "UICTContentSizeCategoryAccessibilityXXXL" : "UICTContentSizeCategoryL" + ] + app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] + app.launch() + assertDynamicType(app, large: large) + let camera = app.buttons["attach photo"] + let send = app.buttons["send message"] + XCTAssertTrue(camera.waitForExistence(timeout: 10)) + XCTAssertTrue(send.exists) + print( + "GEOMETRY large=\(large) glass=\(glass) narrow=\(narrow) attachment=\(camera.frame) send=\(send.frame)" + ) + XCTAssertFalse( + camera.frame.intersects(send.frame), "Attachment and send controls must not overlap") + if large { + XCTAssertGreaterThan( + camera.frame.width, 36, "Attachment accessibility bounds must grow with its Dynamic Type icon") + XCTAssertGreaterThan(send.frame.width, 36) + } else { + XCTAssertEqual(camera.frame.width, 36, accuracy: 1) + } + assertVisibleBounds(camera, large: large) + assertVisibleBounds(send, large: large) + assertContained([camera, send], in: app) + camera.tap() + XCTAssertTrue(app.staticTexts["library requested"].waitForExistence(timeout: 3)) + app.buttons["Fill draft"].tap() + camera.press(forDuration: 1) + XCTAssertTrue( + app.staticTexts["camera requested"].waitForExistence(timeout: 3), + "One-second camera long press should request camera source") + send.tap() + XCTAssertTrue(app.staticTexts["Sent: hello"].waitForExistence(timeout: 3)) + let mic = app.buttons["record voice note"] + XCTAssertTrue(mic.waitForExistence(timeout: 3)) + XCTAssertFalse( + camera.frame.intersects(mic.frame), "Attachment and microphone controls must not overlap") + assertVisibleBounds(mic, large: large) + assertContained([camera, mic], in: app) + app.buttons["Start synthetic recording"].tap() + XCTAssertTrue(app.staticTexts["capture active"].waitForExistence(timeout: 3)) + app.buttons["cancel"].tap() + XCTAssertTrue(app.staticTexts["capture inactive"].waitForExistence(timeout: 3)) + app.buttons["Fill draft"].tap() + XCTAssertTrue(send.waitForExistence(timeout: 3)) + app.buttons["No media context"].tap() + XCTAssertFalse(camera.exists) + app.buttons["Empty draft"].tap() + XCTAssertFalse(send.isEnabled) + app.buttons["Fill draft"].tap() + XCTAssertTrue(send.isEnabled) + assertVisibleBounds(send, large: large) + assertContained([send], in: app) + XCTAssertFalse(app.textFields.firstMatch.frame.intersects(send.frame), "Text field and send-only control must not overlap") + let shot = XCTAttachment(screenshot: app.screenshot()) + shot.lifetime = .keepAlways + add(shot) + } +} diff --git a/composerLayoutTests/NetworkIsolation.c b/composerLayoutTests/NetworkIsolation.c new file mode 100644 index 00000000..ba2463b0 --- /dev/null +++ b/composerLayoutTests/NetworkIsolation.c @@ -0,0 +1,61 @@ +// Test host only. Required dependency; deny app-process networking before startup. +#include +#include +#include +#include +#include +#include +#include +#include + +static int denied(int family, int type) { + int fd = socket(family, type, 0); + int rc = -1; + int error = errno; + if (fd >= 0) { + if (family == AF_INET6) { + struct sockaddr_in6 address = { + .sin6_len = sizeof(address), .sin6_family = AF_INET6, + .sin6_port = htons(9), .sin6_addr = IN6ADDR_LOOPBACK_INIT + }; + rc = connect(fd, (struct sockaddr *)&address, sizeof(address)); + } else { + struct sockaddr_in address = { + .sin_len = sizeof(address), .sin_family = AF_INET, + .sin_port = htons(9), .sin_addr.s_addr = htonl(INADDR_LOOPBACK) + }; + rc = connect(fd, (struct sockaddr *)&address, sizeof(address)); + } + error = errno; + close(fd); + } + if (rc == -1 && (error == EPERM || error == EACCES)) return 1; + fprintf(stderr, "COMPOSER_TEST_ISOLATION_VERIFY_FAILED family=%s protocol=%s rc=%d errno=%d\n", + family == AF_INET6 ? "IPv6" : "IPv4", + type == SOCK_STREAM ? "TCP" : "UDP", rc, error); + return 0; +} + +static int installed = 0; +// Referenced by the iOS host: removing this translation unit is a link error. +int composer_test_isolation_status(void) { return installed; } + +__attribute__((constructor)) static void guard(void) { + typedef int (*Apply)(const char *, int, void *); + Apply apply = (Apply)dlsym(RTLD_DEFAULT, "__sandbox_ms"); + struct { const char *builtin; const char *storage; size_t size; } args = {"no-network", NULL, 0}; + if (!apply) { + fprintf(stderr, "COMPOSER_TEST_ISOLATION_INSTALL_FAILED reason=interface-unavailable\n"); + _exit(90); + } + if (apply("Sandbox", 1, &args) != 0) { + fprintf(stderr, "COMPOSER_TEST_ISOLATION_INSTALL_FAILED reason=installation-rejected errno=%d\n", errno); + _exit(90); + } + if (!denied(AF_INET, SOCK_STREAM) || !denied(AF_INET, SOCK_DGRAM) + || !denied(AF_INET6, SOCK_STREAM) || !denied(AF_INET6, SOCK_DGRAM)) { + _exit(91); + } + installed = 1; + fprintf(stderr, "COMPOSER_TEST_ISOLATION_INSTALLED pid=%d IPv4_IPv6_TCP_UDP_DENIED\n", getpid()); +} diff --git a/composerLayoutTests/README.md b/composerLayoutTests/README.md new file mode 100644 index 00000000..6cf93e5b --- /dev/null +++ b/composerLayoutTests/README.md @@ -0,0 +1,172 @@ +# Composer layout and interaction regression tests + +The Build & Test workflow runs these checks automatically in its existing jobs: + +- The iOS simulator job runs 27 XCUITest cases after the standard app tests, + using a fresh disposable simulator of the selected type/runtime and the resolved Xcode package cache. Eleven cases cover + attachment/send and attachment/microphone bounds, ordinary/accessibility XXXL + text, both themes, 280/390-point rows, attachment bindings, sending, synthetic + recording/cancel and narrow text entry. Four additional cases use the actual + production photo picker in both themes at ordinary/accessibility XXXL text. Twelve + selected-language cases add Arabic/Hebrew/German layout coverage described below. +- The native app matrix job runs four macOS button cases serially after coverage + and performance checks, copying resolved dependencies into a separate composer build directory. They send native + in-process mouse events to the fully mounted composer, checking attachment, + sending, disabled empty send and restored nonempty send. Both themes are + exercised at width 280/ordinary and width 390/accessibility environment settings. + This does not establish that macOS visually scales for that environment value. + +The iOS runner builds the declared `ComposerLayoutHost` target and shared +`Composer Layout` scheme directly. The target shares production sources but +excludes production startup; fixture code and existing in-memory identity, +keychain and transport mocks have explicit target membership. It has no share +extension dependency. + +The macOS runner selects the explicit `COMPOSER_TEST_HOST=1` SwiftPM configuration. +That configuration uses the inert entry point and includes composer support in +the existing app test target; the runner selects its four composer cases. Frame readers are declared behind `COMPOSER_TEST_HOST && os(macOS)`; +normal builds exclude their implementation and calls. The readers do not receive +hit tests and report layout allocations, not accessibility bounds. + +Normal runs do not copy or rewrite source/project files. The macOS runner copies +resolved package inputs, not ordinary build products, into its own configuration +directory. It runs after coverage reporting and benchmarks. Only the optional original-composer control uses a disposable source +copy to substitute the requested baseline file. + +## iOS local command + +Requires macOS, Python 3, Xcode, an installed iOS test simulator and an already +resolved package cache matching `Package.resolved`. Record inputs without building: + +```sh +python3 composerLayoutTests/run.py --output /tmp/composer-layout +``` + +Build and run all 27 cases: + +```sh +python3 composerLayoutTests/run.py --output /tmp/composer-layout-run \ + --simulator "$SIMULATOR_UUID" --packages "$PACKAGE_CACHE" +``` + +For a focused subset, repeat `--test METHOD`; omission runs the complete suite. +Unknown or duplicate method names are rejected. + +The supplied simulator is a template: the runner reads its type/runtime, creates +a new device, builds before boot, and shuts down/deletes its own device on exit. +It imports one generated 96×64 four-color PNG for photo-picker cases. A fresh +device is not assumed to have an empty photo library: the newest matching photo +is selected, and the returned image must match the generated pattern. The real picker runs only in the four cases that set +`ACTUAL_PICKER=1`; the original camera/library-binding cases stay inert. The picker +cases close the system's informational banner if present, tap the measured photo +thumbnail, and check cancellation, returned image dimensions and decoded quadrant colors, draft preservation +and a subsequent send callback. They do not request or grant PhotoKit access, +answer permission alerts, or validate the full-library authorization workflow. + +The declared simulator host compiles the required test-only no-network guard +from `NetworkIsolation.c` directly into its executable. Failed installation or +IP-denial checks terminate the host before app startup. This guards the app process, not Photos/system daemons. +The guard uses the internal simulator sandbox interface `__sandbox_ms` and fails +closed if it is unavailable. Exit 90 with `reason=interface-unavailable` means the +interface could not be resolved; `reason=installation-rejected` means applying +the restriction failed. Exit 91 reports the IPv4/IPv6 and TCP/UDP check that did +not observe denial. Check the host's diagnostic output and Xcode/runtime version; +do not disable the guard to make a run pass. +Recording inputs without running does not build the guard. No guard is added to production. + +## macOS local command + +First resolve the repository's standard SwiftPM dependencies so the supplied +scratch directory contains the matching package inputs. Then run: + +```sh +python3 composerLayoutTests/run-macos.py --output /tmp/composer-macos \ + --scratch-path "$PWD/.build" +``` + +An existing external dependency cache also works; its ordinary build products are not changed. `--prepare-only` records the declared inputs without requiring a cache or +building. Runtime/build process +trees deny network access and real keychain services, with isolated writable +home/cache locations. The four tests run serially with a 120-second watchdog after +a separate build capped at 600 seconds. No real file dialog, external desktop +input injection or Accessibility permission is requested. + +## Results, deadlines and limits + +Use a fresh output folder each time. Both runners retain input hashes, commands, +raw logs, exit codes and post-run hashes; failure log tails are printed; iOS also retains an xcresult bundle. +They reject missing/skipped cases, failed commands and input drift. Setup failures, +timeouts and interruptions produce failure records and clean up owned processes. +The workflow also runs Python runner/negative-control tests, target-membership +checks and shipping Release source/binary exclusions. The iOS runner verifies +the required guard symbol and markers before launch; host startup requires the +guard's verified status. Builds use +two jobs. iOS cases have 60-second execution limits; the xcodebuild build has +a 600-second deadline and the test command a 900-second default deadline, with separate bounded guard/media preparation. +A successful build or zero-case test command is not a passing suite. + +For an iOS baseline control, export the uncorrected composer to a separate file: + +```sh +python3 composerLayoutTests/run.py --output /tmp/composer-baseline \ + --simulator "$SIMULATOR_UUID" --packages "$PACKAGE_CACHE" \ + --composer /tmp/original-composer.swift --test testAccessibilityXXXL +``` + +The intended failure is `Attachment and send controls must not overlap`. +A setup failure, timeout or different assertion is not regression sensitivity. +Fixtures retain model wiring and an app-process network guard. The composer +and its command suggestions use three feature models: conversation UI, private +conversation and location channels. The fixture constructs only those models. +Their underlying chat model uses these dependencies before setup: + +| Dependency | Why the fixture supplies it | +| --- | --- | +| Nostr transport | Inert connectivity; unexpected sends and scheduling fail | +| Deduplication factory | In-memory state instead of the persistent event store | +| Relay manager | Avoid acquiring the live shared relay manager | +| Favorites | Use the mock keychain | +| Preferences | Isolate mutable settings from normal app preferences | +| Geographic coordinator/foreground state | Retain coordinator wiring without live Tor/location dependencies | + +The fixture asserts that injected services were constructed and transport/router +wiring remains connected. Production defaults remain unchanged. Geometry checks +read fresh bounds per assertion group, including after UI transitions; they do +not reuse measurements across states. +The fake recording backend is installed before the first gesture. iOS assertions +check the received Dynamic Type environment and control containment as well as +non-overlap. Camera long-press checks use one second; half-second arbitration is not covered. +Ordinary accessibility dimensions must be positive and at most 37 points (36 plus +rounding), but may describe the icon rather than its full layout allocation. + +These are synthetic fixture tests using production controls/picker delegates and +fixture callbacks. They do not verify real message/media delivery, image-processing +pipelines, physical input/devices, VoiceOver, actual microphone/camera capture, +macOS file-dialog behavior or minimum-OS runtime behavior. macOS tests exercise +layout-frame geometry; the iOS layout cases separately check accessibility bounds. + +## Selected-language layout coverage + +Twelve additional iOS cases cover Arabic, Hebrew and German in both themes, +at ordinary and accessibility XXXL text sizes in 280-point rows. An isolated +display-channel manager lets the fixture select localized channel placeholders +without starting relay subscriptions. They assert +the actual bundle language, SwiftUI layout direction, localized mesh/channel +placeholders, mixed-direction draft preservation, numeric editing, mirrored +control ordering, containment/non-overlap, attachment requests and send callbacks +through populated, empty/microphone and send-only states. Non-Latin keyboard +entry, translation quality and VoiceOver are not established by these fixtures. +The four actual system-photo-picker cases remain English-only. + +## Adding or renaming cases + +The iOS runner checks discovered XCTest methods in `ComposerLayoutUITests.swift` +against the explicit `EXPECTED` inventory in `run.py` before any build, including +focused runs. Update both the methods and inventory when deliberately adding or +renaming cases; deletion, replacement, duplication or an unlisted addition fails +instead of changing the expected coverage. The macOS runner filters +`MacButtonTests` and checks its explicit `EXPECTED` inventory in `run-macos.py`; +update that inventory when adding or renaming a macOS case. Both runners reject +missing, skipped or duplicate results. Keep the README coverage description in +sync. Focused `--test` runs are for local diagnosis; the iOS workflow omits this +option so the complete suite remains automatic. diff --git a/composerLayoutTests/check_invariants.py b/composerLayoutTests/check_invariants.py new file mode 100644 index 00000000..3d99345f --- /dev/null +++ b/composerLayoutTests/check_invariants.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Check declared host membership and optional compiled artifacts, without building.""" +import argparse +import json +from pathlib import Path +import plistlib +import re +import subprocess + +GUARD_MARKERS = (b'COMPOSER_TEST_ISOLATION_INSTALL_FAILED', + b'COMPOSER_TEST_ISOLATION_VERIFY_FAILED', + b'COMPOSER_TEST_ISOLATION_INSTALLED') +HOST_MARKERS = GUARD_MARKERS + (b'composer_test_isolation_status', + b'LocalComposerProbeFrames', b'localComposerProbeFrame', + b'ComposerLayoutFixture') +SOURCE_MARKERS = ('/_ComposerTestHost/', '/ComposerSupport/', '/ComposerMacTests/', + '/composerLayoutTests/') + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def load_project(root): + result = subprocess.run(['plutil', '-convert', 'json', '-o', '-', + str(root / 'bitchat.xcodeproj/project.pbxproj')], + capture_output=True, text=True, check=True, timeout=15) + return json.loads(result.stdout) + + +def check_project(project, root): + """Check actual file-level membership, not folder-name exclusion assumptions.""" + objects = project['objects'] + targets = {obj['name']: (key, obj) for key, obj in objects.items() + if obj.get('isa') == 'PBXNativeTarget'} + + def excluded(target_name, folder): + key, target = targets[target_name] + groups = [objects[group] for group in target.get('fileSystemSynchronizedGroups', []) + if objects[group].get('path') == folder] + require(len(groups) == 1, target_name + ': expected synchronized ' + folder + ' group') + return {path for item in groups[0].get('exceptions', []) + if objects[item].get('target') == key + for path in objects[item].get('membershipExceptions', [])} + + host_files = {str(path.relative_to(root / 'bitchat')) + for path in (root / 'bitchat/_ComposerTestHost').rglob('*.swift')} + support_files = {str(path.relative_to(root / 'bitchatTests')) + for folder in ('ComposerSupport', 'ComposerMacTests') + for path in (root / 'bitchatTests' / folder).rglob('*.swift')} + require(host_files and support_files, 'Composer support files missing') + for name in ('bitchat_iOS', 'bitchat_macOS'): + missing = host_files - excluded(name, 'bitchat') + require(not missing, name + ': test-host sources not excluded: ' + ', '.join(sorted(missing))) + for name in ('bitchatTests_iOS', 'bitchatTests_macOS'): + missing = support_files - excluded(name, 'bitchatTests') + require(not missing, name + ': composer support not excluded: ' + ', '.join(sorted(missing))) + host_excluded = excluded('ComposerLayoutHost', 'bitchat') + require('BitchatApp.swift' in host_excluded, 'ComposerLayoutHost: production startup must be excluded') + require(not host_files.intersection(host_excluded), 'ComposerLayoutHost: inert startup/probes excluded') + host = targets['ComposerLayoutHost'][1] + explicit_sources = {objects[objects[item]['fileRef']].get('path') + for phase in host['buildPhases'] + if objects[phase].get('isa') == 'PBXSourcesBuildPhase' + for item in objects[phase].get('files', [])} + require('composerLayoutTests/NetworkIsolation.c' in explicit_sources, + 'ComposerLayoutHost: required network guard missing from sources') + return {'normal_host_exclusions': sorted(host_files), + 'normal_test_exclusions': sorted(support_files), 'guard_source_member': True} + + +def check_host_bytes(data): + for marker in GUARD_MARKERS: + require(marker in data, 'Built host missing guard marker: ' + marker.decode()) + + +def check_host_binary(path): + check_host_bytes(path.read_bytes()) + result = subprocess.run(['nm', '-g', str(path)], capture_output=True, text=True, + check=True, timeout=30) + require(re.search(r'\b[Tt] _composer_test_isolation_status\s*$', result.stdout, re.M), + 'Built host missing defined composer_test_isolation_status symbol') + # The App initializer calls this symbol before constructing its fixture; the + # function returns 1 only after constructor installation and denial checks. + return {'path': str(path), 'required_status_symbol_defined': True, + 'guard_markers_present': True} + + +def check_shipping_binary(path): + data = path.read_bytes() + for marker in HOST_MARKERS: + require(marker not in data, 'Shipping binary contains test-host marker: ' + marker.decode()) + return {'path': str(path), 'test_host_markers_absent': True} + + +def check_shipping_sources(path): + text = path.read_text() + require(bool(text.strip()), 'Shipping source list is empty') + for marker in SOURCE_MARKERS: + require(marker not in text, 'Shipping source list contains test-host path: ' + marker) + return {'path': str(path), 'test_host_paths_absent': True} + + +def check_shipping_derived(derived): + """Inspect compiler source lists and every shipping Release app image present.""" + lists = sorted(derived.rglob('*.SwiftFileList')) + require(bool(lists), 'Shipping derived data contains no Swift compiler source lists') + sources = [check_shipping_sources(path) for path in lists] + require(any('/bitchat/' in path.read_text() for path in lists), + 'Shipping derived data contains no app Swift compiler source list') + apps = sorted(path for path in (derived / 'Build/Products').glob('Release*/bitchat.app') + if path.is_dir()) + require(bool(apps), 'Shipping derived data contains no Release bitchat.app') + binaries = [] + for app in apps: + macos = (app / 'Contents/Info.plist').is_file() + info_path = app / ('Contents/Info.plist' if macos else 'Info.plist') + with info_path.open('rb') as stream: + executable = plistlib.load(stream)['CFBundleExecutable'] + require(Path(executable).name == executable, 'Unexpected shipping executable path') + binary = app / ('Contents/MacOS' if macos else '') / executable + require(binary.is_file(), 'Shipping executable missing: ' + str(binary)) + binaries.append(check_shipping_binary(binary)) + # Release normally has no debug dylib. If enabled, inspect it as well. + binaries.extend(check_shipping_binary(path) for path in sorted(binary.parent.glob('*.debug.dylib'))) + return {'source_lists': sources, 'binaries': binaries} + + +def check_package_description(description, host): + targets = {target['name']: target for target in description['targets']} + app = set(targets['bitchat']['sources']) + tests = set(targets['bitchatTests']['sources']) + require(('BitchatApp.swift' in app) != host, 'SwiftPM production startup membership incorrect') + require(('_ComposerTestHost/BitchatApp.swift' in app) == host, + 'SwiftPM inert startup membership incorrect') + require(('_ComposerTestHost/FrameProbes.swift' in app) == host, + 'SwiftPM frame probe membership incorrect') + for source in ('ComposerSupport/Models.swift', 'ComposerMacTests/MacButtonTests.swift'): + require((source in tests) == host, 'SwiftPM composer support membership incorrect: ' + source) + return {'host_configuration': host, 'membership_valid': True} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, default=Path(__file__).resolve().parent.parent) + parser.add_argument('--host-binary', type=Path) + parser.add_argument('--shipping-binary', type=Path, action='append', default=[]) + parser.add_argument('--shipping-sources', type=Path, action='append', default=[]) + parser.add_argument('--shipping-derived', type=Path, action='append', default=[]) + parser.add_argument('--package-description', type=Path) + parser.add_argument('--package-host', action='store_true') + args = parser.parse_args() + report = {} + try: + report['declarations'] = check_project(load_project(args.source), args.source) + if args.host_binary: + report['host_binary'] = check_host_binary(args.host_binary) + report['shipping_binaries'] = [check_shipping_binary(p) for p in args.shipping_binary] + report['shipping_sources'] = [check_shipping_sources(p) for p in args.shipping_sources] + report['shipping_derived'] = [check_shipping_derived(p) for p in args.shipping_derived] + if args.package_description: + report['package'] = check_package_description(json.loads(args.package_description.read_text()), + args.package_host) + report['valid'] = True + except (ValueError, KeyError, OSError, subprocess.SubprocessError) as error: + report.update(valid=False, error=str(error)) + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 if report['valid'] else 2 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/composerLayoutTests/run-macos.py b/composerLayoutTests/run-macos.py new file mode 100644 index 00000000..fc03a778 --- /dev/null +++ b/composerLayoutTests/run-macos.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Run four native composer button cases using the declared inert SwiftPM host.""" +import argparse +import json +import os +from pathlib import Path +import re + +from runner_support import Interrupted, bounded, install_signal_handlers, manifest, require_json, save +import shutil + +EXPECTED = {'testMatrixNarrowButtons', 'testGlassNarrowButtons', + 'testMatrixLargeButtons', 'testGlassLargeButtons'} + + +def seed_dependencies(original, scratch): + """Copy resolved inputs, never alternate configuration binaries.""" + scratch.mkdir() + for name in ('artifacts', 'checkouts', 'repositories', 'workspace-state.json'): + source = original / name + if source.is_dir(): + shutil.copytree(source, scratch / name, symlinks=True) + elif source.is_file(): + shutil.copy2(source, scratch / name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, required=True, help='New folder outside the checkout') + parser.add_argument('--scratch-path', type=Path, help='Existing resolved SwiftPM scratch/cache directory') + parser.add_argument('--prepare-only', action='store_true', help='Record declared host inputs without building') + parser.add_argument('--build-timeout', type=int, default=600) + parser.add_argument('--test-timeout', type=int, default=120) + args = parser.parse_args() + package = Path(__file__).resolve().parent + source = package.parent + output = args.output.resolve() + if output == source or source in output.parents: + parser.error('--output must be outside the checkout') + if not 0 < args.build_timeout <= 600 or not 0 < args.test_timeout <= 120: + parser.error('Build/test deadlines must be positive and at most 600/120 seconds') + if not args.prepare_only and (not args.scratch_path or not args.scratch_path.is_dir()): + parser.error('Running requires --scratch-path with already resolved dependencies') + if args.scratch_path: + dependency_cache = args.scratch_path.resolve() + scratch = dependency_cache + if (scratch == source or source in scratch.parents) and scratch != source / '.build': + parser.error('--scratch-path must be outside the checkout or its existing .build cache') + output.mkdir(parents=True, exist_ok=False) + install_signal_handlers() + before = manifest(source) + save(output / 'source-inputs.json', before) + # Package.swift declares the alternate entry point, frame probes and composer + # test membership. This runner filters four cases without rewriting sources. + inputs = before + save(output / 'host-inputs.json', inputs) + if args.prepare_only: + save(output / 'result.json', {'prepared': True, 'executed': False}) + print(source) + return 0 + + # Build the alternate configuration in its own output tree. Only resolved + # package inputs are copied from the ordinary configuration's cache. + scratch = output / 'scratch' + code, reason = 2, 'setup failure' + try: + seed_dependencies(dependency_cache, scratch) + code = execute(source, output, scratch, args) + reason = 'tests passed' if code == 0 else 'build, test or inventory failure' + except (Interrupted, KeyboardInterrupt) as error: + code, reason = 130, str(error) + except Exception as error: + code, reason = 2, f'{type(error).__name__}: {error}' + finally: + after = manifest(source) + save(output / 'after-source-inputs.json', after) + unchanged = before == after + if not unchanged: + code, reason = 2, 'source input drift' + save(output / 'result.json', {'exit': code, 'reason': reason, 'executed': True, + 'inputs_unchanged': unchanged}) + print(f'Mac composer: {reason}; exit {code}; evidence: {output}', flush=True) + return code + + +def execute(source, output, scratch, args): + # Kernel restrictions apply to this process tree, not the whole machine. + # Block network and real keychain services. Redirect mutable home/cache state. + for name in ('home', 'temp', 'cache', 'config', 'security', 'clang-cache', 'swift-cache'): + (output / name).mkdir() + quote = lambda value: json.dumps(str(value)) + profile = '\n'.join([ + '(version 1)', '(allow default)', '(deny network*)', '(deny file-write*)', + '(allow file-write* (literal "/dev/null") (subpath ' + quote(output) + ')', + ' (subpath ' + quote(scratch) + ') (subpath "/private/tmp") (subpath "/private/var/folders"))', + '(deny file-read* (subpath ' + quote(Path.home() / 'Library') + '))', + '(allow file-read* (subpath ' + quote(Path.home() / 'Library/Developer') + '))', + '(deny mach-lookup (global-name "com.apple.securityd"))', + '(deny mach-lookup (global-name "com.apple.cfprefsd.agent"))', + ]) + '\n' + sandbox = output / 'runtime.sb' + sandbox.write_text(profile) + env = dict(os.environ, CFFIXED_USER_HOME=str(output / 'home'), TMPDIR=str(output / 'temp') + '/', + XDG_CACHE_HOME=str(output / 'cache'), CLANG_MODULE_CACHE_PATH=str(output / 'clang-cache'), + SWIFTPM_MODULECACHE_OVERRIDE=str(output / 'swift-cache'), GIT_ALLOW_PROTOCOL='file', + GIT_TERMINAL_PROMPT='0', CI='1', COMPOSER_TEST_HOST='1') + flags = ['--disable-sandbox', '--skip-update', '--disable-automatic-resolution', + '--scratch-path', str(scratch), '--cache-path', str(output / 'cache'), + '--config-path', str(output / 'config'), '--security-path', str(output / 'security'), '--jobs', '2'] + prefix = ['/usr/bin/sandbox-exec', '-f', str(sandbox), 'swift'] + from check_invariants import check_package_description, check_project, load_project + save(output / 'project-invariants.json', check_project(load_project(source), source)) + for host_mode in (False, True): + mode_env = dict(env) + if not host_mode: + mode_env.pop('COMPOSER_TEST_HOST', None) + description = require_json(prefix + ['package'] + flags + ['describe', '--type', 'json'], + source, mode_env, output, 'package-host' if host_mode else 'package-normal', 60) + save(output / ('membership-host.json' if host_mode else 'membership-normal.json'), + check_package_description(description, host_mode)) + code = bounded(prefix + ['build', '--build-tests'] + flags, source, env, output, 'build', args.build_timeout) + if code == 0: + code = bounded(prefix + ['test', '--skip-build', '--filter', 'MacButtonTests'] + flags, + source, env, output, 'test', args.test_timeout) + raw = (output / 'test.log').read_text() + passed = re.findall(r"Test Case '-\[bitchatTests.MacButtonTests (test\w+)\]' passed", raw) + valid = (len(passed) == 4 and set(passed) == EXPECTED + and not re.search(r"Test Case .* (?:skipped|failed)", raw) + and re.search(r'Executed 4 tests, with 0 failures', raw) is not None) + save(output / 'inventory.json', {'expected': sorted(EXPECTED), 'passed': passed, + 'zero_skips_and_exact_inventory': valid}) + if code == 0 and not valid: + code = 2 + return code + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/composerLayoutTests/run.py b/composerLayoutTests/run.py new file mode 100644 index 00000000..cb08c111 --- /dev/null +++ b/composerLayoutTests/run.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Run the declared composer UI host on an owned, disposable simulator.""" +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import struct +import uuid +import zlib +from runner_support import Interrupted, bounded, install_signal_handlers, manifest, require, save + + +# This inventory is intentionally independent of source discovery: removing or +# replacing a case must require an explicit coverage update, even for subset runs. +EXPECTED = { + 'testAccessibilityXXXL', + 'testAccessibilityXXXLWide', + 'testActualPhotoPickerGlassLarge', + 'testActualPhotoPickerGlassOrdinary', + 'testActualPhotoPickerMatrixLarge', + 'testActualPhotoPickerMatrixOrdinary', + 'testArabicGlassLarge', + 'testArabicGlassOrdinary', + 'testArabicMatrixLarge', + 'testArabicMatrixOrdinary', + 'testGermanGlassLarge', + 'testGermanGlassOrdinary', + 'testGermanMatrixLarge', + 'testGermanMatrixOrdinary', + 'testGlassAccessibilityXXXL', + 'testGlassAccessibilityXXXLWide', + 'testGlassOrdinary', + 'testGlassOrdinaryNarrow', + 'testHebrewGlassLarge', + 'testHebrewGlassOrdinary', + 'testHebrewMatrixLarge', + 'testHebrewMatrixOrdinary', + 'testMicrophoneGestureUsesSyntheticCapture', + 'testNarrowGlassLargeTextEditing', + 'testNarrowLargeTextEditing', + 'testOrdinary', + 'testOrdinaryNarrow', +} + + +def declared_inventory(source_text): + methods = re.findall(r'func (test\w+)\(', source_text) + discovered = set(methods) + if len(methods) != len(discovered) or discovered != EXPECTED: + missing = sorted(EXPECTED - discovered) + unexpected = sorted(discovered - EXPECTED) + raise ValueError(f'Composer test definitions differ from required inventory; ' + f'missing={missing}; unexpected={unexpected}; ' + f'duplicate_definitions={len(methods) != len(discovered)}') + return discovered + + +def seed_photo(simulator, output, source, env): + def chunk(kind, data): + return (struct.pack('!I', len(data)) + kind + data + + struct.pack('!I', zlib.crc32(kind + data) & 0xffffffff)) + colors = [(230, 20, 170), (20, 180, 230), (240, 200, 20), (30, 190, 70)] + pixels = b''.join(b'\x00' + b''.join(bytes(colors[(y >= 32) * 2 + (x >= 48)]) + for x in range(96)) for y in range(64)) + png = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!2I5B', 96, 64, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b'')) + photo = output / 'composer-photo.png' + photo.write_bytes(png) + require(['xcrun', 'simctl', 'addmedia', simulator, str(photo)], source, env, output, 'seed', 90) + + +def validate_inventory(summary, raw, expected): + passed = re.findall(r"Test Case '-\[ComposerLayoutUITests.ComposerLayoutUITests (test\w+)\]' passed", raw) + valid = (summary.get('totalTestCount') == len(expected) + and summary.get('passedTests') == len(expected) + and summary.get('skippedTests') == 0 and len(passed) == len(expected) + and set(passed) == expected) + return {'expected': sorted(expected), 'passed': passed, 'valid': valid} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', required=True, type=Path, help='New output folder outside checkout') + parser.add_argument('--simulator', help='Template device UUID; only its type/runtime are read. Omit to prepare.') + parser.add_argument('--packages', type=Path, help='Resolved Xcode package cache') + parser.add_argument('--composer', type=Path, help='Alternate composer for a baseline control') + parser.add_argument('--test', action='append', help='Packaged XCTest method; repeat for a subset') + parser.add_argument('--timeout', type=int, default=600, help='Build command deadline') + parser.add_argument('--test-timeout', type=int, default=900, help='Test command deadline') + args = parser.parse_args() + package = Path(__file__).resolve().parent + source = package.parent + try: + available = declared_inventory((package / 'ComposerLayoutUITests/ComposerLayoutUITests.swift').read_text()) + except ValueError as error: + parser.error(str(error)) + if args.test and (not set(args.test) <= available or len(args.test) != len(set(args.test))): + parser.error('--test must name distinct packaged tests') + output = args.output.resolve() + if output == source or source in output.parents: + parser.error('--output must be outside checkout') + if not 0 < args.timeout <= 600: + parser.error('--timeout must be between 1 and 600 seconds') + if not 0 < args.test_timeout <= 900: + parser.error('--test-timeout must be between 1 and 900 seconds') + if args.simulator and not args.packages: + parser.error('--simulator requires --packages') + output.mkdir(parents=True, exist_ok=False) + install_signal_handlers() + env = dict(os.environ, GIT_TERMINAL_PROMPT='0', GIT_ALLOW_PROTOCOL='file') + code, reason, device, host, before = 2, 'setup failure', None, source, None + try: + if args.composer: + host = output / 'host' + shutil.copytree(source, host, ignore=shutil.ignore_patterns('.git', '.build', 'build', '__pycache__')) + shutil.copyfile(args.composer, host / 'bitchat/Views/ContentComposerView.swift') + before = manifest(host) + save(output / 'inputs.json', before) + if not args.simulator: + code, reason = 0, 'prepared, not executed' + return code + devices = json.loads(require(['xcrun', 'simctl', 'list', 'devices', 'available', '-j'], source, env, output, 'devices')) + matches = [(runtime, item) for runtime, items in devices['devices'].items() for item in items + if item['udid'] == args.simulator] + if len(matches) != 1: + raise RuntimeError('Template simulator not available') + runtime, template = matches[0] + device = require(['xcrun', 'simctl', 'create', 'Composer-' + uuid.uuid4().hex[:8], + template['deviceTypeIdentifier'], runtime], source, env, output, 'create').strip() + save(output / 'owned-device.json', {'udid': device, 'runtime': runtime, 'type': template['deviceTypeIdentifier']}) + common = ['xcodebuild', '-project', 'bitchat.xcodeproj', '-scheme', 'Composer Layout', + '-configuration', 'Debug', '-destination', 'platform=iOS Simulator,id=' + device, + '-derivedDataPath', str(output / 'derived'), '-clonedSourcePackagesDirPath', str(args.packages.resolve()), + '-disableAutomaticPackageResolution', '-skipPackageUpdates', '-jobs', '2', + '-parallel-testing-enabled', 'NO', '-test-timeouts-enabled', 'YES', + '-maximum-test-execution-time-allowance', '60', 'CODE_SIGNING_ALLOWED=NO'] + code = bounded(common + ['build-for-testing'], host, env, output, 'build', args.timeout) + if code: + raise RuntimeError(f'build failed with exit {code}') + # Verify declared membership and the required guard before booting a host. + binary = output / 'derived/Build/Products/Debug-iphonesimulator/ComposerLayoutHost.app/ComposerLayoutHost.debug.dylib' + require(['python3', str(package / 'check_invariants.py'), '--source', str(host), + '--host-binary', str(binary)], source, env, output, 'invariants') + require(['xcrun', 'simctl', 'boot', device], source, env, output, 'boot') + require(['xcrun', 'simctl', 'bootstatus', device, '-b'], source, env, output, 'bootstatus', 120) + selected = set(args.test) if args.test else available + if any(name.startswith('testActualPhotoPicker') for name in selected): + seed_photo(device, output, source, env) + filters = ['-only-testing:ComposerLayoutUITests/ComposerLayoutUITests/' + name + for name in sorted(selected)] if args.test else [ + '-only-testing:ComposerLayoutUITests/ComposerLayoutUITests'] + command = common + ['-resultBundlePath', str(output / 'result.xcresult')] + filters + ['test-without-building'] + code = bounded(command, host, env, output, 'run', args.test_timeout) + reason = 'tests passed' if code == 0 else 'tests failed' + if code == 0: + summary = json.loads(require(['xcrun', 'xcresulttool', 'get', 'test-results', 'summary', '--path', + str(output / 'result.xcresult')], source, env, output, 'summary', 30)) + save(output / 'summary.json', summary) + inventory = validate_inventory(summary, (output / 'run.log').read_text(), selected) + save(output / 'inventory.json', inventory) + if not inventory['valid']: + code, reason = 2, 'missing, skipped, duplicate or unexpected tests' + except (Interrupted, KeyboardInterrupt) as error: + code, reason = 130, str(error) + except Exception as error: + code, reason = 2, f'{type(error).__name__}: {error}' + finally: + if device: + cleanup = {} + for action in ('shutdown', 'delete'): + try: + cleanup[action] = bounded(['xcrun', 'simctl', action, device], source, env, output, action, 30) + except Exception as error: + cleanup[action] = str(error) + save(output / 'cleanup.json', cleanup) + if cleanup.get('delete') != 0: + code, reason = 2, 'owned simulator cleanup failed' + if before is not None: + after = manifest(host) + save(output / 'after-inputs.json', after) + if before != after: + code, reason = 2, 'source input drift' + save(output / 'result.json', {'exit': code, 'reason': reason, 'executed': bool(args.simulator)}) + (output / 'runner-exit.txt').write_text(str(code) + '\n') + print(f'Composer: {reason}; exit {code}; evidence: {output}', flush=True) + return code + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/composerLayoutTests/runner_support.py b/composerLayoutTests/runner_support.py new file mode 100644 index 00000000..8f807b38 --- /dev/null +++ b/composerLayoutTests/runner_support.py @@ -0,0 +1,95 @@ +"""Bounded local commands and failure diagnostics shared by composer runners.""" +import hashlib +import json +import os +from pathlib import Path +import signal +import subprocess +import time + + +class Interrupted(Exception): + pass + + +def install_signal_handlers(): + def interrupt(signum, _frame): + raise Interrupted(f'interrupted by signal {signum}') + signal.signal(signal.SIGTERM, interrupt) + signal.signal(signal.SIGINT, interrupt) + + +def save(path, value): + path.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + + +def manifest(root): + ignored = {'.git', '.build', 'build', '__pycache__'} + return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(root.rglob('*')) if p.is_file() + and not ignored.intersection(p.relative_to(root).parts)} + + +def stop_group(process): + # The new session belongs to this command, never another chat's build. + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + return + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + # Also remove descendants whose parent exited promptly on TERM. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=5) + + +def bounded(command, cwd, env, output, name, timeout, separate_stderr=False): + save(output / (name + '-command.json'), {'argv': command, 'cwd': str(cwd), + 'timeout_seconds': timeout}) + started = time.monotonic() + path = output / (name + '.log') + code, reason, process = 2, 'setup failure', None + try: + with path.open('w') as log, (output / (name + '-stderr.log')).open('w') as error_log: + process = subprocess.Popen(command, cwd=cwd, env=env, stdout=log, + stderr=error_log if separate_stderr else subprocess.STDOUT, start_new_session=True) + try: + code = process.wait(timeout=timeout) + reason = 'passed' if code == 0 else 'command failed' + except subprocess.TimeoutExpired: + code, reason = 124, 'deadline exceeded' + except (Interrupted, KeyboardInterrupt): + code, reason = 130, 'interrupted' + raise + finally: + if process.poll() is None or code in (124, 130): + stop_group(process) + finally: + save(output / (name + '-result.json'), {'exit': code, 'reason': reason, + 'seconds': time.monotonic() - started, + 'log_sha256': hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None}) + if code: + print(f'{name}: {reason} (exit {code})', flush=True) + for diagnostic in (path, output / (name + '-stderr.log')): + if diagnostic.exists() and diagnostic.stat().st_size: + print('\n'.join(diagnostic.read_text(errors='replace').splitlines()[-60:]), flush=True) + return code + + +def require(command, cwd, env, output, name, timeout=60): + code = bounded(command, cwd, env, output, name, timeout) + if code: + raise RuntimeError(f'{name} failed with exit {code}') + return (output / (name + '.log')).read_text() + + +def require_json(command, cwd, env, output, name, timeout=60): + code = bounded(command, cwd, env, output, name, timeout, separate_stderr=True) + if code: + raise RuntimeError(f'{name} failed with exit {code}') + return json.loads((output / (name + '.log')).read_text()) diff --git a/composerLayoutTests/test_invariants.py b/composerLayoutTests/test_invariants.py new file mode 100644 index 00000000..e1335da3 --- /dev/null +++ b/composerLayoutTests/test_invariants.py @@ -0,0 +1,116 @@ +"""Negative controls for declaration and artifact checks; no builds or simulators.""" +import copy +from pathlib import Path +import tempfile +import plistlib +import shutil +import unittest + +import check_invariants as checks + + +class HostInvariantTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root = Path(__file__).resolve().parent.parent + cls.project = checks.load_project(cls.root) + + def test_current_project(self): + checks.check_project(self.project, self.root) + + def test_folder_exclusion_does_not_replace_exact_files(self): + project = copy.deepcopy(self.project) + for obj in project['objects'].values(): + values = obj.get('membershipExceptions', []) + if '_ComposerTestHost/BitchatApp.swift' in values: + obj['membershipExceptions'] = ['_ComposerTestHost'] + with self.assertRaisesRegex(ValueError, 'test-host sources not excluded'): + checks.check_project(project, self.root) + + def test_new_host_file_requires_shipping_exclusion(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for relative in ('bitchat/_ComposerTestHost', 'bitchatTests/ComposerSupport', + 'bitchatTests/ComposerMacTests'): + shutil.copytree(self.root / relative, root / relative) + checks.check_project(self.project, root) + (root / 'bitchat/_ComposerTestHost/NewFixture.swift').write_text('// Future host source\n') + with self.assertRaisesRegex(ValueError, 'test-host sources not excluded: .*NewFixture.swift'): + checks.check_project(self.project, root) + + def test_missing_guard_membership_is_rejected(self): + project = copy.deepcopy(self.project) + refs = {key for key, obj in project['objects'].items() + if obj.get('path') == 'composerLayoutTests/NetworkIsolation.c'} + builds = {key for key, obj in project['objects'].items() if obj.get('fileRef') in refs} + for obj in project['objects'].values(): + if obj.get('isa') == 'PBXSourcesBuildPhase': + obj['files'] = [item for item in obj.get('files', []) if item not in builds] + with self.assertRaisesRegex(ValueError, 'required network guard missing'): + checks.check_project(project, self.root) + + def test_guard_bytes_required(self): + valid = b'\0'.join(checks.GUARD_MARKERS) + checks.check_host_bytes(valid) + for marker in checks.GUARD_MARKERS: + with self.subTest(marker=marker): + with self.assertRaisesRegex(ValueError, 'Built host missing guard marker'): + checks.check_host_bytes(valid.replace(marker, b'')) + + def test_shipping_artifacts_reject_host_content(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / 'artifact' + path.write_bytes(b'production') + checks.check_shipping_binary(path) + for marker in checks.HOST_MARKERS: + path.write_bytes(b'production\0' + marker) + with self.subTest(marker=marker): + with self.assertRaisesRegex(ValueError, 'Shipping binary contains'): + checks.check_shipping_binary(path) + path.write_text('/source/bitchat/BitchatApp.swift\n') + checks.check_shipping_sources(path) + path.write_text('/source/bitchat/_ComposerTestHost/BitchatApp.swift\n') + with self.assertRaisesRegex(ValueError, 'Shipping source list contains'): + checks.check_shipping_sources(path) + path.write_text('') + with self.assertRaisesRegex(ValueError, 'source list is empty'): + checks.check_shipping_sources(path) + + def test_shipping_derived_requires_real_inventory_and_rejects_contamination(self): + with tempfile.TemporaryDirectory() as folder: + derived = Path(folder) + with self.assertRaisesRegex(ValueError, 'no Swift compiler source lists'): + checks.check_shipping_derived(derived) + sources = derived / 'app.SwiftFileList' + sources.write_text('/source/bitchat/BitchatApp.swift\n') + with self.assertRaisesRegex(ValueError, 'no Release bitchat.app'): + checks.check_shipping_derived(derived) + app = derived / 'Build/Products/Release-iphonesimulator/bitchat.app' + app.mkdir(parents=True) + with (app / 'Info.plist').open('wb') as stream: + plistlib.dump({'CFBundleExecutable': 'bitchat'}, stream) + (app / 'bitchat').write_bytes(b'production binary') + checks.check_shipping_derived(derived) + (app / 'bitchat').write_bytes(b'ComposerLayoutFixture') + with self.assertRaisesRegex(ValueError, 'Shipping binary contains'): + checks.check_shipping_derived(derived) + + def test_package_mode_mismatch_rejected(self): + description = {'targets': [ + {'name': 'bitchat', 'sources': ['BitchatApp.swift']}, + {'name': 'bitchatTests', 'sources': ['OtherTests.swift']} ]} + checks.check_package_description(description, host=False) + with self.assertRaisesRegex(ValueError, 'production startup membership incorrect'): + checks.check_package_description(description, host=True) + description['targets'][0]['sources'] = ['_ComposerTestHost/BitchatApp.swift', + '_ComposerTestHost/FrameProbes.swift'] + description['targets'][1]['sources'] = ['ComposerSupport/Models.swift', + 'ComposerMacTests/MacButtonTests.swift'] + checks.check_package_description(description, host=True) + description['targets'][1]['sources'].remove('ComposerMacTests/MacButtonTests.swift') + with self.assertRaisesRegex(ValueError, 'composer support membership incorrect'): + checks.check_package_description(description, host=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/composerLayoutTests/test_runners.py b/composerLayoutTests/test_runners.py new file mode 100644 index 00000000..149acf17 --- /dev/null +++ b/composerLayoutTests/test_runners.py @@ -0,0 +1,148 @@ +"""Portable runner contracts: no simulator, Apple build or network required.""" +import importlib.util +import io +from contextlib import redirect_stdout +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch +from runner_support import Interrupted +from runner_support import bounded, require_json +import run + + +class RunnerContracts(unittest.TestCase): + def test_json_output_is_separate_from_tool_warnings(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + result = require_json([sys.executable, '-c', + 'import sys,json; print("warning", file=sys.stderr); print(json.dumps(dict(valid=True)))'], + output, os.environ, output, 'json', 5) + self.assertEqual(result, {'valid': True}) + self.assertIn('warning', (output / 'json-stderr.log').read_text()) + + def test_failed_json_command_prints_stderr_diagnostics(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + printed = io.StringIO() + with redirect_stdout(printed), self.assertRaises(RuntimeError): + require_json([sys.executable, '-c', + 'import sys; print("metadata failure", file=sys.stderr); sys.exit(3)'], + output, os.environ, output, 'json-failure', 5) + self.assertIn('metadata failure', printed.getvalue()) + + def test_missing_skipped_duplicate_and_failed_inventory(self): + raw = "Test Case '-[ComposerLayoutUITests.ComposerLayoutUITests testExample]' passed" + summary = dict(totalTestCount=1, passedTests=1, skippedTests=0) + self.assertTrue(run.validate_inventory(summary, raw, {'testExample'})['valid']) + self.assertFalse(run.validate_inventory({}, raw, {'testExample'})['valid']) + self.assertFalse(run.validate_inventory(dict(summary, skippedTests=1), raw, {'testExample'})['valid']) + self.assertFalse(run.validate_inventory(summary, raw + raw, {'testExample'})['valid']) + self.assertFalse(run.validate_inventory(summary, '', {'testExample'})['valid']) + + def test_definition_inventory_rejects_removed_renamed_added_and_duplicate_cases(self): + source = '\n'.join(f'func {name}() {{}}' for name in sorted(run.EXPECTED)) + self.assertEqual(run.declared_inventory(source), run.EXPECTED) + first = sorted(run.EXPECTED)[0] + variants = { + 'removed': source.replace(f'func {first}() {{}}', ''), + 'renamed_same_count': source.replace(first, 'testUnexpectedReplacement'), + 'added': source + '\nfunc testUnexpectedAdditional() {}', + 'duplicate': source + f'\nfunc {first}() {{}}', + } + for label, variant in variants.items(): + with self.subTest(label=label), self.assertRaisesRegex(ValueError, 'required inventory'): + run.declared_inventory(variant) + + def test_nonzero_command_and_setup_error_are_recorded(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + self.assertEqual(bounded([sys.executable, '-c', 'raise SystemExit(65)'], output, + os.environ, output, 'failed', 5), 65) + with self.assertRaises(FileNotFoundError): + bounded(['/nonexistent/composer-command'], output, os.environ, output, 'setup', 5) + self.assertEqual(json.loads((output / 'setup-result.json').read_text())['exit'], 2) + + def test_deadline_kills_command(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + self.assertEqual(bounded([sys.executable, '-c', 'import time; time.sleep(30)'], output, + os.environ, output, 'timeout', .1), 124) + + def test_interrupt_records_failure_and_stops_child(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) + script = ("from pathlib import Path; import os,sys; from runner_support import *; " + "install_signal_handlers(); o=Path(sys.argv[1]); " + "bounded([sys.executable,'-c',\"import os,time; from pathlib import Path; " + "Path('child.pid').write_text(str(os.getpid())); time.sleep(30)\"],o,os.environ,o,'child',30)") + process = subprocess.Popen([sys.executable, '-c', script, str(output)], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parent))) + try: + deadline = time.monotonic() + 5 + while not (output / 'child.pid').exists() and time.monotonic() < deadline: + time.sleep(.02) + self.assertTrue((output / 'child.pid').exists()) + process.send_signal(signal.SIGTERM) + process.communicate(timeout=10) + self.assertEqual(json.loads((output / 'child-result.json').read_text())['exit'], 130) + with self.assertRaises(ProcessLookupError): + os.kill(int((output / 'child.pid').read_text()), 0) + finally: + if process.poll() is None: + process.kill() + process.communicate() + + def test_owned_device_deleted_after_build_failure_or_interruption(self): + for interrupted in (False, True): + with self.subTest(interrupted=interrupted), tempfile.TemporaryDirectory() as directory: + output = Path(directory) / 'run' + calls = [] + def require_stub(command, *args): + if command[2] == 'list': + return json.dumps({'devices': {'runtime': [dict(udid='template', deviceTypeIdentifier='phone')]}}) + if command[2] == 'create': + return 'owned-device' + raise AssertionError(command) + def bounded_stub(command, *args): + calls.append(command) + if command[0] == 'xcodebuild': + if interrupted: + raise Interrupted('test interruption') + return 65 + return 0 + with patch.object(sys, 'argv', ['run.py', '--output', str(output), '--simulator', 'template', + '--packages', directory]), \ + patch.object(run, 'require', side_effect=require_stub), \ + patch.object(run, 'bounded', side_effect=bounded_stub), \ + patch.object(run, 'manifest', return_value={'input': 'unchanged'}), \ + patch.object(run, 'install_signal_handlers'): + self.assertNotEqual(run.main(), 0) + self.assertIn(['xcrun', 'simctl', 'delete', 'owned-device'], calls) + self.assertNotIn(['xcrun', 'simctl', 'delete', 'template'], calls) + result = json.loads((output / 'result.json').read_text()) + self.assertEqual(result['exit'], 130 if interrupted else 2) + + def test_configuration_cache_contains_no_binaries(self): + spec = importlib.util.spec_from_file_location('mac_runner', Path(__file__).with_name('run-macos.py')) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); original = root / 'normal'; original.mkdir() + (original / 'checkouts').mkdir(); (original / 'checkouts/package').write_text('resolved') + (original / 'debug').mkdir(); (original / 'debug/bitchat').write_text('ordinary executable') + module.seed_dependencies(original, root / 'composer') + self.assertTrue((root / 'composer/checkouts/package').exists()) + self.assertFalse((root / 'composer/debug').exists()) + self.assertEqual((original / 'debug/bitchat').read_text(), 'ordinary executable') + + +if __name__ == '__main__': + unittest.main()