Skip to content

Commit ee9a0c5

Browse files
ampagenttmm
andcommitted
feat(zbugs-swift): the zbugs app for iOS and macOS
ZBugsUI has the app's screens: the issue list with zbugs' filters and sorts, issue detail with comments, and creating, editing, closing, and commenting, all through the ported queries and mutators. The list also comes in UIKit and AppKit through DiffableAdapter, picked in the sidebar. Login takes a zbugs JWT, from the GitHub login through a web authentication session or from `pnpm dev-token`, and keeps it in the keychain. App/ is an XcodeGen project with one multiplatform target, which macOS CI builds for the iOS simulator and macOS. Amp-Thread-ID: https://ampcode.com/threads/T-c513a037-a257-45e0-b9a9-15c15edfe859 Co-authored-by: tmm <tmm@tmm.dev>
1 parent ba63b8e commit ee9a0c5

14 files changed

Lines changed: 1154 additions & 1 deletion

File tree

‎.github/workflows/swift-macos.yml‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ jobs:
3131
macos:
3232
name: Swift (macOS)
3333
runs-on: macos-26
34+
timeout-minutes: 45
3435
defaults:
3536
run:
3637
working-directory: swift
@@ -46,3 +47,33 @@ jobs:
4647
device="$(xcrun simctl list devices available -j |
4748
python3 -c 'import json,sys; d=json.load(sys.stdin)["devices"]; print(next(x["udid"] for k,v in d.items() if "iOS" in k for x in v if x["name"].startswith("iPhone")))')"
4849
xcodebuild test -scheme Zero-Package -destination "id=$device" -skipPackagePluginValidation
50+
51+
zbugs:
52+
name: zbugs app (iOS and macOS)
53+
runs-on: macos-26
54+
timeout-minutes: 45
55+
defaults:
56+
run:
57+
working-directory: apps/zbugs-swift
58+
steps:
59+
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
60+
with:
61+
persist-credentials: false
62+
# The drift test again, and ZBugsUI (empty on Linux) for macOS.
63+
- name: Build and test (macOS)
64+
run: swift test
65+
- name: Generate the Xcode project
66+
working-directory: apps/zbugs-swift/App
67+
run: brew install xcodegen && xcodegen generate
68+
- name: Build the app (iOS Simulator)
69+
working-directory: apps/zbugs-swift/App
70+
run: >-
71+
xcodebuild build -project ZBugs.xcodeproj -scheme ZBugsApp
72+
-destination 'generic/platform=iOS Simulator'
73+
-skipPackagePluginValidation CODE_SIGNING_ALLOWED=NO
74+
- name: Build the app (macOS)
75+
working-directory: apps/zbugs-swift/App
76+
run: >-
77+
xcodebuild build -project ZBugs.xcodeproj -scheme ZBugsApp
78+
-destination 'generic/platform=macOS'
79+
-skipPackagePluginValidation CODE_SIGNING_ALLOWED=NO

