From d2d0d37984f9d9c4b400a86f93d025d8c9eb707b Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 09:59:59 -0700 Subject: [PATCH 1/7] Add pure sign in validation, error messages, device facts and install ping throttle with tests and a CI runner --- .github/workflows/build.yml | 3 + holmes/holmes/Core/AuthSupport.swift | 218 ++++++++++++++++++++++ holmes/tests/AuthValidationTests.swift | 121 ++++++++++++ holmes/tests/run-auth-validation-tests.sh | 11 ++ 4 files changed, 353 insertions(+) create mode 100644 holmes/holmes/Core/AuthSupport.swift create mode 100644 holmes/tests/AuthValidationTests.swift create mode 100755 holmes/tests/run-auth-validation-tests.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 065ab7d..a2848fd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -81,6 +81,9 @@ jobs: holmes/tests/run-text-entry-tests.sh holmes/tests/run-model-json-tests.sh + - name: Test sign in validation and install tracking + run: holmes/tests/run-auth-validation-tests.sh + - name: Test browser bridge reliability run: | holmes/tests/run-browser-bridge-extension-tests.sh diff --git a/holmes/holmes/Core/AuthSupport.swift b/holmes/holmes/Core/AuthSupport.swift new file mode 100644 index 0000000..f890060 --- /dev/null +++ b/holmes/holmes/Core/AuthSupport.swift @@ -0,0 +1,218 @@ +import Foundation + +// Pure helpers behind sign in and install tracking. Nothing here imports the +// Appwrite SDK, so holmes/tests/run-auth-validation-tests.sh can compile this +// file on its own. + +// MARK: - Input validation + +enum AuthMode: String, CaseIterable { + case signIn + case createAccount +} + +enum AuthValidation { + static let minimumPasswordLength = 8 + + static func isValidEmail(_ raw: String) -> Bool { + let email = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard email.count <= 254, !email.contains(" ") else { return false } + let parts = email.split(separator: "@", omittingEmptySubsequences: false) + guard parts.count == 2 else { return false } + let local = parts[0], domain = parts[1] + guard !local.isEmpty, local.count <= 64 else { return false } + let labels = domain.split(separator: ".", omittingEmptySubsequences: false) + guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty }) else { return false } + guard let tld = labels.last, tld.count >= 2, tld.allSatisfy({ $0.isLetter }) else { return false } + return true + } + + /// The first problem with the form, phrased for the user, or nil when the + /// input is fine to send. + static func problem(mode: AuthMode, name: String, email: String, password: String) -> String? { + if mode == .createAccount, name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return "Enter your name." + } + let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedEmail.isEmpty { return "Enter your email address." } + if !isValidEmail(trimmedEmail) { return "That email address doesn\u{2019}t look right." } + if password.isEmpty { return "Enter your password." } + if mode == .createAccount, password.count < minimumPasswordLength { + return "Use a password of at least \(minimumPasswordLength) characters." + } + return nil + } +} + +// MARK: - Error messages + +enum AuthErrorMessages { + static let offline = "Holmes can\u{2019}t reach the sign in server. Check your internet connection and try again." + static let generic = "Something went wrong signing you in. Please try again." + + /// Maps an Appwrite error code and type to a user facing message. `code` + /// is nil or 0 when the request never got an HTTP response. + static func message(code: Int?, type: String?, mode: AuthMode) -> String { + let type = type ?? "" + switch type { + case "user_invalid_credentials", "user_password_mismatch": + return "That email and password don\u{2019}t match. Check them and try again." + case "user_already_exists", "user_email_already_exists": + return "An account with this email already exists. Sign in instead." + case "password_recently_used", "password_personal_data": + return "Choose a different password." + case "user_blocked": + return "This account has been disabled." + case "general_rate_limit_exceeded": + return "Too many attempts. Wait a minute, then try again." + case "user_session_already_exists": + return "You\u{2019}re already signed in." + default: + break + } + switch code ?? 0 { + case 0: + return offline + case 401: + return mode == .signIn + ? "That email and password don\u{2019}t match. Check them and try again." + : generic + case 409: + return "An account with this email already exists. Sign in instead." + case 400: + if type == "general_argument_invalid" || type.isEmpty { + return mode == .createAccount + ? "Check your details. Passwords need at least \(AuthValidation.minimumPasswordLength) characters." + : "Check your email and password, then try again." + } + return generic + case 429: + return "Too many attempts. Wait a minute, then try again." + case 500...599: + return "The sign in server is having trouble. Try again in a moment." + default: + return generic + } + } +} + +// MARK: - Device facts + +struct DeviceFacts: Equatable { + var holmesVersion: String + var macosVersion: String + var macModel: String + var region: String + var locale: String + + static func formatOSVersion(major: Int, minor: Int, patch: Int) -> String { + "\(major).\(minor).\(patch)" + } + + /// sysctl returns a NUL terminated C string; keep what precedes the first NUL. + static func modelString(fromSysctlBytes bytes: [CChar]) -> String { + let prefix = bytes.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } + let value = String(decoding: prefix, as: UTF8.self).trimmingCharacters(in: .whitespaces) + return value.isEmpty ? "unknown" : value + } + + static func normalized(_ value: String?, fallback: String = "unknown") -> String { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? fallback : trimmed + } + + /// The JSON body for the "track" function. Email is never included; the + /// function reads the verified user server side. + func trackBody(event: String, installID: String) -> String { + let payload: [String: String] = [ + "event": event, + "install_id": installID, + "holmes_version": holmesVersion, + "macos_version": macosVersion, + "mac_model": macModel, + "region": region, + "locale": locale, + ] + guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]), + let json = String(data: data, encoding: .utf8) else { return "{}" } + return json + } +} + +// MARK: - Install ping throttle + +protocol CloudKeyValueStore: AnyObject { + func string(forKey key: String) -> String? + func date(forKey key: String) -> Date? + func set(_ value: Any?, forKey key: String) +} + +final class UserDefaultsCloudStore: CloudKeyValueStore { + private let defaults: UserDefaults + init(_ defaults: UserDefaults = .standard) { self.defaults = defaults } + func string(forKey key: String) -> String? { defaults.string(forKey: key) } + func date(forKey key: String) -> Date? { defaults.object(forKey: key) as? Date } + func set(_ value: Any?, forKey key: String) { defaults.set(value, forKey: key) } +} + +/// Decides when the install ping is due and records success. The first ping +/// goes out as soon as possible; after that at most once every 24 hours. A +/// failed send records nothing, so the next launch simply tries again. +final class InstallPingThrottle { + static let installIDKey = "HolmesCloud.installID" + static let lastSentKey = "HolmesCloud.installPingLastSent" + static let interval: TimeInterval = 24 * 60 * 60 + + private let store: CloudKeyValueStore + private let now: () -> Date + private let lock = NSLock() + private var inFlight = false + + init(store: CloudKeyValueStore, now: @escaping () -> Date = Date.init) { + self.store = store + self.now = now + } + + /// A random UUID created the first time it is asked for, then reused. + var installID: String { + lock.lock(); defer { lock.unlock() } + if let existing = store.string(forKey: Self.installIDKey), UUID(uuidString: existing) != nil { + return existing + } + let fresh = UUID().uuidString + store.set(fresh, forKey: Self.installIDKey) + return fresh + } + + var isDue: Bool { + guard let last = store.date(forKey: Self.lastSentKey) else { return true } + let elapsed = now().timeIntervalSince(last) + // A clock moved backwards counts as due, so a bad date can't mute pings forever. + return elapsed >= Self.interval || elapsed < 0 + } + + /// Runs `send` when due and not already running. Returns true only when a + /// send happened and succeeded. Never throws. + @discardableResult + func runIfDue(_ send: () async -> Bool) async -> Bool { + guard claim() else { return false } + let ok = await send() + release(succeeded: ok) + return ok + } + + private func claim() -> Bool { + lock.withLock { + guard !inFlight, isDue else { return false } + inFlight = true + return true + } + } + + private func release(succeeded: Bool) { + lock.withLock { + if succeeded { store.set(now(), forKey: Self.lastSentKey) } + inFlight = false + } + } +} diff --git a/holmes/tests/AuthValidationTests.swift b/holmes/tests/AuthValidationTests.swift new file mode 100644 index 0000000..124da88 --- /dev/null +++ b/holmes/tests/AuthValidationTests.swift @@ -0,0 +1,121 @@ +import Foundation + +final class MemoryCloudStore: CloudKeyValueStore { + var values: [String: Any] = [:] + func string(forKey key: String) -> String? { values[key] as? String } + func date(forKey key: String) -> Date? { values[key] as? Date } + func set(_ value: Any?, forKey key: String) { values[key] = value } +} + +final class TestClock { + var now = Date(timeIntervalSince1970: 1_800_000_000) + func advance(hours: Double) { now = now.addingTimeInterval(hours * 3600) } +} + +@main +struct AuthValidationTests { + static func main() async { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + + // Email format. + for good in ["a@b.co", "holmes.smoketest+1@example.com", " person@mail.example.org ", "x_y@sub.domain.io"] { + expect(AuthValidation.isValidEmail(good), "Valid email rejected: \(good)") + } + for bad in ["", "plain", "@example.com", "a@", "a@b", "a@b.", "a@.com", "a b@c.com", "a@@b.com", "a@b.c", "a@b.c0m"] { + expect(!AuthValidation.isValidEmail(bad), "Invalid email accepted: \(bad)") + } + + // Form problems, in order. + expect(AuthValidation.problem(mode: .createAccount, name: " ", email: "a@b.co", password: "12345678") == "Enter your name.", + "Create account needs a name") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "a@b.co", password: "x") == nil, + "Sign in needs no name and no minimum length") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "", password: "x") == "Enter your email address.", + "Empty email is reported") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "nope", password: "x")?.contains("look right") == true, + "Malformed email is reported") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "a@b.co", password: "") == "Enter your password.", + "Empty password is reported") + expect(AuthValidation.problem(mode: .createAccount, name: "Ann", email: "a@b.co", password: "1234567")?.contains("at least 8") == true, + "Seven character password is too short") + expect(AuthValidation.problem(mode: .createAccount, name: "Ann", email: "a@b.co", password: "12345678") == nil, + "Eight character password is fine") + + // Error mapping. + let invalid = AuthErrorMessages.message(code: 401, type: "user_invalid_credentials", mode: .signIn) + expect(invalid.contains("don\u{2019}t match"), "Invalid credentials message") + let exists = AuthErrorMessages.message(code: 409, type: "user_already_exists", mode: .createAccount) + expect(exists.contains("already exists") && exists.contains("Sign in"), "Existing user is told to sign in") + expect(AuthErrorMessages.message(code: 409, type: nil, mode: .createAccount) == exists, "Bare 409 means existing user") + expect(AuthErrorMessages.message(code: 400, type: "general_argument_invalid", mode: .createAccount).contains("at least 8"), + "Invalid argument on sign up mentions password length") + expect(AuthErrorMessages.message(code: nil, type: nil, mode: .signIn) == AuthErrorMessages.offline, "No response means offline") + expect(AuthErrorMessages.message(code: 0, type: "", mode: .createAccount) == AuthErrorMessages.offline, "Code 0 means offline") + expect(AuthErrorMessages.message(code: 429, type: "general_rate_limit_exceeded", mode: .signIn).contains("Too many attempts"), + "Rate limit message") + expect(AuthErrorMessages.message(code: 429, type: nil, mode: .signIn).contains("Too many attempts"), "Bare 429 is rate limit") + expect(AuthErrorMessages.message(code: 401, type: "", mode: .signIn).contains("don\u{2019}t match"), "Bare 401 on sign in") + expect(AuthErrorMessages.message(code: 503, type: "general_server_error", mode: .signIn).contains("having trouble"), + "Server errors are named") + expect(AuthErrorMessages.message(code: 418, type: "something_new", mode: .signIn) == AuthErrorMessages.generic, + "Unknown errors fall back to generic") + + // Device facts formatting. + expect(DeviceFacts.formatOSVersion(major: 15, minor: 3, patch: 1) == "15.3.1", "OS version is major.minor.patch") + expect(DeviceFacts.formatOSVersion(major: 26, minor: 0, patch: 0) == "26.0.0", "Zero parts are kept") + let model: [CChar] = Array("Mac15,6".utf8CString) + [0, 0] + expect(DeviceFacts.modelString(fromSysctlBytes: model) == "Mac15,6", "sysctl model stops at NUL") + expect(DeviceFacts.modelString(fromSysctlBytes: [0]) == "unknown", "Empty model is unknown") + expect(DeviceFacts.normalized(nil) == "unknown" && DeviceFacts.normalized(" US ") == "US", "Normalization") + let facts = DeviceFacts(holmesVersion: "0.1.3", macosVersion: "15.3.1", macModel: "Mac15,6", region: "US", locale: "en_US") + let body = facts.trackBody(event: "install", installID: "11111111-2222-3333-4444-555555555555") + let decoded = (try? JSONSerialization.jsonObject(with: Data(body.utf8))) as? [String: String] ?? [:] + expect(decoded == ["event": "install", "install_id": "11111111-2222-3333-4444-555555555555", + "holmes_version": "0.1.3", "macos_version": "15.3.1", "mac_model": "Mac15,6", + "region": "US", "locale": "en_US"], "Track body has exactly the documented fields") + expect(!body.contains("email"), "Track body never carries an email") + + // Install id is created once. + let store = MemoryCloudStore() + let clock = TestClock() + let throttle = InstallPingThrottle(store: store, now: { clock.now }) + let id = throttle.installID + expect(id.count == 36 && UUID(uuidString: id) != nil, "Install id is a 36 character UUID") + expect(throttle.installID == id, "Install id is stable") + expect(InstallPingThrottle(store: store).installID == id, "Install id survives a new launch") + + // Throttle: first send, once per day, retry after failure. + var sends = 0 + expect(throttle.isDue, "First ping is due") + let failedSend = await throttle.runIfDue { sends += 1; return false } + expect(failedSend == false, "Failed send reports false") + expect(store.date(forKey: InstallPingThrottle.lastSentKey) == nil && throttle.isDue, "Failure records nothing and stays due") + let goodSend = await throttle.runIfDue { sends += 1; return true } + expect(goodSend, "Successful send reports true") + expect(sends == 2 && !throttle.isDue, "Success records the date") + clock.advance(hours: 23) + let earlySend = await throttle.runIfDue { sends += 1; return true } + expect(earlySend == false && sends == 2, "Not due again within a day") + clock.advance(hours: 1) + expect(throttle.isDue, "Due again after 24 hours") + let nextDaySend = await throttle.runIfDue { sends += 1; return true } + expect(nextDaySend && sends == 3, "Second day sends once") + clock.advance(hours: -5) + expect(throttle.isDue, "A clock moved backwards counts as due") + + // Throttle: no overlapping sends. + let fresh = InstallPingThrottle(store: MemoryCloudStore(), now: { clock.now }) + var overlapping = 0 + let first = Task { await fresh.runIfDue { overlapping += 1; try? await Task.sleep(nanoseconds: 200_000_000); return true } } + try? await Task.sleep(nanoseconds: 50_000_000) + let second = await fresh.runIfDue { overlapping += 1; return true } + let firstResult = await first.value + expect(firstResult && !second && overlapping == 1, "A send in flight blocks a second one") + + print("Passed \(checks) auth validation, error mapping, device facts and install ping checks") + } +} diff --git a/holmes/tests/run-auth-validation-tests.sh b/holmes/tests/run-auth-validation-tests.sh new file mode 100755 index 0000000..f200822 --- /dev/null +++ b/holmes/tests/run-auth-validation-tests.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +auth_validation_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +auth_validation_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-auth-validation.XXXXXX") +trap 'rm -rf "$auth_validation_test_dir"' EXIT +cd "$auth_validation_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/AuthSupport.swift \ + holmes/tests/AuthValidationTests.swift \ + -o "$auth_validation_test_dir/auth-validation-tests" +"$auth_validation_test_dir/auth-validation-tests" From 852e3ba9cc623c8fa0a71354479b4dd9e41b2462 Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 10:01:01 -0700 Subject: [PATCH 2/7] Add the Appwrite Apple SDK 19.0.0 with a shared cloud client, install and sign in tracking, and an email and password auth service --- holmes/holmes.xcodeproj/project.pbxproj | 29 +++ .../xcshareddata/swiftpm/Package.resolved | 209 +++++++++++++++++- holmes/holmes/Core/AuthService.swift | 143 ++++++++++++ holmes/holmes/Core/HolmesCloud.swift | 106 +++++++++ 4 files changed, 486 insertions(+), 1 deletion(-) create mode 100644 holmes/holmes/Core/AuthService.swift create mode 100644 holmes/holmes/Core/HolmesCloud.swift diff --git a/holmes/holmes.xcodeproj/project.pbxproj b/holmes/holmes.xcodeproj/project.pbxproj index 9cdb43a..6c54227 100644 --- a/holmes/holmes.xcodeproj/project.pbxproj +++ b/holmes/holmes.xcodeproj/project.pbxproj @@ -13,6 +13,10 @@ AA000001000000000000117 /* EmailPredictionSources.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000117 /* EmailPredictionSources.swift */; }; AA000001000000000000118 /* EmailPredictionActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000118 /* EmailPredictionActions.swift */; }; AA000001000000000000119 /* EmailUndoToast.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000119 /* EmailUndoToast.swift */; }; + AA000001000000000000120 /* AuthSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000120 /* AuthSupport.swift */; }; + AA000001000000000000121 /* HolmesCloud.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000121 /* HolmesCloud.swift */; }; + AA000001000000000000122 /* AuthService.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000122 /* AuthService.swift */; }; + AA000001000000000000123 /* Appwrite in Frameworks */ = {isa = PBXBuildFile; productRef = AA00000A000000000000002 /* Appwrite */; }; B7A500010000000000000006 /* ModelJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000006 /* ModelJSON.swift */; }; B7A500010000000000000005 /* TextEntrySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000005 /* TextEntrySupport.swift */; }; B7A500010000000000000004 /* AutonomousRunTally.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000004 /* AutonomousRunTally.swift */; }; @@ -137,6 +141,9 @@ AA000002000000000000117 /* EmailPredictionSources.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailPredictionSources.swift; sourceTree = ""; }; AA000002000000000000118 /* EmailPredictionActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailPredictionActions.swift; sourceTree = ""; }; AA000002000000000000119 /* EmailUndoToast.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailUndoToast.swift; sourceTree = ""; }; + AA000002000000000000120 /* AuthSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthSupport.swift; sourceTree = ""; }; + AA000002000000000000121 /* HolmesCloud.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HolmesCloud.swift; sourceTree = ""; }; + AA000002000000000000122 /* AuthService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthService.swift; sourceTree = ""; }; B7A500020000000000000006 /* ModelJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelJSON.swift; sourceTree = ""; }; B7A500020000000000000005 /* TextEntrySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextEntrySupport.swift; sourceTree = ""; }; B7A500020000000000000004 /* AutonomousRunTally.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutonomousRunTally.swift; sourceTree = ""; }; @@ -262,6 +269,7 @@ buildActionMask = 2147483647; files = ( AA000001000000000000039 /* Lottie in Frameworks */, + AA000001000000000000123 /* Appwrite in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -398,6 +406,9 @@ AA000002000000000000116 /* MailComposeMatcher.swift */, AA000002000000000000117 /* EmailPredictionSources.swift */, AA000002000000000000118 /* EmailPredictionActions.swift */, + AA000002000000000000120 /* AuthSupport.swift */, + AA000002000000000000121 /* HolmesCloud.swift */, + AA000002000000000000122 /* AuthService.swift */, B7A500020000000000000006 /* ModelJSON.swift */, B7A500020000000000000005 /* TextEntrySupport.swift */, B7A500020000000000000004 /* AutonomousRunTally.swift */, @@ -567,6 +578,7 @@ name = holmes; packageProductDependencies = ( AA00000A000000000000001 /* Lottie */, + AA00000A000000000000002 /* Appwrite */, ); productName = holmes; productReference = AA000003000000000000000 /* holmes.app */; @@ -598,6 +610,7 @@ mainGroup = AA000005000000000000000; packageReferences = ( AA00000B000000000000001 /* XCRemoteSwiftPackageReference "lottie-ios" */, + AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */, ); productRefGroup = AA000005000000000000002 /* Products */; projectDirPath = ""; @@ -667,6 +680,9 @@ AA000001000000000000011 /* OnboardingFlow.swift in Sources */, AA000001000000000000012 /* OnboardingViewModel.swift in Sources */, AA000001000000000000013 /* WelcomeScreen.swift in Sources */, + AA000001000000000000120 /* AuthSupport.swift in Sources */, + AA000001000000000000121 /* HolmesCloud.swift in Sources */, + AA000001000000000000122 /* AuthService.swift in Sources */, AA000001000000000000014 /* HowItWorksScreen.swift in Sources */, AA000001000000000000015 /* PermissionsScreen.swift in Sources */, AA000001000000000000016 /* ReadyScreen.swift in Sources */, @@ -959,6 +975,14 @@ minimumVersion = 4.4.0; }; }; + AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/appwrite/sdk-for-apple.git"; + requirement = { + kind = exactVersion; + version = 19.0.0; + }; + }; /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ @@ -967,6 +991,11 @@ package = AA00000B000000000000001 /* XCRemoteSwiftPackageReference "lottie-ios" */; productName = Lottie; }; + AA00000A000000000000002 /* Appwrite */ = { + isa = XCSwiftPackageProductDependency; + package = AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */; + productName = Appwrite; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = AA000008000000000000000 /* Project object */; diff --git a/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1ebf5d3..7b5cca7 100644 --- a/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "0271592b24e5dc1185a09e3f2d980d55521827815d397c9bce8e63d502a51e84", + "originHash" : "0a14469a4b5e4b54376f903fc8d8bdbef5b871bf414067dd084750072bc67f01", "pins" : [ + { + "identity" : "async-http-client", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swift-server/async-http-client.git", + "state" : { + "revision" : "f95c908967e98c68c5ce3fd61a7974e7e869e303", + "version" : "1.36.1" + } + }, { "identity" : "lottie-ios", "kind" : "remoteSourceControl", @@ -9,6 +18,204 @@ "revision" : "a004050748dc197c56256a14dca49a035d74726c", "version" : "4.5.2" } + }, + { + "identity" : "sdk-for-apple", + "kind" : "remoteSourceControl", + "location" : "https://github.com/appwrite/sdk-for-apple.git", + "state" : { + "revision" : "7f801a9ed5f32dbf3febff374fcadb58a6447f0c", + "version" : "19.0.0" + } + }, + { + "identity" : "swift-algorithms", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-algorithms.git", + "state" : { + "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023", + "version" : "1.2.1" + } + }, + { + "identity" : "swift-asn1", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-asn1.git", + "state" : { + "revision" : "d9a5b37470adc940d22c3bcd5ca6953a516b727f", + "version" : "1.7.2" + } + }, + { + "identity" : "swift-async-algorithms", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-async-algorithms.git", + "state" : { + "revision" : "3da39bbc4e687d4192af7c9cf4eab805745a0b9c", + "version" : "1.1.5" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, + { + "identity" : "swift-certificates", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-certificates.git", + "state" : { + "revision" : "c8aece90ea05f9866bd392a5bf13b5cae56c0e03", + "version" : "1.20.0" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", + "version" : "1.6.0" + } + }, + { + "identity" : "swift-configuration", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-configuration.git", + "state" : { + "revision" : "be76c4ad929eb6c4bcaf3351799f2adf9e6848a9", + "version" : "1.2.0" + } + }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f", + "version" : "4.5.2" + } + }, + { + "identity" : "swift-distributed-tracing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-distributed-tracing.git", + "state" : { + "revision" : "dc4030184203ffafbb2ec614352487235d747fe0", + "version" : "1.4.1" + } + }, + { + "identity" : "swift-http-structured-headers", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-http-structured-headers.git", + "state" : { + "revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47", + "version" : "1.7.0" + } + }, + { + "identity" : "swift-http-types", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-http-types.git", + "state" : { + "revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50", + "version" : "1.8.0" + } + }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "9c6fb14227f55d8f711ce3847dc2f419fb0ecacb", + "version" : "1.15.1" + } + }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "a931f2c1de8dd49381ce3bf2e279d033f68d8865", + "version" : "2.102.0" + } + }, + { + "identity" : "swift-nio-extras", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-extras.git", + "state" : { + "revision" : "41449336c8ecfadac6b4b5be75f9c3c306e61ced", + "version" : "1.35.1" + } + }, + { + "identity" : "swift-nio-http2", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-http2.git", + "state" : { + "revision" : "0f3e54e29c944c2e835ad52159da7d9e1c94ac69", + "version" : "1.46.0" + } + }, + { + "identity" : "swift-nio-ssl", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-ssl.git", + "state" : { + "revision" : "03827c1a9fdb2b6b00a4e93ede8861520263af8c", + "version" : "2.37.4" + } + }, + { + "identity" : "swift-nio-transport-services", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-transport-services.git", + "state" : { + "revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5", + "version" : "1.28.0" + } + }, + { + "identity" : "swift-numerics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-numerics.git", + "state" : { + "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", + "version" : "1.1.1" + } + }, + { + "identity" : "swift-service-context", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-service-context.git", + "state" : { + "revision" : "d0997351b0c7779017f88e7a93bc30a1878d7f29", + "version" : "1.3.0" + } + }, + { + "identity" : "swift-service-lifecycle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swift-server/swift-service-lifecycle", + "state" : { + "revision" : "7f9326b0326ff86e3646295ea6e891f68c471c5e", + "version" : "2.12.0" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750", + "version" : "1.8.1" + } } ], "version" : 3 diff --git a/holmes/holmes/Core/AuthService.swift b/holmes/holmes/Core/AuthService.swift new file mode 100644 index 0000000..69b6c7e --- /dev/null +++ b/holmes/holmes/Core/AuthService.swift @@ -0,0 +1,143 @@ +import Foundation +import Appwrite + +struct AuthUser: Equatable { + let id: String + let name: String + let email: String +} + +struct AuthFailure: LocalizedError, Equatable { + let message: String + var errorDescription: String? { message } +} + +extension Notification.Name { + /// Posted after Settings signs the user out; AppDelegate shows sign in again. + static let holmesDidSignOut = Notification.Name("HolmesDidSignOut") +} + +/// Email and password accounts through Appwrite. Signing in is required to use +/// Holmes; the SDK persists the session, so this only asks once per Mac. +@MainActor +final class AuthService: ObservableObject { + static let shared = AuthService() + + @Published private(set) var currentUser: AuthUser? + @Published private(set) var isWorking = false + + private let account = Account(HolmesCloud.client) + private static let lastEmailKey = "HolmesCloud.lastSignedInEmail" + + var isSignedIn: Bool { currentUser != nil } + + /// Restores the session the SDK stored on a previous launch. Returns true + /// when the user is signed in. Offline with a stored session counts as + /// signed in so Holmes still works without a connection. + @discardableResult + func restoreSession() async -> Bool { + do { + currentUser = try await fetchUser() + return true + } catch let error as AppwriteError where (error.code ?? 0) > 0 && (error.code ?? 0) < 500 { + currentUser = nil + return false + } catch { + guard HolmesCloud.hasStoredSession else { + currentUser = nil + return false + } + let email = UserDefaults.standard.string(forKey: Self.lastEmailKey) ?? "" + currentUser = AuthUser(id: "", name: "", email: email) + return true + } + } + + func signIn(email: String, password: String) async throws { + try validate(mode: .signIn, name: "", email: email, password: password) + isWorking = true + defer { isWorking = false } + try await createSession(email: normalized(email), password: password, mode: .signIn) + try await finishSignIn(mode: .signIn) + } + + func signUp(name: String, email: String, password: String) async throws { + try validate(mode: .createAccount, name: name, email: email, password: password) + isWorking = true + defer { isWorking = false } + do { + _ = try await account.create( + userId: ID.unique(), + email: normalized(email), + password: password, + name: name.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } catch { + throw Self.failure(for: error, mode: .createAccount) + } + try await createSession(email: normalized(email), password: password, mode: .createAccount) + try await finishSignIn(mode: .createAccount) + } + + func signOut() async { + do { + _ = try await account.deleteSession(sessionId: "current") + } catch { + print("[Auth] Remote sign out failed, clearing the local session anyway: \(error.localizedDescription)") + } + HolmesCloud.clearStoredSession() + currentUser = nil + } + + // MARK: Helpers + + private func validate(mode: AuthMode, name: String, email: String, password: String) throws { + if let problem = AuthValidation.problem(mode: mode, name: name, email: email, password: password) { + throw AuthFailure(message: problem) + } + } + + private func normalized(_ email: String) -> String { + email.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private func createSession(email: String, password: String, mode: AuthMode) async throws { + do { + _ = try await account.createEmailPasswordSession(email: email, password: password) + } catch let error as AppwriteError where error.type == "user_session_already_exists" { + // A stale session is still stored; replace it with this account's. + _ = try? await account.deleteSession(sessionId: "current") + do { + _ = try await account.createEmailPasswordSession(email: email, password: password) + } catch { + throw Self.failure(for: error, mode: mode) + } + } catch { + throw Self.failure(for: error, mode: mode) + } + } + + private func finishSignIn(mode: AuthMode) async throws { + do { + currentUser = try await fetchUser() + } catch { + throw Self.failure(for: error, mode: mode) + } + HolmesCloud.sendSignInEvent() + } + + private func fetchUser() async throws -> AuthUser { + let user = try await account.get() + UserDefaults.standard.set(user.email, forKey: Self.lastEmailKey) + return AuthUser(id: user.id, name: user.name, email: user.email) + } + + nonisolated static func failure(for error: Error, mode: AuthMode) -> AuthFailure { + if let failure = error as? AuthFailure { return failure } + if let appwrite = error as? AppwriteError { + return AuthFailure(message: AuthErrorMessages.message(code: appwrite.code, type: appwrite.type, mode: mode)) + } + // Anything that isn't an Appwrite response is a transport failure. + return AuthFailure(message: AuthErrorMessages.offline) + } +} diff --git a/holmes/holmes/Core/HolmesCloud.swift b/holmes/holmes/Core/HolmesCloud.swift new file mode 100644 index 0000000..709b2b2 --- /dev/null +++ b/holmes/holmes/Core/HolmesCloud.swift @@ -0,0 +1,106 @@ +import Foundation +import Appwrite +import AppwriteEnums + +/// The only network service Holmes talks to besides the local model: Appwrite, +/// for the account and a tiny usage count. What is sent is exactly +/// `DeviceFacts.trackBody`: an install id, the Holmes and macOS versions, the +/// Mac model, region and locale. Screen, voice and task content never leave +/// this Mac. +enum HolmesCloud { + static let endpoint = "https://sfo.cloud.appwrite.io/v1" + static let projectID = "holmes" + static let trackFunctionID = "track" + + static let client: Client = Client() + .setEndpoint(endpoint) + .setProject(projectID) + + private static let throttle = InstallPingThrottle(store: UserDefaultsCloudStore()) + + static var installID: String { throttle.installID } + + // MARK: Device facts + + static var deviceFacts: DeviceFacts { + let os = ProcessInfo.processInfo.operatingSystemVersion + return DeviceFacts( + holmesVersion: DeviceFacts.normalized( + Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String), + macosVersion: DeviceFacts.formatOSVersion( + major: os.majorVersion, minor: os.minorVersion, patch: os.patchVersion), + macModel: macModel(), + region: DeviceFacts.normalized(Locale.current.region?.identifier), + locale: DeviceFacts.normalized(Locale.current.identifier) + ) + } + + private static func macModel() -> String { + var size = 0 + guard sysctlbyname("hw.model", nil, &size, nil, 0) == 0, size > 0 else { return "unknown" } + var bytes = [CChar](repeating: 0, count: size) + guard sysctlbyname("hw.model", &bytes, &size, nil, 0) == 0 else { return "unknown" } + return DeviceFacts.modelString(fromSysctlBytes: bytes) + } + + // MARK: Events + + /// Fire and forget. Sends once per install, then at most once a day. A + /// failure is only logged; the next launch tries again. + static func sendInstallPing() { + Task.detached(priority: .utility) { + await throttle.runIfDue { await track(event: "install") } + } + } + + /// Fire and forget, after a successful sign in or account creation. + static func sendSignInEvent() { + Task.detached(priority: .utility) { + _ = await track(event: "signin") + } + } + + @discardableResult + static func track(event: String) async -> Bool { + let body = deviceFacts.trackBody(event: event, installID: installID) + do { + let execution = try await Functions(client).createExecution( + functionId: trackFunctionID, + body: body, + async: false, + path: "/", + method: .pOST, + headers: ["content-type": "application/json"] + ) + let ok = (200..<300).contains(execution.responseStatusCode) + && execution.responseBody.replacingOccurrences(of: " ", with: "").contains("\"ok\":true") + if !ok { + print("[HolmesCloud] \(event) event not accepted (status \(execution.responseStatusCode))") + } + return ok + } catch { + print("[HolmesCloud] \(event) event failed: \(error.localizedDescription)") + return false + } + } + + // MARK: Stored session + + /// The SDK keeps the session cookie in UserDefaults under the endpoint host. + private static var cookieKey: String { URL(string: endpoint)?.host ?? "" } + + /// True when a session cookie is stored locally. Used only when the server + /// can't be reached, so an offline launch doesn't lock a signed in user out. + static var hasStoredSession: Bool { + let cookies = UserDefaults.standard.stringArray(forKey: cookieKey) ?? [] + return cookies.contains { cookie in + cookie.hasPrefix("a_session_\(projectID)=") + && !cookie.hasPrefix("a_session_\(projectID)=;") + && !cookie.lowercased().contains("max-age=0") + } + } + + static func clearStoredSession() { + UserDefaults.standard.removeObject(forKey: cookieKey) + } +} From f6241650789c05d42f97c963f239dfbff45acf14 Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 10:01:01 -0700 Subject: [PATCH 3/7] Require sign in before Welcome and at launch for signed out users, send the install ping on launch, add Sign Out in Settings, and keep in app privacy copy accurate --- holmes/holmes.xcodeproj/project.pbxproj | 4 + holmes/holmes/App/AppDelegate.swift | 57 ++++- holmes/holmes/App/holmesApp.swift | 32 ++- .../Views/Onboarding/OnboardingFlow.swift | 33 ++- .../Onboarding/OnboardingViewModel.swift | 30 ++- .../Views/Onboarding/SignInScreen.swift | 242 ++++++++++++++++++ 6 files changed, 364 insertions(+), 34 deletions(-) create mode 100644 holmes/holmes/Views/Onboarding/SignInScreen.swift diff --git a/holmes/holmes.xcodeproj/project.pbxproj b/holmes/holmes.xcodeproj/project.pbxproj index 6c54227..f26a88a 100644 --- a/holmes/holmes.xcodeproj/project.pbxproj +++ b/holmes/holmes.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ AA000001000000000000120 /* AuthSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000120 /* AuthSupport.swift */; }; AA000001000000000000121 /* HolmesCloud.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000121 /* HolmesCloud.swift */; }; AA000001000000000000122 /* AuthService.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000122 /* AuthService.swift */; }; + AA000001000000000000124 /* SignInScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000124 /* SignInScreen.swift */; }; AA000001000000000000123 /* Appwrite in Frameworks */ = {isa = PBXBuildFile; productRef = AA00000A000000000000002 /* Appwrite */; }; B7A500010000000000000006 /* ModelJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000006 /* ModelJSON.swift */; }; B7A500010000000000000005 /* TextEntrySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000005 /* TextEntrySupport.swift */; }; @@ -144,6 +145,7 @@ AA000002000000000000120 /* AuthSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthSupport.swift; sourceTree = ""; }; AA000002000000000000121 /* HolmesCloud.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HolmesCloud.swift; sourceTree = ""; }; AA000002000000000000122 /* AuthService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthService.swift; sourceTree = ""; }; + AA000002000000000000124 /* SignInScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInScreen.swift; sourceTree = ""; }; B7A500020000000000000006 /* ModelJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelJSON.swift; sourceTree = ""; }; B7A500020000000000000005 /* TextEntrySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextEntrySupport.swift; sourceTree = ""; }; B7A500020000000000000004 /* AutonomousRunTally.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutonomousRunTally.swift; sourceTree = ""; }; @@ -502,6 +504,7 @@ children = ( AA000002000000000000107 /* GuidedDemoWindow.swift */, B7A500020000000000000F01 /* LaunchIntroView.swift */, + AA000002000000000000124 /* SignInScreen.swift */, AA000002000000000000106 /* GuidedDemoView.swift */, AA000002000000000000011 /* OnboardingFlow.swift */, AA000002000000000000012 /* OnboardingViewModel.swift */, @@ -683,6 +686,7 @@ AA000001000000000000120 /* AuthSupport.swift in Sources */, AA000001000000000000121 /* HolmesCloud.swift in Sources */, AA000001000000000000122 /* AuthService.swift in Sources */, + AA000001000000000000124 /* SignInScreen.swift in Sources */, AA000001000000000000014 /* HowItWorksScreen.swift in Sources */, AA000001000000000000015 /* PermissionsScreen.swift in Sources */, AA000001000000000000016 /* ReadyScreen.swift in Sources */, diff --git a/holmes/holmes/App/AppDelegate.swift b/holmes/holmes/App/AppDelegate.swift index 129b4f4..344132e 100644 --- a/holmes/holmes/App/AppDelegate.swift +++ b/holmes/holmes/App/AppDelegate.swift @@ -17,6 +17,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { // FileHandle.write then throws EPIPE, which MCPClient already handles. signal(SIGPIPE, SIG_IGN) + // Fire and forget: the service sends once per install, then at most + // once a day, and never blocks launch. + HolmesCloud.sendInstallPing() + do { if let folder = try ExtensionInstaller.refreshInstalledIfNeeded() { extensionUpdateNeedsNotice = true @@ -88,17 +92,38 @@ class AppDelegate: NSObject, NSApplicationDelegate { @MainActor private func handleAuthAndLaunch() async { - // There is no account in Holmes Local: nothing to sign in to, so launch - // goes straight to onboarding (first run) or the main app. - launch() - } - - private func launch() { + // Holmes requires an account. The SDK keeps the session between + // launches, so this only asks when no valid session exists. + let signedIn = await AuthService.shared.restoreSession() + observeSignOut() let hasCompletedOnboarding = UserDefaults.standard.bool(forKey: "hasCompletedOnboarding") - if hasCompletedOnboarding { - startMainApp() + if !hasCompletedOnboarding { + showOnboarding(requiresSignIn: !signedIn) + } else if signedIn { + startMainAppOnce() } else { - showOnboarding() + // Finished onboarding before accounts existed, or signed out. + SignInWindowController.shared.show { [weak self] in + self?.startMainAppOnce() + } + } + } + + private var signOutObserver: NSObjectProtocol? + + private func observeSignOut() { + guard signOutObserver == nil else { return } + signOutObserver = NotificationCenter.default.addObserver( + forName: .holmesDidSignOut, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + for window in NSApp.windows where window.identifier?.rawValue.contains("Settings") == true { + window.close() + } + SignInWindowController.shared.show { + self?.startMainAppOnce() + } + } } } @@ -183,8 +208,8 @@ class AppDelegate: NSObject, NSApplicationDelegate { HotkeyManager.shared.registerHotkeys() } - private func showOnboarding() { - let onboardingView = OnboardingFlow { + private func showOnboarding(requiresSignIn: Bool) { + let onboardingView = OnboardingFlow(requiresSignIn: requiresSignIn) { DispatchQueue.main.async { [weak self] in self?.finishOnboarding() } @@ -238,6 +263,16 @@ class AppDelegate: NSObject, NSApplicationDelegate { onboardingWindow = nil if window.isVisible { window.close() } } + guard AuthService.shared.isSignedIn else { + // Closed before signing in. Sign in is required, so quit; + // onboarding shows again next launch. + NSApp.terminate(nil) + return + } + startMainAppOnce() + } + + private func startMainAppOnce() { guard !mainAppStarted else { return } mainAppStarted = true startMainApp() diff --git a/holmes/holmes/App/holmesApp.swift b/holmes/holmes/App/holmesApp.swift index a826025..34f18c2 100644 --- a/holmes/holmes/App/holmesApp.swift +++ b/holmes/holmes/App/holmesApp.swift @@ -362,26 +362,48 @@ struct PlaybookToggleRow: View { struct GeneralSettingsView: View { @Binding var launchAtLogin: Bool @Binding var showNotchAnimation: Bool - + @ObservedObject private var auth = AuthService.shared + var body: some View { Form { Toggle("Launch at Login", isOn: $launchAtLogin) - + if NotchDetector.hasNotch { Toggle("Show Notch Animation", isOn: $showNotchAnimation) } - + Divider() - + LabeledContent("Side Icon Position") { Button("Reset to Default") { UserDefaults.standard.removeObject(forKey: "SideIconPosition") } } + + Divider() + + LabeledContent("Account") { + HStack(spacing: 10) { + Text(accountLabel) + .foregroundStyle(NoirColors.textSecondary) + Button("Sign Out") { + Task { @MainActor in + await auth.signOut() + NotificationCenter.default.post(name: .holmesDidSignOut, object: nil) + } + } + .disabled(!auth.isSignedIn || auth.isWorking) + } + } } .scrollContentBackground(.hidden) .padding() } + + private var accountLabel: String { + guard let user = auth.currentUser else { return "Not signed in" } + return user.email.isEmpty ? "Signed in" : user.email + } } // MARK: - Voice & Guidance (the Clicky experience) @@ -1022,7 +1044,7 @@ struct AboutSettingsView: View { .font(NoirFonts.font(size: 11, weight: .regular, design: .monospaced)) .foregroundStyle(NoirColors.textTertiary) - Text("Runs entirely on this Mac through Ollama — no account, no API key, nothing leaves the machine.") + Text("Thinks with a local model through Ollama, no API key. Your screen, voice, and tasks stay on this Mac; your account stores only your email, region, macOS version, and Holmes version to count users.") .font(NoirFonts.caption()) .foregroundStyle(NoirColors.textTertiary) .multilineTextAlignment(.center) diff --git a/holmes/holmes/Views/Onboarding/OnboardingFlow.swift b/holmes/holmes/Views/Onboarding/OnboardingFlow.swift index 855a6ef..2929a3b 100644 --- a/holmes/holmes/Views/Onboarding/OnboardingFlow.swift +++ b/holmes/holmes/Views/Onboarding/OnboardingFlow.swift @@ -1,11 +1,17 @@ import SwiftUI struct OnboardingFlow: View { - @StateObject private var viewModel = OnboardingViewModel() - // The brand intro plays once before Welcome; Reduce Motion skips it. + @StateObject private var viewModel: OnboardingViewModel + // The brand intro plays once before the first screen; Reduce Motion skips it. @State private var showLaunchIntro = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion let onComplete: () -> Void - + + /// `requiresSignIn` is false when a valid session was restored at launch. + init(requiresSignIn: Bool = false, onComplete: @escaping () -> Void) { + _viewModel = StateObject(wrappedValue: OnboardingViewModel(startStep: requiresSignIn ? .signIn : .welcome)) + self.onComplete = onComplete + } + var body: some View { ZStack { VisualEffectBlur(material: .hudWindow, blendingMode: .behindWindow) @@ -13,21 +19,28 @@ struct OnboardingFlow: View { VStack(spacing: 0) { HStack { Spacer() - - if viewModel.currentStep != .welcome { + + if viewModel.currentStep.showsStepIndicator { StepIndicator( - currentStep: viewModel.currentStep.rawValue, - totalSteps: OnboardingStep.allCases.count + currentStep: viewModel.currentStep.indicatorIndex, + totalSteps: OnboardingStep.indicatorSteps.count ) } - + Spacer() } .padding(.top, 40) .padding(.horizontal, 40) - + Group { switch viewModel.currentStep { + case .signIn: + // Held back until the intro ends, like Welcome. + if !showLaunchIntro { + SignInScreen(auth: .shared) { + viewModel.goToStep(.welcome) + } + } case .welcome: // Held back until the intro ends so its entrance animation plays. if !showLaunchIntro { @@ -101,7 +114,7 @@ struct LocalModelScreen: View { .font(NoirFonts.headline()) .foregroundColor(NoirColors.textPrimary) - Text("Holmes thinks with an open model that runs on this Mac\nthrough Ollama. Nothing you do is sent to a server.") + Text("Holmes thinks with an open model that runs on this Mac\nthrough Ollama. What you do on screen is never sent to a server.") .font(NoirFonts.caption()) .foregroundColor(NoirColors.textSecondary) .multilineTextAlignment(.center) diff --git a/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift b/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift index 9deb54d..12af74f 100644 --- a/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift +++ b/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift @@ -4,21 +4,35 @@ import AppKit import ScreenCaptureKit enum OnboardingStep: Int, CaseIterable { - case welcome = 0 - case howItWorks = 1 - case permissions = 2 + /// Required account step, skipped when a session already exists. + case signIn = 0 + case welcome = 1 + case howItWorks = 2 + case permissions = 3 /// "Your local model": get Ollama running and the default model pulled, /// so a first-run user leaves onboarding with a working local brain. - case localModel = 3 + case localModel = 4 /// Install + pair the bundled browser extension (exact page reads). - case browser = 4 + case browser = 5 /// Optional Composio connection for the read-only playbook tools. - case integrations = 5 - case ready = 6 + case integrations = 6 + case ready = 7 + + /// Sign in and Welcome are entry screens without progress dots. + var showsStepIndicator: Bool { self != .signIn && self != .welcome } + + /// The steps the progress dots count. Sign in is not one of them. + static var indicatorSteps: [OnboardingStep] { allCases.filter { $0 != .signIn } } + + var indicatorIndex: Int { Self.indicatorSteps.firstIndex(of: self) ?? 0 } } class OnboardingViewModel: ObservableObject { - @Published var currentStep: OnboardingStep = .welcome + @Published var currentStep: OnboardingStep + + init(startStep: OnboardingStep = .welcome) { + currentStep = startStep + } @Published var hasScreenRecordingPermission = false @Published var hasAccessibilityPermission = false @Published var hasAutomationPermission = false diff --git a/holmes/holmes/Views/Onboarding/SignInScreen.swift b/holmes/holmes/Views/Onboarding/SignInScreen.swift new file mode 100644 index 0000000..5d3299f --- /dev/null +++ b/holmes/holmes/Views/Onboarding/SignInScreen.swift @@ -0,0 +1,242 @@ +import SwiftUI +import AppKit + +/// Required account step. Used as the first onboarding step and, for people +/// who finished onboarding before accounts existed or who signed out, inside +/// its own small window at launch. There is no skip. +struct SignInScreen: View { + @ObservedObject var auth: AuthService + let onSignedIn: () -> Void + + @State private var mode: AuthMode + @State private var name = "" + @State private var email = "" + @State private var password = "" + @State private var errorMessage: String? + @State private var contentOpacity: CGFloat = 0 + + static let privacyLine = "Holmes stores your email, region, macOS version, and Holmes version to count users. Everything else stays on this Mac." + + init(auth: AuthService, initialMode: AuthMode = .createAccount, onSignedIn: @escaping () -> Void) { + self.auth = auth + self._mode = State(initialValue: initialMode) + self.onSignedIn = onSignedIn + } + + var body: some View { + VStack(spacing: 0) { + Spacer() + + VStack(spacing: 24) { + VStack(spacing: 10) { + Text("holmes") + .font(NoirFonts.brand(size: 48)) + .foregroundStyle(NoirColors.charcoalDark) + + Text(mode == .signIn ? "Sign in to continue" : "Create your Holmes account") + .font(NoirFonts.body()) + .foregroundStyle(NoirColors.deepTeal) + } + + modePicker + + VStack(spacing: 10) { + if mode == .createAccount { + NoirFormField("Name", text: $name) + } + NoirFormField("Email", text: $email) + NoirFormField("Password", text: $password, isSecure: true) + + if mode == .createAccount { + Text("At least \(AuthValidation.minimumPasswordLength) characters.") + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.textTertiary) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .onSubmit(submit) + .disabled(auth.isWorking) + + if let errorMessage { + Text(errorMessage) + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.error) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .transition(.opacity) + } + } + .frame(maxWidth: 340) + .opacity(contentOpacity) + + Spacer() + + VStack(spacing: 16) { + HStack(spacing: 12) { + if auth.isWorking { + ProgressView() + .controlSize(.small) + .tint(NoirColors.accent) + } + NoirButton(auth.isWorking ? workingTitle : primaryTitle, icon: "arrow.right", action: submit) + .disabled(auth.isWorking) + } + + Text(Self.privacyLine) + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.textTertiary) + .multilineTextAlignment(.center) + .lineSpacing(3) + .frame(maxWidth: 380) + .fixedSize(horizontal: false, vertical: true) + } + .opacity(contentOpacity) + .padding(.bottom, 44) + .padding(.horizontal, 32) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .animation(.easeInOut(duration: 0.15), value: errorMessage) + .onAppear { + withAnimation(.easeOut(duration: 0.5).delay(0.1)) { + contentOpacity = 1.0 + } + } + } + + private var primaryTitle: String { mode == .signIn ? "Sign In" : "Create Account" } + private var workingTitle: String { mode == .signIn ? "Signing In" : "Creating Account" } + + private var modePicker: some View { + HStack(spacing: 3) { + modeButton(.signIn, title: "Sign in") + modeButton(.createAccount, title: "Create account") + } + .padding(3) + .background(NoirColors.glassChrome) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .glassBorder(cornerRadius: 8) + .disabled(auth.isWorking) + } + + private func modeButton(_ target: AuthMode, title: String) -> some View { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + mode = target + errorMessage = nil + } + } label: { + Text(title) + .font(NoirFonts.font(size: 11, weight: .medium, design: .monospaced)) + .foregroundStyle(mode == target ? NoirColors.ctaForeground : NoirColors.textSecondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 7) + .background( + RoundedRectangle(cornerRadius: 6) + .fill(mode == target ? NoirColors.ctaBackground : Color.clear) + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private func submit() { + guard !auth.isWorking else { return } + if let problem = AuthValidation.problem(mode: mode, name: name, email: email, password: password) { + errorMessage = problem + return + } + errorMessage = nil + let mode = self.mode + Task { @MainActor in + do { + if mode == .signIn { + try await auth.signIn(email: email, password: password) + } else { + try await auth.signUp(name: name, email: email, password: password) + } + password = "" + onSignedIn() + } catch { + errorMessage = AuthService.failure(for: error, mode: mode).message + } + } + } +} + +/// The standalone sign in window for people past onboarding without a session. +@MainActor +final class SignInWindowController: NSObject, NSWindowDelegate { + static let shared = SignInWindowController() + + private var window: NSWindow? + private var onSignedIn: (() -> Void)? + private var completed = false + + var isVisible: Bool { window?.isVisible ?? false } + + func show(onSignedIn: @escaping () -> Void) { + self.onSignedIn = onSignedIn + if let window { + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + return + } + completed = false + + let root = ZStack { + VisualEffectBlur(material: .hudWindow, blendingMode: .behindWindow) + .ignoresSafeArea() + SignInScreen(auth: .shared, initialMode: .signIn) { [weak self] in + self?.finish() + } + } + .frame(width: 480, height: 600) + .preferredColorScheme(.dark) + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 480, height: 600), + styleMask: [.titled, .closable, .fullSizeContentView], + backing: .buffered, + defer: false + ) + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.isMovableByWindowBackground = true + window.isOpaque = false + window.backgroundColor = .clear + window.isReleasedWhenClosed = false + window.delegate = self + window.center() + window.contentView = NSHostingView(rootView: root) + window.makeKeyAndOrderFront(nil) + self.window = window + NSApp.activate(ignoringOtherApps: true) + } + + private func finish() { + completed = true + let finished = window + window = nil + finished?.close() + let callback = onSignedIn + onSignedIn = nil + callback?() + } + + func windowWillClose(_ notification: Notification) { + guard !completed else { return } + // Signing in is required: closing the window quits, and the next + // launch asks again. + window = nil + NSApp.terminate(nil) + } +} + +#Preview { + ZStack { + NoirColors.skyBlue.ignoresSafeArea() + SignInScreen(auth: .shared) {} + } + .frame(width: 600, height: 700) + .preferredColorScheme(.dark) +} From 880c913dbb2226e151dd5c7f180a4e314b9db8b7 Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 10:01:02 -0700 Subject: [PATCH 4/7] Update the README and blueprint privacy sections to describe the account and install ping --- README.md | 3 ++- blueprint.md | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7ebbc9b..16e9a6b 100644 --- a/README.md +++ b/README.md @@ -105,8 +105,9 @@ Holmes picks one automatically based on your Mac's memory. Change it anytime in ## ➤ Privacy -Everything stays on your Mac by default. No telemetry, no analytics, no account. +What you do stays on your Mac. Holmes requires a free account, and the only data it sends is what counts users: your email, region, macOS version, and Holmes version. +- Account: email and password sign in through Appwrite. A daily install ping sends a random install id, the Holmes and macOS versions, Mac model, region and locale. Nothing from your screen, voice or tasks is included - Screen capture, Accessibility reads, OCR, dictation: on device, always - Screen context during a task: sent to the local model on your Mac (or wherever you point Ollama) - Spoken text: sent to ElevenLabs only if you add a key diff --git a/blueprint.md b/blueprint.md index a4d3060..0fd4eb8 100644 --- a/blueprint.md +++ b/blueprint.md @@ -1,6 +1,6 @@ # Holmes -Autonomous desktop agent for macOS. Runs entirely on your Mac, no cloud, no account. +Autonomous desktop agent for macOS. Runs on your Mac with a local model; the only cloud piece is your account. > **Beta.** This is Holmes Local, the open source build. It uses an open weights vision model served by [Ollama](https://ollama.com). The hosted version lives in a separate, private repo. @@ -73,8 +73,9 @@ Holmes picks one automatically based on your Mac's memory. Change it anytime in ## Privacy -Everything stays on your Mac by default. No telemetry, no analytics, no account. +What you do stays on your Mac. Holmes requires a free account, and the only data it sends is what counts users: your email, region, macOS version, and Holmes version. +- Account: email and password sign in through Appwrite. A daily install ping sends a random install id, the Holmes and macOS versions, Mac model, region and locale. Nothing from your screen, voice or tasks is included - Screen capture, Accessibility reads, OCR, dictation: on device, always - Screen context during a task: sent to the local model on your Mac (or wherever you point Ollama) - Spoken text: sent to ElevenLabs only if you add a key From b2e4a9959423ade3d8d8787e12aaf7c775d112e3 Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 10:15:17 -0700 Subject: [PATCH 5/7] Add the Appwrite download counter, install and sign in tracker, and admin analytics dashboard sources --- holmes/cloud/README.md | 19 + holmes/cloud/dashboard/holmes.png | Bin 0 -> 16048 bytes holmes/cloud/dashboard/index.html | 672 +++++++++++++++++++ holmes/cloud/dashboard/wordmark.svg | 6 + holmes/cloud/functions/download/package.json | 10 + holmes/cloud/functions/download/src/main.js | 64 ++ holmes/cloud/functions/track/package.json | 10 + holmes/cloud/functions/track/src/main.js | 120 ++++ 8 files changed, 901 insertions(+) create mode 100644 holmes/cloud/README.md create mode 100644 holmes/cloud/dashboard/holmes.png create mode 100644 holmes/cloud/dashboard/index.html create mode 100644 holmes/cloud/dashboard/wordmark.svg create mode 100644 holmes/cloud/functions/download/package.json create mode 100644 holmes/cloud/functions/download/src/main.js create mode 100644 holmes/cloud/functions/track/package.json create mode 100644 holmes/cloud/functions/track/src/main.js diff --git a/holmes/cloud/README.md b/holmes/cloud/README.md new file mode 100644 index 0000000..0d6e884 --- /dev/null +++ b/holmes/cloud/README.md @@ -0,0 +1,19 @@ +# Holmes cloud + +Everything Holmes sends off the Mac lives in one Appwrite Cloud project (`holmes`, region San Francisco). + +| Piece | Where it runs | What it does | +|---|---|---| +| `functions/download` | https://holmes-download.appwrite.network | The website's Download buttons open this. It records the click (country, referrer, browser) in the `downloads` table, then redirects to the GitHub releases page. Crawlers are redirected but not counted. | +| `functions/track` | Called by the app through the Appwrite SDK | `install` events keep one row per Mac in `installs` (Holmes version, macOS version, Mac model, Region setting, country, first and last seen, launches). `signin` events also keep one row per account in `users`, reading the email and name from the verified Appwrite account, never from the request. | +| `dashboard` | https://holmes-analytics.appwrite.network | Admin analytics: downloads, installs, users, regions, versions, GitHub release totals, and the list of people with their email and region. Sign in with an emailed code; only members of the `admins` team can see data. | + +## Data and access + +* Database `holmes` with tables `downloads`, `installs`, and `users`. Each table grants read to `team:admins` only; nothing is readable or writable by the app or the public directly. The functions write with the per execution key Appwrite provides. +* Country comes from Appwrite's country header when present, otherwise from a short lookup of the caller's IP at country.is. The app separately reports the Mac's Region setting. +* Add an admin by adding their account to the `admins` team in the Appwrite console. + +## Deploying + +Each folder is deployed as is. Functions use the Node 22 runtime with entrypoint `src/main.js` and build command `npm install`. The dashboard is a static site served from its folder root. diff --git a/holmes/cloud/dashboard/holmes.png b/holmes/cloud/dashboard/holmes.png new file mode 100644 index 0000000000000000000000000000000000000000..42ddea7ecdfbe96ed717c261427df2de7a54894a GIT binary patch literal 16048 zcmd7(Wpo`evn~j4Gcz;B%*@_qW@g%EW;@1hW`>xVW2TrXW{zWKW_HYWChxuHJNJCE z=KoBurB1<;42LP5F7>oy#8Yap8x=!YyiNSDF7hw4FJG%$?a4V`X`XI z)RnVRQUWmiqu~J%k+uNne-y;OMEEZO08oVx0H}XC#D92&kpC@pDTMlOy5&ELgLq`s z|I{XJHFZ67l@tXmoE=%rK+fitEIy9^sWAW`&$5vKfK8Up|5 z|FBsp$^Vy%hrKYRu97ObgtMC^IS&gP3mc^fA~`v^kQ>NKKwVP$zu^B$!jv{19xei` ztlr+t930I5G??9eojlBZn4R3I{+^$^BoAMA*66{tNVfm;65>_5Kf% zgX{kf`9CE8g%o1_Pq_ah{Qupy|BL&taYYb?SpU1DL=bEJxBfjwLfCSWVwye>mjQ4s zhTgu%-quGmc^wOHIm6ZI_VR)UaF9oUxc3fO)#lBJ?ovkkgi;snT-RKAVotklR}15cJBr0PFnHs4uT)Hy6Ayyg3^!>qWzwIxt7&ljQlQ19&zW6NjSPhy zgt+s$NSn|(O~*<;8aO>@lx%%jOaS*@D_yK->R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/index.html new file mode 100644 index 0000000..00dc412 --- /dev/null +++ b/holmes/cloud/dashboard/index.html @@ -0,0 +1,672 @@ + + + + + + +Holmes analytics + + + + + + + + + + + + + + + + + + diff --git a/holmes/cloud/dashboard/wordmark.svg b/holmes/cloud/dashboard/wordmark.svg new file mode 100644 index 0000000..ea02c96 --- /dev/null +++ b/holmes/cloud/dashboard/wordmark.svg @@ -0,0 +1,6 @@ + + Holmes + Holmes wordmark. + + + diff --git a/holmes/cloud/functions/download/package.json b/holmes/cloud/functions/download/package.json new file mode 100644 index 0000000..3a54e55 --- /dev/null +++ b/holmes/cloud/functions/download/package.json @@ -0,0 +1,10 @@ +{ + "name": "holmes-download-counter", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "src/main.js", + "dependencies": { + "node-appwrite": "29.0.0" + } +} diff --git a/holmes/cloud/functions/download/src/main.js b/holmes/cloud/functions/download/src/main.js new file mode 100644 index 0000000..14f3360 --- /dev/null +++ b/holmes/cloud/functions/download/src/main.js @@ -0,0 +1,64 @@ +import { Client, TablesDB, ID } from 'node-appwrite'; + +// Every Download button on the Holmes website points here. The click is +// recorded, then the visitor lands on the releases page to pick a version. +const RELEASES_URL = 'https://github.com/tryholmes/holmes-local/releases'; + +// Link previews and crawlers should still be redirected, but not counted. +const AUTOMATED_AGENT = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|curl|wget|python|headless/i; + +const clip = (value, max) => { + if (value === undefined || value === null) return null; + const text = String(value).trim().slice(0, max); + return text.length > 0 ? text : null; +}; + +// Appwrite only fills the country header for some requests, so fall back to +// country.is (open source) using the visitor's IP. Never waits long. +async function countryFor(headers) { + const known = clip(headers['x-appwrite-country-code'], 8); + if (known) return known.toUpperCase(); + const ip = String(headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (!ip) return null; + try { + const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(1500) }); + if (!response.ok) return null; + const { country } = await response.json(); + return clip(country, 8); + } catch { + return null; + } +} + +export default async ({ req, res, error }) => { + const headers = req.headers ?? {}; + const agent = String(headers['user-agent'] ?? ''); + + if (req.method === 'GET' && !AUTOMATED_AGENT.test(agent)) { + try { + const country = await countryFor(headers); + const client = new Client() + .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT) + .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) + .setKey(headers['x-appwrite-key'] ?? ''); + + await new TablesDB(client).createRow({ + databaseId: 'holmes', + tableId: 'downloads', + rowId: ID.unique(), + data: { + country, + continent: clip(headers['x-appwrite-continent-code'], 8), + referrer: clip(headers['referer'] ?? headers['referrer'], 512), + user_agent: clip(agent, 512), + source: clip(req.query?.source ?? 'website', 64), + }, + }); + } catch (err) { + // Never block the download because the counter failed. + error(`Could not record the download: ${err.message}`); + } + } + + return res.redirect(RELEASES_URL, 302); +}; diff --git a/holmes/cloud/functions/track/package.json b/holmes/cloud/functions/track/package.json new file mode 100644 index 0000000..6392fc6 --- /dev/null +++ b/holmes/cloud/functions/track/package.json @@ -0,0 +1,10 @@ +{ + "name": "holmes-install-tracker", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "src/main.js", + "dependencies": { + "node-appwrite": "29.0.0" + } +} diff --git a/holmes/cloud/functions/track/src/main.js b/holmes/cloud/functions/track/src/main.js new file mode 100644 index 0000000..593fe61 --- /dev/null +++ b/holmes/cloud/functions/track/src/main.js @@ -0,0 +1,120 @@ +import { Client, TablesDB, Users } from 'node-appwrite'; + +// Holmes calls this on launch ("install") and after signing in ("signin"). +// The email always comes from the verified Appwrite account, never the body. +const DATABASE_ID = 'holmes'; +const INSTALL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const clip = (value, max) => { + if (value === undefined || value === null) return null; + const text = String(value).trim().slice(0, max); + return text.length > 0 ? text : null; +}; + +// Same fallback as the download counter: Appwrite's country header when it is +// present, otherwise a short country.is lookup of the caller's IP. +async function countryFor(headers) { + const known = clip(headers['x-appwrite-country-code'], 8); + if (known) return known.toUpperCase(); + const ip = String(headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (!ip) return null; + try { + const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(1500) }); + if (!response.ok) return null; + const { country } = await response.json(); + return clip(country, 8); + } catch { + return null; + } +} + +function parseBody(req) { + if (req.bodyJson && typeof req.bodyJson === 'object') return req.bodyJson; + const raw = req.bodyText ?? req.body ?? ''; + if (typeof raw === 'object' && raw !== null) return raw; + return raw ? JSON.parse(raw) : {}; +} + +// Creates the row the first time and updates it afterwards, so first seen and +// sign up dates are kept while counters and versions move forward. +async function upsert(db, tableId, rowId, build) { + let existing = null; + try { + existing = await db.getRow({ databaseId: DATABASE_ID, tableId, rowId }); + } catch (err) { + if (err.code !== 404) throw err; + } + const data = build(existing); + return existing + ? db.updateRow({ databaseId: DATABASE_ID, tableId, rowId, data }) + : db.createRow({ databaseId: DATABASE_ID, tableId, rowId, data }); +} + +export default async ({ req, res, error }) => { + if (req.method !== 'POST') return res.json({ ok: false, error: 'Send a POST request.' }, 405); + + let body; + try { + body = parseBody(req); + } catch { + return res.json({ ok: false, error: 'The request body must be JSON.' }, 400); + } + + const event = body.event; + if (event !== 'install' && event !== 'signin') { + return res.json({ ok: false, error: 'event must be install or signin.' }, 400); + } + const installId = String(body.install_id ?? '').toLowerCase(); + if (!INSTALL_ID.test(installId)) { + return res.json({ ok: false, error: 'install_id must be a UUID.' }, 400); + } + + const headers = req.headers ?? {}; + const userId = clip(headers['x-appwrite-user-id'], 36); + if (event === 'signin' && !userId) { + return res.json({ ok: false, error: 'Sign in before sending a signin event.' }, 401); + } + + const client = new Client() + .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT) + .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) + .setKey(headers['x-appwrite-key'] ?? ''); + const db = new TablesDB(client); + const now = new Date().toISOString(); + + const device = { + holmes_version: clip(body.holmes_version, 32), + macos_version: clip(body.macos_version, 32), + mac_model: clip(body.mac_model, 64), + region: clip(body.region, 8), + country: await countryFor(headers), + }; + + try { + await upsert(db, 'installs', installId, (existing) => ({ + ...device, + locale: clip(body.locale, 32), + last_seen: now, + launches: (existing?.launches ?? 0) + 1, + ...(existing ? {} : { first_seen: now }), + })); + + if (event === 'signin') { + const user = await new Users(client).get(userId); + await upsert(db, 'users', userId, (existing) => ({ + ...device, + email: clip(user.email, 320), + name: clip(user.name, 128), + install_id: installId, + last_sign_in_at: now, + sign_ins: (existing?.sign_ins ?? 0) + 1, + ...(existing ? {} : { signed_up_at: user.$createdAt ?? now }), + })); + } + + return res.json({ ok: true }); + } catch (err) { + error(`Could not record the ${event} event: ${err.message}`); + return res.json({ ok: false, error: 'Holmes could not record this event.' }, 500); + } +}; From 195eca7377f729224a1d7a78dd4be6dee57f0e6a Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 10:22:00 -0700 Subject: [PATCH 6/7] Read the visitor country from the CDN client address and fix the dashboard bars and panel spacing --- holmes/cloud/dashboard/index.html | 7 +++--- holmes/cloud/functions/download/src/main.js | 25 ++++++++++++++------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/holmes/cloud/dashboard/index.html b/holmes/cloud/dashboard/index.html index 00dc412..aa11104 100644 --- a/holmes/cloud/dashboard/index.html +++ b/holmes/cloud/dashboard/index.html @@ -42,7 +42,7 @@ /* Sign in */ .gate { min-height: 100vh; display: grid; place-items: center; padding: 32px 16px; } .gate-card { width: min(380px, 100%); text-align: center; } - .gate-card img.character { width: 96px; height: auto; display: block; margin: 0 auto 20px; filter: drop-shadow(0 18px 30px rgba(0,0,0,.6)); } + .gate-card img.character { width: 96px; height: auto; display: block; margin: 0 auto 20px; } .gate-card .wordmark { width: 150px; height: auto; margin: 0 auto 6px; display: block; } .gate-card p.lede { color: var(--ink-2); margin: 0 0 28px; } .field { display: grid; gap: 6px; text-align: left; margin-bottom: 14px; } @@ -83,6 +83,7 @@ .panel-head h3 { margin: 0; font-size: 15px; font-weight: 600; } .panel-head .hint { color: var(--ink-3); font-size: 12.5px; } .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; } + .grid > .panel { margin-top: 0; } /* Line chart */ .chart-wrap { position: relative; } @@ -100,8 +101,8 @@ .bars { display: grid; gap: 9px; } .bar-row { display: grid; grid-template-columns: minmax(110px, 38%) 1fr auto; align-items: center; gap: 12px; } .bar-row .label { color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } - .bar-track { height: 8px; position: relative; } - .bar-fill { height: 8px; border-radius: 0 4px 4px 0; background: var(--cream); min-width: 2px; } + .bar-track { display: block; height: 8px; position: relative; border-radius: 0 4px 4px 0; } + .bar-fill { display: block; height: 8px; border-radius: 0 4px 4px 0; background: var(--cream); min-width: 2px; } .bar-row .count { color: var(--ink-2); min-width: 44px; text-align: right; } .tabs { display: inline-flex; gap: 4px; margin-left: auto; } .tabs button { border: 1px solid var(--rule); background: none; border-radius: 999px; padding: 3px 10px; color: var(--ink-2); cursor: pointer; font-size: 12.5px; } diff --git a/holmes/cloud/functions/download/src/main.js b/holmes/cloud/functions/download/src/main.js index 14f3360..d7c73bd 100644 --- a/holmes/cloud/functions/download/src/main.js +++ b/holmes/cloud/functions/download/src/main.js @@ -15,28 +15,37 @@ const clip = (value, max) => { // Appwrite only fills the country header for some requests, so fall back to // country.is (open source) using the visitor's IP. Never waits long. -async function countryFor(headers) { +async function countryFor(headers, log) { const known = clip(headers['x-appwrite-country-code'], 8); if (known) return known.toUpperCase(); - const ip = String(headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); - if (!ip) return null; + // The CDN puts the real visitor address in its own headers; x-forwarded-for can start with a proxy. + const ip = String(headers['fastly-client-ip'] ?? headers['x-cdn-client-ip'] ?? headers['x-real-ip'] + ?? headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (!ip) { + log('country lookup skipped: no client address header'); + return null; + } try { - const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(1500) }); - if (!response.ok) return null; + const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(2500) }); + if (!response.ok) { + log(`country lookup failed: status ${response.status}`); + return null; + } const { country } = await response.json(); return clip(country, 8); - } catch { + } catch (err) { + log(`country lookup failed: ${err.name}`); return null; } } -export default async ({ req, res, error }) => { +export default async ({ req, res, log, error }) => { const headers = req.headers ?? {}; const agent = String(headers['user-agent'] ?? ''); if (req.method === 'GET' && !AUTOMATED_AGENT.test(agent)) { try { - const country = await countryFor(headers); + const country = await countryFor(headers, log); const client = new Client() .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT) .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) From fb40f2fd0a2502cb0d1a3a1d72348a32a142e182 Mon Sep 17 00:00:00 2001 From: Pranauv Muthuraman Date: Tue, 15 Sep 2026 16:25:44 -0700 Subject: [PATCH 7/7] Split the dashboard into website downloads, accounts, and installs and record every sign in --- holmes/cloud/README.md | 4 +- holmes/cloud/dashboard/index.html | 600 +++++++++++++---------- holmes/cloud/functions/track/src/main.js | 41 +- 3 files changed, 378 insertions(+), 267 deletions(-) diff --git a/holmes/cloud/README.md b/holmes/cloud/README.md index 0d6e884..55f17a5 100644 --- a/holmes/cloud/README.md +++ b/holmes/cloud/README.md @@ -6,11 +6,11 @@ Everything Holmes sends off the Mac lives in one Appwrite Cloud project (`holmes |---|---|---| | `functions/download` | https://holmes-download.appwrite.network | The website's Download buttons open this. It records the click (country, referrer, browser) in the `downloads` table, then redirects to the GitHub releases page. Crawlers are redirected but not counted. | | `functions/track` | Called by the app through the Appwrite SDK | `install` events keep one row per Mac in `installs` (Holmes version, macOS version, Mac model, Region setting, country, first and last seen, launches). `signin` events also keep one row per account in `users`, reading the email and name from the verified Appwrite account, never from the request. | -| `dashboard` | https://holmes-analytics.appwrite.network | Admin analytics: downloads, installs, users, regions, versions, GitHub release totals, and the list of people with their email and region. Sign in with an emailed code; only members of the `admins` team can see data. | +| `dashboard` | https://holmes-analytics.appwrite.network | Admin analytics in three sections: website download tracking, accounts (sign ups and sign ins), and installs (current Macs running Holmes), each with regions, versions, and daily charts. Sign in with an emailed code; only members of the `admins` team can see data. | ## Data and access -* Database `holmes` with tables `downloads`, `installs`, and `users`. Each table grants read to `team:admins` only; nothing is readable or writable by the app or the public directly. The functions write with the per execution key Appwrite provides. +* Database `holmes` with tables `downloads`, `installs`, `users`, and `sign_ins` (one row per sign in, so sign ins can be counted per day). Each table grants read to `team:admins` only; nothing is readable or writable by the app or the public directly. The functions write with the per execution key Appwrite provides. * Country comes from Appwrite's country header when present, otherwise from a short lookup of the caller's IP at country.is. The app separately reports the Mac's Region setting. * Add an admin by adding their account to the `admins` team in the Appwrite console. diff --git a/holmes/cloud/dashboard/index.html b/holmes/cloud/dashboard/index.html index aa11104..37d5398 100644 --- a/holmes/cloud/dashboard/index.html +++ b/holmes/cloud/dashboard/index.html @@ -24,9 +24,9 @@ --cream: #ebe2d1; --danger: #ff7a70; /* Validated categorical trio on the #121212 panel (dataviz validator, all pairs). */ - --series-downloads: #3987e5; - --series-installs: #d95926; - --series-users: #199e70; + --series-1: #3987e5; + --series-2: #d95926; + --series-3: #199e70; --radius-panel: 14px; --radius-control: 8px; font-family: "Geist", ui-sans-serif, -apple-system, "Helvetica Neue", sans-serif; @@ -57,8 +57,9 @@ .message.error { color: var(--danger); } /* Shell */ - .top { position: sticky; top: 0; z-index: 5; background: rgba(6,6,6,.86); backdrop-filter: blur(14px); border-bottom: 1px solid var(--rule); } - .top-inner { max-width: 1180px; margin: 0 auto; padding: 14px 24px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } + .top { position: sticky; top: 0; z-index: 5; background: rgba(6,6,6,.88); backdrop-filter: blur(14px); border-bottom: 1px solid var(--rule); } + .top-inner { max-width: 1180px; margin: 0 auto; padding: 14px 24px 0; } + .top-row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } .top .wordmark { width: 92px; height: auto; display: block; } .top .title { color: var(--ink-2); padding-left: 14px; border-left: 1px solid var(--rule-strong); } .spacer { flex: 1; } @@ -66,10 +67,20 @@ .ranges button { border: 0; background: none; padding: 5px 12px; border-radius: 999px; color: var(--ink-2); cursor: pointer; } .ranges button[aria-pressed="true"] { background: var(--raised); color: var(--ink); box-shadow: inset 0 0 0 1px var(--rule-strong); } .who { color: var(--ink-3); font-size: 13px; } - main { max-width: 1180px; margin: 0 auto; padding: 28px 24px 64px; } + + /* Section tabs: the three categories. */ + .sections { display: flex; gap: 4px; margin-top: 12px; overflow-x: auto; } + .sections button { position: relative; border: 0; background: none; color: var(--ink-2); padding: 10px 14px 12px; cursor: pointer; white-space: nowrap; display: inline-flex; align-items: baseline; gap: 8px; } + .sections button .count { color: var(--ink-3); font-size: 12.5px; } + .sections button:hover { color: var(--ink); } + .sections button[aria-selected="true"] { color: var(--ink); } + .sections button[aria-selected="true"]::after { content: ""; position: absolute; left: 14px; right: 14px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--cream); } + + main { max-width: 1180px; margin: 0 auto; padding: 24px 24px 64px; } + .section-intro { color: var(--ink-2); margin: 0 0 18px; max-width: 72ch; } /* Headline band: one row, divided by rules rather than boxed cards. */ - .band { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); margin-bottom: 28px; } + .band { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); margin-bottom: 24px; } .measure { padding: 18px 20px 20px; border-left: 1px solid var(--rule); } .measure:first-child { border-left: 0; padding-left: 0; } .measure h2 { margin: 0 0 6px; font-size: 13px; font-weight: 500; color: var(--ink-2); display: flex; align-items: center; gap: 8px; } @@ -87,7 +98,7 @@ /* Line chart */ .chart-wrap { position: relative; } - .chart { width: 100%; height: 280px; display: block; overflow: visible; } + .chart { width: 100%; height: 260px; display: block; overflow: visible; } .legend { display: flex; gap: 18px; flex-wrap: wrap; margin-bottom: 8px; color: var(--ink-2); font-size: 13px; } .legend span { display: inline-flex; align-items: center; gap: 7px; } .legend i { width: 14px; height: 2px; border-radius: 2px; display: inline-block; } @@ -104,12 +115,12 @@ .bar-track { display: block; height: 8px; position: relative; border-radius: 0 4px 4px 0; } .bar-fill { display: block; height: 8px; border-radius: 0 4px 4px 0; background: var(--cream); min-width: 2px; } .bar-row .count { color: var(--ink-2); min-width: 44px; text-align: right; } - .tabs { display: inline-flex; gap: 4px; margin-left: auto; } + .tabs { display: inline-flex; gap: 4px; margin-left: auto; flex-wrap: wrap; } .tabs button { border: 1px solid var(--rule); background: none; border-radius: 999px; padding: 3px 10px; color: var(--ink-2); cursor: pointer; font-size: 12.5px; } .tabs button[aria-pressed="true"] { color: var(--ink); border-color: var(--rule-strong); background: var(--raised); } .empty { color: var(--ink-3); padding: 18px 0; } - /* Users table */ + /* People table */ .table-tools { display: flex; gap: 10px; align-items: center; margin-left: auto; } .table-tools input { padding: 7px 10px; border-radius: var(--radius-control); border: 1px solid var(--rule-strong); background: var(--canvas); min-width: 220px; } .table-tools button { border: 1px solid var(--rule-strong); background: var(--raised); border-radius: var(--radius-control); padding: 7px 12px; cursor: pointer; } @@ -121,7 +132,7 @@ td.email { color: var(--ink); } td.muted { color: var(--ink-2); } tr:last-child td { border-bottom: 0; } - .foot { color: var(--ink-3); font-size: 12.5px; margin-top: 12px; } + .foot { color: var(--ink-3); font-size: 12.5px; margin-top: 16px; } @media (max-width: 860px) { .band { grid-template-columns: repeat(2, minmax(0, 1fr)); } @@ -134,7 +145,7 @@ @media (max-width: 520px) { .top .title { display: none; } main { padding: 20px 16px 48px; } - .top-inner { padding: 12px 16px; } + .top-inner { padding: 12px 16px 0; } .measure .value { font-size: 28px; } .panel { padding: 16px; } .table-scroll { margin: 0 -16px; padding: 0 16px; } @@ -151,7 +162,7 @@
Holmes -

