native: EquipoKit for slice 1: client, pairing, session, Roster
The person API client (bearer only, idempotent writes kept until settled), device pairing with the server's own proof bytes (a Go-owned vector file), the session (coalesced refresh, notification polling with acknowledgements, sending and answering) and Roster's presentation from API data only. 30 Swift tests; fixtures checked against the OpenAPI schema.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
52 files changed,
+4,078
−0
docs/superpowers/plans/2026-11-18-equipo-native-slice-1.md+95 −0internal/equipo/personapi/device_proof_vector_test.go+92 −0native/.gitignore+5 −0native/apple/Package.resolved+23 −0native/apple/Package.swift+33 −0native/apple/Sources/EquipoKit/API/Client.swift+124 −0native/apple/Sources/EquipoKit/API/Errors.swift+28 −0native/apple/Sources/EquipoKit/API/Models.swift+228 −0native/apple/Sources/EquipoKit/API/Transport.swift+100 −0native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift+47 −0native/apple/Sources/EquipoKit/Pairing/DeviceProof.swift+88 −0native/apple/Sources/EquipoKit/Pairing/Pairing.swift+126 −0native/apple/Sources/EquipoKit/Pairing/SecretStore.swift+51 −0native/apple/Sources/EquipoKit/Presentation/Roster.swift+150 −0native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift+19 −0native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings+5 −0native/apple/Sources/EquipoKit/Session/EquipoSession.swift+285 −0native/apple/Sources/EquipoKit/UI/Components.swift+105 −0native/apple/Sources/EquipoKit/UI/Controls.swift+88 −0native/apple/Sources/EquipoKit/UI/LiveCards.swift+151 −0native/apple/Sources/EquipoKit/UI/RosterViews.swift+473 −0native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift+32 −0native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift+54 −0native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift+122 −0native/apple/Sources/EquipoKit/UI/Screens/PairingView.swift+111 −0native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift+74 −0native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift+194 −0native/apple/Sources/EquipoKit/UI/Theme.swift+243 −0native/apple/Sources/EquipoMac/main.swift+5 −0native/apple/Tests/EquipoKitTests/ClientTests.swift+88 −0native/apple/Tests/EquipoKitTests/DeviceProofTests.swift+49 −0native/apple/Tests/EquipoKitTests/Fixtures/ack.json+3 −0native/apple/Tests/EquipoKitTests/Fixtures/conversation.json+67 −0native/apple/Tests/EquipoKitTests/Fixtures/device-challenge.json+9 −0native/apple/Tests/EquipoKitTests/Fixtures/device-credential.json+7 −0native/apple/Tests/EquipoKitTests/Fixtures/device-proof-vectors.json+24 −0native/apple/Tests/EquipoKitTests/Fixtures/devices.json+15 −0native/apple/Tests/EquipoKitTests/Fixtures/error-pending.json+5 −0native/apple/Tests/EquipoKitTests/Fixtures/error-revision-conflict.json+6 −0native/apple/Tests/EquipoKitTests/Fixtures/me.json+11 −0native/apple/Tests/EquipoKitTests/Fixtures/message.json+12 −0native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json+67 −0native/apple/Tests/EquipoKitTests/Fixtures/notifications.json+24 −0native/apple/Tests/EquipoKitTests/Fixtures/projects.json+28 −0native/apple/Tests/EquipoKitTests/Fixtures/question.json+23 −0native/apple/Tests/EquipoKitTests/Fixtures/subscription.json+8 −0native/apple/Tests/EquipoKitTests/Fixtures/tasks.json+108 −0native/apple/Tests/EquipoKitTests/Fixtures/thread.json+31 −0native/apple/Tests/EquipoKitTests/PairingTests.swift+71 −0native/apple/Tests/EquipoKitTests/SessionTests.swift+160 −0native/apple/Tests/EquipoKitTests/Support.swift+41 −0native/scripts/check-fixtures.py+70 −0
diff --git a/docs/superpowers/plans/2026-11-18-equipo-native-slice-1.md b/docs/superpowers/plans/2026-11-18-equipo-native-slice-1.md| new file mode 100644 |
| index 00000000..16ce6f66 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-18-equipo-native-slice-1.md |
| @@ -0,0 +1,95 @@ |
| +# Equipo native, slice 1 (plan, 2026-11-18) |
| + |
| +Paul approved building the first production slice of Equipo for iPhone and Mac |
| +on 2026-11-18, with three defaults: Equipo's own device pairing behind a |
| +sign-in interface (Oficina ID later), rastrillo/native's toolchain, and a |
| +Developer ID Mac build with Sparkle plus an iPhone build run from Xcode. The |
| +design is revision 7 of the mockups on `native-mockups-r4` |
| +(`docs/native/r7/index.md`) and the web-led sync proposal |
| +(`docs/native/sync-proposal.md`). The web leads; native follows its parity |
| +rows. |
| + |
| +## What a person can do |
| + |
| +1. Pair the device: the app shows a code, opens the team in the browser, and |
| + waits while the person approves it there. The credential lives in the |
| + Keychain for its thirty days. Sign out revokes the device. |
| +2. Read the conversation and send messages. Answer questions in their cards, |
| + with an option or in their own words when the question allows text. |
| +3. Needs you, Tasks and the task view with its steps, usage and its thread |
| + ("Talk about this"), which can be read and replied to. |
| +4. New activity arrives by polling the device's notification subscription, |
| + with a periodic refresh as the fallback. Offline is shown, never hidden. |
| + |
| +## What waits |
| + |
| +- Merges, approvals, Contra and every other decision card open the web app, |
| + until each has an accepted parity row (sync proposal, "must match"). |
| +- Set aside, the live activity line, the roll-up, stages, Checks, Review and |
| + Branch facts wait for the person API fields in `roster-gaps.json`. Where a |
| + field is missing, the native view leaves it out; it never invents it. |
| +- Push notifications (APNs), Oficina ID, several teams at once, TestFlight. |
| + |
| +## Shape |
| + |
| +``` |
| +native/ |
| + apple/ SwiftPM: EquipoKit (library), EquipoMac (executable), tests |
| + ios/project.yml XcodeGen: EquipoPhone, the iPhone app |
| + mac-updates.json Sparkle settings for rastrillo's bundle-mac.py |
| + scripts/ check-native.sh, build-mac.sh, build-iphone.sh |
| +``` |
| + |
| +Pinned to rastrillo/native `f1c7a14` (the revision Docs uses). Deployment |
| +targets iOS 26 and macOS 26, as Docs. Bundle ID `works.oficina.equipo`; |
| +"Oficina Equipo" in Finder, the Dock and Spotlight and "Equipo" inside the |
| +app (the native level-up's D1 and D2). |
| + |
| +EquipoKit owns: |
| + |
| +- **Transport.** URLSession, ephemeral, no cookies, no cache, no redirects. |
| + Bearer only, never mixed with a browser cookie. Every write carries an |
| + `Idempotency-Key` kept with its body and revision until the result is known; |
| + a retry resends the same three. Responses are bounded. Outcomes are reported |
| + to RastrilloApple's `NativeConnectivity` so its offline banner works. |
| +- **Errors.** The person API's `code`, `copy_key`, `request_id` and |
| + `current_revision`. 401 ends the session; 409 `revision_conflict` refetches |
| + before any new decision; 410 restarts what the API says to restart. |
| +- **Pairing.** Curve25519 (Ed25519) key generated on the device and kept in |
| + the Keychain, `ThisDeviceOnly`. The proof message is the server's own |
| + `personapi.DeviceProofMessage`; a Go test owns a vector file that the Swift |
| + tests must reproduce byte for byte. Poll every five seconds at least, slow |
| + down on 429, start again on 410. |
| +- **Models.** Hand-written Codable for the operations above, checked against |
| + `docs/api/equipo-v1.openapi.json` by `native/scripts/check-fixtures.py` |
| + (fixtures validate against the schema; no invented fields). Null counts and |
| + usage stay unknown, never zero. |
| +- **Sync.** One `CoalescedRunner` per refresh; conversation, needs-you and |
| + tasks reconciled by ID and revision; notification subscription polling with |
| + deduplication by ID and acknowledgement with the subscription revision. |
| +- **Presentation.** Roster from r7 (bylines, raised cards, tone rules), fed |
| + only from API data. |
| + |
| +Locale: dates and times use `Date.FormatStyle` in the reader's locale; |
| +token counts use the locale's number format. Storage and every request stay |
| +canonical (ISO dates, integers). Slice 1 shows no money. |
| + |
| +Copy: native strings live in one String Catalog, English, and are draft |
| +until the copy review. Where the web already has a string (`copy.go`), the |
| +native one uses the same words. |
| + |
| +## Gates |
| + |
| +- `native/scripts/check-native.sh`: Swift tests, the fixture check, the Mac |
| + executable and an unsigned iPhone Simulator build. Runs on a Mac. |
| +- Go: the proof vector test runs inside `make test`, on Linux CI. |
| +- An end-to-end pairing against a local Equipo on 127.0.0.1 before review. |
| +- Mutations of the guards that matter (idempotency reuse, revision on |
| + answers, unknown counts, proof bytes, polling floor) each fail a test. |
| +- One Fable review of the whole branch. Paul lands it. |
| + |
| +## Steps for Paul |
| + |
| +- A Developer ID provisioning profile for `works.oficina.equipo`, and the |
| + Sparkle feed under `native-releases/equipo` when there is something to ship. |
| +- Approving the first device in the browser. |
diff --git a/internal/equipo/personapi/device_proof_vector_test.go b/internal/equipo/personapi/device_proof_vector_test.go| new file mode 100644 |
| index 00000000..9c73a0e9 |
| --- /dev/null |
| +++ b/internal/equipo/personapi/device_proof_vector_test.go |
| @@ -0,0 +1,92 @@ |
| +package personapi |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +// The native apps sign DeviceProofMessage themselves (native/apple, |
| +// EquipoKit's DeviceProof). This file is the server's word on those bytes: |
| +// the Swift tests must reproduce each message exactly and verify each |
| +// signature. Regenerate with EQUIPO_UPDATE_NATIVE_VECTOR=1. |
| +const nativeProofVectorPath = "../../../native/apple/Tests/EquipoKitTests/Fixtures/device-proof-vectors.json" |
| + |
| +type nativeProofVector struct { |
| + Name string `json:"name"` |
| + Seed string `json:"seed"` |
| + PublicKey string `json:"public_key"` |
| + Instance string `json:"instance"` |
| + ID string `json:"id"` |
| + Challenge string `json:"challenge"` |
| + Nonce string `json:"nonce"` |
| + Message string `json:"message"` |
| + Signature string `json:"signature"` |
| +} |
| + |
| +func nativeProofVectors() []nativeProofVector { |
| + enc := base64.RawURLEncoding |
| + challenge := func(instance string) string { |
| + b, _ := json.Marshal([]string{instance, "Q4J7XRZ2M3KP6TBN"}) |
| + return enc.EncodeToString(b) |
| + } |
| + in := []nativeProofVector{ |
| + {Name: "plain", Instance: "inst_7f3a9c", ID: "dev_01JD5Z4Q2X", Nonce: "nPq-7_Rs0tUvWxYz12345A"}, |
| + // Go escapes <, > and & and leaves / alone; Swift's encoders differ on |
| + // both, so the native side must build the array itself. |
| + {Name: "escapes", Instance: "a/b<c>&d é ", ID: "dev_\"quoted\"\\", Nonce: "n/o<n>&ce"}, |
| + } |
| + for i := range in { |
| + seed := make([]byte, ed25519.SeedSize) |
| + for j := range seed { |
| + seed[j] = byte(i*31 + j) |
| + } |
| + key := ed25519.NewKeyFromSeed(seed) |
| + p := PersonDeviceProof{ID: in[i].ID, Challenge: challenge(in[i].Instance), Nonce: in[i].Nonce} |
| + msg := DeviceProofMessage(in[i].Instance, p) |
| + in[i].Seed = enc.EncodeToString(seed) |
| + in[i].PublicKey = enc.EncodeToString(key.Public().(ed25519.PublicKey)) |
| + in[i].Challenge = p.Challenge |
| + in[i].Message = string(msg) |
| + in[i].Signature = enc.EncodeToString(ed25519.Sign(key, msg)) |
| + } |
| + return in |
| +} |
| + |
| +func TestNativeDeviceProofVectors(t *testing.T) { |
| + want := nativeProofVectors() |
| + if os.Getenv("EQUIPO_UPDATE_NATIVE_VECTOR") == "1" { |
| + b, err := json.MarshalIndent(want, "", " ") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.FromSlash(nativeProofVectorPath), append(b, '\n'), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + raw, err := os.ReadFile(filepath.FromSlash(nativeProofVectorPath)) |
| + if err != nil { |
| + t.Fatalf("the native proof vectors are missing; run with EQUIPO_UPDATE_NATIVE_VECTOR=1: %v", err) |
| + } |
| + var got []nativeProofVector |
| + if err := json.Unmarshal(raw, &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(got) != len(want) { |
| + t.Fatalf("%d vectors, want %d", len(got), len(want)) |
| + } |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Fatalf("vector %q drifted from DeviceProofMessage:\n got %+v\nwant %+v", want[i].Name, got[i], want[i]) |
| + } |
| + pub, _ := base64.RawURLEncoding.DecodeString(got[i].PublicKey) |
| + sig, _ := base64.RawURLEncoding.DecodeString(got[i].Signature) |
| + p := PersonDeviceProof{ID: got[i].ID, Challenge: got[i].Challenge, Nonce: got[i].Nonce} |
| + if !ed25519.Verify(pub, DeviceProofMessage(got[i].Instance, p), sig) { |
| + t.Fatalf("vector %q does not verify", got[i].Name) |
| + } |
| + } |
| +} |
diff --git a/native/.gitignore b/native/.gitignore| new file mode 100644 |
| index 00000000..10b89d95 |
| --- /dev/null |
| +++ b/native/.gitignore |
| @@ -0,0 +1,5 @@ |
| +.build/ |
| +.swiftpm/ |
| +DerivedData/ |
| +build/ |
| +*.xcodeproj/ |
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved| new file mode 100644 |
| index 00000000..1e58fce5 |
| --- /dev/null |
| +++ b/native/apple/Package.resolved |
| @@ -0,0 +1,23 @@ |
| +{ |
| + "originHash" : "2a6af65c7a784d5b21d8800f9821f79e73fca703bcece0ae1f22243bdbe1c584", |
| + "pins" : [ |
| + { |
| + "identity" : "native", |
| + "kind" : "remoteSourceControl", |
| + "location" : "https://amadan.net/rastrillo/native", |
| + "state" : { |
| + "revision" : "f1c7a14db2ddb8960afabc8268cd92c490543397" |
| + } |
| + }, |
| + { |
| + "identity" : "sparkle", |
| + "kind" : "remoteSourceControl", |
| + "location" : "https://github.com/sparkle-project/Sparkle", |
| + "state" : { |
| + "revision" : "ac2def288cbff5cfc7df3ffef6abdf45b72bcb0a", |
| + "version" : "2.9.6" |
| + } |
| + } |
| + ], |
| + "version" : 3 |
| +} |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| new file mode 100644 |
| index 00000000..6674e369 |
| --- /dev/null |
| +++ b/native/apple/Package.swift |
| @@ -0,0 +1,33 @@ |
| +// swift-tools-version: 6.2 |
| +import PackageDescription |
| +import Foundation |
| + |
| +// rastrillo/native at the revision Docs uses. OFICINA_NATIVE_PACKAGE_PATH |
| +// points at a local checkout instead, for work on the kit itself. |
| +let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) } |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "f1c7a14db2ddb8960afabc8268cd92c490543397") |
| + |
| +let package = Package( |
| + name: "EquipoNative", |
| + defaultLocalization: "en", |
| + platforms: [.macOS(.v26), .iOS(.v26)], |
| + products: [ |
| + .library(name: "EquipoKit", targets: ["EquipoKit"]), |
| + .executable(name: "EquipoMac", targets: ["EquipoMac"]), |
| + ], |
| + dependencies: [sharedNative], |
| + targets: [ |
| + .target(name: "EquipoKit", |
| + dependencies: [.product(name: "RastrilloApple", package: "native"), |
| + .product(name: "RastrilloNative", package: "native")], |
| + resources: [.process("Resources")]), |
| + .executableTarget(name: "EquipoMac", |
| + dependencies: ["EquipoKit", |
| + .product(name: "RastrilloApple", package: "native"), |
| + .product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS]))], |
| + path: "Sources/EquipoMac"), |
| + .testTarget(name: "EquipoKitTests", |
| + dependencies: ["EquipoKit", .product(name: "RastrilloNative", package: "native")], |
| + resources: [.copy("Fixtures")]), |
| + ] |
| +) |
diff --git a/native/apple/Sources/EquipoKit/API/Client.swift b/native/apple/Sources/EquipoKit/API/Client.swift| new file mode 100644 |
| index 00000000..e9d0de49 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/Client.swift |
| @@ -0,0 +1,124 @@ |
| +import Foundation |
| + |
| +/// A write that must be retried as itself: the same key, body and revision |
| +/// until its result is known (equipo-v1.md, "Retry writes"). Keep it until |
| +/// the call returns a result or a definite error; resend it after `.offline`. |
| +public struct PendingWrite: Sendable, Equatable, Codable { |
| + public let key: String |
| + public let body: Data |
| + public let ifMatch: Int64? |
| + public init(body: Data, ifMatch: Int64? = nil, key: String = UUID().uuidString.lowercased()) { |
| + self.key = key; self.body = body; self.ifMatch = ifMatch |
| + } |
| + public static func json<T: Encodable>(_ value: T, ifMatch: Int64? = nil) throws -> PendingWrite { |
| + PendingWrite(body: try EquipoJSON.encoder.encode(value), ifMatch: ifMatch) |
| + } |
| +} |
| + |
| +/// The person API, for one instance and one device credential. |
| +public struct EquipoClient: Sendable { |
| + public let transport: EquipoTransport |
| + public let token: String? |
| + |
| + public init(transport: EquipoTransport, token: String?) { |
| + self.transport = transport; self.token = token |
| + } |
| + public var origin: URL { transport.origin } |
| + |
| + // MARK: Reads |
| + |
| + public func me() async throws -> Me { try await get("/me") } |
| + public func conversation(cursor: String? = nil, limit: Int = 50) async throws -> ConversationPage { |
| + try await get("/conversation", page(cursor, limit)) |
| + } |
| + public func tasks(cursor: String? = nil, limit: Int = 100) async throws -> Page<EquipoTask> { try await get("/tasks", page(cursor, limit)) } |
| + public func needsYou(cursor: String? = nil, limit: Int = 100) async throws -> Page<EquipoTask> { try await get("/needs-you", page(cursor, limit)) } |
| + public func task(_ id: String) async throws -> EquipoTask { try await get("/tasks/\(escape(id))") } |
| + public func thread(_ taskID: String, cursor: String? = nil, limit: Int = 50) async throws -> ConversationPage { |
| + try await get("/tasks/\(escape(taskID))/thread", page(cursor, limit)) |
| + } |
| + public func question(_ id: String) async throws -> Question { try await get("/questions/\(escape(id))") } |
| + public func projects(cursor: String? = nil, limit: Int = 100) async throws -> Page<Project> { try await get("/projects", page(cursor, limit)) } |
| + public func devices() async throws -> Page<Device> { try await get("/auth/devices") } |
| + public func notifications(cursor: String?) async throws -> Page<EquipoNotification> { |
| + try await get("/notifications", cursor.map { [URLQueryItem(name: "cursor", value: $0)] } ?? []) |
| + } |
| + |
| + // MARK: Writes. Each takes a PendingWrite so a retry is the same request. |
| + |
| + public static func message(_ body: String) throws -> PendingWrite { try .json(["body": body]) } |
| + public func sendMessage(_ write: PendingWrite) async throws -> Message { try await post("/conversation/messages", write) } |
| + public func sendThreadMessage(task taskID: String, _ write: PendingWrite) async throws -> Message { |
| + try await post("/tasks/\(escape(taskID))/thread/messages", write) |
| + } |
| + |
| + /// An answer to a clarification: one option, or the person's own words. |
| + public enum Answer: Sendable, Equatable { |
| + case option(String) |
| + case text(String) |
| + } |
| + /// The answer, bound to the question revision the person saw. |
| + public static func answer(_ answer: Answer, to question: Question) throws -> PendingWrite { |
| + switch answer { |
| + case .option(let id): return try .json(["kind": "clarification", "option_id": id], ifMatch: question.revision) |
| + case .text(let text): return try .json(["kind": "clarification", "text": text], ifMatch: question.revision) |
| + } |
| + } |
| + public func answer(question id: String, _ write: PendingWrite) async throws -> Ack { |
| + guard write.ifMatch != nil else { throw EquipoAPIError.status(428) } |
| + return try await post("/questions/\(escape(id))/answer", write) |
| + } |
| + |
| + public func subscribe(device deviceID: String, _ write: PendingWrite) async throws -> NotificationSubscription { |
| + try await post("/notification-subscriptions", write) |
| + } |
| + public static func subscription(device: String) throws -> PendingWrite { try .json(["device_id": device]) } |
| + public func acknowledge(subscription id: String, _ write: PendingWrite) async throws -> Ack { |
| + try await post("/notification-subscriptions/\(escape(id))/ack", write) |
| + } |
| + public static func acknowledgement(_ notificationID: String, revision: Int64) throws -> PendingWrite { |
| + try .json(["notification_id": notificationID], ifMatch: revision) |
| + } |
| + public func revokeDevice(_ id: String, _ write: PendingWrite) async throws -> Ack { |
| + try await send(APIRequest("DELETE", "/auth/devices/\(escape(id))", body: write.body, bearer: token, |
| + idempotencyKey: write.key, ifMatch: write.ifMatch)) |
| + } |
| + public static func empty(ifMatch: Int64? = nil) -> PendingWrite { PendingWrite(body: Data("{}".utf8), ifMatch: ifMatch) } |
| + |
| + // MARK: Pairing. No bearer: the device has none yet. |
| + |
| + public func beginDevice(_ write: PendingWrite) async throws -> DeviceChallenge { |
| + try await send(APIRequest("POST", "/auth/devices", body: write.body, idempotencyKey: write.key)) |
| + } |
| + public func exchangeDevice(_ write: PendingWrite) async throws -> DeviceCredential { |
| + try await send(APIRequest("POST", "/auth/devices/exchange", body: write.body, idempotencyKey: write.key)) |
| + } |
| + |
| + // MARK: Plumbing |
| + |
| + private func page(_ cursor: String?, _ limit: Int) -> [URLQueryItem] { |
| + var q = [URLQueryItem(name: "limit", value: String(min(max(limit, 1), 100)))] |
| + if let cursor, !cursor.isEmpty { q.append(URLQueryItem(name: "cursor", value: cursor)) } |
| + return q |
| + } |
| + private func escape(_ id: String) -> String { |
| + id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? id |
| + } |
| + private func get<T: Decodable>(_ path: String, _ query: [URLQueryItem] = []) async throws -> T { |
| + try await send(APIRequest("GET", path, query: query, bearer: token)) |
| + } |
| + private func post<T: Decodable>(_ path: String, _ write: PendingWrite) async throws -> T { |
| + try await send(APIRequest("POST", path, body: write.body, bearer: token, idempotencyKey: write.key, ifMatch: write.ifMatch)) |
| + } |
| + func send<T: Decodable>(_ request: APIRequest) async throws -> T { |
| + let response = try await transport.send(request) |
| + guard (200..<300).contains(response.status) else { |
| + if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: response.data) { |
| + throw EquipoAPIError.server(status: response.status, body: body) |
| + } |
| + throw EquipoAPIError.status(response.status) |
| + } |
| + do { return try EquipoJSON.decoder.decode(T.self, from: response.data) } |
| + catch { throw EquipoAPIError.undecodable } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/API/Errors.swift b/native/apple/Sources/EquipoKit/API/Errors.swift| new file mode 100644 |
| index 00000000..9fce2efb |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/Errors.swift |
| @@ -0,0 +1,28 @@ |
| +import Foundation |
| + |
| +/// What can go wrong talking to the person API. |
| +public enum EquipoAPIError: Error, Sendable, Equatable { |
| + /// The request never reached the server or its answer never came back. |
| + case offline |
| + /// The server answered with an error body. |
| + case server(status: Int, body: APIErrorBody) |
| + /// The server answered with an error but no readable body. |
| + case status(Int) |
| + case tooLarge |
| + case undecodable |
| + case badOrigin |
| + case signedOut |
| + |
| + public var code: String? { if case .server(_, let body) = self { return body.code }; return nil } |
| + public var status: Int? { |
| + switch self { |
| + case .server(let s, _), .status(let s): return s |
| + default: return nil |
| + } |
| + } |
| + /// The session is over: sign in again. |
| + public var endsSession: Bool { status == 401 || self == .signedOut } |
| + /// The resource changed: fetch it before deciding again. |
| + public var isStale: Bool { code == "revision_conflict" } |
| + public var currentRevision: Int64? { if case .server(_, let body) = self { return body.currentRevision }; return nil } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/API/Models.swift b/native/apple/Sources/EquipoKit/API/Models.swift| new file mode 100644 |
| index 00000000..459aff29 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/Models.swift |
| @@ -0,0 +1,228 @@ |
| +import Foundation |
| + |
| +// The person API's responses, from docs/api/equipo-v1.openapi.json. Field |
| +// names follow the wire (snake_case is converted by `EquipoJSON.decoder`). |
| +// Optional numbers mean unknown, never zero. |
| + |
| +public struct Person: Codable, Sendable, Equatable { |
| + public var address: String |
| + public var displayIdentity: String |
| + public var active: Bool |
| + public var role: String |
| +} |
| + |
| +public struct Me: Codable, Sendable, Equatable { |
| + public var person: Person |
| + public var teamId: String |
| + public var teamName: String |
| + public var revision: Int64 |
| +} |
| + |
| +public struct Page<Item: Codable & Sendable>: Codable, Sendable { |
| + public var items: [Item] |
| + public var nextCursor: String |
| + public var revision: Int64 |
| +} |
| + |
| +public struct Project: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var name: String |
| + public var repository: String |
| + public var defaultBranch: String |
| + public var kind: String |
| + public var revision: Int64 |
| +} |
| + |
| +public struct Usage: Codable, Sendable, Equatable { |
| + public var calls: Int64 |
| + public var inputTokens: Int64 |
| + public var outputTokens: Int64 |
| +} |
| + |
| +public struct Step: Codable, Sendable, Equatable { |
| + public var key: String |
| + public var category: String |
| + public var action: String |
| + public var state: String |
| + public var model: String |
| + public var account: String |
| + public var actual: String |
| + public var reason: String |
| + public var usage: Usage? |
| + public var allowanceRemaining: Int64? |
| +} |
| + |
| +public struct EquipoTask: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var projectId: Int64 |
| + public var requester: String |
| + public var description: String |
| + public var kind: String |
| + public var state: String |
| + public var revision: Int64 |
| + public var planRevision: Int64 |
| + public var replacementId: String |
| + public var canCancel: Bool |
| + public var canMerge: Bool |
| + public var needsYou: Bool |
| + public var steps: [Step]? |
| + public var usage: Usage? |
| +} |
| + |
| +public struct SourceRef: Codable, Sendable, Equatable { |
| + public var kind: String |
| + public var id: String |
| + public var hash: String |
| + public var revision: Int64 |
| +} |
| + |
| +public struct Message: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var conversationId: String |
| + public var threadId: String |
| + public var authorKind: String |
| + public var authorId: String |
| + public var body: String |
| + public var sequence: Int64 |
| + public var revision: Int64 |
| + public var createdAt: Date |
| + public var sources: [SourceRef]? |
| + public var isOwn: Bool { authorKind == "person" } |
| +} |
| + |
| +public struct Card: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var kind: String |
| + public var resourceId: String |
| + public var taskId: String |
| + public var revision: Int64 |
| + public var copyKey: String |
| + public var actions: [String]? |
| + public var waitingTaskId: String |
| +} |
| + |
| +public struct ConversationPage: Codable, Sendable { |
| + public var messages: [Message]? |
| + public var cards: [Card]? |
| + public var nextCursor: String |
| + public var revision: Int64 |
| +} |
| + |
| +public struct QuestionOption: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var label: String |
| +} |
| + |
| +public struct QuestionField: Codable, Sendable, Equatable { |
| + public var key: String |
| + public var prompt: String |
| +} |
| + |
| +/// A clarification or a native permission question. Only clarifications are |
| +/// answered in slice 1; a native question opens the web app. |
| +public struct Question: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var kind: String |
| + public var taskId: String |
| + public var text: String |
| + public var state: String |
| + public var revision: Int64 |
| + public var canAnswer: Bool |
| + public var canAllow: Bool |
| + public var options: [QuestionOption]? |
| + public var fields: [QuestionField]? |
| + public var allowText: Bool |
| + public var expiresAt: Date? |
| + |
| + /// Whether this person may answer it now. The server still decides. |
| + public func isAnswerable(now: Date = Date()) -> Bool { |
| + guard kind == "clarification", state == "open", canAnswer else { return false } |
| + if let expiresAt, expiresAt <= now { return false } |
| + return true |
| + } |
| +} |
| + |
| +public struct Ack: Codable, Sendable, Equatable { |
| + public var revision: Int64 |
| +} |
| + |
| +public struct DeviceChallenge: Codable, Sendable, Equatable { |
| + public var id: String |
| + public var deviceSecret: String |
| + public var userCode: String |
| + public var challenge: String |
| + public var verificationUri: String |
| + public var expiresAt: Date |
| + public var pollIntervalSeconds: Int |
| +} |
| + |
| +public struct DeviceCredential: Codable, Sendable, Equatable { |
| + public var id: String |
| + public var token: String |
| + public var audience: String |
| + public var instanceId: String |
| + public var expiresAt: Date |
| +} |
| + |
| +public struct Device: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var label: String |
| + public var createdAt: Date |
| + public var expiresAt: Date |
| + public var revokedAt: Date? |
| + public var revision: Int64 |
| + public var lastUsedAt: Date? |
| +} |
| + |
| +public struct EquipoNotification: Codable, Sendable, Identifiable, Equatable { |
| + public var id: String |
| + public var kind: String |
| + public var resourceId: String |
| + public var deepLink: String |
| + public var resourceRevision: Int64 |
| + public var createdAt: Date |
| + public var state: String |
| +} |
| + |
| +public struct NotificationSubscription: Codable, Sendable, Equatable { |
| + public var id: String |
| + public var deviceId: String |
| + public var cursor: String |
| + public var revision: Int64 |
| + public var active: Bool |
| + public var expiresAt: Date |
| +} |
| + |
| +/// The person API's error body. |
| +public struct APIErrorBody: Codable, Sendable, Equatable { |
| + public var code: String |
| + public var copyKey: String |
| + public var requestId: String |
| + public var currentRevision: Int64? |
| +} |
| + |
| +public enum EquipoJSON { |
| + /// Go's time.Time encodes RFC 3339 with optional fractional seconds. |
| + public static var decoder: JSONDecoder { |
| + let d = JSONDecoder() |
| + d.keyDecodingStrategy = .convertFromSnakeCase |
| + d.dateDecodingStrategy = .custom { decoder in |
| + let c = try decoder.singleValueContainer() |
| + let raw = try c.decode(String.self) |
| + if let date = parseDate(raw) { return date } |
| + throw DecodingError.dataCorruptedError(in: c, debugDescription: "not an RFC 3339 time: \(raw)") |
| + } |
| + return d |
| + } |
| + public static var encoder: JSONEncoder { |
| + let e = JSONEncoder() |
| + e.keyEncodingStrategy = .convertToSnakeCase |
| + e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] |
| + return e |
| + } |
| + static func parseDate(_ raw: String) -> Date? { |
| + let fractional = Date.ISO8601FormatStyle(includingFractionalSeconds: true) |
| + let whole = Date.ISO8601FormatStyle() |
| + return (try? fractional.parse(raw)) ?? (try? whole.parse(raw)) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/API/Transport.swift b/native/apple/Sources/EquipoKit/API/Transport.swift| new file mode 100644 |
| index 00000000..c13db024 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/Transport.swift |
| @@ -0,0 +1,100 @@ |
| +import Foundation |
| +import RastrilloApple |
| + |
| +/// One HTTP request to the person API, relative to the instance origin. |
| +public struct APIRequest: Sendable, Equatable { |
| + public var method: String |
| + public var path: String |
| + public var query: [URLQueryItem] = [] |
| + public var body: Data? |
| + public var bearer: String? |
| + public var idempotencyKey: String? |
| + public var ifMatch: Int64? |
| + |
| + public init(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Data? = nil, |
| + bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil) { |
| + self.method = method; self.path = path; self.query = query; self.body = body |
| + self.bearer = bearer; self.idempotencyKey = idempotencyKey; self.ifMatch = ifMatch |
| + } |
| + |
| + /// The request as URLSession sends it. Bearer requests never carry cookies. |
| + public func urlRequest(origin: URL) throws -> URLRequest { |
| + guard var components = URLComponents(url: origin.appendingPathComponent("api/v1" + path), resolvingAgainstBaseURL: false) else { |
| + throw EquipoAPIError.badOrigin |
| + } |
| + if !query.isEmpty { components.queryItems = query } |
| + guard let url = components.url else { throw EquipoAPIError.badOrigin } |
| + var r = URLRequest(url: url) |
| + r.httpMethod = method |
| + r.httpShouldHandleCookies = false |
| + r.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData |
| + r.timeoutInterval = 30 |
| + r.setValue("application/json", forHTTPHeaderField: "Accept") |
| + if let body { |
| + r.httpBody = body |
| + r.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| + } |
| + if let bearer { r.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization") } |
| + if let idempotencyKey { r.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") } |
| + if let ifMatch { r.setValue("\"\(ifMatch)\"", forHTTPHeaderField: "If-Match") } |
| + return r |
| + } |
| +} |
| + |
| +public struct APIResponse: Sendable { |
| + public var status: Int |
| + public var data: Data |
| + public init(status: Int, data: Data) { self.status = status; self.data = data } |
| +} |
| + |
| +/// What the client needs from the network. Tests use a scripted one. |
| +public protocol EquipoTransport: Sendable { |
| + var origin: URL { get } |
| + /// Returns any status. Throws `EquipoAPIError.offline` when the request |
| + /// never reached the server or its answer never came back. |
| + func send(_ request: APIRequest) async throws -> APIResponse |
| +} |
| + |
| +/// URLSession, ephemeral: no cookie store, no cache, no redirects. Each |
| +/// outcome is reported to RastrilloApple's connectivity, so the offline |
| +/// banner follows real traffic. |
| +public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTaskDelegate, @unchecked Sendable { |
| + public let origin: URL |
| + public static let maxBytes = 4 * 1024 * 1024 |
| + private let session: URLSession |
| + private let observe: @Sendable (NativeTransportOutcome) -> Void |
| + |
| + public init(origin: URL, observe: (@Sendable (NativeTransportOutcome) -> Void)? = nil) { |
| + self.origin = origin |
| + let config = URLSessionConfiguration.ephemeral |
| + config.httpCookieStorage = nil |
| + config.httpShouldSetCookies = false |
| + config.urlCache = nil |
| + config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData |
| + config.waitsForConnectivity = false |
| + self.observe = observe ?? { outcome in Task { @MainActor in NativeConnectivity.shared.record(outcome, origin: origin) } } |
| + let delegate = RedirectRefuser() |
| + self.session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil) |
| + super.init() |
| + } |
| + |
| + public func send(_ request: APIRequest) async throws -> APIResponse { |
| + let r = try request.urlRequest(origin: origin) |
| + do { |
| + let (data, response) = try await session.data(for: r) |
| + guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline } |
| + observe(.responded(status: http.statusCode)) |
| + guard data.count <= Self.maxBytes else { throw EquipoAPIError.tooLarge } |
| + return APIResponse(status: http.statusCode, data: data) |
| + } catch let error as URLError { |
| + observe(.offline(error.code)) |
| + throw EquipoAPIError.offline |
| + } |
| + } |
| +} |
| + |
| +/// A bearer must never follow a redirect to another place. |
| +private final class RedirectRefuser: NSObject, URLSessionTaskDelegate { |
| + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, |
| + newRequest request: URLRequest) async -> URLRequest? { nil } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift| new file mode 100644 |
| index 00000000..7ebb9afd |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift |
| @@ -0,0 +1,47 @@ |
| +import CryptoKit |
| +import Foundation |
| + |
| +/// One paired team: where it is, this device's key and its credential. |
| +/// Kept in the Keychain as JSON under the origin. The token is a secret: |
| +/// never log it, never put it in a URL. |
| +public struct DeviceAccount: Codable, Sendable, Equatable { |
| + public var origin: URL |
| + public var keySeed: Data |
| + public var label: String |
| + public var credential: DeviceCredential? |
| + public var teamName: String? |
| + public var address: String? |
| + |
| + /// Throws if the stored key is damaged; pairing then starts again with a new one. |
| + public func signingKey() throws -> Curve25519.Signing.PrivateKey { try .init(rawRepresentation: keySeed) } |
| + public func publicKey() throws -> String { Base64URL.encode(try signingKey().publicKey.rawRepresentation) } |
| + public func isUsable(now: Date = Date()) -> Bool { credential.map { $0.expiresAt > now } ?? false } |
| + |
| + public static func new(origin: URL, label: String) -> DeviceAccount { |
| + DeviceAccount(origin: origin, keySeed: Curve25519.Signing.PrivateKey().rawRepresentation, label: label) |
| + } |
| +} |
| + |
| +/// The paired teams on this device. Slice 1 uses one; the store keeps the |
| +/// list shape so several teams can follow. |
| +public struct DeviceAccounts: Sendable { |
| + let store: SecretStore |
| + static let index = "accounts" |
| + public init(store: SecretStore) { self.store = store } |
| + |
| + public func all() -> [DeviceAccount] { |
| + let origins = (store.read(Self.index).flatMap { try? JSONDecoder().decode([URL].self, from: $0) }) ?? [] |
| + return origins.compactMap { origin in store.read(origin.absoluteString).flatMap { try? JSONDecoder().decode(DeviceAccount.self, from: $0) } } |
| + } |
| + public func save(_ account: DeviceAccount) throws { |
| + try store.write(try JSONEncoder().encode(account), account: account.origin.absoluteString) |
| + var origins = all().map(\.origin) |
| + if !origins.contains(account.origin) { origins.append(account.origin) } |
| + try store.write(try JSONEncoder().encode(origins), account: Self.index) |
| + } |
| + public func remove(_ origin: URL) { |
| + store.remove(origin.absoluteString) |
| + let origins = all().map(\.origin).filter { $0 != origin } |
| + try? store.write((try? JSONEncoder().encode(origins)) ?? Data("[]".utf8), account: Self.index) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Pairing/DeviceProof.swift b/native/apple/Sources/EquipoKit/Pairing/DeviceProof.swift| new file mode 100644 |
| index 00000000..4924ef9b |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Pairing/DeviceProof.swift |
| @@ -0,0 +1,88 @@ |
| +import CryptoKit |
| +import Foundation |
| + |
| +/// The device proof, byte for byte as the server builds it: |
| +/// `personapi.DeviceProofMessage`, Go's `json.Marshal` of |
| +/// `["equipo.person.device.v1", instance, id, challenge, nonce]`. |
| +/// Go escapes <, > and &, and leaves / alone; Swift's encoders do neither, |
| +/// so the array is written here. `device-proof-vectors.json`, owned by a Go |
| +/// test, holds the server's bytes. |
| +public enum DeviceProof { |
| + public static let audience = "equipo.person.device.v1" |
| + |
| + public static func message(instance: String, id: String, challenge: String, nonce: String) -> Data { |
| + let parts = [audience, instance, id, challenge, nonce].map(goJSONString) |
| + return Data(("[" + parts.joined(separator: ",") + "]").utf8) |
| + } |
| + |
| + /// The instance ID is the first element of the challenge, base64url JSON. |
| + public static func instance(fromChallenge challenge: String) -> String? { |
| + guard let data = Base64URL.decode(challenge), |
| + let array = try? JSONSerialization.jsonObject(with: data) as? [Any], |
| + let first = array.first as? String, !first.isEmpty else { return nil } |
| + return first |
| + } |
| + |
| + /// A fresh nonce: 256 random bits, base64url. |
| + public static func nonce() -> String { |
| + var bytes = [UInt8](repeating: 0, count: 32) |
| + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) |
| + precondition(status == errSecSuccess, "no system randomness") |
| + return Base64URL.encode(Data(bytes)) |
| + } |
| + |
| + /// The body for `POST /auth/devices/exchange`. |
| + public struct Body: Codable, Sendable, Equatable { |
| + public var id: String |
| + public var deviceSecret: String |
| + public var challenge: String |
| + public var nonce: String |
| + public var signature: String |
| + } |
| + |
| + public static func body(for challenge: DeviceChallenge, key: Curve25519.Signing.PrivateKey, nonce: String) throws -> Body { |
| + guard let instance = instance(fromChallenge: challenge.challenge) else { throw PairingError.badChallenge } |
| + let signed = try key.signature(for: message(instance: instance, id: challenge.id, challenge: challenge.challenge, nonce: nonce)) |
| + return Body(id: challenge.id, deviceSecret: challenge.deviceSecret, challenge: challenge.challenge, |
| + nonce: nonce, signature: Base64URL.encode(signed)) |
| + } |
| + |
| + /// Go's encoding/json string: HTML-safe, and escaped, the |
| + /// short escapes for ", \, \n, \r and \t, \u00XX for other control bytes. |
| + static func goJSONString(_ s: String) -> String { |
| + var out = "\"" |
| + for scalar in s.unicodeScalars { |
| + switch scalar { |
| + case "\"": out += "\\\"" |
| + case "\\": out += "\\\\" |
| + case "\n": out += "\\n" |
| + case "\r": out += "\\r" |
| + case "\t": out += "\\t" |
| + case "<", ">", "&", "\u{2028}", "\u{2029}": |
| + out += String(format: "\\u%04x", scalar.value) |
| + default: |
| + if scalar.value < 0x20 { out += String(format: "\\u%04x", scalar.value) } |
| + else { out.unicodeScalars.append(scalar) } |
| + } |
| + } |
| + return out + "\"" |
| + } |
| +} |
| + |
| +public enum Base64URL { |
| + public static func encode(_ data: Data) -> String { |
| + data.base64EncodedString().replacingOccurrences(of: "+", with: "-") |
| + .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") |
| + } |
| + public static func decode(_ s: String) -> Data? { |
| + var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") |
| + while b.count % 4 != 0 { b += "=" } |
| + return Data(base64Encoded: b) |
| + } |
| +} |
| + |
| +public enum PairingError: Error, Sendable, Equatable { |
| + case badChallenge |
| + case expired |
| + case refused(String) |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Pairing/Pairing.swift b/native/apple/Sources/EquipoKit/Pairing/Pairing.swift| new file mode 100644 |
| index 00000000..99436f5d |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Pairing/Pairing.swift |
| @@ -0,0 +1,126 @@ |
| +import CryptoKit |
| +import Foundation |
| +import Observation |
| + |
| +/// Pairing a device with a team (equipo-v1.md, "Sign in a device"): ask for |
| +/// a challenge, show its code, open the team in the browser, and poll the |
| +/// exchange until the person approves this device there. |
| +/// |
| +/// One proof per challenge. Every poll resends it unchanged, nonce |
| +/// included: the server keeps no idempotency record for exchange, answers |
| +/// 409 while it waits, and returns the saved credential for the same nonce |
| +/// if a success was lost on the way back. |
| +@MainActor @Observable |
| +public final class PairingModel { |
| + public enum Step: Equatable, Sendable { |
| + case enterTeam |
| + case requesting |
| + case waiting(code: String, verification: URL, expires: Date) |
| + case approved(teamName: String) |
| + case expired |
| + case failed(String) |
| + } |
| + |
| + public private(set) var step: Step = .enterTeam |
| + public private(set) var account: DeviceAccount? |
| + |
| + private let accounts: DeviceAccounts |
| + private let makeTransport: @Sendable (URL) -> EquipoTransport |
| + private let sleep: @Sendable (Duration) async throws -> Void |
| + private let now: @Sendable () -> Date |
| + private var task: Task<Void, Never>? |
| + |
| + /// The floor the API sets; the server enforces it too. |
| + public static let minimumInterval: Duration = .seconds(5) |
| + |
| + public init(accounts: DeviceAccounts, |
| + makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) }, |
| + sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, |
| + now: @escaping @Sendable () -> Date = { Date() }) { |
| + self.accounts = accounts; self.makeTransport = makeTransport; self.sleep = sleep; self.now = now |
| + } |
| + |
| + /// Turns what a person types into the team's origin: a host or a URL, |
| + /// https only, nothing after the host. |
| + public static func origin(from typed: String) -> URL? { |
| + var text = typed.trimmingCharacters(in: .whitespacesAndNewlines) |
| + guard !text.isEmpty else { return nil } |
| + if !text.contains("://") { text = "https://" + text } |
| + guard let url = URL(string: text), url.scheme == "https", let host = url.host, !host.isEmpty, url.user == nil else { return nil } |
| + var c = URLComponents(); c.scheme = "https"; c.host = host.lowercased(); c.port = url.port |
| + return c.url |
| + } |
| + |
| + public func start(origin: URL, label: String) { |
| + task?.cancel() |
| + task = Task { await run(origin: origin, label: label) } |
| + } |
| + public func cancel() { task?.cancel(); task = nil; step = .enterTeam } |
| + |
| + func run(origin: URL, label: String) async { |
| + step = .requesting |
| + // The key is saved before the server hears of it, so a crash after |
| + // the challenge never strands a credential bound to a lost key. |
| + var account = accounts.all().first { $0.origin == origin && $0.credential == nil } ?? .new(origin: origin, label: label) |
| + do { |
| + try accounts.save(account) |
| + let client = EquipoClient(transport: makeTransport(origin), token: nil) |
| + let begin = try PendingWrite.json(["public_key": try account.publicKey(), "label": label]) |
| + let challenge: DeviceChallenge = try await retrying { try await client.beginDevice(begin) } |
| + guard let verification = URL(string: challenge.verificationUri), verification.scheme == "https" else { |
| + throw PairingError.badChallenge |
| + } |
| + step = .waiting(code: challenge.userCode, verification: verification, expires: challenge.expiresAt) |
| + let proof = try PendingWrite.json(DeviceProof.body(for: challenge, key: try account.signingKey(), nonce: DeviceProof.nonce())) |
| + var interval = max(Self.minimumInterval, .seconds(challenge.pollIntervalSeconds)) |
| + while !Task.isCancelled { |
| + if now() >= challenge.expiresAt { step = .expired; return } |
| + try await sleep(interval) |
| + do { |
| + let credential = try await client.exchangeDevice(proof) |
| + account.credential = credential |
| + let me = try await EquipoClient(transport: makeTransport(origin), token: credential.token).me() |
| + account.teamName = me.teamName; account.address = me.person.address |
| + try accounts.save(account) |
| + self.account = account |
| + step = .approved(teamName: me.teamName) |
| + return |
| + } catch let error as EquipoAPIError { |
| + switch error.code { |
| + case "authorization_pending": continue |
| + case "slow_down": interval += .seconds(5) |
| + case "device_expired": step = .expired; return |
| + default: |
| + if error == .offline { continue } |
| + throw error |
| + } |
| + } |
| + } |
| + } catch is CancellationError { |
| + return |
| + } catch let error as EquipoAPIError { |
| + step = .failed(Self.describe(error)) |
| + } catch { |
| + step = .failed(String(localized: "pairing.failed", bundle: .module)) |
| + } |
| + } |
| + |
| + private func retrying<T: Sendable>(_ attempt: @Sendable () async throws -> T) async throws -> T { |
| + var tries = 0 |
| + while true { |
| + do { return try await attempt() } |
| + catch EquipoAPIError.offline where tries < 2 { tries += 1; try await sleep(.seconds(2)) } |
| + } |
| + } |
| + |
| + static func describe(_ error: EquipoAPIError) -> String { |
| + switch error { |
| + case .offline: return String(localized: "pairing.offline", bundle: .module) |
| + case .badOrigin: return String(localized: "pairing.bad_team", bundle: .module) |
| + default: |
| + if error.status == 404 { return String(localized: "pairing.not_equipo", bundle: .module) } |
| + if error.code == "slow_down" { return String(localized: "pairing.slow_down", bundle: .module) } |
| + return String(localized: "pairing.failed", bundle: .module) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Pairing/SecretStore.swift b/native/apple/Sources/EquipoKit/Pairing/SecretStore.swift| new file mode 100644 |
| index 00000000..786ad8a2 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Pairing/SecretStore.swift |
| @@ -0,0 +1,51 @@ |
| +import Foundation |
| +import Security |
| + |
| +/// Where a device keeps its key and credential. The Keychain in the apps; |
| +/// memory in tests. |
| +public protocol SecretStore: Sendable { |
| + func read(_ account: String) -> Data? |
| + func write(_ data: Data, account: String) throws |
| + func remove(_ account: String) |
| +} |
| + |
| +/// A generic-password item per account, this device only, after first |
| +/// unlock (notification polling runs in the background). |
| +public struct KeychainSecretStore: SecretStore { |
| + public let service: String |
| + public init(service: String = (Bundle.main.bundleIdentifier ?? "works.oficina.equipo") + ".device") { self.service = service } |
| + |
| + private func query(_ account: String) -> [String: Any] { |
| + [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account] |
| + } |
| + public func read(_ account: String) -> Data? { |
| + var q = query(account) |
| + q[kSecReturnData as String] = true |
| + q[kSecMatchLimit as String] = kSecMatchLimitOne |
| + var result: CFTypeRef? |
| + guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess else { return nil } |
| + return result as? Data |
| + } |
| + public func write(_ data: Data, account: String) throws { |
| + let updated = SecItemUpdate(query(account) as CFDictionary, [kSecValueData as String: data] as CFDictionary) |
| + if updated == errSecSuccess { return } |
| + guard updated == errSecItemNotFound else { throw StoreError.keychain(updated) } |
| + var q = query(account) |
| + q[kSecValueData as String] = data |
| + q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly |
| + let added = SecItemAdd(q as CFDictionary, nil) |
| + guard added == errSecSuccess else { throw StoreError.keychain(added) } |
| + } |
| + public func remove(_ account: String) { SecItemDelete(query(account) as CFDictionary) } |
| + public enum StoreError: Error, Equatable { case keychain(OSStatus) } |
| +} |
| + |
| +public final class MemorySecretStore: SecretStore, @unchecked Sendable { |
| + private var items: [String: Data] = [:] |
| + private let lock = NSLock() |
| + public init() {} |
| + public func read(_ account: String) -> Data? { lock.withLock { items[account] } } |
| + public func write(_ data: Data, account: String) throws { lock.withLock { items[account] = data } } |
| + public func remove(_ account: String) { lock.withLock { _ = items.removeValue(forKey: account) } } |
| + public var accounts: [String] { lock.withLock { Array(items.keys) } } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Presentation/Roster.swift b/native/apple/Sources/EquipoKit/Presentation/Roster.swift| new file mode 100644 |
| index 00000000..4221e8a2 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Presentation/Roster.swift |
| @@ -0,0 +1,150 @@ |
| +import Foundation |
| + |
| +// Roster (the web's conversation design, chat.html and chat_roster.go) fed |
| +// only by the person API. Fields the API does not carry yet (stage, Checks, |
| +// Review, Branch, a card's time, set aside, the live activity line, the |
| +// roll-up) are left out, not invented. See docs/native/r7/index.md. |
| + |
| +public enum Specialist: String, CaseIterable, Sendable { |
| + case coordinator, engineering, copy, research, checks, review, design |
| + public init(category: String) { self = Specialist(rawValue: category.lowercased()) ?? .coordinator } |
| + public var name: String { |
| + switch self { |
| + case .coordinator: return String(localized: "specialist.coordinator", bundle: .module) |
| + case .engineering: return String(localized: "specialist.engineering", bundle: .module) |
| + case .copy: return String(localized: "specialist.copy", bundle: .module) |
| + case .research: return String(localized: "specialist.research", bundle: .module) |
| + case .checks: return String(localized: "specialist.checks", bundle: .module) |
| + case .review: return String(localized: "specialist.review", bundle: .module) |
| + case .design: return String(localized: "specialist.design", bundle: .module) |
| + } |
| + } |
| + /// SF Symbols matching the web's Lucide icons (wrench, type, search). |
| + public var symbol: String { |
| + switch self { |
| + case .coordinator: return "sparkle" |
| + case .engineering: return "wrench.adjustable" |
| + case .copy: return "textformat" |
| + case .research: return "magnifyingglass" |
| + case .checks: return "checklist.checked" |
| + case .review: return "checkmark.shield" |
| + case .design: return "paintbrush.pointed" |
| + } |
| + } |
| +} |
| + |
| +/// Amber means waiting on you; red only for a failure; green otherwise. |
| +public enum StageTone: String, Sendable { case positive, warning, negative } |
| + |
| +public struct RosterByline: Sendable, Equatable { |
| + public var who: Specialist |
| + public var verb: String |
| + public var project: String? |
| + /// nil when the API has no time for it (cards). |
| + public var time: Date? |
| + public init(who: Specialist, verb: String, project: String?, time: Date?) { |
| + self.who = who; self.verb = verb; self.project = project; self.time = time |
| + } |
| + /// The coordinator shows its bare mark; its name is for VoiceOver only. |
| + public var showsName: Bool { who != .coordinator } |
| + public var timeText: String? { time.map { $0.formatted(date: .omitted, time: .shortened) } } |
| + public var spoken: String { [who.name, verb, project, timeText].compactMap { $0 }.joined(separator: " ") } |
| +} |
| + |
| +/// What a task is doing, from its steps: the API's task state is an |
| +/// internal plan state, not Roster's stage. |
| +public struct TaskSummary: Sendable, Equatable { |
| + public var label: String |
| + public var tone: StageTone |
| + public var specialist: Specialist? |
| + public var needsYou: Bool |
| + |
| + public init(_ task: EquipoTask) { |
| + let steps = task.steps ?? [] |
| + needsYou = task.needsYou |
| + if task.state == "cancelled" || task.state == "cancel_requested" { |
| + label = String(localized: "task.cancelled", bundle: .module); tone = .positive; specialist = nil; return |
| + } |
| + if let failed = steps.first(where: { $0.state == "failed" }) { |
| + specialist = Specialist(category: failed.category) |
| + label = String(localized: "task.step_failed \(Specialist(category: failed.category).name)", bundle: .module); tone = .negative; return |
| + } |
| + if task.needsYou { |
| + let waiting = steps.first { $0.state == "waiting" } |
| + specialist = waiting.map { Specialist(category: $0.category) } |
| + label = String(localized: "task.needs_you", bundle: .module); tone = .warning; return |
| + } |
| + if let active = steps.first(where: { $0.state == "running" }) { |
| + specialist = Specialist(category: active.category) |
| + label = String(localized: "task.step_running \(Specialist(category: active.category).name)", bundle: .module); tone = .positive; return |
| + } |
| + if let waiting = steps.first(where: { $0.state == "waiting" }) { |
| + specialist = Specialist(category: waiting.category) |
| + label = String(localized: "task.step_waiting \(Specialist(category: waiting.category).name)", bundle: .module); tone = .positive; return |
| + } |
| + specialist = nil |
| + if !steps.isEmpty, steps.allSatisfy({ $0.state == "done" }) { |
| + label = String(localized: "task.done", bundle: .module) |
| + } else { |
| + label = String(localized: "task.not_started", bundle: .module) |
| + } |
| + tone = .positive |
| + } |
| +} |
| + |
| +/// One thing in the conversation. |
| +public enum FeedItem: Identifiable, Sendable { |
| + case own(Message) |
| + case coordinator(Message) |
| + case outgoing(EquipoSession.Outgoing) |
| + /// A task the conversation reports on. |
| + case report(Card, RosterByline, EquipoTask) |
| + /// A question to answer here. |
| + case question(Card, RosterByline, Question?, taskTitle: String?) |
| + /// A decision slice 1 sends to the web: merges, approvals and the rest. |
| + case decision(Card, RosterByline, taskTitle: String?) |
| + |
| + public var id: String { |
| + switch self { |
| + case .own(let m), .coordinator(let m): return m.id |
| + case .outgoing(let o): return "outgoing-" + o.id |
| + case .report(let c, _, _), .question(let c, _, _, _), .decision(let c, _, _): return c.id |
| + } |
| + } |
| +} |
| + |
| +public enum Feed { |
| + /// The conversation in order: messages by the server's sequence, then |
| + /// this device's unsent messages, then the cards. The API gives a card |
| + /// no time or position, so cards follow the messages in the API's order. |
| + @MainActor public static func build(_ session: EquipoSession) -> [FeedItem] { |
| + var items: [FeedItem] = session.messages.map { $0.isOwn ? .own($0) : .coordinator($0) } |
| + items += session.outgoing.filter { $0.taskID == nil }.map { .outgoing($0) } |
| + for card in session.cards { |
| + let task = session.task(card.taskId) |
| + let project = task.flatMap { session.project(for: $0)?.name } |
| + switch card.kind { |
| + case "question": |
| + let question = session.questions[card.resourceId] |
| + let asker = task.flatMap { $0.steps?.first { $0.state == "waiting" } }.map { Specialist(category: $0.category) } ?? .coordinator |
| + let byline = RosterByline(who: asker, verb: String(localized: "byline.asks", bundle: .module), project: project, time: nil) |
| + items.append(.question(card, byline, question, taskTitle: task?.description)) |
| + case "task": |
| + guard let task else { continue } |
| + let byline = RosterByline(who: TaskSummary(task).specialist ?? .engineering, verb: String(localized: "byline.reports", bundle: .module), project: project, time: nil) |
| + items.append(.report(card, byline, task)) |
| + default: |
| + let byline = RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: nil) |
| + items.append(.decision(card, byline, taskTitle: task?.description)) |
| + } |
| + } |
| + return items |
| + } |
| + |
| + /// Where a card lives on the web: the conversation, at the card. |
| + public static func webURL(for card: Card, origin: URL) -> URL { |
| + var c = URLComponents(url: origin.appendingPathComponent("conversation"), resolvingAgainstBaseURL: false)! |
| + c.fragment = "card-" + card.id |
| + return c.url! |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift b/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift| new file mode 100644 |
| index 00000000..8c730e85 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift |
| @@ -0,0 +1,19 @@ |
| +import Foundation |
| + |
| +/// One turn of a sub-chat: a task thread or a question's replies. |
| +public struct ThreadTurn: Identifiable, Sendable, Equatable { |
| + public var id: String |
| + public var who: Specialist? // nil is you |
| + public var text: String |
| + public var time: Date? |
| + public var pending = false |
| + public var own: Bool { who == nil } |
| + public var timeText: String { time.map { $0.formatted(date: .omitted, time: .shortened) } ?? "" } |
| + |
| + public init(id: String, who: Specialist?, text: String, time: Date?, pending: Bool = false) { |
| + self.id = id; self.who = who; self.text = text; self.time = time; self.pending = pending |
| + } |
| + public init(_ m: Message) { |
| + self.init(id: m.id, who: m.isOwn ? nil : .coordinator, text: m.body, time: m.createdAt) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings| new file mode 100644 |
| index 00000000..8a470103 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings |
| @@ -0,0 +1,5 @@ |
| +{ |
| + "sourceLanguage" : "en", |
| + "strings" : {}, |
| + "version" : "1.0" |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift| new file mode 100644 |
| index 00000000..a554feb5 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| @@ -0,0 +1,285 @@ |
| +import Foundation |
| +import Observation |
| +import RastrilloNative |
| + |
| +/// One signed-in team: what the screens show, kept current by refreshing and |
| +/// by the device's notification subscription. Reads reconcile by ID; writes |
| +/// keep their idempotency key until they have a result. |
| +@MainActor @Observable |
| +public final class EquipoSession { |
| + public enum Status: Equatable, Sendable { case loading, ready, signedOut } |
| + |
| + /// A message this device is sending. It stays, with its key, until the |
| + /// server has it; offline it waits and is sent again as itself. |
| + public struct Outgoing: Identifiable, Equatable, Sendable { |
| + public enum State: Equatable, Sendable { case sending, waiting, failed } |
| + public let id: String |
| + public let text: String |
| + public let taskID: String? |
| + public var state: State |
| + let write: PendingWrite |
| + } |
| + |
| + public private(set) var status: Status = .loading |
| + public private(set) var account: DeviceAccount |
| + public private(set) var me: Me? |
| + public private(set) var projects: [String: Project] = [:] |
| + public private(set) var messages: [Message] = [] |
| + public private(set) var cards: [Card] = [] |
| + public private(set) var tasks: [EquipoTask] = [] |
| + /// nil until loaded: an unknown count is not zero. |
| + public private(set) var needsYou: [EquipoTask]? |
| + public private(set) var questions: [String: Question] = [:] |
| + public private(set) var threads: [String: [Message]] = [:] |
| + public private(set) var outgoing: [Outgoing] = [] |
| + public private(set) var lastRefresh: Date? |
| + public private(set) var refreshFailed = false |
| + |
| + public let client: EquipoClient |
| + private let accounts: DeviceAccounts |
| + private let defaults: UserDefaults |
| + private let runner = CoalescedRunner() |
| + private var seenNotifications: Set<String> = [] |
| + private var polling: Task<Void, Never>? |
| + private let sleep: @Sendable (Duration) async throws -> Void |
| + |
| + public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil, |
| + defaults: UserDefaults = .standard, |
| + sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) { |
| + self.account = account |
| + self.accounts = accounts |
| + self.defaults = defaults |
| + self.sleep = sleep |
| + self.client = EquipoClient(transport: transport ?? URLSessionTransport(origin: account.origin), token: account.credential?.token) |
| + if !account.isUsable() { status = .signedOut } |
| + } |
| + |
| + public var origin: URL { account.origin } |
| + public var teamName: String { me?.teamName ?? account.teamName ?? origin.host ?? "" } |
| + |
| + // MARK: Reading |
| + |
| + /// Everything the screens show, once at a time: a burst of callers shares one pass. |
| + public func refresh() async { |
| + guard status != .signedOut else { return } |
| + await runner.run { [weak self] in await self?.refreshPass() } |
| + } |
| + |
| + private func refreshPass() async { |
| + let client = self.client |
| + do { |
| + async let meRead = client.me() |
| + async let projectRead = client.projects() |
| + async let conversationRead = client.conversation() |
| + async let taskRead = client.tasks() |
| + async let needsRead = client.needsYou() |
| + let (me, projectPage, page, taskPage, needsPage) = try await (meRead, projectRead, conversationRead, taskRead, needsRead) |
| + self.me = me |
| + projects = Dictionary(projectPage.items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) |
| + messages = Self.merge(messages, (page.messages ?? []).filter { $0.threadId.isEmpty }) |
| + cards = page.cards ?? [] |
| + tasks = taskPage.items |
| + needsYou = needsPage.items |
| + for card in cards where card.kind == "question" { |
| + if let q = try? await client.question(card.resourceId) { questions[q.id] = q } |
| + } |
| + status = .ready |
| + refreshFailed = false |
| + lastRefresh = Date() |
| + if account.teamName != me.teamName { |
| + account.teamName = me.teamName; account.address = me.person.address |
| + try? accounts.save(account) |
| + } |
| + } catch let error as EquipoAPIError where error.endsSession { |
| + endSession() |
| + } catch { |
| + refreshFailed = true |
| + if status == .loading && !messages.isEmpty { status = .ready } |
| + } |
| + } |
| + |
| + public func loadThread(_ taskID: String) async { |
| + guard let page = try? await client.thread(taskID) else { return } |
| + threads[taskID] = Self.merge(threads[taskID] ?? [], page.messages ?? []) |
| + } |
| + |
| + /// Reconciles by ID; the newer revision wins; ordered by the server's sequence. |
| + static func merge(_ old: [Message], _ new: [Message]) -> [Message] { |
| + var byID = Dictionary(old.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) |
| + for m in new where (byID[m.id]?.revision ?? -1) <= m.revision { byID[m.id] = m } |
| + return byID.values.sorted { ($0.sequence, $0.id) < ($1.sequence, $1.id) } |
| + } |
| + |
| + public func project(for task: EquipoTask) -> Project? { projects[String(task.projectId)] } |
| + public func task(_ id: String) -> EquipoTask? { tasks.first { $0.id == id } ?? needsYou?.first { $0.id == id } } |
| + |
| + // MARK: Sending |
| + |
| + public func send(_ text: String, inThreadOf taskID: String? = nil) async { |
| + let text = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| + guard !text.isEmpty, let write = try? EquipoClient.message(text) else { return } |
| + let item = Outgoing(id: write.key, text: text, taskID: taskID, state: .sending, write: write) |
| + outgoing.append(item) |
| + await deliver(item.id) |
| + } |
| + |
| + /// Sends one outgoing message again, as itself. |
| + public func retry(_ id: String) async { await deliver(id) } |
| + |
| + private func deliver(_ id: String) async { |
| + guard let index = outgoing.firstIndex(where: { $0.id == id }) else { return } |
| + var item = outgoing[index] |
| + item.state = .sending; outgoing[index] = item |
| + do { |
| + let sent: Message |
| + if let taskID = item.taskID { sent = try await client.sendThreadMessage(task: taskID, item.write) } |
| + else { sent = try await client.sendMessage(item.write) } |
| + outgoing.removeAll { $0.id == id } |
| + if let taskID = item.taskID { threads[taskID] = Self.merge(threads[taskID] ?? [], [sent]) } |
| + else { messages = Self.merge(messages, [sent]) } |
| + await refresh() |
| + } catch let error as EquipoAPIError { |
| + if error.endsSession { endSession(); return } |
| + if let i = outgoing.firstIndex(where: { $0.id == id }) { |
| + outgoing[i].state = error == .offline ? .waiting : .failed |
| + } |
| + } catch { |
| + if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = .failed } |
| + } |
| + } |
| + |
| + // MARK: Answering |
| + |
| + public enum AnswerOutcome: Equatable, Sendable { |
| + case answered |
| + /// The question changed or closed: show the current one; never resend. |
| + case changed |
| + case offline |
| + case failed |
| + } |
| + |
| + /// Answers a clarification as the person saw it. The question is read |
| + /// again first; if its revision moved, nothing is sent. |
| + public func answer(_ question: Question, with answer: EquipoClient.Answer) async -> AnswerOutcome { |
| + let current: Question |
| + do { current = try await client.question(question.id) } |
| + catch EquipoAPIError.offline { return .offline } |
| + catch { return .failed } |
| + questions[current.id] = current |
| + guard current.revision == question.revision, current.isAnswerable() else { return .changed } |
| + guard let write = try? EquipoClient.answer(answer, to: current) else { return .failed } |
| + var attempts = 0 |
| + while true { |
| + do { |
| + _ = try await client.answer(question: current.id, write) |
| + await refresh() |
| + return .answered |
| + } catch let error as EquipoAPIError { |
| + if error.endsSession { endSession(); return .failed } |
| + if error.isStale || error.status == 410 { if let q = try? await client.question(current.id) { questions[q.id] = q }; return .changed } |
| + // A lost answer is retried with its own key, body and revision. |
| + if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue } |
| + return error == .offline ? .offline : .failed |
| + } catch { return .failed } |
| + } |
| + } |
| + |
| + // MARK: Notifications |
| + |
| + private var subscriptionKey: String { "equipo.subscription." + origin.absoluteString } |
| + struct StoredSubscription: Codable, Equatable { var id: String; var revision: Int64; var cursor: String } |
| + |
| + /// Polls the device's subscription while the app is in front, with a |
| + /// periodic full refresh as the fallback. |
| + public func startPolling(every interval: Duration = .seconds(15)) { |
| + polling?.cancel() |
| + polling = Task { [weak self] in |
| + var ticks = 0 |
| + while !Task.isCancelled { |
| + guard let self else { return } |
| + await self.pollOnce() |
| + ticks += 1 |
| + if ticks % 4 == 0 { await self.refresh() } |
| + try? await self.sleep(interval) |
| + } |
| + } |
| + } |
| + public func stopPolling() { polling?.cancel(); polling = nil } |
| + |
| + func pollOnce() async { |
| + guard status != .signedOut, let deviceID = account.credential?.id else { return } |
| + var sub = storedSubscription() |
| + if sub == nil { |
| + guard let created = try? await client.subscribe(device: deviceID, EquipoClient.subscription(device: deviceID)) else { return } |
| + sub = StoredSubscription(id: created.id, revision: created.revision, cursor: created.cursor) |
| + store(sub) |
| + } |
| + guard var current = sub else { return } |
| + do { |
| + let page = try await client.notifications(cursor: current.cursor.isEmpty ? nil : current.cursor) |
| + let fresh = page.items.filter { !seenNotifications.contains($0.id) } |
| + for n in page.items where n.state == "unread" { |
| + seenNotifications.insert(n.id) |
| + current.revision = await acknowledge(n.id, subscription: current) |
| + } |
| + seenNotifications.formUnion(page.items.map(\.id)) |
| + if !page.nextCursor.isEmpty { current.cursor = page.nextCursor } |
| + store(current) |
| + if !fresh.isEmpty { await refresh() } |
| + } catch let error as EquipoAPIError { |
| + if error.endsSession { endSession(); return } |
| + switch error.code { |
| + case "subscription_expired": store(nil) |
| + case "cursor_expired": current.cursor = ""; store(current); await refresh() |
| + default: break |
| + } |
| + } catch {} |
| + } |
| + |
| + /// Acknowledges one delivered notification and returns the subscription's |
| + /// new revision. A lost acknowledgement is retried as itself; a stale |
| + /// revision takes the server's current one and tries once more. |
| + /// Acknowledging records delivery only: it never answers anything. |
| + private func acknowledge(_ id: String, subscription: StoredSubscription) async -> Int64 { |
| + var revision = subscription.revision |
| + guard var write = try? EquipoClient.acknowledgement(id, revision: revision) else { return revision } |
| + for _ in 0..<3 { |
| + do { return try await client.acknowledge(subscription: subscription.id, write).revision } |
| + catch let error as EquipoAPIError { |
| + if error == .offline { continue } |
| + guard error.isStale, let current = error.currentRevision, |
| + let next = try? EquipoClient.acknowledgement(id, revision: current) else { return revision } |
| + revision = current; write = next |
| + } catch { return revision } |
| + } |
| + return revision |
| + } |
| + |
| + func storedSubscription() -> StoredSubscription? { |
| + defaults.data(forKey: subscriptionKey).flatMap { try? JSONDecoder().decode(StoredSubscription.self, from: $0) } |
| + } |
| + private func store(_ sub: StoredSubscription?) { |
| + if let sub, let data = try? JSONEncoder().encode(sub) { defaults.set(data, forKey: subscriptionKey) } |
| + else { defaults.removeObject(forKey: subscriptionKey) } |
| + } |
| + |
| + // MARK: Signing out |
| + |
| + private func endSession() { |
| + status = .signedOut |
| + stopPolling() |
| + } |
| + |
| + /// Revokes this device on the server, then forgets it here. Forgetting |
| + /// happens even if the server cannot be reached. |
| + public func signOut() async { |
| + stopPolling() |
| + if let id = account.credential?.id, let page = try? await client.devices(), |
| + let device = page.items.first(where: { $0.id == id }) { |
| + _ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision)) |
| + } |
| + accounts.remove(origin) |
| + store(nil) |
| + status = .signedOut |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Components.swift b/native/apple/Sources/EquipoKit/UI/Components.swift| new file mode 100644 |
| index 00000000..c004f26a |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Components.swift |
| @@ -0,0 +1,105 @@ |
| +// Ported from the r7 mockups (Components.swift). |
| +import SwiftUI |
| + |
| +struct Hairline: View { |
| + var body: some View { Rectangle().fill(Palette.border).frame(height: 1) } |
| +} |
| +struct StepNode: View { |
| + let state: String |
| + let needsYou: Bool |
| + var body: some View { |
| + ZStack { |
| + switch state { |
| + case "done": |
| + Image(systemName: "checkmark.circle.fill").resizable().foregroundStyle(Palette.positive) |
| + case "waiting": |
| + Image(systemName: needsYou ? "hand.raised.circle.fill" : "pause.circle.fill").resizable() |
| + .foregroundStyle(Palette.warning) |
| + case "running": |
| + Circle().strokeBorder(Palette.positive, lineWidth: 2) |
| + Circle().fill(Palette.positive).padding(6) |
| + default: |
| + Circle().strokeBorder(Palette.controlBorder, style: StrokeStyle(lineWidth: 1.5, dash: [3, 3])) |
| + } |
| + }.frame(width: 22, height: 22) |
| + } |
| +} |
| +/// The task's steps as a connected timeline, in plan order. |
| +struct StepsView: View { |
| + let task: EquipoTask |
| + var body: some View { |
| + let steps = task.steps ?? [] |
| + VStack(alignment: .leading, spacing: 0) { |
| + ForEach(Array(steps.enumerated()), id: \.element.key) { index, step in |
| + let last = index == steps.count - 1 |
| + let needsYou = waitsOnYou(step, in: task) |
| + HStack(alignment: .top, spacing: 12) { |
| + VStack(spacing: 4) { |
| + StepNode(state: step.state, needsYou: needsYou) |
| + if !last { |
| + Capsule().fill(step.state == "done" ? Palette.positive.opacity(0.55) : Palette.border) |
| + .frame(width: 2).frame(maxHeight: .infinity) |
| + } |
| + }.padding(.bottom, last ? 0 : 4) |
| + VStack(alignment: .leading, spacing: 4) { |
| + HStack(alignment: .firstTextBaseline) { |
| + SpecialistLabel(category: step.category, tone: step.state == "queued" ? Palette.secondary : Palette.text) |
| + Spacer(minLength: 8) |
| + Text(label(step, needsYou: needsYou)).font(Typo.caption) |
| + .foregroundStyle(needsYou ? Palette.warning : step.state == "done" ? Palette.positive : Palette.secondary) |
| + } |
| + Text(step.action).font(Typo.secondary) |
| + .foregroundStyle(step.state == "queued" ? Palette.secondary : Palette.text) |
| + .fixedSize(horizontal: false, vertical: true) |
| + if !step.actual.isEmpty { QuietLabel(text: step.actual) } |
| + else if let reason = ["needs_macos": "Needs a Mac to run", "copy_question": "Waiting for your answer"][step.reason] { QuietLabel(text: reason) } |
| + if let usage = step.usage { |
| + Text("\(usage.calls) calls · \(compact(usage.inputTokens)) in · \(compact(usage.outputTokens)) out") |
| + .font(Typo.caption).monospacedDigit().foregroundStyle(Palette.faint) |
| + } |
| + }.padding(.bottom, last ? 0 : 20) |
| + }.fixedSize(horizontal: false, vertical: true) |
| + .accessibilityElement(children: .combine) |
| + } |
| + } |
| + } |
| + private func label(_ step: Step, needsYou: Bool) -> String { |
| + if needsYou { return "Waiting for you" } |
| + switch step.state { |
| + case "done": return "Done" |
| + case "running": return "Running" |
| + case "waiting": return "Waiting" |
| + default: return "Queued" |
| + } |
| + } |
| +} |
| +struct AppGlyph: View { |
| + var size: CGFloat = 38 |
| + var body: some View { |
| + RoundedRectangle(cornerRadius: size * 0.225, style: .continuous) |
| + .fill(LinearGradient(colors: [Color(light: 0x3A6FF0, dark: 0x3A6FF0), Color(light: 0x1A46B8, dark: 0x1A46B8)], startPoint: .top, endPoint: .bottom)) |
| + .frame(width: size, height: size) |
| + .overlay(Image(systemName: "bubble.left.and.bubble.right.fill").font(.system(size: size * 0.42, weight: .semibold)).foregroundStyle(.white)) |
| + .accessibilityHidden(true) |
| + } |
| +} |
| +struct StatTile: View { |
| + let label: String |
| + let value: String |
| + var body: some View { |
| + VStack(alignment: .leading, spacing: 4) { |
| + Text(value).font(Typo.stat).monospacedDigit().foregroundStyle(Palette.text) |
| + Text(label).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + } |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + .padding(Metric.cardPadding - 2) |
| + .background(Palette.surface, in: RoundedRectangle(cornerRadius: Metric.card, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: Metric.card, style: .continuous).strokeBorder(Palette.border, lineWidth: 1)) |
| + .accessibilityElement(children: .combine) |
| + } |
| +} |
| + |
| +/// A waiting step waits on you only when it is not waiting for a machine. |
| +func waitsOnYou(_ step: Step, in task: EquipoTask) -> Bool { |
| + step.state == "waiting" && task.needsYou && step.reason != "needs_macos" |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Controls.swift b/native/apple/Sources/EquipoKit/UI/Controls.swift| new file mode 100644 |
| index 00000000..8e7e66b3 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Controls.swift |
| @@ -0,0 +1,88 @@ |
| +// Ported from the r7 mockups (Controls.swift). |
| +import SwiftUI |
| + |
| +enum ControlState: String, CaseIterable { case rest, hover, pressed, focus, disabled, loading } |
| + |
| +/// The web's button, drawn natively: a face, a full hairline border and a |
| +/// short contact shadow that goes away when the control is pressed in. |
| +struct EquipoButtonStyle: ButtonStyle { |
| + var primary = false |
| + var loading = false |
| + var forced: ControlState? |
| + func makeBody(configuration: Configuration) -> some View { |
| + Face(configuration: configuration, primary: primary, loading: loading || forced == .loading, forced: forced) |
| + } |
| + private struct Face: View { |
| + let configuration: ButtonStyleConfiguration |
| + let primary: Bool |
| + let loading: Bool |
| + let forced: ControlState? |
| + @Environment(\.isEnabled) private var isEnabled |
| + @Environment(\.colorScheme) private var scheme |
| + @State private var hovering = false |
| + var body: some View { |
| + let enabled = isEnabled && forced != .disabled |
| + let pressed = configuration.isPressed || forced == .pressed |
| + let hover = (hovering || forced == .hover) && enabled |
| + let shape = RoundedRectangle(cornerRadius: Metric.control, style: .continuous) |
| + ZStack { |
| + configuration.label.opacity(loading ? 0 : 1) |
| + if loading { ProgressView().controlSize(.small).tint(primary ? Color.white : Palette.secondary).environment(\.colorScheme, primary ? .dark : scheme) } |
| + } |
| + .font(Typo.button) |
| + .foregroundStyle(primary ? Color.white : Palette.controlText) |
| + .padding(.horizontal, 16).padding(.vertical, 6) |
| + .frame(minHeight: Metric.buttonHeight) |
| + .background(shape.fill(fill(pressed: pressed, hover: hover))) |
| + .overlay(shape.strokeBorder(primary ? Palette.primaryEdge : Palette.controlBorder, lineWidth: 1)) |
| + .shadow(color: Palette.contactShadow.opacity(pressed || !enabled ? 0 : 0.08), radius: 1, y: 1) |
| + .overlay { if forced == .focus { shape.inset(by: -3).stroke(Palette.accent.opacity(0.55), lineWidth: 3) } } |
| + .opacity(enabled ? 1 : 0.45) |
| + .contentShape(shape) |
| + .onHover { hovering = $0 } |
| + .animation(.easeOut(duration: 0.12), value: pressed) |
| + .animation(.easeOut(duration: 0.12), value: hover) |
| + } |
| + private func fill(pressed: Bool, hover: Bool) -> Color { |
| + if primary { return pressed ? Palette.primaryEdge : hover ? Palette.primaryFillHover : Palette.primaryFill } |
| + return pressed ? Palette.controlFacePressed : hover ? Palette.controlFaceHover : Palette.controlFace |
| + } |
| + } |
| +} |
| +struct EquipoButton: View { |
| + let title: String |
| + var icon: String? |
| + var primary = false |
| + var expanded = false |
| + var loading = false |
| + let action: () -> Void |
| + var body: some View { |
| + Button(action: action) { |
| + HStack(spacing: 7) { |
| + if let icon { Image(systemName: icon) } |
| + Text(title).multilineTextAlignment(.center) |
| + } |
| + .frame(maxWidth: expanded ? .infinity : nil) |
| + .fixedSize(horizontal: false, vertical: true) |
| + } |
| + .buttonStyle(EquipoButtonStyle(primary: primary, loading: loading)) |
| + } |
| +} |
| +struct QuietAction: View { |
| + let title: String |
| + var icon: String? |
| + let action: () -> Void |
| + @State private var hovering = false |
| + var body: some View { |
| + Button(action: action) { |
| + HStack(spacing: 5) { |
| + Text(title).underline(hovering) |
| + if let icon { Image(systemName: icon).imageScale(.small) } |
| + } |
| + .font(Typo.secondary).foregroundStyle(Palette.accent) |
| + .frame(minHeight: Metric.target).contentShape(Rectangle()) |
| + }.buttonStyle(.plain).onHover { hovering = $0 } |
| + } |
| +} |
| + |
| +/// Every state of the two button kinds on one sheet, for review. |
diff --git a/native/apple/Sources/EquipoKit/UI/LiveCards.swift b/native/apple/Sources/EquipoKit/UI/LiveCards.swift| new file mode 100644 |
| index 00000000..cd8c26da |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/LiveCards.swift |
| @@ -0,0 +1,151 @@ |
| +import SwiftUI |
| + |
| +/// A question card: the question as the first turn of its thread, the |
| +/// options, and the compact composer when the question allows text. |
| +/// Answering reads the question again first; a changed question is shown, |
| +/// never answered on the person's behalf. |
| +struct LiveQuestionCard: View { |
| + let card: Card |
| + let question: Question? |
| + let taskTitle: String? |
| + let session: EquipoSession |
| + @State private var phase: Phase = .open |
| + @State private var draft = "" |
| + @Environment(\.openURL) private var openURL |
| + |
| + enum Phase: Equatable { case open, sending(String), answered(String), changed, offline, failed } |
| + |
| + var body: some View { |
| + RaisedCard(flat: phase.isAnswered) { |
| + if let taskTitle, !(question?.text.contains(taskTitle) ?? false) { |
| + Text(taskTitle).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + } |
| + Text(question?.text ?? String(localized: "question.loading", bundle: .module)) |
| + .font(Typo.cardLine).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + content |
| + } |
| + .accessibilityElement(children: .contain) |
| + } |
| + |
| + @ViewBuilder private var content: some View { |
| + if let question, question.kind != "clarification" { |
| + openOnWeb |
| + } else if let question { |
| + switch phase { |
| + case .answered(let what): |
| + Label { Text(String(localized: "question.answered \(what)", bundle: .module)) } icon: { Image(systemName: "checkmark") } |
| + .font(Typo.secondaryStrong).foregroundStyle(Palette.positive) |
| + default: |
| + if !question.isAnswerable() { |
| + Text(String(localized: "question.closed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) |
| + } else { |
| + choices(question) |
| + if question.allowText { |
| + MiniComposer(placeholder: String(localized: "question.answer_placeholder", bundle: .module), busy: isSending) { text in |
| + Task { await submit(question, .text(text), shown: text) } |
| + } |
| + } |
| + feedback |
| + } |
| + } |
| + } else { |
| + ProgressView().controlSize(.small) |
| + } |
| + } |
| + |
| + private var isSending: Bool { if case .sending = phase { return true }; return false } |
| + |
| + @ViewBuilder private func choices(_ question: Question) -> some View { |
| + let options = question.options ?? [] |
| + if !options.isEmpty { |
| + ViewThatFits(in: .horizontal) { |
| + HStack(spacing: 10) { optionButtons(question, options, expanded: true) } |
| + VStack(spacing: 10) { optionButtons(question, options, expanded: true) } |
| + } |
| + } |
| + } |
| + @ViewBuilder private func optionButtons(_ question: Question, _ options: [QuestionOption], expanded: Bool) -> some View { |
| + ForEach(options) { option in |
| + let busy: String? = { if case .sending(let id) = phase, id == option.id { return String(localized: "action.sending", bundle: .module) }; return nil }() |
| + RosterButton(title: option.label, expanded: expanded, busy: busy) { |
| + Task { await submit(question, .option(option.id), shown: option.label, sendingID: option.id) } |
| + } |
| + .disabled(isSending) |
| + } |
| + } |
| + |
| + @ViewBuilder private var feedback: some View { |
| + switch phase { |
| + case .changed: Text(String(localized: "card.changed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) |
| + case .offline: Text(String(localized: "card.offline", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) |
| + case .failed: Text(String(localized: "card.failed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) |
| + default: EmptyView() |
| + } |
| + } |
| + |
| + private var openOnWeb: some View { |
| + RosterButton(title: String(localized: "card.open_on_web", bundle: .module)) { |
| + openURL(Feed.webURL(for: card, origin: session.origin)) |
| + } |
| + } |
| + |
| + private func submit(_ question: Question, _ answer: EquipoClient.Answer, shown: String, sendingID: String = "text") async { |
| + phase = .sending(sendingID) |
| + switch await session.answer(question, with: answer) { |
| + case .answered: phase = .answered(shown) |
| + case .changed: phase = .changed |
| + case .offline: phase = .offline |
| + case .failed: phase = .failed |
| + } |
| + } |
| +} |
| + |
| +extension LiveQuestionCard.Phase { |
| + var isAnswered: Bool { if case .answered = self { return true }; return false } |
| +} |
| + |
| +/// A decision this slice does not take natively: merges, approvals and the |
| +/// rest open the web app, where the full context and the must-match |
| +/// behaviour already are (sync proposal, parity rows R-02 and R-03). |
| +struct LiveDecisionCard: View { |
| + let card: Card |
| + let taskTitle: String? |
| + let origin: URL |
| + @Environment(\.openURL) private var openURL |
| + var body: some View { |
| + RaisedCard { |
| + Text(taskTitle ?? String(localized: "decision.untitled", bundle: .module)) |
| + .font(Typo.cardLine).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + Text(String(localized: "decision.on_web", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) |
| + .fixedSize(horizontal: false, vertical: true) |
| + RosterButton(title: String(localized: "card.open_on_web", bundle: .module), primary: true) { |
| + openURL(Feed.webURL(for: card, origin: origin)) |
| + } |
| + } |
| + } |
| +} |
| + |
| +/// A task report, flat on its rail: the title, what it is doing and the |
| +/// Needs you chip. Stage, Checks, Review and Branch wait for the API. |
| +struct LiveReport: View { |
| + let task: EquipoTask |
| + var onOpen: () -> Void = {} |
| + var body: some View { |
| + let summary = TaskSummary(task) |
| + Button(action: onOpen) { |
| + FlowLayout(spacing: 8, lineSpacing: 4) { |
| + Text(task.description).font(Typo.compactTitle).foregroundStyle(Palette.text) |
| + Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot) |
| + if summary.needsYou { NeedsChip() } |
| + } |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + .contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain) |
| + .padding(.leading, Metric.indent).padding(.bottom, 2) |
| + .background(alignment: .topLeading) { |
| + Capsule().fill(Palette.border).frame(width: 2).padding(.leading, Metric.tile / 2 - 1) |
| + } |
| + .accessibilityHint(Text(String(localized: "task.open_hint", bundle: .module))) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/RosterViews.swift b/native/apple/Sources/EquipoKit/UI/RosterViews.swift| new file mode 100644 |
| index 00000000..e916d0f0 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/RosterViews.swift |
| @@ -0,0 +1,473 @@ |
| +// Ported from the r7 mockups (RosterViews.swift): marks, bylines, cards, |
| +// sub-chats and messages. Fed by EquipoKit/Presentation, never by fixtures. |
| +import SwiftUI |
| + |
| +// MARK: - Marks and tiles |
| + |
| +/// The web's coordinator mark (chat.html "roster-mark"): an outline |
| +/// four-point star in a 24-unit box. |
| +struct SparkleShape: Shape { |
| + func path(in rect: CGRect) -> Path { |
| + let s = min(rect.width, rect.height) / 24 |
| + let ox = rect.midX - 12 * s, oy = rect.midY - 12 * s |
| + func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: ox + x * s, y: oy + y * s) } |
| + var path = Path() |
| + path.move(to: p(12, 3)) |
| + path.addCurve(to: p(21, 12), control1: p(13.1, 8.8), control2: p(15.2, 10.9)) |
| + path.addCurve(to: p(12, 21), control1: p(15.2, 13.1), control2: p(13.1, 15.2)) |
| + path.addCurve(to: p(3, 12), control1: p(10.9, 15.2), control2: p(8.8, 13.1)) |
| + path.addCurve(to: p(12, 3), control1: p(8.8, 10.9), control2: p(10.9, 8.8)) |
| + path.closeSubpath() |
| + return path |
| + } |
| +} |
| +/// The coordinator: a bare, muted outline sparkle. No name on screen. |
| +struct CoordinatorMark: View { |
| + var size: CGFloat = 22 |
| + var thinking = false |
| + var body: some View { |
| + SparkleShape() |
| + .stroke(Palette.secondary, style: StrokeStyle(lineWidth: size / 24 * 1.6, lineCap: .round, lineJoin: .round)) |
| + .frame(width: size, height: size) |
| + .rotationEffect(.degrees(thinking ? 45 : 0)).scaleEffect(thinking ? 0.85 : 1).opacity(thinking ? 0.5 : 1) |
| + .animation(thinking ? .easeInOut(duration: 1.3).repeatForever(autoreverses: true) : nil, value: thinking) |
| + .accessibilityLabel("Coordinator") |
| + } |
| +} |
| +/// A specialist: its icon centred in a tile, beside its name. Never a letter. |
| +struct SpecialistTile: View { |
| + let who: Specialist |
| + var size: CGFloat = Metric.tile |
| + var body: some View { |
| + let shape = RoundedRectangle(cornerRadius: size * 0.3, style: .continuous) |
| + ZStack { |
| + shape.fill(Palette.surface) |
| + .shadow(color: Palette.contactShadow.opacity(0.08), radius: 1, y: 1) |
| + shape.strokeBorder(Palette.border, lineWidth: 1) |
| + Image(systemName: who.symbol) |
| + .font(.system(size: size * 0.46, weight: .medium)) |
| + .foregroundStyle(Palette.text) |
| + .frame(width: size, height: size, alignment: .center) |
| + } |
| + .frame(width: size, height: size) |
| + .accessibilityHidden(true) |
| + } |
| +} |
| +/// The author column: a tile for a specialist, the bare mark for the coordinator. |
| +struct Avatar: View { |
| + let who: Specialist |
| + var size: CGFloat = Metric.tile |
| + var body: some View { |
| + if who == .coordinator { |
| + CoordinatorMark(size: size * 0.74).frame(width: size, height: size, alignment: .leading) |
| + } else { |
| + SpecialistTile(who: who, size: size) |
| + } |
| + } |
| +} |
| +/// A project's monogram, kept neutral: no hue, so nothing reads as purple. |
| +struct Monogram: View { |
| + let name: String |
| + var size: CGFloat = 16 |
| + var body: some View { |
| + Text(String(name.prefix(1)).uppercased()) |
| + .font(.system(size: size * 0.62, weight: .bold, design: .rounded)) |
| + .foregroundStyle(Palette.neutral) |
| + .frame(width: size, height: size) |
| + .background(Palette.neutralBackground, in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)) |
| + .accessibilityHidden(true) |
| + } |
| +} |
| + |
| +// MARK: - Byline |
| + |
| +struct ProjectChip: View { |
| + let name: String |
| + var action: (() -> Void)? |
| + var menu: Binding<Bool>? |
| + @State private var hovering = false |
| + var body: some View { |
| + chip |
| + } |
| + @ViewBuilder private var chip: some View { |
| + let label = HStack(spacing: 4) { |
| + Monogram(name: name) |
| + Text(name).lineLimit(1).truncationMode(.tail) |
| + .underline(hovering && action != nil) |
| + } |
| + .font(Typo.bylineVerb).foregroundStyle(Palette.secondary) |
| + if let action { |
| + Button(action: action) { label.frame(minHeight: Metric.tile).contentShape(Rectangle()) } |
| + .buttonStyle(.plain).onHover { hovering = $0 } |
| + .accessibilityLabel("Project \(name). Wrong project?") |
| + } else { label } |
| + } |
| +} |
| +/// "Engineering reports · W Woodstar 11:59". The coordinator's byline is |
| +/// only its mark, the project and the time. |
| +struct Byline: View { |
| + let byline: RosterByline |
| + var onProject: (() -> Void)? |
| + var menu: Binding<Bool>? |
| + var body: some View { |
| + HStack(alignment: .center, spacing: 0) { |
| + Avatar(who: byline.who).frame(width: Metric.indent, alignment: .leading) |
| + FlowLayout(spacing: 6, lineSpacing: 2) { |
| + if byline.showsName { |
| + Text(byline.who.name).font(Typo.bylineName).foregroundStyle(Palette.text) |
| + Text(byline.verb).font(Typo.bylineVerb).foregroundStyle(Palette.secondary) |
| + } |
| + if let project = byline.project { |
| + if byline.showsName { Text("·").font(Typo.bylineVerb).foregroundStyle(Palette.faint).accessibilityHidden(true) } |
| + ProjectChip(name: project, action: onProject ?? {}, menu: menu) |
| + } |
| + if let time = byline.timeText { Text(time).font(Typo.time).foregroundStyle(Palette.faint) } |
| + } |
| + } |
| + .frame(minHeight: Metric.tile) |
| + .accessibilityElement(children: .combine) |
| + .accessibilityLabel(byline.spoken) |
| + } |
| +} |
| + |
| +extension StageTone { |
| + var dot: Color { self == .warning ? Palette.warning : self == .negative ? Palette.negative : Palette.positive } |
| + var halo: Color { self == .warning ? Palette.warningBackground : self == .negative ? Palette.negativeBackground : Palette.positiveBackground } |
| + var text: Color { dot } |
| + /// The eyebrow is coloured only when the stage needs attention. |
| + var eyebrow: Color { self == .positive ? Palette.secondary : dot } |
| +} |
| + |
| +// MARK: - Facts, chips and links |
| + |
| +struct NeedsChip: View { |
| + var body: some View { |
| + HStack(spacing: 4) { |
| + Image(systemName: "hand.raised").font(.system(size: 11, weight: .semibold)) |
| + Text("Needs you").textCase(.uppercase).kerning(0.3) |
| + } |
| + .font(Typo.chip).foregroundStyle(Palette.warning) |
| + .padding(.horizontal, 8).padding(.vertical, 3) |
| + .background(Palette.warningBackground, in: Capsule()) |
| + .fixedSize() |
| + } |
| +} |
| +/// A quiet text link: muted, no underline until hovered. |
| +struct QuietLink: View { |
| + let title: String |
| + var icon: String? |
| + var action: () -> Void = {} |
| + @State private var hovering = false |
| + var body: some View { |
| + Button(action: action) { |
| + HStack(spacing: 3) { |
| + Text(title).underline(hovering) |
| + if let icon { Image(systemName: icon).font(.system(size: 10, weight: .semibold)) } |
| + } |
| + .font(Typo.secondary).foregroundStyle(hovering ? Palette.text : Palette.secondary) |
| + .frame(minHeight: Metric.target).contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain).onHover { hovering = $0 } |
| + } |
| +} |
| +/// A button that can show its busy label, as the web's data-busy-label does. |
| +struct RosterButton: View { |
| + let title: String |
| + var primary = false |
| + var expanded = false |
| + var busy: String? |
| + var forced: ControlState? |
| + var measure = true |
| + var action: () -> Void = {} |
| + var body: some View { |
| + let button = Button(action: action) { |
| + ZStack { |
| + Text(title).opacity(busy == nil ? 1 : 0) |
| + if let busy { |
| + HStack(spacing: 6) { |
| + ProgressView().controlSize(.small).tint(primary ? .white : Palette.secondary) |
| + Text(busy) |
| + } |
| + } |
| + } |
| + .multilineTextAlignment(.center) |
| + .frame(maxWidth: expanded ? .infinity : nil) |
| + } |
| + .buttonStyle(EquipoButtonStyle(primary: primary, forced: forced)) |
| + .allowsHitTesting(busy == nil) |
| + .accessibilityLabel(busy ?? title) |
| + if measure { button } else { button } |
| + } |
| +} |
| + |
| +// MARK: - Raised cards |
| + |
| +struct SetAsideButton: View { |
| + var busy = false |
| + var forced: ControlState? |
| + var action: () -> Void |
| + @State private var hovering = false |
| + var body: some View { |
| + Button(action: action) { |
| + Group { |
| + if busy { |
| + Text("Setting aside…").font(Typo.caption).padding(.horizontal, 8) |
| + } else { |
| + Image(systemName: "xmark").font(.system(size: 13, weight: .semibold)).frame(width: 36, height: 36) |
| + } |
| + } |
| + .foregroundStyle(Palette.secondary) |
| + .frame(minWidth: Metric.target, minHeight: Metric.target) |
| + .background { |
| + let on = hovering || forced == .hover || forced == .pressed |
| + RoundedRectangle(cornerRadius: 8, style: .continuous) |
| + .fill(forced == .pressed ? Palette.controlFacePressed : on ? Palette.controlFaceHover : .clear) |
| + .frame(width: busy ? nil : 32, height: 32) |
| + } |
| + .contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain).onHover { hovering = $0 } |
| + .disabled(busy) |
| + .accessibilityLabel("Set aside") |
| + .help("Set aside") |
| + } |
| +} |
| +/// Only things that need you are raised: a surface, a rim and a soft shadow. |
| +struct RaisedCard<Content: View>: View { |
| + var flat = false |
| + @ViewBuilder var content: Content |
| + var body: some View { |
| + let shape = RoundedRectangle(cornerRadius: Metric.raised, style: .continuous) |
| + VStack(alignment: .leading, spacing: Metric.gap) { content } |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + .padding(Metric.raisedPadding) |
| + .background { |
| + shape.fill(flat ? Palette.surface2 : Palette.surface) |
| + .shadow(color: Palette.contactShadow.opacity(flat ? 0 : 0.06), radius: 2, y: 2) |
| + .shadow(color: Palette.contactShadow.opacity(flat ? 0 : 0.10), radius: 8, y: 6) |
| + } |
| + .overlay(shape.strokeBorder(flat ? Palette.border : Palette.lightRim, lineWidth: 1)) |
| + } |
| +} |
| +/// The first line of a card, with Set aside centred on it. |
| +struct CardHead: View { |
| + let text: String |
| + var aside: (() -> Void)? |
| + var settingAside = false |
| + var forced: ControlState? |
| + var body: some View { |
| + HStack(alignment: .top, spacing: 4) { |
| + Text(text).font(Typo.cardLine).foregroundStyle(Palette.text) |
| + .fixedSize(horizontal: false, vertical: true) |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + if let aside { |
| + // A 44-point target, centred on the first line of text. |
| + SetAsideButton(busy: settingAside, forced: forced, action: aside) |
| + .padding(.top, -(Metric.target - lineHeight) / 2) |
| + .padding(.trailing, -(Metric.target - 32) / 2 - 4) |
| + .padding(.bottom, -(Metric.target - lineHeight) / 2) |
| + } |
| + } |
| + } |
| + private var lineHeight: CGFloat { |
| + #if os(iOS) |
| + return 22 |
| + #else |
| + return 18 |
| + #endif |
| + } |
| +} |
| +// MARK: - Sub-chats |
| + |
| +struct ThreadBubble: View { |
| + let turn: ThreadTurn |
| + var body: some View { |
| + if turn.own { |
| + VStack(alignment: .trailing, spacing: 4) { |
| + Text(turn.text).font(Typo.thread).foregroundStyle(Palette.text) |
| + .fixedSize(horizontal: false, vertical: true) |
| + .padding(.horizontal, 12).padding(.vertical, 8) |
| + .background(Palette.soft, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.lightRim, lineWidth: 1)) |
| + Text("Sent").font(Typo.caption).foregroundStyle(Palette.faint) |
| + } |
| + .padding(.leading, 32) |
| + .frame(maxWidth: .infinity, alignment: .trailing) |
| + .accessibilityElement(children: .combine) |
| + .accessibilityLabel("You said: \(turn.text). Sent") |
| + } else { |
| + let who = turn.who ?? .coordinator |
| + HStack(alignment: .top, spacing: 8) { |
| + Avatar(who: who, size: 24) |
| + VStack(alignment: .leading, spacing: 3) { |
| + HStack(spacing: 6) { |
| + Text(who.name).font(Typo.threadWho).foregroundStyle(Palette.secondary) |
| + Text(turn.timeText).font(Typo.time).foregroundStyle(Palette.faint) |
| + } |
| + Text(turn.text).font(Typo.thread).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + } |
| + .padding(.horizontal, 12).padding(.top, 6).padding(.bottom, 8) |
| + .background(Palette.surface, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border, lineWidth: 1)) |
| + Spacer(minLength: 24) |
| + } |
| + .accessibilityElement(children: .combine) |
| + } |
| + } |
| +} |
| +struct ReadingLine: View { |
| + let who: Specialist |
| + var body: some View { |
| + HStack(spacing: 8) { |
| + HStack(spacing: 3) { ForEach(0..<3, id: \.self) { _ in Circle().frame(width: 4, height: 4) } } |
| + Text("\(who.name) is reading") |
| + } |
| + .font(Typo.secondary).foregroundStyle(Palette.secondary) |
| + .accessibilityElement(children: .combine) |
| + } |
| +} |
| +/// The card's composer: the main composer's pill, smaller. The send |
| +/// button is a 44-point target centred in a 46-point pill. |
| +struct MiniComposer: View { |
| + var placeholder = "Reply" |
| + @State var text: String |
| + var busy = false |
| + var focused = false |
| + var onSend: (String) -> Void = { _ in } |
| + init(placeholder: String = "Reply", text: String = "", busy: Bool = false, focused: Bool = false, onSend: @escaping (String) -> Void = { _ in }) { |
| + self.placeholder = placeholder; _text = State(initialValue: text); self.busy = busy; self.focused = focused; self.onSend = onSend |
| + } |
| + var body: some View { |
| + let has = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| + let shape = RoundedRectangle(cornerRadius: 23, style: .continuous) |
| + HStack(alignment: .bottom, spacing: 4) { |
| + TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) |
| + .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) |
| + .lineLimit(1...5) |
| + .focusEffectDisabled() |
| + .padding(.leading, 16).padding(.vertical, 12) |
| + .frame(minHeight: 46) |
| + .accessibilityLabel(placeholder) |
| + Button { if has { onSend(text); text = "" } } label: { |
| + Group { |
| + if busy { |
| + HStack(spacing: 5) { ProgressView().controlSize(.mini).tint(.white); Text("Sending…").font(Typo.caption) } |
| + .foregroundStyle(.white).padding(.horizontal, 12).frame(height: 36) |
| + .background(Palette.primaryFill, in: Capsule()) |
| + } else { |
| + Image(systemName: "arrow.up").font(.system(size: 14, weight: .bold)) |
| + .foregroundStyle(has ? Color.white : Palette.faint) |
| + .frame(width: 36, height: 36) |
| + .background(has ? Palette.primaryFill : Palette.surface2, in: Circle()) |
| + } |
| + } |
| + .frame(minWidth: 44, minHeight: 44).contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain).padding(.trailing, 1).padding(.bottom, 1) |
| + .accessibilityLabel(busy ? "Sending" : "Send") |
| + .disabled(!has || busy) |
| + } |
| + .background(Palette.surface, in: shape) |
| + .overlay(shape.strokeBorder(focused || has ? Palette.accent : Palette.controlBorder, lineWidth: 1)) |
| + .background(shape.stroke(Palette.accent.opacity(focused || has ? 0.18 : 0), lineWidth: 6)) |
| + } |
| +} |
| +/// "Talk about this": the task's thread, in a drawer under the report. |
| +struct SubChatDrawer: View { |
| + let turns: [ThreadTurn] |
| + var body: some View { |
| + VStack(alignment: .leading, spacing: Metric.gap) { |
| + ForEach(turns) { ThreadBubble(turn: $0) } |
| + MiniComposer(placeholder: "Reply") |
| + } |
| + .padding(12) |
| + .background(Palette.surface2, in: RoundedRectangle(cornerRadius: Metric.raised - 4, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: Metric.raised - 4, style: .continuous).strokeBorder(Palette.border, lineWidth: 1)) |
| + } |
| +} |
| + |
| +// MARK: - Messages, the thinking line and the roll-up |
| + |
| +struct CoordinatorMessage: View { |
| + let message: Message |
| + var body: some View { |
| + VStack(alignment: .leading, spacing: 4) { |
| + HStack(spacing: 0) { |
| + CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading) |
| + Text(message.createdAt.formatted(date: .omitted, time: .shortened)).font(Typo.time).foregroundStyle(Palette.faint) |
| + }.frame(minHeight: Metric.tile) |
| + Text(message.body).font(Typo.message).foregroundStyle(Palette.text).lineSpacing(3) |
| + .fixedSize(horizontal: false, vertical: true).textSelection(.enabled) |
| + } |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + .accessibilityElement(children: .combine) |
| + .accessibilityLabel("Coordinator, \(message.createdAt.formatted(date: .omitted, time: .shortened)). \(message.body)") |
| + } |
| +} |
| +struct OwnMessage: View { |
| + let text: String |
| + var body: some View { |
| + Text(text).font(Typo.message).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + .padding(.horizontal, 14).padding(.vertical, 10) |
| + .background(Palette.soft, in: RoundedRectangle(cornerRadius: 18, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Palette.lightRim.opacity(0.7), lineWidth: 1)) |
| + .padding(.leading, 48) |
| + .frame(maxWidth: .infinity, alignment: .trailing) |
| + .accessibilityLabel("You said: \(text)") |
| + } |
| +} |
| +/// One line: the mark, the real activity, elapsed time and a quiet Stop. |
| +struct TodayDivider: View { |
| + let label: String |
| + var body: some View { |
| + HStack(spacing: 12) { |
| + Hairline() |
| + Text(label).font(Typo.caption).foregroundStyle(Palette.secondary).fixedSize() |
| + Hairline() |
| + }.accessibilityAddTraits(.isHeader) |
| + } |
| +} |
| +// MARK: - Layout |
| + |
| +/// Wraps its children onto as many lines as they need. |
| +struct FlowLayout: Layout { |
| + var spacing: CGFloat = 8 |
| + var lineSpacing: CGFloat = 4 |
| + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { |
| + let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews) |
| + let width = rows.map { $0.width }.max() ?? 0 |
| + let height = rows.reduce(0) { $0 + $1.height } + CGFloat(max(0, rows.count - 1)) * lineSpacing |
| + return CGSize(width: proposal.width.map { min($0, width) } ?? width, height: height) |
| + } |
| + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { |
| + var y = bounds.minY |
| + for row in arrange(width: bounds.width, subviews: subviews) { |
| + var x = bounds.minX |
| + for index in row.items { |
| + let size = subviews[index].sizeThatFits(.unspecified) |
| + let fitted = min(size.width, bounds.maxX - x) |
| + subviews[index].place(at: CGPoint(x: x, y: y + (row.height - size.height) / 2), proposal: ProposedViewSize(width: fitted, height: size.height)) |
| + x += fitted + spacing |
| + } |
| + y += row.height + lineSpacing |
| + } |
| + } |
| + private struct Row { var items: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0 } |
| + private func arrange(width: CGFloat, subviews: Subviews) -> [Row] { |
| + var rows: [Row] = [Row()] |
| + for (index, view) in subviews.enumerated() { |
| + let size = view.sizeThatFits(.unspecified) |
| + if size.width == 0 && size.height == 0 { continue } |
| + var row = rows[rows.count - 1] |
| + let needed = row.items.isEmpty ? size.width : row.width + spacing + size.width |
| + if needed > width && !row.items.isEmpty { |
| + rows.append(Row(items: [index], width: size.width, height: size.height)) |
| + continue |
| + } |
| + row.items.append(index); row.width = needed; row.height = max(row.height, size.height) |
| + rows[rows.count - 1] = row |
| + } |
| + return rows.filter { !$0.items.isEmpty } |
| + } |
| +} |
| + |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift| new file mode 100644 |
| index 00000000..570352a6 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift |
| @@ -0,0 +1,32 @@ |
| +import SwiftUI |
| + |
| +/// The paired team and this device: who you are, until when, and Sign out, |
| +/// which revokes the device on the server. |
| +public struct AccountScreen: View { |
| + let model: EquipoAppModel |
| + let session: EquipoSession |
| + @State private var confirming = false |
| + public init(model: EquipoAppModel, session: EquipoSession) { self.model = model; self.session = session } |
| + public var body: some View { |
| + Form { |
| + Section(String(localized: "account.team", bundle: .module)) { |
| + LabeledContent(String(localized: "account.team_name", bundle: .module), value: session.teamName) |
| + LabeledContent(String(localized: "account.address", bundle: .module), value: session.origin.host ?? session.origin.absoluteString) |
| + if let me = session.me { LabeledContent(String(localized: "account.signed_in_as", bundle: .module), value: me.person.displayIdentity) } |
| + } |
| + Section(String(localized: "account.device", bundle: .module)) { |
| + LabeledContent(String(localized: "account.device_name", bundle: .module), value: session.account.label) |
| + if let expires = session.account.credential?.expiresAt { |
| + LabeledContent(String(localized: "account.until", bundle: .module), value: expires.formatted(date: .long, time: .omitted)) |
| + } |
| + } |
| + Section { |
| + Button(String(localized: "account.sign_out", bundle: .module), role: .destructive) { confirming = true } |
| + } footer: { Text(String(localized: "account.sign_out_footer", bundle: .module)) } |
| + } |
| + .formStyle(.grouped) |
| + .confirmationDialog(String(localized: "account.sign_out_confirm", bundle: .module), isPresented: $confirming) { |
| + Button(String(localized: "account.sign_out", bundle: .module), role: .destructive) { Task { await model.signOut() } } |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift| new file mode 100644 |
| index 00000000..9449a914 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift |
| @@ -0,0 +1,54 @@ |
| +import Foundation |
| +import Observation |
| +import RastrilloApple |
| + |
| +/// The app's state above any one screen: the paired team, if any, its |
| +/// session, and pairing when there is none. |
| +@MainActor @Observable |
| +public final class EquipoAppModel { |
| + public let accounts: DeviceAccounts |
| + public private(set) var session: EquipoSession? |
| + public let pairing: PairingModel |
| + /// Set when the server ended the session, so pairing can say why. |
| + public private(set) var endedTeam: String? |
| + |
| + public init(store: SecretStore = KeychainSecretStore()) { |
| + accounts = DeviceAccounts(store: store) |
| + pairing = PairingModel(accounts: accounts) |
| + if let account = accounts.all().first(where: { $0.isUsable() }) { |
| + session = EquipoSession(account: account, accounts: accounts) |
| + } |
| + } |
| + |
| + public var needsPairing: Bool { session == nil || session?.status == .signedOut } |
| + |
| + /// After pairing approves this device. |
| + public func paired() { |
| + guard let account = pairing.account else { return } |
| + endedTeam = nil |
| + session = EquipoSession(account: account, accounts: accounts) |
| + foreground() |
| + } |
| + |
| + /// The server ended the session (revoked, removed or expired): pair again. |
| + public func sessionEnded() { |
| + endedTeam = session?.teamName |
| + session = nil |
| + pairing.cancel() |
| + } |
| + |
| + public func signOut() async { |
| + await session?.signOut() |
| + session = nil |
| + endedTeam = nil |
| + pairing.cancel() |
| + } |
| + |
| + public func foreground() { |
| + NativeConnectivity.shared.foregrounded() |
| + guard let session else { return } |
| + Task { await session.refresh() } |
| + session.startPolling() |
| + } |
| + public func background() { session?.stopPolling() } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift| new file mode 100644 |
| index 00000000..711d9412 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift |
| @@ -0,0 +1,122 @@ |
| +import RastrilloApple |
| +import SwiftUI |
| + |
| +/// The conversation: Roster's bylines and cards over live data, with the |
| +/// composer at the bottom. Used as is on iPhone; the Mac draws the same feed |
| +/// in AppKit. |
| +public struct ConversationScreen: View { |
| + let session: EquipoSession |
| + var openTask: (String) -> Void |
| + public init(session: EquipoSession, openTask: @escaping (String) -> Void) { self.session = session; self.openTask = openTask } |
| + |
| + public var body: some View { |
| + let items = Feed.build(session) |
| + ScrollViewReader { proxy in |
| + ScrollView { |
| + LazyVStack(alignment: .leading, spacing: 20) { |
| + if items.isEmpty && session.status == .ready { |
| + Text(String(localized: "conversation.empty", bundle: .module)) |
| + .font(Typo.body).foregroundStyle(Palette.secondary).padding(.top, 40) |
| + } |
| + ForEach(items) { item in row(item).id(item.id) } |
| + Color.clear.frame(height: 8).id("bottom") |
| + } |
| + .padding(.horizontal, 16).padding(.top, 12).padding(.bottom, 20) |
| + .frame(maxWidth: 760).frame(maxWidth: .infinity) |
| + } |
| + .defaultScrollAnchor(.bottom) |
| + .refreshable { await session.refresh() } |
| + .onChange(of: items.count) { _, _ in withAnimation { proxy.scrollTo("bottom", anchor: .bottom) } } |
| + } |
| + .background(Palette.background) |
| + .safeAreaInset(edge: .top, spacing: 0) { NativeOfflineBanner(origin: session.origin) } |
| + .safeAreaInset(edge: .bottom, spacing: 0) { |
| + Composer(placeholder: String(localized: "conversation.placeholder", bundle: .module)) { text in |
| + Task { await session.send(text) } |
| + } |
| + } |
| + } |
| + |
| + @ViewBuilder private func row(_ item: FeedItem) -> some View { |
| + switch item { |
| + case .own(let m): OwnMessage(text: m.body) |
| + case .coordinator(let m): CoordinatorMessage(message: m) |
| + case .outgoing(let o): OutgoingMessage(item: o) { Task { await session.retry(o.id) } } |
| + case .report(_, let byline, let task): |
| + VStack(alignment: .leading, spacing: 8) { |
| + Byline(byline: byline) |
| + LiveReport(task: task) { openTask(task.id) } |
| + } |
| + case .question(let card, let byline, let question, let title): |
| + VStack(alignment: .leading, spacing: 8) { |
| + Byline(byline: byline) |
| + LiveQuestionCard(card: card, question: question, taskTitle: title, session: session) |
| + } |
| + case .decision(let card, let byline, let title): |
| + VStack(alignment: .leading, spacing: 8) { |
| + Byline(byline: byline) |
| + LiveDecisionCard(card: card, taskTitle: title, origin: session.origin) |
| + } |
| + } |
| + } |
| +} |
| + |
| +/// A message this device is still sending, and how it is going. |
| +struct OutgoingMessage: View { |
| + let item: EquipoSession.Outgoing |
| + var retry: () -> Void |
| + var body: some View { |
| + VStack(alignment: .trailing, spacing: 4) { |
| + OwnMessage(text: item.text).opacity(item.state == .sending ? 0.7 : 1) |
| + switch item.state { |
| + case .sending: Text(String(localized: "message.sending", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.faint) |
| + case .waiting: |
| + Button(action: retry) { Text(String(localized: "message.waiting", bundle: .module)).underline() } |
| + .buttonStyle(.plain).font(Typo.caption).foregroundStyle(Palette.secondary).frame(minHeight: Metric.target) |
| + case .failed: |
| + Button(action: retry) { Text(String(localized: "message.failed", bundle: .module)).underline() } |
| + .buttonStyle(.plain).font(Typo.caption).foregroundStyle(Palette.negative).frame(minHeight: Metric.target) |
| + } |
| + } |
| + .frame(maxWidth: .infinity, alignment: .trailing) |
| + } |
| +} |
| + |
| +/// The composer: a pill with a send button centred in it. |
| +struct Composer: View { |
| + let placeholder: String |
| + var onSend: (String) -> Void |
| + @State private var text = "" |
| + @FocusState private var focused: Bool |
| + var body: some View { |
| + let has = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| + let shape = RoundedRectangle(cornerRadius: 22, style: .continuous) |
| + HStack(alignment: .bottom, spacing: 0) { |
| + TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) |
| + .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) |
| + .lineLimit(1...6).focused($focused) |
| + .padding(.leading, 18).padding(.vertical, 11) |
| + .accessibilityLabel(placeholder) |
| + .onSubmit(send) |
| + Button(action: send) { |
| + Image(systemName: "arrow.up").font(.system(size: 16, weight: .bold)) |
| + .foregroundStyle(has ? Color.white : Palette.faint) |
| + .frame(width: 34, height: 34) |
| + .background(has ? Palette.primaryFill : Palette.surface2, in: Circle()) |
| + .frame(width: 44, height: 44).contentShape(Circle()) |
| + } |
| + .buttonStyle(.plain).disabled(!has) |
| + .accessibilityLabel(Text(String(localized: "composer.send", bundle: .module))) |
| + } |
| + .background(Palette.surface, in: shape) |
| + .overlay(shape.strokeBorder(focused ? Palette.accent : Palette.controlBorder, lineWidth: 1)) |
| + .padding(.horizontal, 16).padding(.top, 10).padding(.bottom, 8) |
| + .frame(maxWidth: 760).frame(maxWidth: .infinity) |
| + .background(.bar) |
| + } |
| + private func send() { |
| + let value = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| + guard !value.isEmpty else { return } |
| + onSend(value); text = "" |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/PairingView.swift b/native/apple/Sources/EquipoKit/UI/Screens/PairingView.swift| new file mode 100644 |
| index 00000000..80c77285 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/PairingView.swift |
| @@ -0,0 +1,111 @@ |
| +import SwiftUI |
| +#if canImport(UIKit) |
| +import UIKit |
| +#endif |
| + |
| +/// First run: name the team, show the code, approve in the browser. One |
| +/// action per screen. The wizard's later steps (model account, first |
| +/// project) stay on the web for now. |
| +public struct PairingView: View { |
| + @Bindable var model: EquipoAppModel |
| + @State private var team = "" |
| + @Environment(\.openURL) private var openURL |
| + public init(model: EquipoAppModel) { self.model = model } |
| + |
| + public var body: some View { |
| + let pairing = model.pairing |
| + VStack(alignment: .leading, spacing: 20) { |
| + Spacer(minLength: 12) |
| + AppGlyph(size: 56) |
| + switch pairing.step { |
| + case .enterTeam, .failed, .expired: |
| + enterTeam(pairing) |
| + case .requesting: |
| + title(String(localized: "pairing.title", bundle: .module), String(localized: "pairing.requesting", bundle: .module)) |
| + ProgressView() |
| + case .waiting(let code, let verification, _): |
| + title(String(localized: "pairing.title", bundle: .module), String(localized: "pairing.approve_lede", bundle: .module)) |
| + codePanel(code) |
| + HStack(spacing: 10) { |
| + ProgressView().controlSize(.small) |
| + Text(String(localized: "pairing.waiting", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) |
| + } |
| + Spacer() |
| + RosterButton(title: String(localized: "pairing.open_browser", bundle: .module), primary: true, expanded: true) { openURL(verification) } |
| + QuietAction(title: String(localized: "pairing.cancel", bundle: .module)) { pairing.cancel() } |
| + case .approved(let teamName): |
| + title(String(localized: "pairing.approved_title", bundle: .module), String(localized: "pairing.approved \(teamName)", bundle: .module)) |
| + Spacer() |
| + RosterButton(title: String(localized: "pairing.continue", bundle: .module), primary: true, expanded: true) { model.paired() } |
| + } |
| + Spacer(minLength: 12) |
| + } |
| + .padding(24) |
| + .frame(maxWidth: 520, maxHeight: .infinity, alignment: .topLeading) |
| + .frame(maxWidth: .infinity) |
| + .background(Palette.background.ignoresSafeArea()) |
| + .tint(Palette.accent) |
| + } |
| + |
| + @ViewBuilder private func enterTeam(_ pairing: PairingModel) -> some View { |
| + title(String(localized: "pairing.welcome_title", bundle: .module), String(localized: "pairing.welcome_lede", bundle: .module)) |
| + if let ended = model.endedTeam { |
| + Text(String(localized: "pairing.ended \(ended)", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.warning) |
| + } |
| + VStack(alignment: .leading, spacing: 6) { |
| + Text(String(localized: "pairing.team_label", bundle: .module)).font(Typo.captionStrong).foregroundStyle(Palette.secondary) |
| + TextField(String(localized: "pairing.team_placeholder", bundle: .module), text: $team) |
| + .textContentType(.URL) |
| + #if os(iOS) |
| + .keyboardType(.URL).textInputAutocapitalization(.never) |
| + #endif |
| + .autocorrectionDisabled() |
| + .font(Typo.body) |
| + .padding(.horizontal, 12).frame(minHeight: Metric.target) |
| + .background(Palette.controlFace, in: RoundedRectangle(cornerRadius: Metric.control, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: Metric.control, style: .continuous).strokeBorder(Palette.controlBorder, lineWidth: 1)) |
| + .onSubmit { start(pairing) } |
| + Text(String(localized: "pairing.team_hint", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + } |
| + if case .failed(let message) = pairing.step { |
| + Text(message).font(Typo.secondary).foregroundStyle(Palette.negative) |
| + } |
| + if case .expired = pairing.step { |
| + Text(String(localized: "pairing.expired", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) |
| + } |
| + Spacer() |
| + RosterButton(title: String(localized: "pairing.pair", bundle: .module), primary: true, expanded: true) { start(pairing) } |
| + .disabled(PairingModel.origin(from: team) == nil) |
| + } |
| + |
| + private func start(_ pairing: PairingModel) { |
| + guard let origin = PairingModel.origin(from: team) else { return } |
| + pairing.start(origin: origin, label: Self.deviceLabel) |
| + } |
| + |
| + static var deviceLabel: String { |
| + #if canImport(UIKit) |
| + return UIDevice.current.name |
| + #else |
| + return Host.current().localizedName ?? "Mac" |
| + #endif |
| + } |
| + |
| + private func title(_ title: String, _ lede: String) -> some View { |
| + VStack(alignment: .leading, spacing: 8) { |
| + Text(title).font(.largeTitle.weight(.bold)).foregroundStyle(Palette.text) |
| + Text(lede).font(Typo.body).foregroundStyle(Palette.secondary).fixedSize(horizontal: false, vertical: true) |
| + } |
| + } |
| + |
| + private func codePanel(_ code: String) -> some View { |
| + Panel { |
| + VStack(spacing: 8) { |
| + Text(String(localized: "pairing.your_code", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + Text(code).font(.system(size: 40, weight: .semibold, design: .monospaced)).foregroundStyle(Palette.text) |
| + .textSelection(.enabled).accessibilityLabel(code.map(String.init).joined(separator: " ")) |
| + Text(String(localized: "pairing.shown_as \(Self.deviceLabel)", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + }.frame(maxWidth: .infinity).padding(.vertical, 8) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift| new file mode 100644 |
| index 00000000..c574335c |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift |
| @@ -0,0 +1,74 @@ |
| +import SwiftUI |
| + |
| +#if os(iOS) |
| +/// The iPhone app: pairing until there is a team, then Conversation, Needs |
| +/// you and Tasks as tabs, with the task view pushed from any of them. |
| +public struct PhoneRoot: View { |
| + @State var model: EquipoAppModel |
| + @Environment(\.scenePhase) private var phase |
| + public init(model: EquipoAppModel = EquipoAppModel()) { _model = State(initialValue: model) } |
| + |
| + public var body: some View { |
| + Group { |
| + if let session = model.session, session.status != .signedOut { |
| + PhoneTabs(model: model, session: session) |
| + } else { |
| + PairingView(model: model) |
| + } |
| + } |
| + .tint(Palette.accent) |
| + .onChange(of: phase) { _, now in now == .active ? model.foreground() : model.background() } |
| + .onChange(of: model.session?.status) { _, status in if status == .signedOut { model.sessionEnded() } } |
| + .task { model.foreground() } |
| + } |
| +} |
| + |
| +struct PhoneTabs: View { |
| + let model: EquipoAppModel |
| + let session: EquipoSession |
| + @State private var conversationPath: [String] = [] |
| + @State private var needsPath: [String] = [] |
| + @State private var tasksPath: [String] = [] |
| + @State private var showingAccount = false |
| + |
| + var body: some View { |
| + TabView { |
| + Tab(String(localized: "tab.conversation", bundle: .module), systemImage: "bubble.left.and.bubble.right") { |
| + stack($conversationPath, title: String(localized: "tab.conversation", bundle: .module)) { |
| + ConversationScreen(session: session) { conversationPath.append($0) } |
| + } |
| + } |
| + Tab(String(localized: "tab.needs", bundle: .module), systemImage: "tray") { |
| + stack($needsPath, title: String(localized: "tab.needs", bundle: .module)) { |
| + NeedsScreen(session: session) { needsPath.append($0) } |
| + } |
| + } |
| + .badge(session.needsYou?.count ?? 0) |
| + Tab(String(localized: "tab.tasks", bundle: .module), systemImage: "checklist") { |
| + stack($tasksPath, title: String(localized: "tab.tasks", bundle: .module)) { |
| + TasksScreen(session: session) { tasksPath.append($0) } |
| + } |
| + } |
| + } |
| + .sheet(isPresented: $showingAccount) { |
| + NavigationStack { AccountScreen(model: model, session: session).navigationTitle(session.teamName) } |
| + } |
| + } |
| + |
| + private func stack<C: View>(_ path: Binding<[String]>, title: String, @ViewBuilder content: () -> C) -> some View { |
| + NavigationStack(path: path) { |
| + content() |
| + .navigationTitle(title).navigationBarTitleDisplayMode(.inline) |
| + .toolbar { |
| + ToolbarItem(placement: .topBarLeading) { |
| + Button { showingAccount = true } label: { Image(systemName: "person.crop.circle") } |
| + .accessibilityLabel(Text(String(localized: "account.title", bundle: .module))) |
| + } |
| + } |
| + .navigationDestination(for: String.self) { id in |
| + TaskScreen(session: session, taskID: id).navigationTitle(String(localized: "task.title", bundle: .module)).navigationBarTitleDisplayMode(.inline) |
| + } |
| + } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift b/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift| new file mode 100644 |
| index 00000000..5dd0b3c4 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift |
| @@ -0,0 +1,194 @@ |
| +import SwiftUI |
| + |
| +/// Needs you: every task waiting on this person, with its question or |
| +/// decision card where the conversation has one. |
| +public struct NeedsScreen: View { |
| + let session: EquipoSession |
| + var openTask: (String) -> Void |
| + public init(session: EquipoSession, openTask: @escaping (String) -> Void) { self.session = session; self.openTask = openTask } |
| + public var body: some View { |
| + ScrollView { |
| + VStack(alignment: .leading, spacing: 20) { |
| + if let needs = session.needsYou { |
| + if needs.isEmpty { |
| + ContentUnavailableView { |
| + Label(String(localized: "needs.empty_title", bundle: .module), systemImage: "checkmark.circle") |
| + } description: { Text(String(localized: "needs.empty", bundle: .module)) } |
| + .padding(.top, 40) |
| + } |
| + ForEach(needs) { task in |
| + VStack(alignment: .leading, spacing: 8) { |
| + TaskRowButton(task: task, project: session.project(for: task)?.name) { openTask(task.id) } |
| + ForEach(session.cards.filter { $0.taskId == task.id && $0.kind != "task" }) { card in |
| + if card.kind == "question" { |
| + LiveQuestionCard(card: card, question: session.questions[card.resourceId], taskTitle: nil, session: session) |
| + } else { |
| + LiveDecisionCard(card: card, taskTitle: task.description, origin: session.origin) |
| + } |
| + } |
| + } |
| + } |
| + } else { |
| + ProgressView().frame(maxWidth: .infinity).padding(.top, 40) |
| + } |
| + } |
| + .padding(16).frame(maxWidth: 760).frame(maxWidth: .infinity) |
| + } |
| + .refreshable { await session.refresh() } |
| + .background(Palette.background) |
| + } |
| +} |
| + |
| +/// Tasks, grouped as the web groups them. |
| +public struct TasksScreen: View { |
| + let session: EquipoSession |
| + var openTask: (String) -> Void |
| + public init(session: EquipoSession, openTask: @escaping (String) -> Void) { self.session = session; self.openTask = openTask } |
| + public var body: some View { |
| + List { |
| + group(String(localized: "tasks.needs_you", bundle: .module), session.tasks.filter(\.needsYou)) |
| + group(String(localized: "tasks.in_progress", bundle: .module), session.tasks.filter { !$0.needsYou && !Self.finished($0) }) |
| + group(String(localized: "tasks.finished", bundle: .module), session.tasks.filter { !$0.needsYou && Self.finished($0) }) |
| + } |
| + .scrollContentBackground(.hidden).background(Palette.background) |
| + .refreshable { await session.refresh() } |
| + .overlay { |
| + if session.status == .ready && session.tasks.isEmpty { |
| + ContentUnavailableView(String(localized: "tasks.empty_title", bundle: .module), systemImage: "checklist", |
| + description: Text(String(localized: "tasks.empty", bundle: .module))) |
| + } |
| + } |
| + } |
| + static func finished(_ t: EquipoTask) -> Bool { |
| + let steps = t.steps ?? [] |
| + return t.state == "cancelled" || (!steps.isEmpty && steps.allSatisfy { $0.state == "done" }) |
| + } |
| + @ViewBuilder private func group(_ title: String, _ tasks: [EquipoTask]) -> some View { |
| + if !tasks.isEmpty { |
| + Section(title) { |
| + ForEach(tasks) { task in |
| + TaskRowButton(task: task, project: session.project(for: task)?.name) { openTask(task.id) } |
| + } |
| + }.listRowBackground(Palette.surface) |
| + } |
| + } |
| +} |
| + |
| +struct TaskRowButton: View { |
| + let task: EquipoTask |
| + let project: String? |
| + var action: () -> Void |
| + var body: some View { |
| + let summary = TaskSummary(task) |
| + Button(action: action) { |
| + HStack(alignment: .center, spacing: 10) { |
| + VStack(alignment: .leading, spacing: 5) { |
| + HStack(spacing: 8) { |
| + if let project { ProjectChip(name: project) } |
| + Spacer(minLength: 8) |
| + if summary.needsYou { NeedsChip() } |
| + } |
| + Text(task.description).font(Typo.cardTitle).foregroundStyle(Palette.text).multilineTextAlignment(.leading) |
| + Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot) |
| + } |
| + Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.faint) |
| + } |
| + .padding(.vertical, 4).contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityElement(children: .combine) |
| + } |
| +} |
| + |
| +/// One task: what it is doing, any question or decision, its steps, its |
| +/// usage and its thread ("Talk about this"). |
| +public struct TaskScreen: View { |
| + let session: EquipoSession |
| + let taskID: String |
| + @State private var talking = false |
| + public init(session: EquipoSession, taskID: String) { self.session = session; self.taskID = taskID } |
| + |
| + public var body: some View { |
| + Group { |
| + if let task = session.task(taskID) { |
| + ScrollView { content(task).padding(16).frame(maxWidth: 760).frame(maxWidth: .infinity) } |
| + } else { |
| + ContentUnavailableView(String(localized: "task.missing", bundle: .module), systemImage: "questionmark.folder") |
| + } |
| + } |
| + .background(Palette.background) |
| + .task { await session.loadThread(taskID) } |
| + .refreshable { await session.refresh(); await session.loadThread(taskID) } |
| + } |
| + |
| + @ViewBuilder private func content(_ task: EquipoTask) -> some View { |
| + let summary = TaskSummary(task) |
| + VStack(alignment: .leading, spacing: 20) { |
| + VStack(alignment: .leading, spacing: 6) { |
| + HStack { |
| + if let project = session.project(for: task)?.name { ProjectChip(name: project) } |
| + Spacer() |
| + if summary.needsYou { NeedsChip() } |
| + } |
| + Text(task.description).font(Typo.reportTitle).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot) |
| + } |
| + ForEach(session.cards.filter { $0.taskId == task.id && $0.kind != "task" }) { card in |
| + if card.kind == "question" { |
| + LiveQuestionCard(card: card, question: session.questions[card.resourceId], taskTitle: nil, session: session) |
| + } else { |
| + LiveDecisionCard(card: card, taskTitle: task.description, origin: session.origin) |
| + } |
| + } |
| + HStack(spacing: 18) { |
| + RosterButton(title: talking ? String(localized: "task.hide_talk", bundle: .module) : String(localized: "task.talk", bundle: .module)) { talking.toggle() } |
| + QuietLink(title: String(localized: "task.open_web", bundle: .module), icon: "arrow.up.right") { |
| + #if canImport(UIKit) |
| + UIApplication.shared.open(session.origin.appendingPathComponent("tasks/\(task.id)")) |
| + #else |
| + NSWorkspace.shared.open(session.origin.appendingPathComponent("tasks/\(task.id)")) |
| + #endif |
| + } |
| + } |
| + if talking { TaskThread(session: session, taskID: task.id) } |
| + if !(task.steps ?? []).isEmpty { |
| + VStack(alignment: .leading, spacing: 10) { |
| + SectionTitle(text: String(localized: "task.steps", bundle: .module)) |
| + Panel { StepsView(task: task) } |
| + } |
| + } |
| + if let usage = task.usage { |
| + VStack(alignment: .leading, spacing: 10) { |
| + SectionTitle(text: String(localized: "task.usage", bundle: .module)) |
| + HStack(spacing: 10) { |
| + StatTile(label: String(localized: "usage.calls", bundle: .module), value: usage.calls.formatted()) |
| + StatTile(label: String(localized: "usage.tokens_in", bundle: .module), value: usage.inputTokens.formatted(.number.notation(.compactName))) |
| + StatTile(label: String(localized: "usage.tokens_out", bundle: .module), value: usage.outputTokens.formatted(.number.notation(.compactName))) |
| + } |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +/// "Talk about this": the task's own thread, with a compact composer. |
| +struct TaskThread: View { |
| + let session: EquipoSession |
| + let taskID: String |
| + var body: some View { |
| + let turns = (session.threads[taskID] ?? []).map(ThreadTurn.init) |
| + + session.outgoing.filter { $0.taskID == taskID }.map { ThreadTurn(id: $0.id, who: nil, text: $0.text, time: nil, pending: true) } |
| + VStack(alignment: .leading, spacing: Metric.gap) { |
| + if turns.isEmpty { |
| + Text(String(localized: "task.thread_empty", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) |
| + } |
| + ForEach(turns) { ThreadBubble(turn: $0) } |
| + MiniComposer(placeholder: String(localized: "task.reply", bundle: .module)) { text in |
| + Task { await session.send(text, inThreadOf: taskID) } |
| + } |
| + } |
| + .padding(12) |
| + .background(Palette.surface2, in: RoundedRectangle(cornerRadius: Metric.raised - 4, style: .continuous)) |
| + .overlay(RoundedRectangle(cornerRadius: Metric.raised - 4, style: .continuous).strokeBorder(Palette.border, lineWidth: 1)) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/Theme.swift b/native/apple/Sources/EquipoKit/UI/Theme.swift| new file mode 100644 |
| index 00000000..cb152c57 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/Theme.swift |
| @@ -0,0 +1,243 @@ |
| +// Ported from the r7 mockups (native-mockups-r4, native/mockups/Shared/Theme.swift). |
| +import SwiftUI |
| +#if os(macOS) |
| +import AppKit |
| +#else |
| +import UIKit |
| +#endif |
| + |
| +// Colours transcribed from the web day theme (internal/equipo/static/theme.css). |
| +enum Palette { |
| + static let text = Color(light: 0x18181B, dark: 0xEDEDF0) |
| + static let secondary = Color(light: 0x52525C, dark: 0xA1A1AA) |
| + static let faint = Color(light: 0x6B6B75, dark: 0x8C8C96) |
| + static let background = Color(light: 0xFBFBFC, dark: 0x0C0D0F) |
| + static let surface = Color(light: 0xFFFFFF, dark: 0x141518) |
| + static let surface2 = Color(light: 0xF3F3F5, dark: 0x18191D) |
| + static let border = Color(light: 0xE6E6EA, dark: 0x26282E) |
| + static let accent = Color(light: 0x1F56D6, dark: 0x7AA2FF) |
| + static let soft = Color(light: 0xECF1FF, dark: 0x16234A) |
| + static let softBorder = Color(light: 0xC9D7FA, dark: 0x27397A) |
| + static let controlFace = Color(light: 0xFFFFFF, dark: 0x141518) |
| + static let controlFaceHover = Color(light: 0xF7F8FA, dark: 0x1B1D22) |
| + static let controlFacePressed = Color(light: 0xE6E9EE, dark: 0x202329) |
| + /// --rst-line-strong: hollow track dots. |
| + static let lineStrong = Color(light: 0x868691, dark: 0x71737C) |
| + /// --rst-light-rim: the edge of a raised card, accent mixed into the line. |
| + static let lightRim = Color(light: 0xB8C5E5, dark: 0x5D6986) |
| + static let controlText = Color(light: 0x18181B, dark: 0xEDEDF0) |
| + static let controlBorder = Color(light: 0xD0D4DC, dark: 0x343843) |
| + static let placeholder = Color(light: 0x6B6B75, dark: 0x8C8C96) |
| + static let primaryFill = Color(light: 0x2257DF, dark: 0x2F61E8) |
| + static let primaryFillHover = Color(light: 0x1D4DC8, dark: 0x2956D0) |
| + static let primaryEdge = Color(light: 0x153CA0, dark: 0x1F43A6) |
| + static let positive = Color(light: 0x166534, dark: 0x6EE7A8) |
| + static let positiveBackground = Color(light: 0xDCFCE7, dark: 0x10281C) |
| + static let warning = Color(light: 0x854D0E, dark: 0xF0C46A) |
| + static let warningBackground = Color(light: 0xFEF3C7, dark: 0x2C2110) |
| + static let negative = Color(light: 0xB91C1C, dark: 0xF79AA0) |
| + static let negativeBackground = Color(light: 0xFEE2E2, dark: 0x331819) |
| + static let neutral = Color(light: 0x374151, dark: 0xC3C9D1) |
| + static let neutralBackground = Color(light: 0xEEF0F2, dark: 0x262C34) |
| + static let contactShadow = Color(light: 0x101828, dark: 0x000000) |
| +} |
| +extension Color { |
| + init(light: UInt32, dark: UInt32) { |
| + #if os(macOS) |
| + self.init(nsColor: NSColor(name: nil) { appearance in |
| + let hex = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua ? dark : light |
| + return NSColor(srgbRed: Double((hex >> 16) & 255) / 255, green: Double((hex >> 8) & 255) / 255, blue: Double(hex & 255) / 255, alpha: 1) |
| + }) |
| + #else |
| + self.init(uiColor: UIColor { traits in |
| + let hex = traits.userInterfaceStyle == .dark ? dark : light |
| + return UIColor(red: Double((hex >> 16) & 255) / 255, green: Double((hex >> 8) & 255) / 255, blue: Double(hex & 255) / 255, alpha: 1) |
| + }) |
| + #endif |
| + } |
| +} |
| + |
| +// One scale per platform: text styles on iPhone so Dynamic Type works, |
| +// fixed AppKit-sized type on the Mac. |
| +enum Typo { |
| + #if os(iOS) |
| + static let screenTitle = Font.title2.weight(.bold) |
| + static let question = Font.title3.weight(.semibold) |
| + static let cardTitle = Font.headline |
| + static let body = Font.body |
| + static let secondary = Font.subheadline |
| + static let secondaryStrong = Font.subheadline.weight(.semibold) |
| + static let caption = Font.footnote |
| + static let captionStrong = Font.footnote.weight(.semibold) |
| + static let button = Font.body.weight(.medium) |
| + static let stat = Font.system(.title2, design: .rounded).weight(.semibold) |
| + static let bylineName = Font.headline |
| + static let bylineVerb = Font.subheadline |
| + static let time = Font.footnote.monospacedDigit() |
| + static let eyebrow = Font.footnote.weight(.semibold) |
| + static let reportTitle = Font.title3.weight(.semibold) |
| + static let compactTitle = Font.body.weight(.semibold) |
| + static let cardLine = Font.body |
| + static let factLabel = Font.footnote |
| + static let factValue = Font.subheadline.weight(.semibold) |
| + static let code = Font.system(.footnote, design: .monospaced).weight(.semibold) |
| + static let thread = Font.subheadline |
| + static let threadWho = Font.caption.weight(.semibold) |
| + static let chip = Font.caption.weight(.bold) |
| + static let message = Font.body |
| + #else |
| + static let screenTitle = Font.system(size: 20, weight: .bold) |
| + static let question = Font.system(size: 15, weight: .semibold) |
| + static let cardTitle = Font.system(size: 13, weight: .semibold) |
| + static let body = Font.system(size: 13) |
| + static let secondary = Font.system(size: 12) |
| + static let secondaryStrong = Font.system(size: 12, weight: .semibold) |
| + static let caption = Font.system(size: 11) |
| + static let captionStrong = Font.system(size: 11, weight: .semibold) |
| + static let button = Font.system(size: 13, weight: .medium) |
| + static let stat = Font.system(size: 20, weight: .semibold, design: .rounded) |
| + static let bylineName = Font.system(size: 13, weight: .bold) |
| + static let bylineVerb = Font.system(size: 12) |
| + static let time = Font.system(size: 11).monospacedDigit() |
| + static let eyebrow = Font.system(size: 11, weight: .semibold) |
| + static let reportTitle = Font.system(size: 15, weight: .semibold) |
| + static let compactTitle = Font.system(size: 13, weight: .semibold) |
| + static let cardLine = Font.system(size: 14) |
| + static let factLabel = Font.system(size: 11) |
| + static let factValue = Font.system(size: 12, weight: .semibold) |
| + static let code = Font.system(size: 11, weight: .semibold, design: .monospaced) |
| + static let thread = Font.system(size: 13) |
| + static let threadWho = Font.system(size: 11, weight: .semibold) |
| + static let chip = Font.system(size: 10, weight: .bold) |
| + static let message = Font.system(size: 14) |
| + #endif |
| +} |
| +enum Metric { |
| + #if os(iOS) |
| + static let card: CGFloat = 14 |
| + static let control: CGFloat = 10 |
| + static let buttonHeight: CGFloat = 48 |
| + static let cardPadding: CGFloat = 16 |
| + static let target: CGFloat = 44 |
| + static let raised: CGFloat = 18 |
| + static let raisedPadding: CGFloat = 14 |
| + static let tile: CGFloat = 30 |
| + /// Where a report's content starts: past the byline tile. |
| + static let indent: CGFloat = 40 |
| + static let gap: CGFloat = 12 |
| + #else |
| + static let card: CGFloat = 10 |
| + static let control: CGFloat = 6 |
| + static let buttonHeight: CGFloat = 32 |
| + static let cardPadding: CGFloat = 14 |
| + static let target: CGFloat = 32 |
| + static let raised: CGFloat = 14 |
| + static let raisedPadding: CGFloat = 16 |
| + static let tile: CGFloat = 30 |
| + static let indent: CGFloat = 48 |
| + static let gap: CGFloat = 12 |
| + #endif |
| +} |
| + |
| +enum Tone { |
| + case neutral, accent, positive, warning, negative |
| + var foreground: Color { |
| + switch self { |
| + case .neutral: return Palette.neutral |
| + case .accent: return Palette.accent |
| + case .positive: return Palette.positive |
| + case .warning: return Palette.warning |
| + case .negative: return Palette.negative |
| + } |
| + } |
| + var background: Color { |
| + switch self { |
| + case .neutral: return Palette.neutralBackground |
| + case .accent: return Palette.soft |
| + case .positive: return Palette.positiveBackground |
| + case .warning: return Palette.warningBackground |
| + case .negative: return Palette.negativeBackground |
| + } |
| + } |
| +} |
| + |
| +/// A card: surface, full hairline border, and an optional tint. Never a coloured edge. |
| +struct Panel<Content: View>: View { |
| + var tinted = false |
| + var tone: Tone = .accent |
| + var padding: CGFloat = Metric.cardPadding |
| + var spacing: CGFloat = 12 |
| + @ViewBuilder var content: Content |
| + var body: some View { |
| + let shape = RoundedRectangle(cornerRadius: Metric.card, style: .continuous) |
| + VStack(alignment: .leading, spacing: spacing) { content } |
| + .frame(maxWidth: .infinity, alignment: .leading) |
| + .padding(padding) |
| + .background(shape.fill(tinted ? tone.background : Palette.surface)) |
| + .overlay(shape.strokeBorder(tinted ? (tone == .accent ? Palette.softBorder : tone.foreground.opacity(0.25)) : Palette.border, lineWidth: 1)) |
| + } |
| +} |
| +struct QuietLabel: View { |
| + let text: String |
| + var body: some View { Text(text).font(Typo.caption).foregroundStyle(Palette.secondary).fixedSize(horizontal: false, vertical: true) } |
| +} |
| +struct SectionTitle: View { |
| + let text: String |
| + var body: some View { |
| + Text(text).font(Typo.captionStrong).textCase(.uppercase).kerning(0.4) |
| + .foregroundStyle(Palette.secondary).accessibilityAddTraits(.isHeader) |
| + } |
| +} |
| +struct StatusPill: View { |
| + let text: String |
| + var tone: Tone = .neutral |
| + var icon: String? |
| + var body: some View { |
| + HStack(spacing: 4) { |
| + if let icon { Image(systemName: icon).imageScale(.small) } |
| + Text(text) |
| + } |
| + .font(Typo.captionStrong) |
| + .foregroundStyle(tone.foreground) |
| + .padding(.horizontal, 8).padding(.vertical, 3) |
| + .background(tone.background, in: Capsule()) |
| + } |
| +} |
| +struct CountBadge: View { |
| + let count: Int |
| + var body: some View { |
| + Text(count.formatted()).font(Typo.captionStrong).monospacedDigit() |
| + .foregroundStyle(Palette.warning) |
| + .padding(.horizontal, 7).frame(minWidth: 22, minHeight: 20) |
| + .background(Palette.warningBackground, in: Capsule()) |
| + .accessibilityLabel("\(count) waiting") |
| + } |
| +} |
| +/// A specialist is always an icon beside its name. No lettered squares. |
| +struct SpecialistLabel: View { |
| + let category: String |
| + var tone: Color = Palette.text |
| + var body: some View { |
| + HStack(spacing: 6) { |
| + Image(systemName: specialistIcon(category)).foregroundStyle(Palette.secondary) |
| + Text(category.capitalized).foregroundStyle(tone) |
| + }.font(Typo.secondaryStrong) |
| + } |
| +} |
| +struct Meter: View { |
| + let value: Double |
| + var tone: Tone = .accent |
| + var body: some View { |
| + GeometryReader { proxy in |
| + ZStack(alignment: .leading) { |
| + Capsule().fill(Palette.neutralBackground) |
| + Capsule().fill(tone == .accent ? Palette.primaryFill : tone.foreground) |
| + .frame(width: max(6, proxy.size.width * min(1, max(0, value)))) |
| + } |
| + }.frame(height: 6).accessibilityElement().accessibilityValue("\(Int(value * 100)) percent") |
| + } |
| +} |
| +func specialistIcon(_ category: String) -> String { Specialist(category: category).symbol } |
| +func compact(_ value: Int64) -> String { |
| + Int(value).formatted(.number.notation(.compactName).precision(.fractionLength(0...1))) |
| +} |
diff --git a/native/apple/Sources/EquipoMac/main.swift b/native/apple/Sources/EquipoMac/main.swift| new file mode 100644 |
| index 00000000..1984571b |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoMac/main.swift |
| @@ -0,0 +1,5 @@ |
| +import EquipoKit |
| + |
| +// The Mac app; built out below. |
| +struct EquipoMacMain { static func main() {} } |
| +EquipoMacMain.main() |
diff --git a/native/apple/Tests/EquipoKitTests/ClientTests.swift b/native/apple/Tests/EquipoKitTests/ClientTests.swift| new file mode 100644 |
| index 00000000..2067615d |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/ClientTests.swift |
| @@ -0,0 +1,88 @@ |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +@Suite struct ClientTests { |
| + @Test func everyFixtureDecodes() throws { |
| + _ = try Fixture.decode("me", as: Me.self) |
| + _ = try Fixture.decode("projects", as: Page<Project>.self) |
| + let tasks = try Fixture.decode("tasks", as: Page<EquipoTask>.self) |
| + _ = try Fixture.decode("needs-you", as: Page<EquipoTask>.self) |
| + let page = try Fixture.decode("conversation", as: ConversationPage.self) |
| + _ = try Fixture.decode("thread", as: ConversationPage.self) |
| + _ = try Fixture.decode("message", as: Message.self) |
| + _ = try Fixture.decode("question", as: Question.self) |
| + _ = try Fixture.decode("ack", as: Ack.self) |
| + _ = try Fixture.decode("device-challenge", as: DeviceChallenge.self) |
| + _ = try Fixture.decode("device-credential", as: DeviceCredential.self) |
| + _ = try Fixture.decode("devices", as: Page<Device>.self) |
| + _ = try Fixture.decode("subscription", as: NotificationSubscription.self) |
| + _ = try Fixture.decode("notifications", as: Page<EquipoNotification>.self) |
| + // Go writes nanoseconds; they parse. |
| + #expect(page.messages?[1].createdAt != nil) |
| + // Unknown usage stays unknown. |
| + #expect(tasks.items[1].usage == nil) |
| + } |
| + |
| + @Test func readsCarryTheBearerAndNoCookies() async throws { |
| + let t = ScriptedTransport(); t.on("GET /me", fixture: "me") |
| + _ = try await EquipoClient(transport: t, token: "secret-token").me() |
| + let r = try #require(t.requests.first) |
| + let url = try r.urlRequest(origin: t.origin) |
| + #expect(url.url?.absoluteString == "https://oficina.example.test/api/v1/me") |
| + #expect(url.value(forHTTPHeaderField: "Authorization") == "Bearer secret-token") |
| + #expect(url.httpShouldHandleCookies == false) |
| + #expect(url.value(forHTTPHeaderField: "Idempotency-Key") == nil) |
| + } |
| + |
| + @Test func writesCarryKeyAndQuotedRevision() async throws { |
| + let t = ScriptedTransport(); t.on("POST /questions/question-vat/answer", fixture: "ack") |
| + let q: Question = try Fixture.decode("question") |
| + let write = try EquipoClient.answer(.option("vat"), to: q) |
| + _ = try await EquipoClient(transport: t, token: "tok").answer(question: q.id, write) |
| + let url = try t.requests[0].urlRequest(origin: t.origin) |
| + #expect(url.value(forHTTPHeaderField: "Idempotency-Key") == write.key) |
| + #expect(url.value(forHTTPHeaderField: "If-Match") == "\"7\"") |
| + let body = try JSONSerialization.jsonObject(with: url.httpBody!) as! [String: String] |
| + #expect(body == ["kind": "clarification", "option_id": "vat"]) |
| + } |
| + |
| + @Test func anAnswerWithoutARevisionIsNeverSent() async throws { |
| + let t = ScriptedTransport() |
| + let unbound = PendingWrite(body: Data("{}".utf8)) |
| + await #expect(throws: EquipoAPIError.status(428)) { _ = try await EquipoClient(transport: t, token: "t").answer(question: "q", unbound) } |
| + #expect(t.requests.isEmpty) |
| + } |
| + |
| + @Test func errorsKeepCodeAndCurrentRevision() async throws { |
| + let t = ScriptedTransport(); t.on("GET /me", status: 409, fixture: "error-revision-conflict") |
| + do { _ = try await EquipoClient(transport: t, token: "t").me(); Issue.record("no error") } |
| + catch let e as EquipoAPIError { |
| + #expect(e.isStale); #expect(e.currentRevision == 9); #expect(e.status == 409) |
| + } |
| + t.on("GET /tasks", .success(APIResponse(status: 401, data: Data("not json".utf8)))) |
| + do { _ = try await EquipoClient(transport: t, token: "t").tasks(); Issue.record("no error") } |
| + catch let e as EquipoAPIError { #expect(e.endsSession) } |
| + } |
| + |
| + @Test func listLimitsStayInRange() async throws { |
| + let t = ScriptedTransport(); t.on("GET /tasks", fixture: "tasks") |
| + _ = try await EquipoClient(transport: t, token: "t").tasks(limit: 500) |
| + #expect(t.requests[0].query.first { $0.name == "limit" }?.value == "100") |
| + } |
| + |
| + @Test func idsAreEscapedInPaths() async throws { |
| + let t = ScriptedTransport() |
| + _ = try? await EquipoClient(transport: t, token: "t").task("a/b?c") |
| + #expect(t.requests[0].path == "/tasks/a%2Fb%3Fc") |
| + } |
| + |
| + @Test func questionAnswerability() throws { |
| + var q: Question = try Fixture.decode("question") |
| + #expect(q.isAnswerable()) |
| + q.state = "answered"; #expect(!q.isAnswerable()) |
| + q.state = "open"; q.canAnswer = false; #expect(!q.isAnswerable()) |
| + q.canAnswer = true; q.expiresAt = Date(timeIntervalSince1970: 0); #expect(!q.isAnswerable()) |
| + q.expiresAt = nil; q.kind = "native"; #expect(!q.isAnswerable()) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/DeviceProofTests.swift b/native/apple/Tests/EquipoKitTests/DeviceProofTests.swift| new file mode 100644 |
| index 00000000..326bb57b |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/DeviceProofTests.swift |
| @@ -0,0 +1,49 @@ |
| +import CryptoKit |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +/// The server's bytes, from `personapi.TestNativeDeviceProofVectors`. |
| +struct ProofVector: Decodable { |
| + let name, seed, publicKey, instance, id, challenge, nonce, message, signature: String |
| +} |
| + |
| +@Suite struct DeviceProofTests { |
| + let vectors: [ProofVector] = try! Fixture.decode("device-proof-vectors") |
| + |
| + @Test func messageIsTheServersBytes() { |
| + for v in vectors { |
| + let ours = DeviceProof.message(instance: v.instance, id: v.id, challenge: v.challenge, nonce: v.nonce) |
| + #expect(String(decoding: ours, as: UTF8.self) == v.message, "vector \(v.name)") |
| + } |
| + } |
| + |
| + @Test func signaturesVerifyBothWays() throws { |
| + for v in vectors { |
| + let key = try Curve25519.Signing.PrivateKey(rawRepresentation: Base64URL.decode(v.seed)!) |
| + #expect(Base64URL.encode(key.publicKey.rawRepresentation) == v.publicKey) |
| + let message = Data(v.message.utf8) |
| + // The server's signature verifies here, and ours verifies with the server's key. |
| + #expect(key.publicKey.isValidSignature(Base64URL.decode(v.signature)!, for: message)) |
| + #expect(key.publicKey.isValidSignature(try key.signature(for: message), for: message)) |
| + } |
| + } |
| + |
| + @Test func instanceComesFromTheChallenge() { |
| + for v in vectors { #expect(DeviceProof.instance(fromChallenge: v.challenge) == v.instance) } |
| + #expect(DeviceProof.instance(fromChallenge: "not base64 json") == nil) |
| + } |
| + |
| + @Test func noncesAreFreshAndLongEnough() { |
| + let a = DeviceProof.nonce(), b = DeviceProof.nonce() |
| + #expect(a != b) |
| + #expect(Base64URL.decode(a)!.count == 32) |
| + } |
| + |
| + @Test func exchangeBodyIsSnakeCase() throws { |
| + let challenge: DeviceChallenge = try Fixture.decode("device-challenge") |
| + let body = try DeviceProof.body(for: challenge, key: .init(), nonce: "nonce-0123456789ab") |
| + let json = try JSONSerialization.jsonObject(with: EquipoJSON.encoder.encode(body)) as! [String: String] |
| + #expect(Set(json.keys) == ["id", "device_secret", "challenge", "nonce", "signature"]) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/ack.json b/native/apple/Tests/EquipoKitTests/Fixtures/ack.json| new file mode 100644 |
| index 00000000..9f444f00 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/ack.json |
| @@ -0,0 +1,3 @@ |
| +{ |
| + "revision": 8 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json b/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json| new file mode 100644 |
| index 00000000..191876ac |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json |
| @@ -0,0 +1,67 @@ |
| +{ |
| + "messages": [ |
| + { |
| + "id": "message-1", |
| + "conversation_id": "conversation-paul", |
| + "thread_id": "", |
| + "author_kind": "person", |
| + "author_id": "paul@example.test", |
| + "body": "Can you fix the VAT rounding on invoice PDFs?", |
| + "sequence": 1, |
| + "revision": 1, |
| + "created_at": "2026-11-13T09:41:00Z", |
| + "sources": [] |
| + }, |
| + { |
| + "id": "message-2", |
| + "conversation_id": "conversation-paul", |
| + "thread_id": "", |
| + "author_kind": "coordinator", |
| + "author_id": "coordinator", |
| + "body": "Engineering has fixed the rounding. Copy has one question.", |
| + "sequence": 2, |
| + "revision": 1, |
| + "created_at": "2026-11-13T09:42:00.123456789Z", |
| + "sources": [] |
| + } |
| + ], |
| + "cards": [ |
| + { |
| + "id": "card-vat-report", |
| + "kind": "task", |
| + "resource_id": "task-vat", |
| + "task_id": "task-vat", |
| + "revision": 7, |
| + "copy_key": "chat.card.task", |
| + "actions": null, |
| + "waiting_task_id": "" |
| + }, |
| + { |
| + "id": "card-vat", |
| + "kind": "question", |
| + "resource_id": "question-vat", |
| + "task_id": "task-vat", |
| + "revision": 7, |
| + "copy_key": "questions.clarification", |
| + "actions": [ |
| + "answer" |
| + ], |
| + "waiting_task_id": "task-vat" |
| + }, |
| + { |
| + "id": "card-merge", |
| + "kind": "merge", |
| + "resource_id": "task-signin", |
| + "task_id": "task-signin", |
| + "revision": 4, |
| + "copy_key": "chat.card.merge_question", |
| + "actions": [ |
| + "merge", |
| + "wait" |
| + ], |
| + "waiting_task_id": "task-signin" |
| + } |
| + ], |
| + "next_cursor": "", |
| + "revision": 11 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/device-challenge.json b/native/apple/Tests/EquipoKitTests/Fixtures/device-challenge.json| new file mode 100644 |
| index 00000000..85e45923 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/device-challenge.json |
| @@ -0,0 +1,9 @@ |
| +{ |
| + "id": "dev_01JD5Z4Q2X", |
| + "device_secret": "equipo.person.device.v1.SECRETFIXTURE", |
| + "user_code": "K7QM-4XTR", |
| + "challenge": "WyJpbnN0XzdmM2E5YyIsIlE0SjdYUloyTTNLUDZUQk4iXQ", |
| + "verification_uri": "https://oficina.example.test/devices/approve?id=dev_01JD5Z4Q2X", |
| + "expires_at": "2099-01-01T00:10:00Z", |
| + "poll_interval_seconds": 5 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/device-credential.json b/native/apple/Tests/EquipoKitTests/Fixtures/device-credential.json| new file mode 100644 |
| index 00000000..d776b078 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/device-credential.json |
| @@ -0,0 +1,7 @@ |
| +{ |
| + "id": "dev_01JD5Z4Q2X", |
| + "token": "equipo.person.v1.TOKENFIXTURE", |
| + "audience": "equipo.person.v1", |
| + "instance_id": "inst_7f3a9c", |
| + "expires_at": "2099-01-31T00:00:00Z" |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/device-proof-vectors.json b/native/apple/Tests/EquipoKitTests/Fixtures/device-proof-vectors.json| new file mode 100644 |
| index 00000000..0230808f |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/device-proof-vectors.json |
| @@ -0,0 +1,24 @@ |
| +[ |
| + { |
| + "name": "plain", |
| + "seed": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8", |
| + "public_key": "A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg", |
| + "instance": "inst_7f3a9c", |
| + "id": "dev_01JD5Z4Q2X", |
| + "challenge": "WyJpbnN0XzdmM2E5YyIsIlE0SjdYUloyTTNLUDZUQk4iXQ", |
| + "nonce": "nPq-7_Rs0tUvWxYz12345A", |
| + "message": "[\"equipo.person.device.v1\",\"inst_7f3a9c\",\"dev_01JD5Z4Q2X\",\"WyJpbnN0XzdmM2E5YyIsIlE0SjdYUloyTTNLUDZUQk4iXQ\",\"nPq-7_Rs0tUvWxYz12345A\"]", |
| + "signature": "cSXdizp7cTpx_YbbS-fYmTJFNYzS4BOtC4QSx-M1kcTxPOAuVnIm2PPcSn2fgKcJBXRJ_hnmk7YqB09caM5rDQ" |
| + }, |
| + { |
| + "name": "escapes", |
| + "seed": "HyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4", |
| + "public_key": "rz0gJk-cJu8IW1zlN_QX1CQDegljpjhv9tBQ5b93NxQ", |
| + "instance": "a/b\u003cc\u003e\u0026d é\u2028", |
| + "id": "dev_\"quoted\"\\", |
| + "challenge": "WyJhL2JcdTAwM2NjXHUwMDNlXHUwMDI2ZCDDqVx1MjAyOCIsIlE0SjdYUloyTTNLUDZUQk4iXQ", |
| + "nonce": "n/o\u003cn\u003e\u0026ce", |
| + "message": "[\"equipo.person.device.v1\",\"a/b\\u003cc\\u003e\\u0026d é\\u2028\",\"dev_\\\"quoted\\\"\\\\\",\"WyJhL2JcdTAwM2NjXHUwMDNlXHUwMDI2ZCDDqVx1MjAyOCIsIlE0SjdYUloyTTNLUDZUQk4iXQ\",\"n/o\\u003cn\\u003e\\u0026ce\"]", |
| + "signature": "7DVst_PqFo8W12gYPjRU4CtUbdKrPr9ryX00iSbsDC789Yrk5D4ty0MTgIq2J5ALrKwwcozZambpO0bjft4YAw" |
| + } |
| +] |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/devices.json b/native/apple/Tests/EquipoKitTests/Fixtures/devices.json| new file mode 100644 |
| index 00000000..bbfbaefe |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/devices.json |
| @@ -0,0 +1,15 @@ |
| +{ |
| + "items": [ |
| + { |
| + "id": "dev_01JD5Z4Q2X", |
| + "label": "Paul's iPhone", |
| + "created_at": "2026-11-18T10:00:00Z", |
| + "expires_at": "2026-12-18T10:00:00Z", |
| + "revoked_at": null, |
| + "revision": 2, |
| + "last_used_at": null |
| + } |
| + ], |
| + "next_cursor": "", |
| + "revision": 2 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/error-pending.json b/native/apple/Tests/EquipoKitTests/Fixtures/error-pending.json| new file mode 100644 |
| index 00000000..8ff3ab1d |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/error-pending.json |
| @@ -0,0 +1,5 @@ |
| +{ |
| + "code": "authorization_pending", |
| + "copy_key": "api.authorization_pending", |
| + "request_id": "req_2" |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/error-revision-conflict.json b/native/apple/Tests/EquipoKitTests/Fixtures/error-revision-conflict.json| new file mode 100644 |
| index 00000000..f2429e0e |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/error-revision-conflict.json |
| @@ -0,0 +1,6 @@ |
| +{ |
| + "code": "revision_conflict", |
| + "copy_key": "api.revision_conflict", |
| + "request_id": "req_1", |
| + "current_revision": 9 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/me.json b/native/apple/Tests/EquipoKitTests/Fixtures/me.json| new file mode 100644 |
| index 00000000..5a3e856e |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/me.json |
| @@ -0,0 +1,11 @@ |
| +{ |
| + "person": { |
| + "address": "paul@example.test", |
| + "display_identity": "Paul", |
| + "active": true, |
| + "role": "owner" |
| + }, |
| + "team_id": "team_1", |
| + "team_name": "Oficina", |
| + "revision": 3 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/message.json b/native/apple/Tests/EquipoKitTests/Fixtures/message.json| new file mode 100644 |
| index 00000000..008e87d6 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/message.json |
| @@ -0,0 +1,12 @@ |
| +{ |
| + "id": "message-3", |
| + "conversation_id": "conversation-paul", |
| + "thread_id": "", |
| + "author_kind": "person", |
| + "author_id": "paul@example.test", |
| + "body": "Thanks", |
| + "sequence": 3, |
| + "revision": 1, |
| + "created_at": "2026-11-13T12:05:00Z", |
| + "sources": [] |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json b/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json| new file mode 100644 |
| index 00000000..1cba4aad |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json |
| @@ -0,0 +1,67 @@ |
| +{ |
| + "items": [ |
| + { |
| + "id": "task-vat", |
| + "project_id": 1, |
| + "requester": "paul@example.test", |
| + "description": "Fix VAT on invoice PDFs", |
| + "kind": "bug", |
| + "state": "waiting", |
| + "revision": 7, |
| + "plan_revision": 2, |
| + "replacement_id": "", |
| + "can_cancel": true, |
| + "can_merge": false, |
| + "needs_you": true, |
| + "steps": [ |
| + { |
| + "key": "eng", |
| + "category": "engineering", |
| + "action": "Fix the rounding", |
| + "state": "done", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "Fixed rounding before totals.", |
| + "reason": "", |
| + "usage": { |
| + "calls": 4, |
| + "input_tokens": 18400, |
| + "output_tokens": 2600 |
| + }, |
| + "allowance_remaining": null |
| + }, |
| + { |
| + "key": "copy", |
| + "category": "copy", |
| + "action": "Check the wording", |
| + "state": "waiting", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "", |
| + "reason": "copy_question", |
| + "usage": null, |
| + "allowance_remaining": null |
| + }, |
| + { |
| + "key": "checks", |
| + "category": "checks", |
| + "action": "Run invoice tests", |
| + "state": "queued", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "", |
| + "reason": "", |
| + "usage": null, |
| + "allowance_remaining": null |
| + } |
| + ], |
| + "usage": { |
| + "calls": 4, |
| + "input_tokens": 18400, |
| + "output_tokens": 2600 |
| + } |
| + } |
| + ], |
| + "next_cursor": "", |
| + "revision": 9 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json b/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json| new file mode 100644 |
| index 00000000..0eded994 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json |
| @@ -0,0 +1,24 @@ |
| +{ |
| + "items": [ |
| + { |
| + "id": "n1", |
| + "kind": "question", |
| + "resource_id": "question-vat", |
| + "deep_link": "/questions/question-vat", |
| + "resource_revision": 7, |
| + "created_at": "2026-11-18T10:01:00Z", |
| + "state": "unread" |
| + }, |
| + { |
| + "id": "n2", |
| + "kind": "task_ready", |
| + "resource_id": "task-signin", |
| + "deep_link": "/tasks/task-signin", |
| + "resource_revision": 4, |
| + "created_at": "2026-11-18T10:02:00Z", |
| + "state": "acknowledged" |
| + } |
| + ], |
| + "next_cursor": "c2", |
| + "revision": 3 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/projects.json b/native/apple/Tests/EquipoKitTests/Fixtures/projects.json| new file mode 100644 |
| index 00000000..83f2f25b |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/projects.json |
| @@ -0,0 +1,28 @@ |
| +{ |
| + "items": [ |
| + { |
| + "id": "1", |
| + "account_id": 1, |
| + "name": "Equipo", |
| + "repository": "https://forge.example.test/oficina/equipo", |
| + "app_name": "equipo", |
| + "default_branch": "main", |
| + "kind": "app", |
| + "owners": [], |
| + "revision": 1 |
| + }, |
| + { |
| + "id": "2", |
| + "account_id": 1, |
| + "name": "Woodstar", |
| + "repository": "https://forge.example.test/oficina/woodstar", |
| + "app_name": "woodstar", |
| + "default_branch": "main", |
| + "kind": "app", |
| + "owners": null, |
| + "revision": 1 |
| + } |
| + ], |
| + "next_cursor": "", |
| + "revision": 1 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/question.json b/native/apple/Tests/EquipoKitTests/Fixtures/question.json| new file mode 100644 |
| index 00000000..e65a2a13 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/question.json |
| @@ -0,0 +1,23 @@ |
| +{ |
| + "id": "question-vat", |
| + "kind": "clarification", |
| + "task_id": "task-vat", |
| + "text": "Which tax label should appear on the invoice?", |
| + "state": "open", |
| + "revision": 7, |
| + "can_answer": true, |
| + "can_allow": false, |
| + "options": [ |
| + { |
| + "id": "vat", |
| + "label": "VAT" |
| + }, |
| + { |
| + "id": "sales-tax", |
| + "label": "Sales tax" |
| + } |
| + ], |
| + "fields": [], |
| + "allow_text": true, |
| + "expires_at": "2099-01-01T00:00:00Z" |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json b/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json| new file mode 100644 |
| index 00000000..8be19334 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json |
| @@ -0,0 +1,8 @@ |
| +{ |
| + "id": "sub_1", |
| + "device_id": "dev_01JD5Z4Q2X", |
| + "cursor": "", |
| + "revision": 1, |
| + "active": true, |
| + "expires_at": "2099-01-31T00:00:00Z" |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json b/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json| new file mode 100644 |
| index 00000000..d5b75e4c |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json |
| @@ -0,0 +1,108 @@ |
| +{ |
| + "items": [ |
| + { |
| + "id": "task-vat", |
| + "project_id": 1, |
| + "requester": "paul@example.test", |
| + "description": "Fix VAT on invoice PDFs", |
| + "kind": "bug", |
| + "state": "waiting", |
| + "revision": 7, |
| + "plan_revision": 2, |
| + "replacement_id": "", |
| + "can_cancel": true, |
| + "can_merge": false, |
| + "needs_you": true, |
| + "steps": [ |
| + { |
| + "key": "eng", |
| + "category": "engineering", |
| + "action": "Fix the rounding", |
| + "state": "done", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "Fixed rounding before totals.", |
| + "reason": "", |
| + "usage": { |
| + "calls": 4, |
| + "input_tokens": 18400, |
| + "output_tokens": 2600 |
| + }, |
| + "allowance_remaining": null |
| + }, |
| + { |
| + "key": "copy", |
| + "category": "copy", |
| + "action": "Check the wording", |
| + "state": "waiting", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "", |
| + "reason": "copy_question", |
| + "usage": null, |
| + "allowance_remaining": null |
| + }, |
| + { |
| + "key": "checks", |
| + "category": "checks", |
| + "action": "Run invoice tests", |
| + "state": "queued", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "", |
| + "reason": "", |
| + "usage": null, |
| + "allowance_remaining": null |
| + } |
| + ], |
| + "usage": { |
| + "calls": 4, |
| + "input_tokens": 18400, |
| + "output_tokens": 2600 |
| + } |
| + }, |
| + { |
| + "id": "task-signin", |
| + "project_id": 2, |
| + "requester": "paul@example.test", |
| + "description": "Check sign-in recovery", |
| + "kind": "bug", |
| + "state": "running", |
| + "revision": 4, |
| + "plan_revision": 1, |
| + "replacement_id": "", |
| + "can_cancel": true, |
| + "can_merge": false, |
| + "needs_you": false, |
| + "steps": [ |
| + { |
| + "key": "eng", |
| + "category": "engineering", |
| + "action": "Fix the recovery link", |
| + "state": "done", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "The link survives a second request.", |
| + "reason": "", |
| + "usage": null, |
| + "allowance_remaining": null |
| + }, |
| + { |
| + "key": "review", |
| + "category": "review", |
| + "action": "Review the change", |
| + "state": "running", |
| + "model": "fixture-model", |
| + "account": "connection-claude", |
| + "actual": "Reading the session tests.", |
| + "reason": "", |
| + "usage": null, |
| + "allowance_remaining": null |
| + } |
| + ], |
| + "usage": null |
| + } |
| + ], |
| + "next_cursor": "", |
| + "revision": 9 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/thread.json b/native/apple/Tests/EquipoKitTests/Fixtures/thread.json| new file mode 100644 |
| index 00000000..65a2ad85 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Fixtures/thread.json |
| @@ -0,0 +1,31 @@ |
| +{ |
| + "messages": [ |
| + { |
| + "id": "message-t1", |
| + "conversation_id": "conversation-paul", |
| + "thread_id": "task-signin", |
| + "author_kind": "person", |
| + "author_id": "paul@example.test", |
| + "body": "Does this cover the passkey reset too?", |
| + "sequence": 1, |
| + "revision": 1, |
| + "created_at": "2026-11-13T12:02:00Z", |
| + "sources": [] |
| + }, |
| + { |
| + "id": "message-t2", |
| + "conversation_id": "conversation-paul", |
| + "thread_id": "task-signin", |
| + "author_kind": "coordinator", |
| + "author_id": "coordinator", |
| + "body": "Not yet.", |
| + "sequence": 2, |
| + "revision": 1, |
| + "created_at": "2026-11-13T12:02:30Z", |
| + "sources": [] |
| + } |
| + ], |
| + "cards": [], |
| + "next_cursor": "", |
| + "revision": 2 |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/PairingTests.swift b/native/apple/Tests/EquipoKitTests/PairingTests.swift| new file mode 100644 |
| index 00000000..644b18a1 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/PairingTests.swift |
| @@ -0,0 +1,71 @@ |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +private func err(_ status: Int, _ code: String) -> Result<APIResponse, EquipoAPIError> { |
| + .success(APIResponse(status: status, data: Data(#"{"code":"\#(code)","copy_key":"api.\#(code)","request_id":"r"}"#.utf8))) |
| +} |
| + |
| +/// Records each wait; never actually sleeps. |
| +final class Sleeps: @unchecked Sendable { |
| + private let lock = NSLock(); private(set) var waits: [Duration] = [] |
| + var sleep: @Sendable (Duration) async throws -> Void { { d in self.lock.withLock { self.waits.append(d) } } } |
| +} |
| + |
| +@MainActor @Suite struct PairingTests { |
| + @Test func pairsAfterPendingAndSlowDown() async throws { |
| + let t = ScriptedTransport() |
| + t.on("POST /auth/devices", fixture: "device-challenge") |
| + t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), err(429, "slow_down"), .success(APIResponse(status: 200, data: Fixture.data("device-credential")))) |
| + t.on("GET /me", fixture: "me") |
| + let store = MemorySecretStore(); let sleeps = Sleeps() |
| + let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: sleeps.sleep) |
| + await model.run(origin: t.origin, label: "Test") |
| + |
| + #expect(model.step == .approved(teamName: "Oficina")) |
| + // One proof, resent unchanged: same key, same body, same nonce. |
| + let polls = t.sent("POST /auth/devices/exchange") |
| + #expect(polls.count == 3) |
| + #expect(Set(polls.map(\.idempotencyKey)).count == 1) |
| + #expect(Set(polls.map(\.body)).count == 1) |
| + #expect(polls.allSatisfy { $0.bearer == nil }) |
| + // Never faster than five seconds; slower after slow_down. |
| + #expect(sleeps.waits.allSatisfy { $0 >= .seconds(5) }) |
| + #expect(sleeps.waits.last == .seconds(10)) |
| + // The credential is kept, with the key that earned it. |
| + let saved = try #require(DeviceAccounts(store: store).all().first) |
| + #expect(saved.credential?.token == "equipo.person.v1.TOKENFIXTURE") |
| + #expect(saved.teamName == "Oficina") |
| + let begin = try JSONSerialization.jsonObject(with: t.sent("POST /auth/devices")[0].body!) as! [String: String] |
| + #expect(begin["public_key"] == (try saved.publicKey())) |
| + } |
| + |
| + @Test func expiredChallengeStops() async throws { |
| + let t = ScriptedTransport() |
| + t.on("POST /auth/devices", fixture: "device-challenge") |
| + t.on("POST /auth/devices/exchange", err(410, "device_expired")) |
| + let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| + await model.run(origin: t.origin, label: "Test") |
| + #expect(model.step == .expired) |
| + } |
| + |
| + @Test func keyIsSavedBeforeTheServerHearsOfIt() async throws { |
| + let t = ScriptedTransport() |
| + t.on("POST /auth/devices", .failure(.offline)) |
| + let store = MemorySecretStore() |
| + let model = PairingModel(accounts: DeviceAccounts(store: store), makeTransport: { _ in t }, sleep: Sleeps().sleep) |
| + await model.run(origin: t.origin, label: "Test") |
| + #expect(DeviceAccounts(store: store).all().count == 1) |
| + if case .failed = model.step {} else { Issue.record("expected failure, got \(model.step)") } |
| + // Offline begins are retried as themselves. |
| + #expect(Set(t.sent("POST /auth/devices").map(\.idempotencyKey)).count == 1) |
| + } |
| + |
| + @Test func originParsing() { |
| + #expect(PairingModel.origin(from: "paulca.equipo.oficina.works")?.absoluteString == "https://paulca.equipo.oficina.works") |
| + #expect(PairingModel.origin(from: " https://Team.Example.test/some/path?x ")?.absoluteString == "https://team.example.test") |
| + #expect(PairingModel.origin(from: "http://team.example.test") == nil) |
| + #expect(PairingModel.origin(from: "https://user@team.example.test") == nil) |
| + #expect(PairingModel.origin(from: "") == nil) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/SessionTests.swift b/native/apple/Tests/EquipoKitTests/SessionTests.swift| new file mode 100644 |
| index 00000000..1fe6c35f |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/SessionTests.swift |
| @@ -0,0 +1,160 @@ |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +@MainActor private func paired(_ t: ScriptedTransport, store: MemorySecretStore = MemorySecretStore(), defaults: UserDefaults? = nil) throws -> EquipoSession { |
| + var account = DeviceAccount.new(origin: t.origin, label: "Test") |
| + account.credential = try Fixture.decode("device-credential") |
| + let accounts = DeviceAccounts(store: store) |
| + try accounts.save(account) |
| + let d = defaults ?? UserDefaults(suiteName: "equipo-tests-\(UUID().uuidString)")! |
| + return EquipoSession(account: account, accounts: accounts, transport: t, defaults: d, sleep: { _ in }) |
| +} |
| + |
| +private func readable(_ t: ScriptedTransport) { |
| + t.on("GET /me", fixture: "me"); t.on("GET /projects", fixture: "projects") |
| + t.on("GET /conversation", fixture: "conversation"); t.on("GET /tasks", fixture: "tasks") |
| + t.on("GET /needs-you", fixture: "needs-you"); t.on("GET /questions/question-vat", fixture: "question") |
| +} |
| + |
| +@MainActor @Suite struct SessionTests { |
| + @Test func refreshFillsEverything() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + let s = try paired(t) |
| + #expect(s.needsYou == nil, "unknown until loaded, never zero") |
| + await s.refresh() |
| + #expect(s.status == .ready) |
| + #expect(s.messages.map(\.id) == ["message-1", "message-2"]) |
| + #expect(s.needsYou?.map(\.id) == ["task-vat"]) |
| + #expect(s.questions["question-vat"]?.revision == 7) |
| + #expect(s.project(for: s.tasks[0])?.name == "Equipo") |
| + #expect(t.requests.allSatisfy { $0.bearer == "equipo.person.v1.TOKENFIXTURE" }) |
| + } |
| + |
| + @Test func feedFollowsRoster() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + let s = try paired(t); await s.refresh() |
| + let feed = Feed.build(s) |
| + #expect(feed.map(\.id) == ["message-1", "message-2", "card-vat-report", "card-vat", "card-merge"]) |
| + guard case .question(_, let byline, let q, _) = feed[3] else { Issue.record("not a question"); return } |
| + #expect(byline.who == .copy) |
| + #expect(byline.project == "Equipo") |
| + #expect(byline.time == nil, "the API gives cards no time") |
| + #expect(q?.id == "question-vat") |
| + guard case .decision = feed[4] else { Issue.record("merges go to the web"); return } |
| + } |
| + |
| + @Test func coordinatorIsUnnamedOnScreen() { |
| + let b = RosterByline(who: .coordinator, verb: "asks", project: "Woodstar", time: nil) |
| + #expect(!b.showsName) |
| + #expect(b.spoken.hasPrefix(Specialist.coordinator.name)) |
| + } |
| + |
| + @Test func mergeKeepsTheNewerRevision() { |
| + let old = Message(id: "m", conversationId: "c", threadId: "", authorKind: "coordinator", authorId: "c", body: "old", sequence: 2, revision: 2, createdAt: .now, sources: nil) |
| + var newer = old; newer.body = "new"; newer.revision = 3 |
| + var stale = old; stale.body = "stale"; stale.revision = 1 |
| + #expect(EquipoSession.merge([old], [newer]).first?.body == "new") |
| + #expect(EquipoSession.merge([newer], [stale]).first?.body == "new") |
| + } |
| + |
| + @Test func aLostMessageIsResentAsItself() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("POST /conversation/messages", .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("message")))) |
| + let s = try paired(t) |
| + await s.send("Thanks") |
| + #expect(s.outgoing.first?.state == .waiting) |
| + await s.retry(s.outgoing[0].id) |
| + #expect(s.outgoing.isEmpty) |
| + let posts = t.sent("POST /conversation/messages") |
| + #expect(posts.count == 2) |
| + #expect(posts[0].idempotencyKey == posts[1].idempotencyKey) |
| + #expect(posts[0].body == posts[1].body) |
| + #expect(s.messages.contains { $0.id == "message-3" }) |
| + } |
| + |
| + @Test func aChangedQuestionIsNotAnswered() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + let s = try paired(t); await s.refresh() |
| + var seen = s.questions["question-vat"]! |
| + seen.revision = 6 |
| + #expect(await s.answer(seen, with: .option("vat")) == .changed) |
| + #expect(t.sent("POST /questions/question-vat/answer").isEmpty) |
| + } |
| + |
| + @Test func aStaleAnswerIsNeverRetried() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("POST /questions/question-vat/answer", status: 409, fixture: "error-revision-conflict") |
| + let s = try paired(t); await s.refresh() |
| + #expect(await s.answer(s.questions["question-vat"]!, with: .text("VAT, with the rate")) == .changed) |
| + #expect(t.sent("POST /questions/question-vat/answer").count == 1) |
| + } |
| + |
| + @Test func answeringSendsTheRevisionSeen() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("POST /questions/question-vat/answer", fixture: "ack") |
| + let s = try paired(t); await s.refresh() |
| + #expect(await s.answer(s.questions["question-vat"]!, with: .option("vat")) == .answered) |
| + #expect(t.sent("POST /questions/question-vat/answer").first?.ifMatch == 7) |
| + } |
| + |
| + @Test func unauthorisedEndsTheSession() async throws { |
| + let t = ScriptedTransport() |
| + t.on("GET /projects", fixture: "projects"); t.on("GET /conversation", fixture: "conversation") |
| + t.on("GET /tasks", fixture: "tasks"); t.on("GET /needs-you", fixture: "needs-you") |
| + t.on("GET /me", .success(APIResponse(status: 401, data: Data(#"{"code":"unauthenticated","copy_key":"api.unauthenticated","request_id":"r"}"#.utf8)))) |
| + let s = try paired(t); await s.refresh() |
| + #expect(s.status == .signedOut) |
| + } |
| + |
| + @Test func notificationsAreAcknowledgedOnceAndOnlyWhenUnread() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("POST /notification-subscriptions", fixture: "subscription") |
| + t.on("GET /notifications", fixture: "notifications") |
| + t.on("POST /notification-subscriptions/sub_1/ack", fixture: "ack") |
| + let defaults = UserDefaults(suiteName: "equipo-tests-\(UUID().uuidString)")! |
| + let s = try paired(t, defaults: defaults) |
| + await s.pollOnce() |
| + await s.pollOnce() |
| + let acks = t.sent("POST /notification-subscriptions/sub_1/ack") |
| + #expect(acks.count == 2, "the unread one, once per poll it is still unread; never the acknowledged one") |
| + #expect(acks.allSatisfy { String(decoding: $0.body!, as: UTF8.self).contains("\"n1\"") }) |
| + #expect(acks[0].ifMatch == 1) |
| + #expect(acks[1].ifMatch == 8, "the revision the last acknowledgement returned") |
| + #expect(t.sent("POST /notification-subscriptions").count == 1, "one subscription, reused") |
| + #expect(s.storedSubscription()?.cursor == "c2") |
| + } |
| + |
| + @Test func anExpiredSubscriptionIsReplaced() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("POST /notification-subscriptions", fixture: "subscription") |
| + t.on("GET /notifications", .success(APIResponse(status: 410, data: Data(#"{"code":"subscription_expired","copy_key":"api.not_found","request_id":"r"}"#.utf8))), .success(APIResponse(status: 200, data: Fixture.data("notifications")))) |
| + let s = try paired(t) |
| + await s.pollOnce() |
| + #expect(s.storedSubscription() == nil) |
| + await s.pollOnce() |
| + #expect(t.sent("POST /notification-subscriptions").count == 2) |
| + } |
| + |
| + @Test func signOutRevokesThenForgets() async throws { |
| + let t = ScriptedTransport(); readable(t) |
| + t.on("GET /auth/devices", fixture: "devices") |
| + t.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack") |
| + let store = MemorySecretStore() |
| + let s = try paired(t, store: store) |
| + await s.signOut() |
| + let revoke = try #require(t.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").first) |
| + #expect(revoke.ifMatch == 2) |
| + #expect(DeviceAccounts(store: store).all().isEmpty) |
| + #expect(s.status == .signedOut) |
| + } |
| + |
| + @Test func taskSummaryFromSteps() throws { |
| + let tasks: Page<EquipoTask> = try Fixture.decode("tasks") |
| + #expect(TaskSummary(tasks.items[0]).tone == .warning) |
| + #expect(TaskSummary(tasks.items[0]).specialist == .copy) |
| + #expect(TaskSummary(tasks.items[1]).specialist == .review) |
| + var failed = tasks.items[1]; failed.steps?[1].state = "failed" |
| + #expect(TaskSummary(failed).tone == .negative) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/Support.swift b/native/apple/Tests/EquipoKitTests/Support.swift| new file mode 100644 |
| index 00000000..9d478d17 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/Support.swift |
| @@ -0,0 +1,41 @@ |
| +import Foundation |
| +@testable import EquipoKit |
| + |
| +/// Answers requests from a script and records each one. A route is |
| +/// "METHOD /path"; each answer is used once, the last one repeats. |
| +final class ScriptedTransport: EquipoTransport, @unchecked Sendable { |
| + let origin = URL(string: "https://oficina.example.test")! |
| + private let lock = NSLock() |
| + private var script: [String: [Result<APIResponse, EquipoAPIError>]] = [:] |
| + private(set) var requests: [APIRequest] = [] |
| + |
| + func on(_ route: String, _ answers: Result<APIResponse, EquipoAPIError>...) { |
| + lock.withLock { script[route, default: []] += answers } |
| + } |
| + func on(_ route: String, fixture: String, status: Int = 200) { on(route, .success(APIResponse(status: status, data: Fixture.data(fixture)))) } |
| + func on(_ route: String, status: Int, fixture: String) { on(route, .success(APIResponse(status: status, data: Fixture.data(fixture)))) } |
| + |
| + func send(_ request: APIRequest) async throws -> APIResponse { |
| + let route = request.method + " " + request.path |
| + let answer: Result<APIResponse, EquipoAPIError>? = lock.withLock { |
| + requests.append(request) |
| + guard var queue = script[route], !queue.isEmpty else { return nil } |
| + let next = queue.count > 1 ? queue.removeFirst() : queue[0] |
| + script[route] = queue |
| + return next |
| + } |
| + guard let answer else { return APIResponse(status: 404, data: Data(#"{"code":"not_found","copy_key":"api.not_found","request_id":"r"}"#.utf8)) } |
| + return try answer.get() |
| + } |
| + func sent(_ route: String) -> [APIRequest] { lock.withLock { requests.filter { $0.method + " " + $0.path == route } } } |
| +} |
| + |
| +enum Fixture { |
| + static func data(_ name: String) -> Data { |
| + let url = Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures")! |
| + return try! Data(contentsOf: url) |
| + } |
| + static func decode<T: Decodable>(_ name: String, as: T.Type = T.self) throws -> T { |
| + try EquipoJSON.decoder.decode(T.self, from: data(name)) |
| + } |
| +} |
diff --git a/native/scripts/check-fixtures.py b/native/scripts/check-fixtures.py| new file mode 100644 |
| index 00000000..4e8e4995 |
| --- /dev/null |
| +++ b/native/scripts/check-fixtures.py |
| @@ -0,0 +1,70 @@ |
| +#!/usr/bin/env python3 |
| +"""Validate the native test fixtures against the person API schema. |
| + |
| +Every fixture under native/apple/Tests/EquipoKitTests/Fixtures is a response |
| +the API could send: it must match its schema exactly, with no invented |
| +field. Runs anywhere Python runs; Linux CI included.""" |
| +import json, re, sys |
| +from pathlib import Path |
| + |
| +root = Path(__file__).resolve().parents[2] |
| +spec = json.loads((root / 'docs/api/equipo-v1.openapi.json').read_text()) |
| +fixtures = root / 'native/apple/Tests/EquipoKitTests/Fixtures' |
| +contracts = { |
| + 'me': 'Me', 'projects': 'ProjectPage', 'tasks': 'TaskPage', 'needs-you': 'TaskPage', |
| + 'conversation': 'ConversationPage', 'thread': 'ConversationPage', 'message': 'Message', |
| + 'question': 'Question', 'ack': 'Ack', 'device-challenge': 'PersonDeviceChallenge', |
| + 'device-credential': 'PersonCredential', 'devices': 'DevicePage', |
| + 'subscription': 'NotificationSubscription', 'notifications': 'NotificationPage', |
| + 'error-revision-conflict': 'Error', 'error-pending': 'Error', |
| +} |
| + |
| +def validate(value, schema, path='$'): |
| + if '$ref' in schema: |
| + return validate(value, spec['components']['schemas'][schema['$ref'].split('/')[-1]], path) |
| + for key in ('oneOf', 'anyOf'): |
| + if key in schema: |
| + matched = 0 |
| + for variant in schema[key]: |
| + try: |
| + validate(value, variant, path); matched += 1 |
| + except AssertionError: |
| + pass |
| + assert (matched == 1 if key == 'oneOf' else matched >= 1), f'{path}: {key} mismatch' |
| + if 'const' in schema: assert value == schema['const'], f'{path}: const mismatch' |
| + if 'enum' in schema: assert value in schema['enum'], f'{path}: enum mismatch' |
| + kind = schema.get('type') |
| + kinds = kind if isinstance(kind, list) else [kind] |
| + actual = ('null' if value is None else 'boolean' if isinstance(value, bool) else |
| + 'integer' if isinstance(value, int) else 'number' if isinstance(value, float) else |
| + 'string' if isinstance(value, str) else 'array' if isinstance(value, list) else 'object') |
| + if kind: assert actual in kinds or (actual == 'integer' and 'number' in kinds), f'{path}: {actual} is not {kinds}' |
| + if isinstance(value, dict): |
| + props = schema.get('properties', {}) |
| + missing = set(schema.get('required', [])) - value.keys() |
| + assert not missing, f'{path}: missing {sorted(missing)}' |
| + if schema.get('additionalProperties') is False: |
| + extra = value.keys() - props.keys() |
| + assert not extra, f'{path}: invented {sorted(extra)}' |
| + for name, item in value.items(): |
| + child = props.get(name, schema.get('additionalProperties', {})) |
| + if isinstance(child, dict): validate(item, child, f'{path}.{name}') |
| + elif isinstance(value, list) and 'items' in schema: |
| + for i, item in enumerate(value): validate(item, schema['items'], f'{path}[{i}]') |
| + elif isinstance(value, str): |
| + if 'pattern' in schema: assert re.search(schema['pattern'], value), f'{path}: pattern' |
| + if schema.get('format') == 'date-time': assert RFC3339.match(value), f'{path}: not RFC 3339' |
| + |
| +# Go's time.Time: RFC 3339 with up to nine fractional digits. |
| +RFC3339 = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$') |
| + |
| +failed = False |
| +for name, contract in contracts.items(): |
| + try: |
| + validate(json.loads((fixtures / f'{name}.json').read_text()), {'$ref': '#/components/schemas/' + contract}) |
| + except (AssertionError, ValueError) as e: |
| + failed = True; print(f'{name}.json: {e}') |
| +unlisted = {p.stem for p in fixtures.glob('*.json')} - set(contracts) - {'device-proof-vectors'} |
| +if unlisted: failed = True; print('fixtures without a contract:', sorted(unlisted)) |
| +if failed: sys.exit(1) |
| +print(f'{len(contracts)} native fixtures match the person API schema') |