‎apps/zbugs-swift/.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
.swiftpm/
33
*.xcodeproj/xcuserdata/
44
Package.resolved
5+
App/*.xcodeproj/

‎apps/zbugs-swift/App/Info.plist‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<!-- A development app: zero-cache and the zbugs API often run on plain HTTP. -->
6+
<key>NSAppTransportSecurity</key>
7+
<dict>
8+
<key>NSAllowsArbitraryLoads</key>
9+
<true/>
10+
<key>NSAllowsLocalNetworking</key>
11+
<true/>
12+
</dict>
13+
</dict>
14+
</plist>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import SwiftUI
2+
import ZBugsUI
3+
4+
@main
5+
struct ZBugsApp: App {
6+
var body: some Scene {
7+
WindowGroup {
8+
RootView()
9+
}
10+
}
11+
}

‎apps/zbugs-swift/App/project.yml‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# The zbugs app for iOS and macOS. Generate the Xcode project with
2+
# XcodeGen (`brew install xcodegen`): `xcodegen generate`, then open
3+
# ZBugs.xcodeproj.
4+
name: ZBugs
5+
options:
6+
bundleIdPrefix: dev.rocicorp
7+
deploymentTarget:
8+
iOS: "26.0"
9+
macOS: "26.0"
10+
packages:
11+
ZBugs:
12+
path: ..
13+
targets:
14+
ZBugsApp:
15+
type: application
16+
supportedDestinations: [iOS, macOS]
17+
sources:
18+
- path: ZBugsApp.swift
19+
- path: Info.plist
20+
buildPhase: none
21+
dependencies:
22+
- package: ZBugs
23+
product: ZBugsUI
24+
settings:
25+
base:
26+
PRODUCT_NAME: ZBugs
27+
PRODUCT_BUNDLE_IDENTIFIER: dev.rocicorp.zbugs
28+
SWIFT_VERSION: "6.0"
29+
GENERATE_INFOPLIST_FILE: YES
30+
INFOPLIST_FILE: Info.plist
31+
INFOPLIST_KEY_CFBundleDisplayName: Zero Bugs
32+
INFOPLIST_KEY_UILaunchScreen_Generation: YES
33+
INFOPLIST_KEY_UIApplicationSceneManifest_Generation: YES
34+
INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-tools
35+
TARGETED_DEVICE_FAMILY: "1,2"
36+
CODE_SIGN_STYLE: Automatic
37+
ENABLE_USER_SCRIPT_SANDBOXING: YES

‎apps/zbugs-swift/Package.swift‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,30 @@ let package = Package(
77
name: "ZBugs",
88
platforms: [.iOS(.v26), .macOS(.v26)],
99
products: [
10-
.library(name: "ZBugs", targets: ["ZBugs"])
10+
.library(name: "ZBugs", targets: ["ZBugs"]),
11+
// The app's screens; the Xcode project in App/ wraps them in an app.
12+
.library(name: "ZBugsUI", targets: ["ZBugsUI"]),
1113
],
1214
dependencies: [
1315
.package(name: "Zero", path: "../../swift")
1416
],
1517
targets: [
1618
.target(name: "ZBugs", dependencies: [.product(name: "Zero", package: "Zero")]),
19+
// SwiftUI, with a UIKit or AppKit list; empty where there is no SwiftUI.
20+
.target(
21+
name: "ZBugsUI",
22+
dependencies: [
23+
"ZBugs",
24+
.product(name: "Zero", package: "Zero"),
25+
.product(name: "ZeroUI", package: "Zero"),
26+
]),
1727
.testTarget(
1828
name: "ZBugsTests",
1929
dependencies: [
2030
"ZBugs",
2131
.product(name: "Zero", package: "Zero"),
2232
.product(name: "ZeroTesting", package: "Zero"),
33+
.product(name: "ZeroNIOTesting", package: "Zero"),
2334
],
2435
exclude: ["drift-vectors.json"]),
2536
],

‎apps/zbugs-swift/Sources/ZBugs/Auth.swift‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,52 @@ func assertUserCanSeeComment(_ tx: Transaction, _ userID: String, _ commentID: S
8989
let comment = try must(tx.run(zql.comment.where(\.id, commentID).one()))
9090
try assertUserCanSeeIssue(tx, userID, comment.issueID)
9191
}
92+
93+
extension AuthData {
94+
/// The claims of a zbugs JWT, without checking its signature (the API
95+
/// server checks it): nil when `jwt` is not one, or has expired by `now`
96+
/// (seconds since 1970).
97+
public init?(jwt: String, now: Double) {
98+
let parts = jwt.split(separator: ".", omittingEmptySubsequences: false)
99+
guard parts.count == 3, let payload = base64URLDecode(parts[1]),
100+
let claims = try? JSONParser.parse(payload),
101+
let sub = claims["sub"]?.stringValue,
102+
let role = claims["role"]?.stringValue.flatMap(UserRole.init(rawValue:))
103+
else { return nil }
104+
if let exp = claims["exp"]?.numberValue, exp < now { return nil }
105+
self.init(sub: sub, role: role)
106+
}
107+
}
108+
109+
/// RFC 4648 §5 base64url, padded or not.
110+
private func base64URLDecode(_ s: Substring) -> [UInt8]? {
111+
var bits: UInt32 = 0
112+
var count = 0
113+
var out: [UInt8] = []
114+
for c in s.utf8 {
115+
let v: UInt32
116+
switch c {
117+
case UInt8(ascii: "A")...UInt8(ascii: "Z"): v = UInt32(c - UInt8(ascii: "A"))
118+
case UInt8(ascii: "a")...UInt8(ascii: "z"): v = UInt32(c - UInt8(ascii: "a")) + 26
119+
case UInt8(ascii: "0")...UInt8(ascii: "9"): v = UInt32(c - UInt8(ascii: "0")) + 52
120+
case UInt8(ascii: "-"), UInt8(ascii: "+"): v = 62
121+
case UInt8(ascii: "_"), UInt8(ascii: "/"): v = 63
122+
case UInt8(ascii: "="): continue
123+
default: return nil
124+
}
125+
bits = bits << 6 | v
126+
count += 6
127+
if count >= 8 {
128+
count -= 8
129+
out.append(UInt8(truncatingIfNeeded: bits >> UInt32(count)))
130+
}
131+
}
132+
return out
133+
}
134+
135+
/// A new row ID, as zbugs makes them (`nanoid`): 21 URL-safe characters.
136+
public func makeID() -> String {
137+
let alphabet = Array("useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict")
138+
var rng = SystemRandomNumberGenerator()
139+
return String((0..<21).map { _ in alphabet[Int(rng.next() % 64)] })
140+
}
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
#if canImport(SwiftUI)
2+
import Foundation
3+
import Observation
4+
import Security
5+
import ZBugs
6+
import Zero
7+
8+
/// The app's state outside its views: where the servers are, who is
9+
/// logged in, and the client for them.
10+
@Observable
11+
@MainActor
12+
public final class AppModel {
13+
/// zero-cache.
14+
public private(set) var cacheURL: String
15+
/// The zbugs API server: login, and the queries and mutators zero-cache
16+
/// forwards.
17+
public private(set) var apiURL: String
18+
public private(set) var auth: AuthData?
19+
/// A new client whenever the servers or the user change, as zbugs'
20+
/// `ZeroProvider` makes one.
21+
public private(set) var zero: Zero<AuthData?>
22+
@ObservationIgnored private var token: String?
23+
private let defaults: UserDefaults
24+
25+
public static let projectName = zeroProjectName
26+
27+
public init(defaults: UserDefaults = .standard) {
28+
self.defaults = defaults
29+
let cacheURL = defaults.string(forKey: "cacheURL") ?? "http://localhost:4848"
30+
let apiURL = defaults.string(forKey: "apiURL") ?? "http://localhost:5173"
31+
// An expired token logs out.
32+
let auth = Keychain.token.flatMap { AuthData(jwt: $0, now: Date().timeIntervalSince1970) }
33+
let token = auth == nil ? nil : Keychain.token
34+
self.cacheURL = cacheURL
35+
self.apiURL = apiURL
36+
self.token = token
37+
self.auth = auth
38+
zero = Self.makeZero(cacheURL: cacheURL, apiURL: apiURL, token: token, auth: auth)
39+
preload()
40+
}
41+
42+
/// Logs in with a zbugs JWT, from the GitHub login or a dev token.
43+
public func logIn(token: String) throws {
44+
let token = token.trimmingCharacters(in: .whitespacesAndNewlines)
45+
guard let auth = AuthData(jwt: token, now: Date().timeIntervalSince1970) else {
46+
throw LoginError("That is not a current zbugs token.")
47+
}
48+
Keychain.token = token
49+
self.token = token
50+
self.auth = auth
51+
restart()
52+
}
53+
54+
public func logOut() {
55+
Keychain.token = nil
56+
token = nil
57+
auth = nil
58+
restart()
59+
}
60+
61+
public func setServers(cacheURL: String, apiURL: String) {
62+
defaults.set(cacheURL, forKey: "cacheURL")
63+
defaults.set(apiURL, forKey: "apiURL")
64+
self.cacheURL = cacheURL
65+
self.apiURL = apiURL
66+
restart()
67+
}
68+
69+
/// Why the last mutation failed, for an alert; nil once seen.
70+
public var mutationError: String?
71+
72+
/// Runs a mutator and reports its failure, on the client or the server.
73+
public func mutate(_ request: MutateRequest<AuthData?>) {
74+
let result = zero.mutate(request)
75+
if case .success(let outcome)? = result.client.result, let message = outcome.errorMessage {
76+
mutationError = message
77+
return
78+
}
79+
Task { [weak self] in
80+
if let message = try? await result.server.value.errorMessage {
81+
self?.mutationError = message
82+
}
83+
}
84+
}
85+
86+
/// The URL that starts the GitHub login and ends at `callbackScheme`
87+
/// with the token.
88+
public var loginURL: URL? {
89+
var c = URLComponents(string: apiURL + "/api/login/github")
90+
c?.queryItems = [URLQueryItem(name: "redirect", value: "\(Self.callbackScheme)://auth")]
91+
return c?.url
92+
}
93+
94+
public static let callbackScheme = "zbugs-swift"
95+
96+
private func restart() {
97+
zero.close()
98+
zero = Self.makeZero(cacheURL: cacheURL, apiURL: apiURL, token: token, auth: auth)
99+
preload()
100+
}
101+
102+
/// What zbugs preloads: the project's issues with their first comments,
103+
/// and the users, labels, and projects.
104+
private func preload() {
105+
let ttl = TTL.seconds(10)
106+
_ = zero.preload(
107+
Queries.issuePreloadV2(ProjectArgs(projectName: Self.projectName)), ttl: ttl)
108+
_ = zero.preload(Queries.allUsers(), ttl: ttl)
109+
_ = zero.preload(Queries.allLabels(), ttl: ttl)
110+
_ = zero.preload(Queries.allProjects(), ttl: ttl)
111+
}
112+
113+
private static func makeZero(
114+
cacheURL: String, apiURL: String, token: String?, auth: AuthData?
115+
) -> Zero<AuthData?> {
116+
var options = ZeroOptions(cacheURL: cacheURL, userID: auth?.sub, auth: token)
117+
options.mutateURL = apiURL + "/api/mutate"
118+
options.queryURL = apiURL + "/api/query"
119+
options.logLevel = .info
120+
do {
121+
return try Zero(schema: .zbugs, context: auth, mutators: Mutators.all, options: options)
122+
} catch {
123+
// Only a mutator registered twice fails; storage falls back to
124+
// memory on its own.
125+
preconditionFailure("zbugs' mutators: \(error)")
126+
}
127+
}
128+
}
129+
130+
extension MutationOutcome {
131+
var errorMessage: String? {
132+
switch self {
133+
case .success: nil
134+
case .appError(let message, _), .zeroError(let message): message
135+
}
136+
}
137+
}
138+
139+
public struct LoginError: Error, CustomStringConvertible {
140+
public let description: String
141+
init(_ description: String) { self.description = description }
142+
}
143+
144+
/// The token in the keychain, so it outlives the app.
145+
enum Keychain {
146+
private static var query: [String: Any] {
147+
[
148+
kSecClass as String: kSecClassGenericPassword,
149+
kSecAttrService as String: "dev.rocicorp.zbugs",
150+
kSecAttrAccount as String: "jwt",
151+
]
152+
}
153+
154+
static var token: String? {
155+
get {
156+
var q = query
157+
q[kSecReturnData as String] = true
158+
var item: CFTypeRef?
159+
guard SecItemCopyMatching(q as CFDictionary, &item) == errSecSuccess,
160+
let data = item as? Data
161+
else { return nil }
162+
return String(data: data, encoding: .utf8)
163+
}
164+
set {
165+
SecItemDelete(query as CFDictionary)
166+
guard let newValue else { return }
167+
var q = query
168+
q[kSecValueData as String] = Data(newValue.utf8)
169+
SecItemAdd(q as CFDictionary, nil)
170+
}
171+
}
172+
}
173+
#endif

0 commit comments

Comments
 (0)