diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e877a48..e72e069 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,20 @@ jobs: steps: - uses: actions/checkout@v4 + # learner-server (public) at the commit config/learner-server.ref pins: its pairing + # harness runs on this runner for the desktop + server pairing tests. + - name: Read the pinned learner-server commit + id: server-ref + run: echo "sha=$(tr -d '[:space:]' < config/learner-server.ref)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: learner-studio/learner-server + ref: ${{ steps.server-ref.outputs.sha }} + path: learner-server + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.0 + - name: Use the newest Xcode on the runner run: | newest="$(ls -d /Applications/Xcode_*.app | sort -V | tail -1)" @@ -61,6 +75,20 @@ jobs: - name: fixtures (synthetic sample as ~/ai-vault-data) if: ${{ !cancelled() }} run: scripts/ci.sh fixtures + - name: Cache screenpipe's engine and models + uses: actions/cache@v4 + with: + path: | + ~/.cache/learner-screenpipe + ~/.cache/huggingface/hub/models--ggerganov--whisper.cpp + ~/Library/Caches/screenpipe + key: screenpipe-${{ hashFiles('config/screenpipe-settings.json') }} + - name: screenpipe (real engine on :3030) + if: ${{ !cancelled() }} + run: scripts/ci.sh screenpipe + - name: server (learner-server's pairing harness, Postgres 17) + if: ${{ !cancelled() }} + run: scripts/ci.sh server - name: speech (Siri and Dictation on) if: ${{ !cancelled() }} run: scripts/ci.sh speech diff --git a/.gitignore b/.gitignore index a63284c..47d697e 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ third_party/sherpa-onnx/artifacts/ menu-bar-app/Models/*.onnx ci-out/ ci-app/ +learner-server/ diff --git a/Tests/HeavyTests/CaptureLiveTests.swift b/Tests/HeavyTests/CaptureLiveTests.swift index bf2059c..257ebca 100644 --- a/Tests/HeavyTests/CaptureLiveTests.swift +++ b/Tests/HeavyTests/CaptureLiveTests.swift @@ -16,7 +16,7 @@ enum Live { /// On the GitHub runner (TestEnvironment): a clean Mac with the app and a virtual /// microphone, and none of the owner's live stack. Suites that need it skip, by name. static let ci = TestEnvironment.isRunner - static let notOnCI: Comment = "runner: needs the owner's live screenpipe (LEARNER_TEST_ENV=runner)" + static let notOnCI: Comment = "runner: needs the screenpipe app and the owner's launchd setup, not just its engine (LEARNER_TEST_ENV=runner)" static let api = env["SCREENPIPE_API"] ?? "http://localhost:3030" static func json(_ url: String, body: Any? = nil) -> Any? { @@ -37,11 +37,19 @@ enum Live { struct CaptureLiveTests { let health = Live.health ?? [:] - @Test func audioPipelineIsHealthyAndRealtime() { + /// Runs everywhere: chunked mode reintroduces the transcription backlog the coach cannot + /// live with. + @Test func audioPipelineIsRealtime() { + #expect((health["audio_pipeline"] as? [String: Any])?["transcription_mode"] as? String == "realtime") + } + + /// The owner's Mac only. On the runner BlackHole's loopback goes dead mid-run: the + /// virtual mic read RMS 0.000000 with the room tone playing (runs 7 and 11, at two tone + /// levels), so screenpipe's 30 s no-data rule cannot be met there. + @Test(.enabled(if: !Live.ci, "runner: BlackHole's loopback goes dead mid-run (RMS 0.000000 measured on the virtual mic in runs 7 and 11), so screenpipe's 30 s no-data rule cannot be met there")) + func audioIsFlowingAndHealthy() { #expect(health["status"] as? String == "healthy") #expect(health["audio_status"] as? String == "ok") - // Chunked mode reintroduces the transcription backlog the coach cannot live with. - #expect((health["audio_pipeline"] as? [String: Any])?["transcription_mode"] as? String == "realtime") } @Test(.enabled(if: !LiveMachine.screenpipeWaiting, "screenpipe has paused capture (screen locked)")) @@ -87,7 +95,8 @@ struct CaptureLiveTests { #expect(off.isEmpty, "rows whose stamp is neither the chunk start nor chunk start + start_time: \(off.prefix(3))") } - @Test(.enabled(if: FileManager.default.fileExists(atPath: NSHomeDirectory() + "/.screenpipe/store.bin"), "no ~/.screenpipe/store.bin")) + @Test(.enabled(if: !Live.ci, "runner: the store.bin there is the engine's, not the screenpipe app's settings"), + .enabled(if: FileManager.default.fileExists(atPath: NSHomeDirectory() + "/.screenpipe/store.bin"), "no ~/.screenpipe/store.bin")) func liveSettingsMatchTheCommittedCapture() throws { let live = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: NSHomeDirectory() + "/.screenpipe/store.bin"))) as? [String: Any])["settings"] as? [String: Any] ?? [:] let expected = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: toolsRepoRoot() + "/config/screenpipe-settings.json"))) as? [String: Any])["settings"] as? [String: Any] ?? [:] @@ -96,7 +105,10 @@ struct CaptureLiveTests { #expect(drift.isEmpty, "settings drifted from config/screenpipe-settings.json (update it if deliberate): \(drift)") } - @Test func preflightPassesAgainstTheLiveStack() { + /// Needs the screenpipe app's own settings (~/.screenpipe/store.bin); the runner runs + /// screenpipe's engine without the app. + @Test(.enabled(if: !Live.ci, "runner: screenpipe's engine runs without the app, so there is no store.bin to check")) + func preflightPassesAgainstTheLiveStack() { let r = ChildProcess.run(appBinary, ["tool", "preflight"], timeout: 120, stderr: true) #expect(r.status == 0, "preflight reported drift:\n\(r.output)") } diff --git a/Tests/HeavyTests/CoachAudioLatencyTests.swift b/Tests/HeavyTests/CoachAudioLatencyTests.swift index 1f3380f..2961978 100644 --- a/Tests/HeavyTests/CoachAudioLatencyTests.swift +++ b/Tests/HeavyTests/CoachAudioLatencyTests.swift @@ -105,7 +105,6 @@ final class NoCalls: CallSource { @Suite("Coach, heavy: audio to warning latency", .tags(.heavy, .coach), .quietLog, .enabled(if: env["LEARNER_HEAVY"] == "1", "heavy lane: set LEARNER_HEAVY=1"), .enabled(if: env["LEARNER_HEAVY_AUDIO"] != "0", "audio benchmark switched off (LEARNER_HEAVY_AUDIO=0)"), - .enabled(if: !Live.ci, Live.notOnCI), .timeLimit(.minutes(2)), .serialized) struct CoachAudioLatencyTests { /// Two real-time passes of ~36 s each; a push runs the fast speaker only (the slower @@ -153,7 +152,17 @@ struct CoachAudioLatencyTests { let delay = shown.timeIntervalSince(origin.addingTimeInterval(30)) Log("Coach").info("audio benchmark \(wpm) wpm: warning \(String(format: "%.2f", delay)) s after 30 s of audio; median STT \(String(format: "%.2f", stt.sorted()[stt.count / 2])) s") #expect(delay >= 0, "warned early") - #expect(delay < 6, "warning came \(delay) s after the 30 s mark") + // 6 s is the owner's Mac (its whisper speed). The GitHub runner's 3 shared cores run the + // same model several times slower and unevenly (21 s, then 34 s), so no time there says + // anything about the Mac: on the runner the test proves the pipeline end to end (the + // warning comes, never early) and prints the delay; the 6 s budget is the Mac's only. + if TestEnvironment.isRunner { + // stderr: the suite's quiet log swallows print(). 90 s only catches a broken pipeline. + FileHandle.standardError.write(Data("RUNNER audio benchmark: warning \(String(format: "%.1f", delay)) s after the 30 s mark (the Mac's budget is 6 s)\n".utf8)) + #expect(delay < 90, "warning came \(delay) s after the 30 s mark: the pipeline is stuck, not slow") + } else { + #expect(delay < 6, "warning came \(delay) s after the 30 s mark") + } coach.resetStreak() logger.close() } diff --git a/Tests/HeavyTests/MasteryE2ETests.swift b/Tests/HeavyTests/MasteryE2ETests.swift index c83ed69..10789fe 100644 --- a/Tests/HeavyTests/MasteryE2ETests.swift +++ b/Tests/HeavyTests/MasteryE2ETests.swift @@ -41,7 +41,7 @@ private final class Recording: HTTPTransport, @unchecked Sendable { } @MainActor -@Suite("Mastery end to end (learner-server harness on ovh)", .tags(.heavy, .mastery), .quietLog, .serialized, +@Suite("Mastery end to end (learner-server's pairing harness)", .tags(.heavy, .mastery), .quietLog, .serialized, .timeLimit(.minutes(3)), .enabled(if: Live.heavy && Live.env["LEARNER_MASTERY_E2E"] == "1", "opt-in: set LEARNER_HEAVY=1 LEARNER_MASTERY_E2E=1")) struct MasteryE2ETests { @@ -75,7 +75,11 @@ struct MasteryE2ETests { // One run of the feed job: the seeded gain, and the live baseline. let feed = MasteryFeed(rpc: rpc, defaults: defaults, jobName: "mastery-e2e-\(UUID().uuidString.prefix(8))", stateDir: local.file("jobs"), sendFeedbackAtOnce: false) - if case let .ok(summary, _) = feed.runOnce() { #expect(summary == "1 new") } else { Issue.record("the feed run did not succeed") } + let outcome = feed.runOnce() + if case let .ok(summary, _) = outcome { #expect(summary == "1 new") } else { + // What the server said (no keys travel in a job outcome), plus the RPCs it made. + Issue.record("the feed run did not succeed: \(outcome); calls: \(["getMasteryNotifications", "getBaselineStatus"].map { "\($0) \(wire.raw($0).prefix(2))" })") + } let gain = try #require(feed.pending.first) #expect(feed.pending.map(\.runId) == [runId], "exactly the seeded gain") #expect(gain.conceptId == conceptId) diff --git a/Tests/HeavyTests/PairingE2ETests.swift b/Tests/HeavyTests/PairingE2ETests.swift index 149b6ba..79beff0 100644 --- a/Tests/HeavyTests/PairingE2ETests.swift +++ b/Tests/HeavyTests/PairingE2ETests.swift @@ -4,7 +4,7 @@ import Testing import TestSupport // Pairing end to end against a real learner-server: learner-server's own harness -// (scripts/pairing-server.ts, on ovh, its TEST database and a throwaway gate-* device that +// (scripts/pairing-server.ts, on ovh, its TEST database and a throwaway device (gate-* or ci-*) that // its teardown revokes), reached through one `ssh -L 3019:127.0.0.1:3019 ovh` session. // The app's real code does everything: the pairing import (health check first), the // endpoints, and a heartbeat carrying the pairing report, after which the server must call @@ -13,27 +13,52 @@ import TestSupport // // Opt-in (LEARNER_HEAVY=1 LEARNER_PAIRING_E2E=1): it starts a server on ovh. The remote // variant also needs `127.0.0.1 learner-pairing.test` in /etc/hosts (the owner's to add). -@Suite("Pairing end to end (learner-server harness on ovh)", .tags(.heavy, .outbox), .quietLog, .serialized, +@Suite("Pairing end to end (learner-server's pairing harness)", .tags(.heavy, .outbox), .quietLog, .serialized, .timeLimit(.minutes(3)), .enabled(if: Live.heavy && Live.env["LEARNER_PAIRING_E2E"] == "1", "opt-in: set LEARNER_HEAVY=1 LEARNER_PAIRING_E2E=1")) struct PairingE2ETests { static let port = 3019 static let remoteHost = "learner-pairing.test" - /// The harness behind its tunnel, stopped through its own teardown (SIGTERM). + /// learner-server's own pairing harness (scripts/pairing-server.ts: its TEST database, a + /// throwaway device (`gate-` or `ci-`) it revokes at teardown), stopped through that teardown + /// (SIGTERM). Two places it runs: + /// local LEARNER_SERVER_DIR names a learner-server checkout on this machine (the + /// GitHub runner: scripts/ci.sh's server phase installs Postgres, bun and the + /// checkout, and exports TEST_DATABASE_URL/DATABASE_URL); + /// ovh otherwise, behind one `ssh -L` tunnel, as on the owner's Mac. final class Harness: @unchecked Sendable { + static let localServer = Live.env["LEARNER_SERVER_DIR"] let dir = "/tmp/learner-pairing-e2e-\(UUID().uuidString.prefix(8))" let ssh = Process() private let out = Pipe() private let lock = NSLock() private var text = "" + var local: Bool { Self.localServer != nil } init(_ topologyArgs: [String]) throws { - let command = "mkdir -p \(dir) && cd /root/learner && exec bun --env-file=/etc/learner/db.env --env-file=/etc/learner/learner.env " - + "scripts/pairing-server.ts --port \(PairingE2ETests.port) --pairing-dir \(dir) " + topologyArgs.joined(separator: " ") - ssh.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") - ssh.arguments = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "-o", "ExitOnForwardFailure=yes", - "-L", "\(PairingE2ETests.port):127.0.0.1:\(PairingE2ETests.port)", "ovh", command] + if let server = Self.localServer { + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + ssh.executableURL = URL(fileURLWithPath: Live.env["LEARNER_BUN"] ?? "/opt/homebrew/bin/bun") + ssh.arguments = ["scripts/pairing-server.ts", "--port", "\(PairingE2ETests.port)", "--pairing-dir", dir] + topologyArgs + ssh.currentDirectoryURL = URL(fileURLWithPath: server) + // The server's throwaway secrets (scripts/ci.sh's server phase) go to the + // harness alone: no test process carries them. + var env = ProcessInfo.processInfo.environment + if let path = Live.env["LEARNER_SERVER_SECRETS"], let text = try? String(contentsOfFile: path, encoding: .utf8) { + for line in text.split(separator: "\n") { + let parts = line.split(separator: "=", maxSplits: 1).map(String.init) + if parts.count == 2 { env[parts[0]] = parts[1] } + } + } + ssh.environment = env + } else { + let command = "mkdir -p \(dir) && cd /root/learner && exec bun --env-file=/etc/learner/db.env --env-file=/etc/learner/learner.env " + + "scripts/pairing-server.ts --port \(PairingE2ETests.port) --pairing-dir \(dir) " + topologyArgs.joined(separator: " ") + ssh.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") + ssh.arguments = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "-o", "ExitOnForwardFailure=yes", + "-L", "\(PairingE2ETests.port):127.0.0.1:\(PairingE2ETests.port)", "ovh", command] + } ssh.standardOutput = out ssh.standardError = out ssh.standardInput = FileHandle.nullDevice @@ -45,7 +70,8 @@ struct PairingE2ETests { } /// The harness's `{"event":"pairing-server",...}` line, once it is ready. - func ready(within seconds: TimeInterval = 120) -> [String: Any]? { + /// 200 s: the harness itself waits up to 180 s for its API to answer. + func ready(within seconds: TimeInterval = 200) -> [String: Any]? { let deadline = Date().addingTimeInterval(seconds) while Date() < deadline, ssh.isRunning { let lines = lock.withLock { text }.split(separator: "\n") @@ -59,8 +85,9 @@ struct PairingE2ETests { var output: String { lock.withLock { text } } - /// The pairing file, read over ssh into memory. + /// The pairing file, read into memory (over ssh when the harness is on ovh). func pairingFile(_ path: String) -> Data? { + if local { return FileManager.default.contents(atPath: path) } let r = ChildProcess.run("/usr/bin/ssh", ["-o", "BatchMode=yes", "ovh", "cat", path], timeout: 30) return r.ok ? Data(r.output.utf8) : nil } @@ -68,6 +95,32 @@ struct PairingE2ETests { /// SIGTERM to the harness (its teardown revokes the device and checks nothing is /// left), then the tunnel ends with it; the remote dir goes. func stop() { + if local { + // The harness itself is the child (no shell): SIGTERM runs its teardown. + if ssh.isRunning { ssh.terminate() } + let deadline = Date().addingTimeInterval(60) + while ssh.isRunning && Date() < deadline { usleep(200_000) } + var killed = false + if ssh.isRunning { + killed = true + kill(ssh.processIdentifier, SIGKILL) + // The harness starts its API detached: a killed harness leaves it on the + // port, and the next test would find "something already answers". + let held = ChildProcess.run("/usr/sbin/lsof", ["-ti", "tcp:\(PairingE2ETests.port)"], timeout: 10) + for pid in held.output.split(separator: "\n").compactMap({ Int32($0) }) { kill(pid, SIGKILL) } + } + try? FileManager.default.removeItem(atPath: dir) + // Its teardown revokes the device and checks nothing is left; a failure there + // would leave a live key behind, so it fails the test. + usleep(300_000) + let said = output + // It exits 130 after its signal-driven cleanup (pairing-server.ts); a failed revoke + // prints revoke-failed. + if killed || said.contains("revoke-failed") { + Issue.record("the harness's teardown did not finish cleanly (killed: \(killed), exit \(ssh.isRunning ? -1 : ssh.terminationStatus)): \(said.suffix(600))") + } + return + } // Bracketed, so the pattern does not match the remote shell running this very // command (pkill would kill that shell first). One TERM; teardown takes ~5 s // (revoke, check the old key gets 401, check the database, stop nginx and the API), @@ -133,6 +186,54 @@ struct PairingE2ETests { #expect(other.status == 403) } + /// The installed app itself, paired the one-paste way: the harness's payload as a pairing + /// code, piped to the installed binary's `tool pair` (as CI and scripts pair), the app + /// restarted onto it, and the server then sees the app's OWN heartbeat with its pairing + /// report (pairing state ok). Runner only: on the owner's Mac this would re-pair the + /// owner's real app with a throwaway server. + @Test(.enabled(if: TestEnvironment.isRunner && Live.env["GITHUB_ACTIONS"] == "true", "GitHub runner only: it re-pairs the installed app"), + .enabled(if: Harness.localServer != nil, "needs the local harness (LEARNER_SERVER_DIR)"), + .enabled(if: FileManager.default.isExecutableFile(atPath: PairingE2ETests.installedBinary), "no installed app")) + func theInstalledAppPairsFromACodeAndTheServerSeesItsHeartbeat() throws { + let harness = try Harness(["--topology", "same-machine"]) + defer { harness.stop() } + let ready = try #require(harness.ready(), "the harness did not start: \(harness.output.suffix(1500))") + let pairingPath = try #require(ready["pairingFile"] as? String) + let data = try #require(harness.pairingFile(pairingPath)) + guard case .success(let p) = Pairing.parse(data) else { Issue.record("the harness's payload does not parse"); return } + + // The app's log from here on (by byte offset, before `tool pair` writes to it). + let logStart = ((try? FileManager.default.attributesOfItem(atPath: AppLog.path))?[.size] as? NSNumber)?.intValue ?? 0 + // `tool pair`, the code on stdin, by the installed binary (its own defaults domain and Keychain item). + let paired = ChildProcess.run(Self.installedBinary, ["tool", "pair"], timeout: 60, stderr: true, input: Data((Pairing.code(for: p) + "\n").utf8)) + try #require(paired.status == 0, "tool pair: \(paired.output)") + #expect(paired.output.contains("paired with \(p.apiUrl) as \(p.clientId)")) + // A Bool first: a failed #expect prints its operands, and this log is public. + let keyPrinted = paired.output.contains(p.apiKey) + #expect(!keyPrinted, "the key is never printed") + + // The app restarts onto the pairing; its launch heartbeat carries the pairing report. + _ = ChildProcess.run("/bin/launchctl", ["kickstart", "-k", "gui/\(getuid())/com.benpollack.learner-desktop"], timeout: 15) + let rpc = LearnerRPC(baseURL: p.apiUrl, clientId: p.clientId, key: { _ in p.apiKey }) + let link = PairingLink(path: TempDir("pairing-installed").file("endpoints.json")) + var state = "?" + let deadline = Date().addingTimeInterval(90) + while Date() < deadline { + if link.refresh(rpc: rpc).kind == .ok, let held = link.held { + state = held.pairingState + if state == "ok" { break } + } + sleep(3) + } + let whole = FileManager.default.contents(atPath: AppLog.path) ?? Data() + let log = whole.count >= logStart ? String(decoding: whole.dropFirst(logStart), as: UTF8.self) : String(decoding: whole, as: UTF8.self) + #expect(state == "ok", "the server never saw the installed app's heartbeat (pairing state \(state)); app log since the restart:\n\(log.suffix(2000))") + let keyLogged = log.contains(p.apiKey) + #expect(!keyLogged, "the key is never logged") + } + + static let installedBinary = NSHomeDirectory() + "/Applications/Learner Desktop.app/Contents/MacOS/learner-desktop" + @Test func pairsWithAServerOnTheSameMachine() throws { try pairs(["--topology", "same-machine"], expectRemote: false) } diff --git a/config/learner-server.ref b/config/learner-server.ref new file mode 100644 index 0000000..7605356 --- /dev/null +++ b/config/learner-server.ref @@ -0,0 +1 @@ +84fb766b51611fd54d0b3d8c22d0372cc18109d9 diff --git a/scripts/ci.sh b/scripts/ci.sh index c40f3ae..fe8dd89 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -6,6 +6,8 @@ # virtual-mic two BlackHole loopback devices; "BlackHole 2ch" becomes the default input # grant microphone + speech-recognition grants for the app's bundle id (TCC.db) # fixtures the synthetic sample (Tests/Fixtures/sample) as ~/ai-vault-data + its ledger +# screenpipe screenpipe's engine (the pinned version, the owner's audio settings) on :3030 +# server learner-server's pairing harness ready to run (Postgres 17, its test database, web build) # speech Siri and Dictation on, which Apple's speech recognizer needs # install release build, installed and started by scripts/build-app.sh # mic-e2e speech played into the virtual mic is heard by the installed app; the @@ -44,6 +46,12 @@ APP_LOG="$HOME/.ai-aggregator/logs/menubar.log" BUNDLE_ID="com.benpollack.ai-aggregator-menubar" MIC_A="BlackHole 2ch" MIC_B="BlackHole 16ch" +# The default output: its own device, so system-audio capture never hears what is played +# into the two microphones. +SPEAKER="BlackHole 64ch" + +# What the server phase exported for later phases (each workflow step is its own shell). +if [ -f "$OUT/server.env" ]; then set -a; . "$OUT/server.env"; set +a; fi RESULTS="$OUT/results.tsv" # PASS|FAIL phase seconds note @@ -92,14 +100,20 @@ virtual_mic() { command -v SwitchAudioSource >/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install switchaudio-osx command -v sox >/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install sox # diagnose_input # BlackHole is a CoreAudio driver (a HAL plug-in): coreaudiod loads it on restart. - HOMEBREW_NO_AUTO_UPDATE=1 brew install --cask blackhole-2ch blackhole-16ch + HOMEBREW_NO_AUTO_UPDATE=1 brew install --cask blackhole-2ch blackhole-16ch blackhole-64ch sudo killall coreaudiod || true local until=$((SECONDS + 30)) - until SwitchAudioSource -a -t input | grep -qx "$MIC_B" && SwitchAudioSource -a -t input | grep -qx "$MIC_A"; do + until SwitchAudioSource -a -t input | grep -qx "$MIC_B" && SwitchAudioSource -a -t input | grep -qx "$MIC_A" \ + && SwitchAudioSource -a -t output | grep -qx "$SPEAKER"; do [ $SECONDS -lt $until ] || { echo "BlackHole devices did not appear:"; SwitchAudioSource -a -t input; return 1; } sleep 1 done SwitchAudioSource -t input -s "$MIC_A" + # A real default output, so screenpipe's system-audio capture has something to tap (with + # none, its device check times out and /health reports degraded). Not a microphone: what + # the run plays into the mics must not also reach system audio as "someone else". + SwitchAudioSource -t output -s "$SPEAKER" + echo "default output: $(SwitchAudioSource -c -t output)" echo "inputs:"; SwitchAudioSource -a -t input | sed 's/^/ /' echo "default input: $(SwitchAudioSource -c -t input)" [ "$(SwitchAudioSource -c -t input)" = "$MIC_A" ] @@ -132,6 +146,124 @@ fixtures() { echo "ledger: $(sqlite3 "$HOME/.ai-aggregator/sync-ledger.sqlite" "select sync_status || ' ' || count(*) from archive_ledger group by sync_status;" | paste -sd, -)" } +# screenpipe's open-source engine, the version config/screenpipe-settings.json pins, with +# the owner's audio settings, recording BlackHole 2ch: the heavy lane's capture suites then +# run against a real screenpipe. The CLI, not the app: the app records only when signed in +# to a screenpipe account (checked in its source at app-v2.7.145). npm never changes a +# published version, and the tarball must match its pinned integrity hash. +SCREENPIPE_CLI_VERSION=0.4.58 +SCREENPIPE_CLI_SHA512="EhpKXwvgNmIMNNBV6blOFlJqNdMFvAnn+fN9F2/1gOEM/lmaXtDBNYYFr1HoPlIjI8FTO0sBZognNcsNQuMsgg==" +screenpipe() { + set -e + local pinned; pinned="$(python3 -c "import json; print(json.load(open('config/screenpipe-settings.json'))['_screenpipe_engine_version'])")" + [ "$pinned" = "$SCREENPIPE_CLI_VERSION" ] || { echo "config pins screenpipe engine $pinned but ci.sh installs $SCREENPIPE_CLI_VERSION: update SCREENPIPE_CLI_VERSION and its SHA512"; return 1; } + local cache="$HOME/.cache/learner-screenpipe" dir="$HOME/.local/screenpipe-cli" + mkdir -p "$cache" "$dir" + local tgz="$cache/cli-darwin-arm64-$SCREENPIPE_CLI_VERSION.tgz" + [ -f "$tgz" ] || curl -fsSL --retry 3 -o "$tgz" "https://registry.npmjs.org/@screenpipe/cli-darwin-arm64/-/cli-darwin-arm64-$SCREENPIPE_CLI_VERSION.tgz" + [ "$(openssl dgst -sha512 -binary "$tgz" | base64)" = "$SCREENPIPE_CLI_SHA512" ] || { echo "screenpipe CLI tarball does not match its pinned SHA-512"; rm -f "$tgz"; return 1; } + tar -xzf "$tgz" -C "$dir" + local bin; bin="$(find "$dir/package" -type f -name screenpipe -perm +111 | head -1)" + [ -x "$bin" ] || { echo "no screenpipe binary in the tarball:"; find "$dir/package" -maxdepth 3 | head -20; return 1; } + echo "screenpipe: $bin ($("$bin" --version 2>/dev/null || echo "version unknown"))" + # Screen and system-audio capture (system TCC.db) and the microphone (user TCC.db), for + # the binary by path, as the runner image does for its own tools. + local now; now=$(date +%s) + for service in kTCCServiceScreenCapture kTCCServiceAudioCapture; do + sudo sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" \ + "INSERT OR REPLACE INTO access VALUES('$service','$bin',1,2,3,1,NULL,NULL,NULL,'UNUSED',NULL,0,$now,NULL,NULL,'UNUSED',$now);" + done + sqlite3 "$HOME/Library/Application Support/com.apple.TCC/TCC.db" \ + "INSERT OR REPLACE INTO access VALUES('kTCCServiceMicrophone','$bin',1,2,3,1,NULL,NULL,NULL,'UNUSED',NULL,0,$now,NULL,NULL,'UNUSED',$now);" + sudo launchctl kickstart -k system/com.apple.tccd || true + echo "audio devices:"; "$bin" audio list 2>&1 | sed 's/^/ /' | head -20 + local mic; mic="$("$bin" audio list 2>/dev/null | grep -o "${MIC_A} (input)" | head -1)" + [ -n "$mic" ] || mic="${MIC_A} (input)" + # The owner's settings: realtime transcription, 5 s chunks, whisper-tiny-quantized, + # system audio through Core Audio, no PII removal, no API auth (the app's apiAuth: false; + # the engine's own default is on, and every query the app makes then gets 403). + SCREENPIPE_NO_REMINDERS=1 SCREENPIPE_NO_UPDATE_CHECK=1 nohup "$bin" record --port 3030 \ + -a whisper-tiny-quantized -d 5 --transcription-mode realtime \ + -i "$mic" -i "System Audio (output)" --experimental-coreaudio-system-audio \ + --use-pii-removal false --disable-telemetry --api-auth false > "$OUT/screenpipe-engine.log" 2>&1 & + echo $! > "$OUT/screenpipe.pid" + local until=$((SECONDS + 240)) + until curl -sf -m 3 http://localhost:3030/health >/dev/null; do + if ! kill -0 "$(cat "$OUT/screenpipe.pid")" 2>/dev/null; then echo "screenpipe exited:"; tail -40 "$OUT/screenpipe-engine.log"; return 1; fi + [ $SECONDS -lt $until ] || { echo "screenpipe did not answer /health in 240 s:"; tail -40 "$OUT/screenpipe-engine.log"; return 1; } + sleep 2 + done + echo "health: $(curl -s -m 3 http://localhost:3030/health | head -c 400)" + # One transcription row, so the live-SQL suites have something to read: spoken once + # screenpipe records the mic (it starts that a while after /health answers), then seen. + # It starts the mic after loading its model: 4+ minutes on a busy runner (run 14). + local until=$((SECONDS + 420)) + until grep -q "starting continuous recording for ${MIC_A}" "$OUT/screenpipe-engine.log"; do + [ $SECONDS -lt $until ] || { echo "::warning title=screenpipe::not recording $MIC_A after 7 min; the capture suites will say what is missing"; return 0; } + sleep 2 + done + local rows=0 n + for attempt in 1 2 3; do + say -a "$MIC_A" "This is the runner checking that screenpipe hears the virtual microphone." + for _ in $(seq 1 20); do + n="$(curl -s -m 5 -X POST http://localhost:3030/raw_sql -H 'content-type: application/json' \ + -d '{"query":"SELECT count(*) AS n FROM audio_transcriptions"}' | python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["n"])' 2>/dev/null || echo 0)" + [ "${n:-0}" -gt 0 ] && { rows=$n; break 2; } + sleep 3 + done + done + echo "audio_transcriptions rows: $rows" + # Loud, not fatal: the runner's virtual loopback can go dead (runs 7, 11, 13), and the heavy + # lane's raw_sql suite fails by itself if screenpipe has no rows. + [ "$rows" -gt 0 ] || echo "::warning title=screenpipe::no transcription row from the spoken line (the virtual loopback may be dead); the raw_sql suite will say if rows are missing" +} + +# learner-server's own pairing harness on the runner, for the heavy lane's pairing and +# mastery end-to-end suites: the checkout at config/learner-server.ref (the workflow checks +# it out into ./learner-server; learner-server is public), Postgres 17 with its migrated +# TEST database, and its web build. Exported for the lanes through $OUT/server.env. +server() { + set -e + local dir="$PWD/learner-server" + [ -d "$dir/scripts" ] || { echo "no learner-server checkout in $dir"; return 1; } + echo "learner-server at $(git -C "$dir" rev-parse --short HEAD) (pinned: $(cut -c1-7 config/learner-server.ref))" + command -v bun >/dev/null || { echo "bun is not on PATH"; return 1; } + # nginx: the remote topology runs the SHIPPED deploy/nginx config in front of the API. + # shellcheck: the light lane's script check. The hosts entry: remote pairing advertises a + # non-loopback name that resolves here (PairingE2E's remote case). + HOMEBREW_NO_AUTO_UPDATE=1 brew install postgresql@17 nginx shellcheck >/dev/null + grep -q "learner-pairing.test" /etc/hosts || echo "127.0.0.1 learner-pairing.test" | sudo tee -a /etc/hosts >/dev/null + local pg; pg="$(brew --prefix postgresql@17)/bin" + rm -rf "$HOME/learner-pg" + "$pg/initdb" -D "$HOME/learner-pg" -U learner --auth=trust >/dev/null + "$pg/pg_ctl" -D "$HOME/learner-pg" -l "$OUT/postgres.log" -o "-p 5432 -k /tmp" -w start + "$pg/createdb" -h 127.0.0.1 -U learner learner_test + "$pg/createdb" -h 127.0.0.1 -U learner learner_dev + { + echo "TEST_DATABASE_URL=postgres://learner@127.0.0.1:5432/learner_test" + echo "DATABASE_URL=postgres://learner@127.0.0.1:5432/learner_dev" + echo "LEARNER_SERVER_DIR=$dir" + echo "LEARNER_BUN=$(command -v bun)" + echo "LEARNER_PAIRING_E2E=1" + echo "LEARNER_MASTERY_E2E=1" + } > "$OUT/server.env" + # Throwaway secrets the server needs (on ovh they come from /etc/learner/learner.env): made + # here, kept out of ci-out (its logs are a public artifact), gone with the runner. + umask 077 + { + echo "LEARNER_AUTH_SECRET=$(openssl rand -hex 32)" + echo "LEARNER_BASE_URL=http://127.0.0.1:3019" + } > "$HOME/.learner-ci-secrets.env" + umask 022 + set -a; . "$OUT/server.env"; set +a + # Each server start runs pikku's code generation first: done once here, so a start in the + # heavy lane fits the harness's 180 s wait on 3 busy cores. + ( cd "$dir" && bun install --frozen-lockfile && bun packages/server/src/db/migrate.ts --test && bun run build:web \ + && bun run prepare:runtime ) 2>&1 | tail -15 + [ -f "$dir/apps/web/dist/index.html" ] || { echo "learner-server's web build is missing"; return 1; } + echo "ready: Postgres 17 (learner_test migrated), web built; the heavy lane runs the pairing harness locally" +} + speech() { # Apple's speech recognizer refuses with "Siri and Dictation are disabled" until one of # them is on; the owner's Mac has Siri on ("Assistant Enabled"). Both, for the runner. @@ -139,6 +271,28 @@ speech() { defaults write com.apple.assistant.support "Dictation Enabled" -bool true killall assistantd corespeechd 2>/dev/null || true # they reread the settings on relaunch defaults read com.apple.assistant.support | grep -E '"(Assistant|Dictation) Enabled"' | sed 's/^ */ /' + ensure_say +} + +# Many checks speak with `say` (the mic end to end, the speech model, screenpipe's rows, +# the audio benchmark), and the runner's synthesizer can break mid-run: it passed this +# check, then made silence later in runs 8 and 12 (85 samples for a passage). So before +# each phase that speaks: check it, restart the synthesizer if it is silent, and fail +# plainly if it stays broken. +ensure_say() { + local wav="$OUT/say-check.wav" n=0 attempt + # Up to a minute: it has come back by itself within a phase (run 14). + for attempt in 1 2 3 4 5 6; do + rm -f "$wav" + say -o "$wav" --file-format=WAVE --data-format=LEI16@16000 "The quick brown fox checks the speech synthesizer." 2>&1 | tail -2 + n=$(( ( $(stat -f %z "$wav" 2>/dev/null || echo 0) - 44 ) / 2 )) + echo "say check, attempt $attempt: $n samples" + [ "$n" -gt 16000 ] && break + killall speechsynthesisd SpeechSynthesisServer com.apple.speech.speechsynthesisd 2>/dev/null || true + sleep 10 + done + rm -f "$wav" + [ "$n" -gt 16000 ] || { echo "the runner's speech synthesizer is broken (say makes silence); every check that speaks would fail"; return 1; } } install() { @@ -184,15 +338,19 @@ diagnose_input() { speak_into() { say -a "$1" "I would like to explain the plan for our next project in a little more detail. The first step is to understand what people need from the product and what gets in their way today."; } mic_e2e() { + ensure_say || return 1 local from ok=0 from=1 echo "1. the app listens on the default input ($MIC_A)" # The app names the input by its format; BlackHole 2ch and 16ch differ in channel count. wait_log "listening on .* 2-channel input" 90 "$from" || ok=1 from=$(log_lines) - echo "2. speech played into $MIC_A is heard" + echo "2. speech played into $MIC_A is heard, and the coach closes that turn" speak_into "$MIC_A" wait_log "\[Coach\] heard " 30 "$from" || ok=1 + # The coach closes the turn. (The voice is macOS's, not the owner's, so it ends as + # "someone else spoke"; run 10. What matters is that the heard turn is processed.) + wait_log "turn [0-9]+ ended " 60 "$from" || ok=1 from=$(log_lines) echo "3. the default input switches to $MIC_B; the app reopens the microphone on it" SwitchAudioSource -t input -s "$MIC_B" @@ -203,11 +361,36 @@ mic_e2e() { sleep 15 # the previous turn ends after 14 s of silence, so this one is a new turn speak_into "$MIC_B" wait_log "\[Coach\] heard " 30 "$from" || { ok=1; diagnose_input "$MIC_B"; } + wait_log "turn [0-9]+ ended " 60 "$from" || ok=1 SwitchAudioSource -t input -s "$MIC_A" >/dev/null return $ok } -lane() { scripts/test.sh "$1"; } +# What the virtual mic carries right now (diagnosis for screenpipe's audio health). +audio_check() { + echo "default input: $(SwitchAudioSource -c -t input 2>/dev/null), output: $(SwitchAudioSource -c -t output 2>/dev/null)" + echo "level on $MIC_A over 2 s: $(sox -q -t coreaudio "$MIC_A" -n trim 0 2 stat 2>&1 | awk -F: '/RMS +amplitude/{gsub(/ /,"",$2); print "RMS " $2}')" + echo "screenpipe audio: $(curl -s -m 3 http://localhost:3030/health | python3 -c 'import json,sys; h=json.load(sys.stdin); print(h.get("status"), h.get("audio_status"))' 2>/dev/null)" +} + +# The server phase's exports, read again here (in `ci.sh all` it ran in a subshell). Its +# secrets are not: only the harness reads them (LEARNER_SERVER_SECRETS), so no test +# process carries them. +lane() { + if [ "$1" = heavy ]; then + audio_check + # The microphone grant again, unbound: each build on the runner is ad-hoc signed (its own + # code hash), and the heavy lane's bundle self-test is another build (run 10 asked it + # for permission). Shown as it stands, then reset. + local db="$HOME/Library/Application Support/com.apple.TCC/TCC.db" + echo "microphone grant before the heavy lane: $(sqlite3 "$db" "SELECT auth_value || ' csreq=' || (CASE WHEN csreq IS NULL THEN 'none' ELSE 'bound' END) FROM access WHERE service='kTCCServiceMicrophone' AND client='$BUNDLE_ID';")" + grant >/dev/null + fi + if [ -f "$OUT/server.env" ]; then set -a; . "$OUT/server.env"; set +a; fi + export LEARNER_SERVER_SECRETS="$HOME/.learner-ci-secrets.env" + if [ "$1" != light ]; then ensure_say || return 1; fi + scripts/test.sh "$1" +} # The automatic updater installs and loads (on the runner it finds no GitHub token and # waits); uninstall must then remove it with everything else. @@ -225,6 +408,11 @@ report() { local failed=0 skips nskips [ -f "$RESULTS" ] && grep -q '^FAIL' "$RESULTS" && failed=1 [ -f "$RESULTS" ] || failed=1 + # A phase that never reported (its step skipped or killed) is a failure, not a gap. + local p missing="" + for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium heavy updater uninstall; do + grep -q " $p " "$RESULTS" 2>/dev/null || { missing="$missing $p"; failed=1; } + done # Swift Testing names every skip and cancellation: `➜ Test x() skipped: "why"`. skips="$(cat "$OUT"/light.log "$OUT"/medium.log "$OUT"/heavy.log 2>/dev/null \ | grep -E '^➜ (Test|Suite) .* (skipped|was cancelled)' | sed -E 's/^➜ //' | sort -u)" @@ -234,12 +422,19 @@ report() { echo echo "Test environment: **runner** (a clean Mac; no owner accounts or live data)." echo + [ -n "$missing" ] && { echo "❌ phases that never reported:$missing"; echo; } echo "| | phase | time | note |" echo "|---|---|---|---|" [ -f "$RESULTS" ] && while IFS=$'\t' read -r verdict name took note; do echo "| $([ "$verdict" = PASS ] && echo ✅ || echo ❌) $verdict | $name | ${took}s | $note |" done < "$RESULTS" echo + # Known issues: a test marked with withKnownIssue (and why), never counted as a pass. + local known + known="$(cat "$OUT"/light.log "$OUT"/medium.log "$OUT"/heavy.log 2>/dev/null | grep -E 'recorded a known issue|^.? ?Test .* with [0-9]+ known issue' | sed -E 's/^[^A-Za-z]*//' | sort -u)" + if [ -n "$known" ]; then + echo "### ⚠️ Known issues (expected failures, not passes)"; echo; echo '```'; echo "$known"; echo '```'; echo + fi echo "### $nskips test(s) skipped, not passed" if [ "$nskips" -gt 0 ]; then echo; echo '```'; echo "$skips"; echo '```'; fi } > "$OUT/summary.md" @@ -263,6 +458,8 @@ run() { virtual-mic) phase virtual-mic virtual_mic ;; grant) phase grant grant ;; fixtures) phase fixtures fixtures ;; + screenpipe) phase screenpipe screenpipe ;; + server) phase server server ;; speech) phase speech speech ;; install) phase install install ;; mic-e2e) phase mic-e2e mic_e2e ;; @@ -272,9 +469,9 @@ run() { report) report ;; all) rm -f "$RESULTS" - for p in fetch virtual-mic grant fixtures speech install mic-e2e light medium heavy updater uninstall; do run "$p" || true; done + for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium heavy updater uninstall; do run "$p" || true; done report ;; - *) echo "usage: scripts/ci.sh fetch|virtual-mic|grant|fixtures|speech|install|mic-e2e|light|medium|heavy|updater|uninstall|report|all" >&2; return 2 ;; + *) echo "usage: scripts/ci.sh fetch|virtual-mic|grant|fixtures|screenpipe|server|speech|install|mic-e2e|light|medium|heavy|updater|uninstall|report|all" >&2; return 2 ;; esac } diff --git a/scripts/uninstall-app.sh b/scripts/uninstall-app.sh index 42ae79e..6c131d2 100755 --- a/scripts/uninstall-app.sh +++ b/scripts/uninstall-app.sh @@ -23,6 +23,11 @@ UPDATER_DIR="${HOME}/Library/Application Support/Learner Desktop/updater" echo "Stopping the automatic updater..." launchctl bootout "${DOMAIN}/${UPDATER_LABEL}" 2>/dev/null || true +# bootout returns before the job has left the domain (a run in progress finishes first). +for _ in $(seq 1 40); do + launchctl print "${DOMAIN}/${UPDATER_LABEL}" >/dev/null 2>&1 || break + sleep 0.5 +done rm -f "${UPDATER_AGENT}" rm -rf "${UPDATER_DIR}"