Downloads, installs, and people using Holmes.

+

Downloads, accounts, and installs for Holmes.

@@ -178,122 +189,146 @@ @@ -305,6 +340,8 @@

People

const DATABASE = 'holmes'; const ADMIN_TEAM = 'admins'; const RELEASES_API = 'https://api.github.com/repos/tryholmes/holmes-local/releases?per_page=100'; + const DAY = 86400000; + const CURRENT_WINDOW_DAYS = 30; const client = new Client().setEndpoint(ENDPOINT).setProject(PROJECT); const account = new Account(client); @@ -312,20 +349,23 @@

People

const teams = new Teams(client); const $ = (id) => document.getElementById(id); + const fmt = new Intl.NumberFormat('en-US'); + const dateFmt = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); + const dayFmt = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' }); + const escapeHTML = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const regionName = (() => { let names = null; try { names = new Intl.DisplayNames(['en'], { type: 'region' }); } catch {} return (code) => { if (!code) return 'Unknown'; - try { return names ? `${names.of(code.toUpperCase())}` : code; } catch { return code; } + try { return names ? names.of(String(code).toUpperCase()) : code; } catch { return code; } }; })(); - const fmt = new Intl.NumberFormat('en-US'); - const dateFmt = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); - const dayFmt = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' }); - const escapeHTML = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); - const state = { rangeDays: 30, regionSource: 'users', versionKey: 'macos_version', sort: { key: 'signed_up_at', dir: -1 }, search: '', data: null, pendingUserId: null }; + const state = { + view: 'downloads', rangeDays: 30, versionKey: 'macos_version', + sort: { key: 'signed_up_at', dir: -1 }, search: '', data: null, pendingUserId: null, + }; /* ---------- Sign in with an emailed code ---------- */ function setGateMessage(text, isError = false) { @@ -401,6 +441,7 @@

People

$('who').textContent = me.email; $('gate').hidden = true; $('app').hidden = false; + showView(location.hash.replace('#', '') || 'downloads'); await load(); } @@ -436,10 +477,10 @@

People

async function load() { $('updated').textContent = 'Loading…'; try { - const [downloads, installs, users, releases] = await Promise.all([ - allRows('downloads'), allRows('installs'), allRows('users'), releaseCounts(), + const [downloads, installs, users, signIns, releases] = await Promise.all([ + allRows('downloads'), allRows('installs'), allRows('users'), allRows('sign_ins'), releaseCounts(), ]); - state.data = { downloads, installs, users, releases }; + state.data = { downloads, installs, users, signIns, releases }; render(); $('updated').textContent = `Updated ${new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}`; } catch (err) { @@ -448,85 +489,159 @@

People

} } - /* ---------- Rendering ---------- */ - const since = () => state.rangeDays ? Date.now() - state.rangeDays * 86400000 : 0; + /* ---------- Helpers ---------- */ + const since = () => state.rangeDays ? Date.now() - state.rangeDays * DAY : 0; const stamp = (row, key) => Date.parse(row[key] ?? row.$createdAt); const inRange = (rows, key) => rows.filter((r) => stamp(r, key) >= since()); + const scopeText = () => state.rangeDays ? `In the last ${state.rangeDays} days` : 'All time'; - function render() { - const { downloads, installs, users, releases } = state.data; - const d = inRange(downloads, '$createdAt'); - const i = inRange(installs, 'first_seen'); - const u = inRange(users, 'signed_up_at'); - const scope = state.rangeDays ? `in the last ${state.rangeDays} days` : 'all time'; - - $('m-downloads').textContent = fmt.format(d.length); - $('m-downloads-sub').textContent = `Website clicks ${scope}`; - $('m-installs').textContent = fmt.format(i.length); - $('m-installs-sub').textContent = `${fmt.format(installs.length)} Macs all time`; - $('m-users').textContent = fmt.format(u.length); - $('m-users-sub').textContent = `${fmt.format(users.length)} accounts all time`; - const regions = new Set([...u, ...i].map((r) => r.region || r.country).filter(Boolean)); - $('m-regions').textContent = fmt.format(regions.size); - $('m-regions-sub').textContent = `From users and installs ${scope}`; - - renderActivity(d, i, u); - renderRegions(); - renderVersions(); - renderReleases(releases); - renderUsers(); + function tally(rows, pick, limit = 10, groupRest = true) { + const counts = new Map(); + rows.forEach((r) => { + const key = pick(r); + counts.set(key, (counts.get(key) ?? 0) + 1); + }); + const sorted = [...counts.entries()].map(([label, count]) => ({ label, count })).sort((a, b) => b.count - a.count); + if (sorted.length <= limit) return sorted; + if (!groupRest) return sorted.slice(0, limit); + const rest = sorted.slice(limit - 1).reduce((s, e) => s + e.count, 0); + return [...sorted.slice(0, limit - 1), { label: 'Other', count: rest }]; } - function renderBars(container, entries, total, emptyText, valueLabel = (n) => fmt.format(n)) { + function renderBars(container, entries, emptyText) { if (!entries.length) { container.innerHTML = `
${escapeHTML(emptyText)}
`; return; } - const max = Math.max(...entries.map((e) => e.count)); + const total = entries.reduce((s, e) => s + e.count, 0); + const max = Math.max(...entries.map((e) => e.count), 1); container.innerHTML = entries.map((e) => { const share = total ? Math.round((e.count / total) * 100) : 0; - return `
+ return `
${escapeHTML(e.label)} - ${valueLabel(e.count)} + ${fmt.format(e.count)}
`; }).join(''); } - function tally(rows, pick, limit = 10) { - const counts = new Map(); - rows.forEach((r) => { - const key = pick(r); - counts.set(key, (counts.get(key) ?? 0) + 1); - }); - const sorted = [...counts.entries()].map(([label, count]) => ({ label, count })).sort((a, b) => b.count - a.count); - if (sorted.length <= limit) return sorted; - const rest = sorted.slice(limit - 1).reduce((s, e) => s + e.count, 0); - return [...sorted.slice(0, limit - 1), { label: 'Other', count: rest }]; + function referrerLabel(raw) { + if (!raw) return 'Direct or unknown'; + try { return new URL(raw).hostname.replace(/^www\./, ''); } catch { return 'Direct or unknown'; } } - function renderRegions() { - const source = state.regionSource; - const key = source === 'downloads' ? '$createdAt' : source === 'installs' ? 'first_seen' : 'signed_up_at'; - const rows = inRange(state.data[source], key); - const entries = tally(rows, (r) => regionName(source === 'downloads' ? r.country : (r.region || r.country))); - renderBars($('regions'), entries, rows.length, `No ${source} with a region in this range yet.`); - } + // Daily line chart for one or more series that share one count axis. + function renderLineChart(svg, rowsBySeries) { + const tip = svg.parentElement.querySelector('.tooltip'); + const width = svg.clientWidth || 900, height = 260; + const pad = { top: 12, right: 18, bottom: 28, left: 36 }; + const allStamps = rowsBySeries.flatMap((s) => s.rows.map((r) => stamp(r, s.key))).filter((n) => Number.isFinite(n)); + const earliest = state.rangeDays ? since() : Math.min(Date.now() - 6 * DAY, ...(allStamps.length ? allStamps : [Date.now()])); + const start = new Date(earliest); start.setHours(0, 0, 0, 0); + const days = Math.max(2, Math.min(400, Math.ceil((Date.now() - start) / DAY))); + const series = rowsBySeries.map((s) => { + const values = new Array(days).fill(0); + s.rows.forEach((r) => { + const idx = Math.floor((stamp(r, s.key) - start) / DAY); + if (idx >= 0 && idx < days) values[idx] += 1; + }); + return { ...s, values }; + }); + const maxY = Math.max(4, ...series.flatMap((s) => s.values)); + const niceMax = Math.ceil(maxY / 4) * 4; + const x = (i) => pad.left + (i / (days - 1)) * (width - pad.left - pad.right); + const y = (v) => pad.top + (1 - v / niceMax) * (height - pad.top - pad.bottom); + const dayDate = (i) => new Date(start.getTime() + i * DAY); - function renderVersions() { - const k = state.versionKey; - const rows = inRange(state.data.installs, 'first_seen'); - const entries = tally(rows, (r) => r[k] ? (k === 'holmes_version' ? `Holmes ${r[k]}` : k === 'macos_version' ? `macOS ${r[k]}` : r[k]) : 'Unknown'); - renderBars($('versions'), entries, rows.length, 'No installs in this range yet.'); + let markup = ''; + for (let t = 0; t <= 4; t++) { + const v = (niceMax / 4) * t; + markup += ``; + markup += `${fmt.format(v)}`; + } + const ticks = Math.min(6, days); + for (let t = 0; t < ticks; t++) { + const i = Math.round((t / (ticks - 1)) * (days - 1)); + markup += `${dayFmt.format(dayDate(i))}`; + } + series.forEach((s) => { + const d = s.values.map((v, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' '); + markup += ``; + }); + markup += ``; + series.forEach((s, n) => { markup += ``; }); + markup += ``; + svg.setAttribute('viewBox', `0 0 ${width} ${height}`); + svg.innerHTML = markup; + svg.setAttribute('aria-label', series.map((s) => `${s.values.reduce((a, b) => a + b, 0)} ${s.name.toLowerCase()}`).join(', ')); + + const hit = svg.querySelector('.hit'); + hit.addEventListener('pointermove', (e) => { + const rect = svg.getBoundingClientRect(); + const px = ((e.clientX - rect.left) / rect.width) * width; + const i = Math.max(0, Math.min(days - 1, Math.round(((px - pad.left) / (width - pad.left - pad.right)) * (days - 1)))); + const cx = x(i); + const cross = svg.querySelector('.cross'); + cross.setAttribute('x1', cx); cross.setAttribute('x2', cx); cross.setAttribute('visibility', 'visible'); + series.forEach((s, n) => { + const dot = svg.querySelector(`.dot-${n}`); + dot.setAttribute('cx', cx); dot.setAttribute('cy', y(s.values[i])); dot.setAttribute('visibility', 'visible'); + }); + tip.innerHTML = `
${dateFmt.format(dayDate(i))}
` + series.map((s) => + `
${s.name}${fmt.format(s.values[i])}
`).join(''); + tip.hidden = false; + const left = (cx / width) * rect.width; + tip.style.left = `${Math.min(rect.width - tip.offsetWidth, Math.max(0, left + (left > rect.width / 2 ? -tip.offsetWidth - 14 : 14)))}px`; + tip.style.top = '16px'; + }); + hit.addEventListener('pointerleave', () => { + tip.hidden = true; + svg.querySelector('.cross').setAttribute('visibility', 'hidden'); + series.forEach((_, n) => svg.querySelector(`.dot-${n}`).setAttribute('visibility', 'hidden')); + }); } - function renderReleases(releases) { + /* ---------- Sections ---------- */ + function renderDownloads() { + const { downloads, releases } = state.data; + const clicks = inRange(downloads, '$createdAt'); + $('d-range').textContent = fmt.format(clicks.length); + $('d-range-sub').textContent = scopeText(); + $('d-total').textContent = fmt.format(downloads.length); + const countries = new Set(clicks.map((r) => r.country).filter(Boolean)); + $('d-countries').textContent = fmt.format(countries.size); + $('d-countries-sub').textContent = scopeText(); + renderLineChart($('d-chart'), [{ name: 'Clicks', color: 'var(--series-1)', rows: clicks, key: '$createdAt' }]); + renderBars($('d-countries-bars'), tally(clicks, (r) => regionName(r.country)), 'No clicks in this range yet.'); + renderBars($('d-referrers-bars'), tally(clicks, (r) => referrerLabel(r.referrer), 8), 'No clicks in this range yet.'); if (releases.error) { - $('releases').innerHTML = `
Couldn't reach GitHub: ${escapeHTML(releases.error)}
`; - return; + $('d-github').textContent = '0'; + $('d-releases-bars').innerHTML = `
Couldn't reach GitHub: ${escapeHTML(releases.error)}
`; + } else { + $('d-github').textContent = fmt.format(releases.reduce((s, r) => s + r.count, 0)); + renderBars($('d-releases-bars'), releases.map((r) => ({ label: r.tag, count: r.count })), 'No releases published yet.'); } - const total = releases.reduce((s, r) => s + r.count, 0); - renderBars($('releases'), releases.map((r) => ({ label: r.tag, count: r.count })), total, 'No releases published yet.'); + } + + function renderAccounts() { + const { users, signIns } = state.data; + const signups = inRange(users, 'signed_up_at'); + const signinRows = inRange(signIns, '$createdAt'); + const activeAccounts = new Set(signinRows.map((r) => r.user_id)); + $('a-total').textContent = fmt.format(users.length); + $('a-signups').textContent = fmt.format(signups.length); + $('a-signups-sub').textContent = scopeText(); + $('a-signins').textContent = fmt.format(signinRows.length); + $('a-signins-sub').textContent = `${fmt.format(activeAccounts.size)} accounts signed in`; + $('a-regions').textContent = fmt.format(new Set(users.map((u) => u.region || u.country).filter(Boolean)).size); + renderLineChart($('a-chart'), [ + { name: 'Sign ups', color: 'var(--series-3)', rows: signups, key: 'signed_up_at' }, + { name: 'Sign ins', color: 'var(--series-1)', rows: signinRows, key: '$createdAt' }, + ]); + renderBars($('a-regions-bars'), tally(users, (u) => regionName(u.region || u.country)), 'No accounts yet.'); + const emails = new Map(users.map((u) => [u.$id, u.email])); + renderBars($('a-active-bars'), tally(signinRows, (r) => emails.get(r.user_id) ?? 'Deleted account', 8, false), 'No sign ins in this range yet.'); + renderUsers(); } function renderUsers() { @@ -550,96 +665,72 @@

People

${date(r.last_sign_in_at)} ${fmt.format(r.sign_ins ?? 0)} `).join('') - : `${state.data.users.length ? 'Nobody matches that search.' : 'No one has signed in to Holmes yet.'}`; + : `${state.data.users.length ? 'Nobody matches that search.' : 'No one has signed up yet.'}`; } - function renderActivity(d, i, u) { - const svg = $('activity'); - const width = svg.clientWidth || 900, height = 280; - const pad = { top: 12, right: 18, bottom: 28, left: 36 }; - const earliest = state.rangeDays ? since() : Math.min(Date.now() - 6 * 86400000, ...[...d, ...i, ...u].map((r) => stamp(r, r.first_seen ? 'first_seen' : r.signed_up_at ? 'signed_up_at' : '$createdAt'))); - const start = new Date(earliest); start.setHours(0, 0, 0, 0); - const days = Math.max(2, Math.ceil((Date.now() - start) / 86400000)); - const bucket = (rows, key) => { - const counts = new Array(days).fill(0); - rows.forEach((r) => { - const idx = Math.floor((stamp(r, key) - start) / 86400000); - if (idx >= 0 && idx < days) counts[idx] += 1; - }); - return counts; - }; - const series = [ - { name: 'Downloads', color: 'var(--series-downloads)', values: bucket(d, '$createdAt') }, - { name: 'Installs', color: 'var(--series-installs)', values: bucket(i, 'first_seen') }, - { name: 'Sign ups', color: 'var(--series-users)', values: bucket(u, 'signed_up_at') }, - ]; - const maxY = Math.max(4, ...series.flatMap((s) => s.values)); - const niceMax = Math.ceil(maxY / 4) * 4; - const x = (idx) => pad.left + (idx / (days - 1)) * (width - pad.left - pad.right); - const y = (v) => pad.top + (1 - v / niceMax) * (height - pad.top - pad.bottom); - const dayDate = (idx) => new Date(start.getTime() + idx * 86400000); + const currentInstalls = () => state.data.installs.filter((r) => stamp(r, 'last_seen') >= Date.now() - CURRENT_WINDOW_DAYS * DAY); + + function renderInstalls() { + const { installs, users } = state.data; + const current = currentInstalls(); + const fresh = inRange(installs, 'first_seen'); + $('i-current').textContent = fmt.format(current.length); + $('i-new').textContent = fmt.format(fresh.length); + $('i-new-sub').textContent = scopeText(); + $('i-total').textContent = fmt.format(installs.length); + const linked = new Set(users.map((u) => u.install_id).filter(Boolean)); + const linkedCurrent = current.filter((r) => linked.has(r.$id)).length; + $('i-linked').textContent = fmt.format(linkedCurrent); + $('i-linked-sub').textContent = current.length ? `${Math.round((linkedCurrent / current.length) * 100)}% of current installs` : 'Of current installs'; + renderLineChart($('i-chart'), [{ name: 'New installs', color: 'var(--series-2)', rows: fresh, key: 'first_seen' }]); + renderBars($('i-regions-bars'), tally(current, (r) => regionName(r.region || r.country)), 'No current installs yet.'); + renderVersions(); + } - let markup = ''; - for (let t = 0; t <= 4; t++) { - const v = (niceMax / 4) * t; - markup += ``; - markup += `${fmt.format(v)}`; - } - const ticks = Math.min(6, days); - for (let t = 0; t < ticks; t++) { - const idx = Math.round((t / (ticks - 1)) * (days - 1)); - markup += `${dayFmt.format(dayDate(idx))}`; - } - series.forEach((s) => { - const path = s.values.map((v, idx) => `${idx ? 'L' : 'M'}${x(idx).toFixed(1)},${y(v).toFixed(1)}`).join(' '); - markup += ``; - }); - markup += ``; - series.forEach((s, n) => { markup += ``; }); - markup += ``; - svg.setAttribute('viewBox', `0 0 ${width} ${height}`); - svg.innerHTML = markup; - svg.setAttribute('aria-label', `Daily activity: ${series.map((s) => `${s.values.reduce((a, b) => a + b, 0)} ${s.name.toLowerCase()}`).join(', ')}`); + function renderVersions() { + const k = state.versionKey; + const label = (r) => r[k] ? (k === 'holmes_version' ? `Holmes ${r[k]}` : k === 'macos_version' ? `macOS ${r[k]}` : r[k]) : 'Unknown'; + renderBars($('i-versions-bars'), tally(currentInstalls(), label), 'No current installs yet.'); + } - const tip = $('activity-tip'); - const hit = svg.querySelector('#hit'); - const move = (clientX) => { - const rect = svg.getBoundingClientRect(); - const px = ((clientX - rect.left) / rect.width) * width; - const idx = Math.max(0, Math.min(days - 1, Math.round(((px - pad.left) / (width - pad.left - pad.right)) * (days - 1)))); - const cx = x(idx); - const cross = svg.querySelector('#cross'); - cross.setAttribute('x1', cx); cross.setAttribute('x2', cx); cross.setAttribute('visibility', 'visible'); - series.forEach((s, n) => { - const dot = svg.querySelector(`#dot-${n}`); - dot.setAttribute('cx', cx); dot.setAttribute('cy', y(s.values[idx])); dot.setAttribute('visibility', 'visible'); - }); - tip.innerHTML = `
${dateFmt.format(dayDate(idx))}
` + series.map((s) => - `
${s.name}${fmt.format(s.values[idx])}
`).join(''); - tip.hidden = false; - const left = (cx / width) * rect.width; - tip.style.left = `${Math.min(rect.width - tip.offsetWidth, Math.max(0, left + (left > rect.width / 2 ? -tip.offsetWidth - 14 : 14)))}px`; - tip.style.top = '16px'; - }; - const leave = () => { - tip.hidden = true; - svg.querySelector('#cross')?.setAttribute('visibility', 'hidden'); - series.forEach((_, n) => svg.querySelector(`#dot-${n}`)?.setAttribute('visibility', 'hidden')); - }; - hit.addEventListener('pointermove', (e) => move(e.clientX)); - hit.addEventListener('pointerleave', leave); + function render() { + if (!state.data) return; + const { downloads, users } = state.data; + $('tab-count-downloads').textContent = fmt.format(inRange(downloads, '$createdAt').length); + $('tab-count-accounts').textContent = fmt.format(users.length); + $('tab-count-installs').textContent = fmt.format(currentInstalls().length); + if (state.view === 'downloads') renderDownloads(); + if (state.view === 'accounts') renderAccounts(); + if (state.view === 'installs') renderInstalls(); + } + + function showView(view) { + if (!['downloads', 'accounts', 'installs'].includes(view)) view = 'downloads'; + state.view = view; + document.querySelectorAll('[data-view]').forEach((tab) => { + const selected = tab.dataset.view === view; + tab.setAttribute('aria-selected', String(selected)); + tab.tabIndex = selected ? 0 : -1; + $(`view-${tab.dataset.view}`).hidden = !selected; + }); + if (location.hash !== `#${view}`) history.replaceState(null, '', `#${view}`); + render(); } /* ---------- Controls ---------- */ + document.querySelectorAll('[data-view]').forEach((tab, index, all) => { + tab.addEventListener('click', () => showView(tab.dataset.view)); + tab.addEventListener('keydown', (e) => { + if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return; + const next = all[(index + (e.key === 'ArrowRight' ? 1 : all.length - 1)) % all.length]; + next.focus(); + showView(next.dataset.view); + }); + }); document.querySelectorAll('[data-range]').forEach((btn) => btn.addEventListener('click', () => { state.rangeDays = Number(btn.dataset.range); document.querySelectorAll('[data-range]').forEach((b) => b.setAttribute('aria-pressed', String(b === btn))); - if (state.data) render(); - })); - document.querySelectorAll('[data-region]').forEach((btn) => btn.addEventListener('click', () => { - state.regionSource = btn.dataset.region; - document.querySelectorAll('[data-region]').forEach((b) => b.setAttribute('aria-pressed', String(b === btn))); - if (state.data) renderRegions(); + render(); })); document.querySelectorAll('[data-version]').forEach((btn) => btn.addEventListener('click', () => { state.versionKey = btn.dataset.version; @@ -658,12 +749,13 @@

People

const csv = [cols.join(',')].concat(state.data.users.map((r) => cols.map((c) => `"${String(r[c] ?? '').replace(/"/g, '""')}"`).join(','))).join('\n'); const link = document.createElement('a'); link.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' })); - link.download = `holmes-users-${new Date().toISOString().slice(0, 10)}.csv`; + link.download = `holmes-accounts-${new Date().toISOString().slice(0, 10)}.csv`; link.click(); URL.revokeObjectURL(link.href); }); + window.addEventListener('hashchange', () => showView(location.hash.replace('#', ''))); let resizeTimer; - window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => state.data && render(), 150); }); + window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(render, 150); }); /* ---------- Start ---------- */ enter().catch(() => showGate()); diff --git a/holmes/cloud/functions/track/src/main.js b/holmes/cloud/functions/track/src/main.js index 593fe61..736b29f 100644 --- a/holmes/cloud/functions/track/src/main.js +++ b/holmes/cloud/functions/track/src/main.js @@ -1,4 +1,4 @@ -import { Client, TablesDB, Users } from 'node-appwrite'; +import { Client, TablesDB, Users, ID } from 'node-appwrite'; // Holmes calls this on launch ("install") and after signing in ("signin"). // The email always comes from the verified Appwrite account, never the body. @@ -16,7 +16,8 @@ const clip = (value, max) => { async function countryFor(headers) { const known = clip(headers['x-appwrite-country-code'], 8); if (known) return known.toUpperCase(); - const ip = String(headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + const ip = String(headers['fastly-client-ip'] ?? headers['x-cdn-client-ip'] ?? headers['x-real-ip'] + ?? headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); if (!ip) return null; try { const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(1500) }); @@ -101,15 +102,33 @@ export default async ({ req, res, error }) => { if (event === 'signin') { const user = await new Users(client).get(userId); - await upsert(db, 'users', userId, (existing) => ({ - ...device, - email: clip(user.email, 320), - name: clip(user.name, 128), - install_id: installId, - last_sign_in_at: now, - sign_ins: (existing?.sign_ins ?? 0) + 1, - ...(existing ? {} : { signed_up_at: user.$createdAt ?? now }), - })); + let isNewAccount = false; + await upsert(db, 'users', userId, (existing) => { + isNewAccount = !existing; + return { + ...device, + email: clip(user.email, 320), + name: clip(user.name, 128), + install_id: installId, + last_sign_in_at: now, + sign_ins: (existing?.sign_ins ?? 0) + 1, + ...(existing ? {} : { signed_up_at: user.$createdAt ?? now }), + }; + }); + // One row per sign in, so the dashboard can chart sign ins per day. + await db.createRow({ + databaseId: DATABASE_ID, + tableId: 'sign_ins', + rowId: ID.unique(), + data: { + user_id: userId, + new_account: isNewAccount, + region: device.region, + country: device.country, + holmes_version: device.holmes_version, + macos_version: device.macos_version, + }, + }); } return res.json({ ok: true });