Add Base's client, Ask's events and the session
BaseClient calls Base over the kit's NativeHTTP, which sends the native session's cookie, Origin and Accept JSON: /api/v1/me and /home, Ask's web routes (state, events, and the messages, cancel and answer forms, form-encoded as ask.js posts them) and Task 7's Ask set-up. Any 401 is Base ending the session and calls the kit's sessionRejected(); Equipo refusing Ask's key is Ask's own 409 reconnect. Errors are typed, with Ask's state and the API's code from the body. The SSE parser reads Base's stream as the standard says (ids, event types, multi-line data, retry, pings); AskEvent decodes its frames. AskModel keeps the thread as ask.js does: replies take their thinking bubble's or draft's place, deltas land by byte offset, jobs redraw in place with their open cards under them and ended ones in their view, connect offers wait for their reply, quiet turns show nothing. Sending keeps one idempotency key per message until its outcome is known; a stale card reads the state afresh. A stream Base ends reconnects from the last id; one it refuses, or that drops offline, reads the state afresh first. BaseSession wraps the kit's Oficina ID model for app "base", swaps a renewed session under the client, and refreshes Home and Ask on foreground. The catalog is re-synced with copy review's revision (scripts/sync-strings.py), with the badge's plural.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+2,598
−17
native/apple/Sources/BaseKit/API/Client.swift+181 −0native/apple/Sources/BaseKit/API/Events.swift+122 −0native/apple/Sources/BaseKit/API/Models.swift+352 −0native/apple/Sources/BaseKit/Ask/AskModel.swift+591 −0native/apple/Sources/BaseKit/BaseText.swift+6 −0native/apple/Sources/BaseKit/Resources/Localizable.xcstrings+552 −12native/apple/Sources/BaseKit/Session/BaseSession.swift+120 −0native/apple/Tests/BaseKitTests/AskModelTests.swift+231 −0native/apple/Tests/BaseKitTests/CatalogTests.swift+9 −1native/apple/Tests/BaseKitTests/ClientTests.swift+114 −0native/apple/Tests/BaseKitTests/EventsTests.swift+108 −0native/apple/Tests/BaseKitTests/Fixtures/.keep+0 −0native/apple/Tests/BaseKitTests/Fixtures/events.sse+43 −0native/apple/Tests/BaseKitTests/Fixtures/home.json+6 −0native/apple/Tests/BaseKitTests/Fixtures/me.json+3 −0native/apple/Tests/BaseKitTests/Fixtures/state-connect.json+1 −0native/apple/Tests/BaseKitTests/Fixtures/state-ready.json+17 −0native/apple/Tests/BaseKitTests/Support.swift+85 −0native/scripts/check-strings.py+15 −4native/scripts/sync-strings.py+42 −0
diff --git a/native/apple/Sources/BaseKit/API/Client.swift b/native/apple/Sources/BaseKit/API/Client.swift| new file mode 100644 |
| index 0000000..4a8a384 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/API/Client.swift |
| @@ -0,0 +1,181 @@ |
| +import Foundation |
| +import RastrilloApple |
| + |
| +/// Why a call to Base failed, typed so the app can tell an ended session |
| +/// from Ask's own states and from the network. |
| +public enum BaseAPIError: Error, Sendable, Equatable { |
| + /// Base doesn't know the session (`401 {"code":"unauthenticated"}`, or an |
| + /// old Base's redirect to /signin): |
| + /// the client has already told the kit (`sessionRejected()`). |
| + case unauthenticated |
| + /// The request never reached Base, or its answer never came back. A |
| + /// write's outcome is unknown: resend it with the same key. |
| + case offline |
| + /// Base answered with a status outside 2xx. `state` is Ask's (ask.go: |
| + /// `reconnect`, `norunner`, …), `code` the API's (`card_stale`, |
| + /// `cursor_expired`, …), when the body says. |
| + case server(status: Int, code: String?, state: String?) |
| + /// A 2xx whose body isn't what the contract says. |
| + case badResponse |
| +} |
| + |
| +/// Base's API for the apps, over the kit's transport: `NativeHTTP` sends |
| +/// the native session's cookie and `Origin` (so Base's CSRF check passes) |
| +/// and `Accept: application/json`, and refuses redirects. Ask's routes are |
| +/// the web's own (P4); the rest are `/api/v1` reads. |
| +/// |
| +/// A 401 is only ever Base refusing the session (`{"code": |
| +/// "unauthenticated"}`): it calls `rejected` (the kit's `sessionRejected()`) |
| +/// before it throws. Equipo refusing Base's key for this person is Ask's |
| +/// own state, `409 {"state":"reconnect"}`, and is only thrown. |
| +public struct BaseClient: Sendable { |
| + public let transport: NativeTransport |
| + let rejected: @Sendable () async -> Void |
| + |
| + public init(transport: NativeTransport, rejected: @escaping @Sendable () async -> Void) { |
| + self.transport = transport |
| + self.rejected = rejected |
| + } |
| + |
| + public var origin: URL { transport.origin } |
| + |
| + // MARK: Reads |
| + |
| + public func me() async throws(BaseAPIError) -> Me { try await get("/api/v1/me") } |
| + public func home() async throws(BaseAPIError) -> HomeData { try await get("/api/v1/home") } |
| + public func askState() async throws(BaseAPIError) -> AskSnapshot { try await get("/ask/state") } |
| + |
| + // MARK: Ask's writes (the forms ask.js posts) |
| + |
| + public func send(_ text: String, key: String) async throws(BaseAPIError) -> AskSent { |
| + try await post("/ask/messages", form: [("text", text), ("key", key)]) |
| + } |
| + |
| + public func cancel(turn id: String, key: String) async throws(BaseAPIError) { |
| + let _: Ignored = try await post("/ask/turns/\(Self.segment(id))/cancel", form: [("key", key)]) |
| + } |
| + |
| + public func answer(card id: String, choice: String, revision: Int64, key: String) async throws(BaseAPIError) -> AskAnswered { |
| + try await post("/ask/cards/\(Self.segment(id))/answer", form: [("revision", String(revision)), ("choice", choice), ("key", key)]) |
| + } |
| + |
| + /// `POST /api/v1/ask/oficina` (Task 7): connects Ask with an Oficina ID |
| + /// assertion addressed to Equipo. |
| + public func connectAsk(assertion: String, verifier: String) async throws(BaseAPIError) -> AskSetupAnswer { |
| + let body = try? JSONSerialization.data(withJSONObject: ["assertion": assertion, "verifier": verifier]) |
| + return try await call("/api/v1/ask/oficina", method: "POST", body: body, contentType: "application/json") |
| + } |
| + |
| + // MARK: Ask's events |
| + |
| + /// `GET /ask/events?after=`: Base's relay of the conversation's events, |
| + /// each handed to `onEvent` with its id (nil for a live-only glance). |
| + /// Returns when the stream ends cleanly (Base ends one after ten |
| + /// minutes; reconnect with the last id) and throws as the other calls |
| + /// do. `onRetry` hears the stream's `retry:` advice. |
| + public func events(after cursor: Int64?, onOpen: @escaping @Sendable () async -> Void = {}, |
| + onRetry: @escaping @Sendable (Int) async -> Void = { _ in }, |
| + onEvent: @escaping @Sendable (AskEvent, Int64?) async -> Void) async throws(BaseAPIError) { |
| + var path = "/ask/events" |
| + if let cursor { path += "?after=\(cursor)" } |
| + let parser = SSEStream() |
| + do { |
| + try await transport.stream(path, onOpen: { await onOpen() }) { line in |
| + guard let event = await parser.feed(line) else { return } |
| + if let retry = event.retry { await onRetry(retry) } |
| + guard let decoded = AskEvent.decode(event) else { return } |
| + await onEvent(decoded, event.id.flatMap { Int64($0) }) |
| + } |
| + } catch { |
| + throw await mapped(error) |
| + } |
| + } |
| + |
| + // MARK: Plumbing |
| + |
| + struct Ignored: Decodable { init(from decoder: Decoder) throws {} } |
| + |
| + func get<T: Decodable>(_ path: String) async throws(BaseAPIError) -> T { |
| + try await call(path, method: "GET", body: nil, contentType: "application/json") |
| + } |
| + |
| + func post<T: Decodable>(_ path: String, form fields: [(String, String)]) async throws(BaseAPIError) -> T { |
| + try await call(path, method: "POST", body: Data(Self.form(fields).utf8), contentType: "application/x-www-form-urlencoded") |
| + } |
| + |
| + func call<T: Decodable>(_ path: String, method: String, body: Data?, contentType: String) async throws(BaseAPIError) -> T { |
| + let response: NativeResponse |
| + do { |
| + response = try await transport.responseDetails(path, method: method, body: body, contentType: contentType) |
| + } catch { |
| + throw await mapped(error) |
| + } |
| + guard (200..<300).contains(response.status) else { |
| + throw await refused(status: response.status, body: response.data) |
| + } |
| + do { return try JSONDecoder().decode(T.self, from: response.data) } catch { throw .badResponse } |
| + } |
| + |
| + /// The error for a status outside 2xx, telling the kit first if it is |
| + /// Base refusing the session. |
| + func refused(status: Int, body: Data) async -> BaseAPIError { |
| + let fields = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] |
| + let code = fields?["code"] as? String, state = fields?["state"] as? String |
| + // 303: NativeHTTP refuses redirects, so an old Base's redirect to |
| + // /signin arrives as a status. |
| + if status == 401 || status == 303 { |
| + await rejected() |
| + return .unauthenticated |
| + } |
| + return .server(status: status, code: code, state: state) |
| + } |
| + |
| + func mapped(_ error: Error) async -> BaseAPIError { |
| + if let error = error as? BaseAPIError { return error } |
| + switch error as? NativeClientError { |
| + case .offline?: return .offline |
| + case .unauthorized?: |
| + await rejected() |
| + return .unauthenticated |
| + case .conflict(let body)?: return await refused(status: 409, body: body) |
| + case .rejected(let status, let body)?: return await refused(status: status, body: body) |
| + case .server(let status)?: return .server(status: status, code: nil, state: nil) |
| + case .forbidden?: return .server(status: 403, code: nil, state: nil) |
| + case .notFound?: return .server(status: 404, code: nil, state: nil) |
| + case .tooLarge?: return .server(status: 413, code: nil, state: nil) |
| + case .rateLimited?: return .server(status: 429, code: nil, state: nil) |
| + case .transport?: return .offline |
| + default: return .badResponse |
| + } |
| + } |
| + |
| + /// `application/x-www-form-urlencoded`, as a browser's form posts it. |
| + static func form(_ fields: [(String, String)]) -> String { |
| + var allowed = CharacterSet.alphanumerics |
| + allowed.insert(charactersIn: "-._*") |
| + return fields.map { name, value in |
| + let v = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| + return "\(name)=\(v)" |
| + }.joined(separator: "&") |
| + } |
| + |
| + /// One path segment, escaped. |
| + static func segment(_ id: String) -> String { |
| + var allowed = CharacterSet.alphanumerics |
| + allowed.insert(charactersIn: "-._~") |
| + return id.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| + } |
| + |
| + /// A fresh idempotency key: 16 random bytes in hex, as ask.js makes one. |
| + public static func newKey() -> String { |
| + var bytes = [UInt8](repeating: 0, count: 16) |
| + for i in bytes.indices { bytes[i] = UInt8.random(in: .min ... .max) } |
| + return bytes.map { String(format: "%02x", $0) }.joined() |
| + } |
| +} |
| + |
| +/// The SSE parser behind one stream, shared by its line callbacks. |
| +actor SSEStream { |
| + private var parser = SSEParser() |
| + func feed(_ line: String) -> SSEEvent? { parser.feed(line) } |
| +} |
diff --git a/native/apple/Sources/BaseKit/API/Events.swift b/native/apple/Sources/BaseKit/API/Events.swift| new file mode 100644 |
| index 0000000..fd5d9cd |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/API/Events.swift |
| @@ -0,0 +1,122 @@ |
| +import Foundation |
| + |
| +/// One Server-Sent Event, as the HTML standard assembles it from lines. |
| +public struct SSEEvent: Sendable, Equatable { |
| + /// The event's own `id:`, if it had one. (A glance has none: Base sends |
| + /// it live only, so the cursor stays where the last event put it.) |
| + public var id: String? |
| + /// `event:`, or "message". |
| + public var type: String |
| + /// Every `data:` line, joined with newlines. |
| + public var data: String |
| + /// `retry:`, in milliseconds. |
| + public var retry: Int? |
| +} |
| + |
| +/// Assembles lines into events (the HTML standard's "interpret an event |
| +/// stream"): a blank line dispatches; `:` starts a comment (Base's pings); |
| +/// `data` lines join with "\n"; `id`, `event` and `retry` as the standard |
| +/// says. An event with no data is dropped, but its `retry` is kept for the |
| +/// next. Lines come framed by the kit's NativeStreamLines (CR, LF, CRLF). |
| +public struct SSEParser: Sendable { |
| + private var id: String? |
| + private var type = "" |
| + private var data: [String] = [] |
| + private var retry: Int? |
| + private var sawData = false |
| + |
| + public init() {} |
| + |
| + public mutating func feed(_ line: String) -> SSEEvent? { |
| + if line.isEmpty { return dispatch() } |
| + if line.hasPrefix(":") { return nil } |
| + let name: Substring, value: Substring |
| + if let colon = line.firstIndex(of: ":") { |
| + name = line[..<colon] |
| + var rest = line[line.index(after: colon)...] |
| + if rest.first == " " { rest = rest.dropFirst() } |
| + value = rest |
| + } else { |
| + name = line[...]; value = "" |
| + } |
| + switch name { |
| + case "event": type = String(value) |
| + case "data": data.append(String(value)); sawData = true |
| + case "id": if !value.contains("\0") { id = String(value) } |
| + case "retry": if !value.isEmpty, value.allSatisfy(\.isASCII), value.allSatisfy(\.isNumber) { retry = Int(value) } |
| + default: break |
| + } |
| + return nil |
| + } |
| + |
| + private mutating func dispatch() -> SSEEvent? { |
| + defer { id = nil; type = ""; data = []; sawData = false } |
| + guard sawData else { return nil } |
| + let event = SSEEvent(id: id, type: type.isEmpty ? "message" : type, data: data.joined(separator: "\n"), retry: retry) |
| + retry = nil |
| + return event |
| + } |
| +} |
| + |
| +/// A few of the reply's words, streamed: `offset` counts the UTF-8 bytes |
| +/// before them. |
| +public struct AskDelta: Decodable, Sendable, Equatable { |
| + public var turnID: String |
| + public var offset: Int64 |
| + public var text: String |
| + public init(turnID: String, offset: Int64, text: String) { self.turnID = turnID; self.offset = offset; self.text = text } |
| + enum CodingKeys: String, CodingKey { case turnID = "turn_id", offset, text } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + turnID = c.value(.turnID, ""); offset = c.value(.offset, -1); text = c.value(.text, "") |
| + } |
| +} |
| + |
| +/// A line about a turn in flight: Equipo's glance (said once, before the |
| +/// first words) or an activity label. |
| +public struct AskLine: Decodable, Sendable, Equatable { |
| + public var turnID: String |
| + public var text: String |
| + public init(turnID: String, text: String) { self.turnID = turnID; self.text = text } |
| + enum CodingKeys: String, CodingKey { case turnID = "turn_id", text, label } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + turnID = c.value(.turnID, ""); text = c.optional(.text) ?? c.value(.label, "") |
| + } |
| +} |
| + |
| +/// What Base's stream says (ask_relay.go `frame`, ask.js `listen`). Each |
| +/// conversation event's data is `{"type": …, "data": …}`, the data in |
| +/// `/ask/state`'s shapes; a stream that can't start says why in one |
| +/// `state` event whose data is `{"state": …}`. |
| +public enum AskEvent: Sendable, Equatable { |
| + case message(AskMessage) |
| + case turn(AskTurn) |
| + case card(AskCard) |
| + case delta(AskDelta) |
| + case glance(AskLine) |
| + case activity(AskLine) |
| + case state(AskPhase) |
| + |
| + /// The event, or nil for one this app doesn't know or can't read. |
| + public static func decode(_ event: SSEEvent) -> AskEvent? { |
| + let raw = Data(event.data.utf8) |
| + let decoder = JSONDecoder() |
| + if event.type == "state" { |
| + struct State: Decodable { var state: String? } |
| + guard let s = try? decoder.decode(State.self, from: raw) else { return nil } |
| + return .state(AskPhase(server: s.state)) |
| + } |
| + struct Envelope<T: Decodable>: Decodable { var data: T } |
| + func data<T: Decodable>(_: T.Type) -> T? { (try? decoder.decode(Envelope<T>.self, from: raw))?.data } |
| + switch event.type { |
| + case "message": return data(AskMessage.self).flatMap { $0.id.isEmpty ? nil : .message($0) } |
| + case "turn": return data(AskTurn.self).flatMap { $0.id.isEmpty ? nil : .turn($0) } |
| + case "card": return data(AskCard.self).flatMap { $0.id.isEmpty ? nil : .card($0) } |
| + case "delta": return data(AskDelta.self).flatMap { $0.turnID.isEmpty ? nil : .delta($0) } |
| + case "glance": return data(AskLine.self).flatMap { $0.turnID.isEmpty ? nil : .glance($0) } |
| + case "activity": return data(AskLine.self).flatMap { $0.turnID.isEmpty ? nil : .activity($0) } |
| + default: return nil |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift| new file mode 100644 |
| index 0000000..625c270 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/API/Models.swift |
| @@ -0,0 +1,352 @@ |
| +import Foundation |
| + |
| +// What Base's server answers the apps, decoded tolerantly: a field a newer |
| +// Base adds is ignored, and one an older Base leaves out takes its default, |
| +// so neither ends a session or empties a screen. The shapes are the plan's |
| +// Task 5 (`/api/v1/me`, `/api/v1/home`) and Ask's existing JSON |
| +// (internal/web/ask.go askStateJSON, ask_relay.go, internal/equipo/chat.go), |
| +// the same contract ask.js reads (docs/api/base-native-v1.md, Task 6). |
| + |
| +extension KeyedDecodingContainer { |
| + /// The value at `key`, or `fallback` when it is missing, null or of |
| + /// another type. |
| + func value<T: Decodable>(_ key: Key, _ fallback: T) -> T { |
| + ((try? decodeIfPresent(T.self, forKey: key)) ?? nil) ?? fallback |
| + } |
| + func optional<T: Decodable>(_ key: Key) -> T? { (try? decodeIfPresent(T.self, forKey: key)) ?? nil } |
| + /// An RFC 3339 time (Go's, with or without fractional seconds); nil when |
| + /// missing, empty or unreadable. |
| + func date(_ key: Key) -> Date? { BaseJSON.date(optional(key)) } |
| + /// An http(s) URL; nil when missing, empty or anything else. |
| + func webURL(_ key: Key) -> URL? { BaseJSON.webURL(optional(key)) } |
| +} |
| + |
| +public enum BaseJSON { |
| + public static func date(_ text: String?) -> Date? { |
| + guard let text, !text.isEmpty else { return nil } |
| + if let d = try? Date(text, strategy: .iso8601.year().month().day().time(includingFractionalSeconds: true).timeZone(separator: .omitted)) { return d } |
| + if let d = try? Date(text, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) { return d } |
| + return try? Date(text, strategy: .iso8601) |
| + } |
| + |
| + /// `equipo.WebURL`: an absolute http or https URL with a host and no |
| + /// user info, else nil. Links the server passes are already clean; this |
| + /// holds the apps to the same rule. |
| + public static func webURL(_ text: String?) -> URL? { |
| + guard let text, let c = URLComponents(string: text), let scheme = c.scheme?.lowercased(), scheme == "http" || scheme == "https", |
| + let host = c.host, !host.isEmpty, c.user == nil, c.password == nil, let url = c.url else { return nil } |
| + return url |
| + } |
| +} |
| + |
| +// MARK: /api/v1/me |
| + |
| +/// `GET /api/v1/me`: who is signed in, to which Base, and their Appearance. |
| +public struct Me: Decodable, Sendable, Equatable { |
| + public struct Member: Decodable, Sendable, Equatable { |
| + public var id = "", name = "", email = "", initials = "" |
| + public var owner = false |
| + public init(id: String = "", name: String = "", email: String = "", initials: String = "", owner: Bool = false) { |
| + self.id = id; self.name = name; self.email = email; self.initials = initials; self.owner = owner |
| + } |
| + enum CodingKeys: String, CodingKey { case id, name, email, initials, owner } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); name = c.value(.name, ""); email = c.value(.email, "") |
| + initials = c.value(.initials, ""); owner = c.value(.owner, false) |
| + } |
| + } |
| + public struct Base: Decodable, Sendable, Equatable { |
| + public var name = "", slug = "", timezone = "" |
| + public var origin: URL? |
| + public init(name: String = "", slug: String = "", origin: URL? = nil, timezone: String = "") { |
| + self.name = name; self.slug = slug; self.origin = origin; self.timezone = timezone |
| + } |
| + enum CodingKeys: String, CodingKey { case name, slug, origin, timezone } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + name = c.value(.name, ""); slug = c.value(.slug, ""); origin = c.webURL(.origin); timezone = c.value(.timezone, "") |
| + } |
| + /// Base's time zone, for when a job started; nil if unknown. |
| + public var timeZone: TimeZone? { TimeZone(identifier: timezone) } |
| + } |
| + public var member: Member |
| + public var base: Base |
| + public var appearance: BaseAppearance |
| + public var equipoOrigin: URL? |
| + |
| + public init(member: Member, base: Base, appearance: BaseAppearance = .system, equipoOrigin: URL? = nil) { |
| + self.member = member; self.base = base; self.appearance = appearance; self.equipoOrigin = equipoOrigin |
| + } |
| + enum CodingKeys: String, CodingKey { case member, base, appearance, equipoOrigin = "equipo_origin" } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + member = c.value(.member, Member()); base = c.value(.base, Base()) |
| + appearance = BaseAppearance(server: c.optional(.appearance)); equipoOrigin = c.webURL(.equipoOrigin) |
| + } |
| +} |
| + |
| +// MARK: /api/v1/home |
| + |
| +/// `GET /api/v1/home`: Home's greeting, its first steps and the apps, in |
| +/// Home's order (P6). |
| +public struct HomeData: Decodable, Sendable, Equatable { |
| + public struct Step: Decodable, Sendable, Equatable, Hashable { |
| + public var label: String |
| + public var done: Bool |
| + public init(label: String, done: Bool) { self.label = label; self.done = done } |
| + enum CodingKeys: String, CodingKey { case label, done } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + label = c.value(.label, ""); done = c.value(.done, false) |
| + } |
| + } |
| + public struct App: Decodable, Sendable, Equatable, Identifiable { |
| + public enum Kind: String, Sendable, Equatable { case oficina, installed, own, other } |
| + public var id: String |
| + public var kind: Kind |
| + public var name: String |
| + public var url: URL? |
| + public var iconURL: String? |
| + public var tint: String? |
| + public var iconSVG: String? |
| + public var bundleID: String? |
| + public var scheme: String? |
| + public init(id: String, kind: Kind, name: String, url: URL?, iconURL: String? = nil, tint: String? = nil, |
| + iconSVG: String? = nil, bundleID: String? = nil, scheme: String? = nil) { |
| + self.id = id; self.kind = kind; self.name = name; self.url = url; self.iconURL = iconURL |
| + self.tint = tint; self.iconSVG = iconSVG; self.bundleID = bundleID; self.scheme = scheme |
| + } |
| + enum CodingKeys: String, CodingKey { |
| + case id, kind, name, url, tint, scheme |
| + case iconURL = "icon_url", iconSVG = "icon_svg", bundleID = "bundle_id" |
| + } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); kind = Kind(rawValue: c.value(.kind, "")) ?? .other; name = c.value(.name, "") |
| + url = c.webURL(.url); iconURL = c.optional(.iconURL); tint = c.optional(.tint); iconSVG = c.optional(.iconSVG) |
| + bundleID = c.optional(.bundleID); scheme = c.optional(.scheme) |
| + } |
| + } |
| + public var greeting: String |
| + public var lede: String |
| + public var steps: [Step] |
| + public var apps: [App] |
| + enum CodingKeys: String, CodingKey { case greeting, lede, steps, apps } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + greeting = c.value(.greeting, ""); lede = c.value(.lede, "") |
| + steps = c.value(.steps, []); apps = c.value(.apps, []).filter { !$0.id.isEmpty } |
| + } |
| +} |
| + |
| +// MARK: Ask |
| + |
| +/// Ask's states (ask.go): `ready` shows the conversation; `norunner` and |
| +/// `oldrunner` show it with a note; the rest stand in its place. |
| +/// `not_linked` is the app's own (Task 7: Equipo doesn't know this person); |
| +/// anything a newer Base says that this app doesn't know is `unavailable`. |
| +public enum AskPhase: String, Sendable, Equatable, CaseIterable { |
| + case loading, connect, pending, reconnect, unavailable, ready, norunner, oldrunner |
| + case notLinked = "not_linked" |
| + |
| + public init(server value: String?) { self = value.flatMap(AskPhase.init(rawValue:)).flatMap { $0 == .loading ? nil : $0 } ?? .unavailable } |
| + |
| + /// The states that show the conversation (ask.js `chatting`). |
| + public var chatting: Bool { self == .ready || self == .norunner || self == .oldrunner } |
| +} |
| + |
| +/// One line of the conversation (equipo.Message). Role is `person` or the |
| +/// Assistant's. |
| +public struct AskMessage: Decodable, Sendable, Equatable, Identifiable { |
| + public var id: String |
| + public var role: String |
| + public var text: String |
| + public var turnID: String |
| + public var createdAt: Date? |
| + public var isPerson: Bool { role == "person" } |
| + public init(id: String, role: String, text: String, turnID: String = "", createdAt: Date? = nil) { |
| + self.id = id; self.role = role; self.text = text; self.turnID = turnID; self.createdAt = createdAt |
| + } |
| + enum CodingKeys: String, CodingKey { case id, role, text, turnID = "turn_id", createdAt = "created_at" } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); role = c.value(.role, ""); text = c.value(.text, "") |
| + turnID = c.value(.turnID, ""); createdAt = c.date(.createdAt) |
| + } |
| +} |
| + |
| +/// The Assistant's answer to the person's messages (equipo.Turn). |
| +public struct AskTurn: Decodable, Sendable, Equatable { |
| + public var id: String |
| + public var kind: String |
| + public var state: String |
| + public var reason: String |
| + /// The reply's message id, when the server says it (ask.js reads it). |
| + public var replyID: String |
| + public init(id: String, kind: String = "", state: String, reason: String = "", replyID: String = "") { |
| + self.id = id; self.kind = kind; self.state = state; self.reason = reason; self.replyID = replyID |
| + } |
| + enum CodingKeys: String, CodingKey { case id, kind, state, reason, replyID = "reply_id" } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); kind = c.value(.kind, ""); state = c.value(.state, "") |
| + reason = c.value(.reason, ""); replyID = c.value(.replyID, "") |
| + } |
| + /// replied, failed and cancelled end a turn. |
| + public var ended: Bool { state == "replied" || state == "failed" || state == "cancelled" } |
| + /// A team_update turn is the Assistant taking a job's news by itself: |
| + /// quiet, with no status, activity or Stop. |
| + public var quiet: Bool { kind == "team_update" } |
| +} |
| + |
| +/// Something in the conversation to act on (equipo.Card): a question, |
| +/// confirm, outcome or connect card, or a job (`kind` "job"). |
| +public struct AskCard: Decodable, Sendable, Equatable, Identifiable { |
| + public struct Option: Decodable, Sendable, Equatable, Hashable { |
| + public var value: String |
| + public var label: String |
| + public init(value: String, label: String) { self.value = value; self.label = label } |
| + enum CodingKeys: String, CodingKey { case value, label } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + value = c.value(.value, ""); label = c.value(.label, "") |
| + } |
| + } |
| + public struct Link: Decodable, Sendable, Equatable, Hashable { |
| + public var label: String |
| + public var url: URL? |
| + public var rel: String |
| + public init(label: String, url: URL?, rel: String = "") { self.label = label; self.url = url; self.rel = rel } |
| + enum CodingKeys: String, CodingKey { case label, url, rel } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + label = c.value(.label, ""); url = c.webURL(.url); rel = c.value(.rel, "") |
| + } |
| + } |
| + public var id: String |
| + public var revision: Int64 |
| + public var kind: String |
| + public var state: String |
| + public var question: String |
| + public var options: [Option] |
| + public var links: [Link] |
| + public var result: String |
| + public var job: String |
| + public var detail: String |
| + public var startedAt: Date? |
| + public var turnID: String |
| + |
| + public init(id: String, revision: Int64 = 1, kind: String, state: String, question: String = "", options: [Option] = [], |
| + links: [Link] = [], result: String = "", job: String = "", detail: String = "", startedAt: Date? = nil, turnID: String = "") { |
| + self.id = id; self.revision = revision; self.kind = kind; self.state = state; self.question = question |
| + self.options = options; self.links = links; self.result = result; self.job = job; self.detail = detail |
| + self.startedAt = startedAt; self.turnID = turnID |
| + } |
| + enum CodingKeys: String, CodingKey { |
| + case id, revision, kind, state, question, options, links, result, job, detail |
| + case startedAt = "started_at", turnID = "turn_id" |
| + } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); revision = c.value(.revision, 0); kind = c.value(.kind, ""); state = c.value(.state, "") |
| + question = c.value(.question, ""); options = c.value(.options, []).filter { !$0.value.isEmpty } |
| + links = c.value(.links, []).filter { $0.url != nil }; result = c.value(.result, "") |
| + job = c.value(.job, ""); detail = c.value(.detail, ""); startedAt = c.date(.startedAt); turnID = c.value(.turnID, "") |
| + } |
| + |
| + public var isOpen: Bool { state == "open" } |
| + public var isJob: Bool { kind == "job" } |
| + public var jobState: JobState? { isJob ? JobState(rawValue: state) : nil } |
| + /// The kinds drawn as cards (ask.js `kinds`). |
| + public static let drawnKinds: Set<String> = ["question", "confirm", "outcome", "connect"] |
| + /// Where to see a job's work once there is something to see (ready, |
| + /// done): its first link with no rel. |
| + public var go: Link? { |
| + guard isJob, state == "ready" || state == "done" else { return nil } |
| + return links.first { $0.rel.isEmpty } |
| + } |
| + /// The job's own page in Equipo (rel "equipo"): the job view's title. |
| + public var equipoLink: Link? { isJob ? links.first { $0.rel == "equipo" } : nil } |
| + /// An open connect card's link to Base's own connect page. |
| + public var connectLink: Link? { kind == "connect" ? links.first { $0.rel == "oficina_connect" } : nil } |
| +} |
| + |
| +/// A job as `/ask/state` lists it: its card, with the cards that belong |
| +/// to it (jobView in ask.go). |
| +public struct AskJob: Decodable, Sendable, Equatable { |
| + public var card: AskCard |
| + public var cards: [AskCard] |
| + public init(card: AskCard, cards: [AskCard] = []) { self.card = card; self.cards = cards } |
| + enum CodingKeys: String, CodingKey { case cards } |
| + public init(from decoder: Decoder) throws { |
| + card = try AskCard(from: decoder) |
| + cards = try decoder.container(keyedBy: CodingKeys.self).value(.cards, []) |
| + } |
| +} |
| + |
| +/// `GET /ask/state`: what the conversation draws, and the cursor its event |
| +/// stream starts after. `renew_after` and `equipo_origin` are Task 7's. |
| +public struct AskSnapshot: Decodable, Sendable, Equatable { |
| + public var state: AskPhase |
| + public var messages: [AskMessage] |
| + public var jobs: [AskJob] |
| + public var cards: [AskCard] |
| + public var turn: AskTurn? |
| + public var status: String |
| + public var cursor: Int64 |
| + public var renewAfter: Date? |
| + public var equipoOrigin: URL? |
| + enum CodingKeys: String, CodingKey { |
| + case state, messages, jobs, cards, turn, status, cursor |
| + case renewAfter = "renew_after", equipoOrigin = "equipo_origin" |
| + } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + state = AskPhase(server: c.optional(.state)); messages = c.value(.messages, []).filter { !$0.id.isEmpty } |
| + jobs = c.value(.jobs, []); cards = c.value(.cards, []).filter { !$0.id.isEmpty } |
| + turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } |
| + status = c.value(.status, ""); cursor = c.value(.cursor, 0) |
| + renewAfter = c.date(.renewAfter); equipoOrigin = c.webURL(.equipoOrigin) |
| + } |
| +} |
| + |
| +/// `POST /ask/messages`'s answer: the person's message and the turn it |
| +/// started (equipo.Sent). |
| +public struct AskSent: Decodable, Sendable, Equatable { |
| + public var message: AskMessage? |
| + public var turn: AskTurn? |
| + enum CodingKeys: String, CodingKey { case message, turn } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + message = c.optional(.message).flatMap { (m: AskMessage) in m.id.isEmpty ? nil : m } |
| + turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } |
| + } |
| +} |
| + |
| +/// `POST /ask/cards/{id}/answer`'s answer: the card as it is now, and the |
| +/// message and turn the answer started (both null for an outcome card). |
| +public struct AskAnswered: Decodable, Sendable, Equatable { |
| + public var card: AskCard? |
| + public var message: AskMessage? |
| + public var turn: AskTurn? |
| + enum CodingKeys: String, CodingKey { case card, message, turn } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + card = c.optional(.card).flatMap { (k: AskCard) in k.id.isEmpty ? nil : k } |
| + message = c.optional(.message).flatMap { (m: AskMessage) in m.id.isEmpty ? nil : m } |
| + turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } |
| + } |
| +} |
| + |
| +/// `POST /api/v1/ask/oficina`'s answer (Task 7): `ready` with when to renew, |
| +/// or `not_linked`. |
| +public struct AskSetupAnswer: Decodable, Sendable, Equatable { |
| + public var state: AskPhase |
| + public var renewAfter: Date? |
| + enum CodingKeys: String, CodingKey { case state, renewAfter = "renew_after" } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + state = AskPhase(server: c.optional(.state)); renewAfter = c.date(.renewAfter) |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift| new file mode 100644 |
| index 0000000..83072ca |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| @@ -0,0 +1,591 @@ |
| +import Foundation |
| +import Observation |
| + |
| +/// Ask Base: the conversation, its jobs and cards and the turn in flight, |
| +/// kept as ask.js keeps them (internal/look/static/ask.js), so the apps |
| +/// draw the same thread the web draws from the same JSON and events. |
| +/// |
| +/// - `load()` reads `/ask/state` and starts the event stream after its |
| +/// cursor; `pause()` stops it; `resume()` is the app coming forward. |
| +/// - Events apply in place: a reply takes its thinking bubble's or draft's |
| +/// place; a job redraws in place and keeps its cards; a card of a job |
| +/// hangs under it while open and goes into its view once ended. |
| +/// - Writes carry idempotency keys: a message resent after a lost answer |
| +/// reuses its key, so Equipo does the work once. |
| +@MainActor @Observable public final class AskModel { |
| + // MARK: What the thread draws |
| + |
| + /// The Assistant's reply, streaming in. |
| + public struct Draft: Equatable, Sendable { |
| + public var turnID: String |
| + public var text: String |
| + /// Equipo's offsets count UTF-8 bytes. |
| + var bytes: Int |
| + /// The turn ended: no caret. |
| + public var settled: Bool |
| + } |
| + |
| + /// The bubble that sits where the reply will be while the Assistant |
| + /// works: three dots, then Equipo's glance or activity line. |
| + public struct Thinking: Equatable, Sendable { |
| + public var turnID: String |
| + public var line: String? |
| + var glanced: Bool |
| + } |
| + |
| + /// A job's pill, the open cards hanging under it, and the cards that |
| + /// have ended, listed in its view. |
| + public struct Job: Equatable, Sendable { |
| + public var card: AskCard |
| + public var open: [AskCard] |
| + public var ended: [AskCard] |
| + public var state: JobState { card.jobState ?? .working } |
| + } |
| + |
| + /// An open connect card, drawn as the Connect Oficina button; connected, |
| + /// a quiet line. |
| + public struct Offer: Equatable, Sendable { |
| + public var card: AskCard |
| + public var connected: Bool |
| + } |
| + |
| + public enum Entry: Equatable, Sendable, Identifiable { |
| + case message(AskMessage) |
| + case draft(Draft) |
| + case thinking(Thinking) |
| + case job(Job) |
| + case card(AskCard) |
| + case offer(Offer) |
| + |
| + public var id: String { |
| + switch self { |
| + case .message(let m): "m:" + m.id |
| + case .draft(let d): "d:" + d.turnID |
| + case .thinking(let t): "t:" + t.turnID |
| + case .job(let j): "j:" + j.card.id |
| + case .card(let c): "c:" + c.id |
| + case .offer(let o): "o:" + o.card.id |
| + } |
| + } |
| + } |
| + |
| + public private(set) var phase: AskPhase = .loading |
| + public private(set) var entries: [Entry] = [] |
| + /// The person's turn in flight (never a quiet one): Stop shows while |
| + /// there is one. |
| + public private(set) var turn: AskTurn? |
| + /// The line under the conversation: a waiting turn's notice, a failure, |
| + /// an activity with no bubble to say it in. |
| + public private(set) var status = "" |
| + /// When Ask's Oficina ID key wants renewing (Task 7), and where Equipo is. |
| + public private(set) var renewAfter: Date? |
| + public private(set) var equipoOrigin: URL? |
| + /// The composer's text. |
| + public var text = "" |
| + public private(set) var sending = false |
| + /// Cards with an answer on its way: their buttons are disabled. |
| + public private(set) var answering: Set<String> = [] |
| + |
| + /// Jobs waiting on the person (asking or stopped): the sidebar's badge. |
| + public var waitingJobs: Int { |
| + entries.reduce(0) { n, entry in |
| + if case .job(let j) = entry, j.state == .asking || j.state == .stopped { return n + 1 } |
| + return n |
| + } |
| + } |
| + |
| + /// The thread is empty: Ask's empty line shows. |
| + public var isEmpty: Bool { entries.isEmpty } |
| + |
| + // MARK: Wiring |
| + |
| + let client: BaseClient |
| + /// Runs `body` after `delay` (tests run it at once, or never). |
| + let schedule: @MainActor (Duration, @escaping @MainActor () -> Void) -> Void |
| + |
| + public init(client: BaseClient, |
| + schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later) { |
| + self.client = client |
| + self.schedule = schedule |
| + } |
| + |
| + public static func later(_ delay: Duration, _ body: @escaping @MainActor () -> Void) { |
| + Task { @MainActor in |
| + try? await Task.sleep(for: delay) |
| + body() |
| + } |
| + } |
| + |
| + // Turns that have ended stay ended: the send's answer, carrying the |
| + // turn as it was queued, can come after the turn's events ended it. |
| + private var over: Set<String> = [] |
| + private var quiet: Set<String> = [] |
| + /// Each job's newest card, for its job to place when it is drawn. |
| + private var jobCards: [String: AskCard] = [:] |
| + /// The message in flight or of unknown outcome, and its key. |
| + private var pendingSend: (text: String, key: String)? |
| + private var answerKeys: [String: (signature: String, key: String)] = [:] |
| + private var cancelKey: (turn: String, key: String)? |
| + private var stream: Task<Void, Never>? |
| + private var generation = 0 |
| + /// The newest event id the stream has seen: where a reconnect starts. |
| + public private(set) var cursor: Int64? |
| + |
| + // MARK: Loading and the stream |
| + |
| + /// Reads `/ask/state`, draws it, and listens for what comes after it. |
| + public func load() async { |
| + stopStream() |
| + let snapshot: AskSnapshot |
| + do { |
| + snapshot = try await client.askState() |
| + } catch { |
| + if error != .unauthenticated { phase = .unavailable } |
| + return |
| + } |
| + apply(snapshot) |
| + if phase.chatting { listen(after: snapshot.cursor) } |
| + } |
| + |
| + /// The app came forward: read afresh and listen again. |
| + public func resume() async { await load() } |
| + |
| + /// The app went away: stop listening. |
| + public func pause() { stopStream() } |
| + |
| + /// Ask set itself up elsewhere (Task 12): its new state, before a load. |
| + public func show(_ phase: AskPhase) { |
| + self.phase = phase |
| + if !phase.chatting { stopStream() } |
| + } |
| + |
| + func stopStream() { |
| + generation += 1 |
| + stream?.cancel() |
| + stream = nil |
| + } |
| + |
| + /// Listens from `cursor`. A stream Base ends cleanly reconnects from the |
| + /// newest id after its `retry:`; an offline one waits (two seconds |
| + /// more each time, up to twelve) then reads the state afresh; one Base |
| + /// refuses (a 410 `cursor_expired` from an old cursor, a 502) reads the |
| + /// state afresh at once, as ask.js does. A `state` event ends it. |
| + func listen(after start: Int64) { |
| + stopStream() |
| + cursor = start |
| + let epoch = generation |
| + stream = Task { [weak self] in |
| + var failures = 0 |
| + while !Task.isCancelled { |
| + guard let self, self.generation == epoch else { return } |
| + let client = self.client |
| + do { |
| + try await client.events(after: self.cursor, onRetry: { [weak self] ms in await self?.retryAfter(ms) }) { [weak self] event, id in |
| + await self?.receive(event, id: id, epoch: epoch) |
| + } |
| + failures = 0 |
| + guard self.generation == epoch, self.phase.chatting else { return } |
| + try? await Task.sleep(for: .milliseconds(max(500, self.retryMilliseconds))) |
| + } catch { |
| + guard self.generation == epoch, !Task.isCancelled else { return } |
| + switch error as? BaseAPIError ?? .badResponse { |
| + case .unauthenticated: |
| + return |
| + case .offline: |
| + failures = min(failures + 1, 6) |
| + try? await Task.sleep(for: .seconds(2 * failures)) |
| + guard self.generation == epoch, !Task.isCancelled else { return } |
| + await self.load() |
| + return |
| + default: |
| + await self.load() |
| + return |
| + } |
| + } |
| + } |
| + } |
| + } |
| + |
| + /// The stream's `retry:` advice: how long to wait before reconnecting. |
| + private var retryMilliseconds = 3000 |
| + private func retryAfter(_ ms: Int) { retryMilliseconds = ms } |
| + |
| + private func receive(_ event: AskEvent, id: Int64?, epoch: Int) { |
| + guard generation == epoch else { return } |
| + if let id { cursor = id } |
| + apply(event) |
| + } |
| + |
| + // MARK: Writes |
| + |
| + /// Sends the composer's text. Its key is kept until the outcome is |
| + /// known, so sending the same text again after a lost answer is the same |
| + /// message to Equipo; different text gets a fresh key. |
| + public func send() async { |
| + let body = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| + guard !body.isEmpty, !sending, turn == nil else { return } |
| + let key = pendingSend?.text == body ? pendingSend!.key : BaseClient.newKey() |
| + pendingSend = (body, key) |
| + sending = true |
| + defer { sending = false } |
| + do { |
| + let sent = try await client.send(body, key: key) |
| + pendingSend = nil |
| + text = "" |
| + status = "" |
| + if phase != .ready { phase = .ready } |
| + if let message = sent.message { add(message) } |
| + if let t = sent.turn { setTurn(t) } |
| + } catch { |
| + refusedWrite(error, keepsKey: { pendingSend = nil }) |
| + // The message's own failure line (copy review), in place of |
| + // the answers' and Stop's. |
| + if status == BaseText.text("ask.not_sent") { status = BaseText.text("native.ask.send.error") } |
| + } |
| + } |
| + |
| + /// Stop: cancels the turn in flight. |
| + public func stop() async { |
| + guard let turn else { return } |
| + let key = cancelKey?.turn == turn.id ? cancelKey!.key : BaseClient.newKey() |
| + cancelKey = (turn.id, key) |
| + do { |
| + try await client.cancel(turn: turn.id, key: key) |
| + cancelKey = nil |
| + } catch { |
| + refusedWrite(error, keepsKey: { cancelKey = nil }) |
| + } |
| + } |
| + |
| + /// One of a card's choices, bound to the revision the person saw. A 409 |
| + /// means the card moved on (a new revision, or answered elsewhere): the |
| + /// conversation is read afresh and the person chooses again; it is never |
| + /// resent. Without a runner that can answer, nothing was answered and |
| + /// the card stays open. |
| + public func answer(_ card: AskCard, _ option: AskCard.Option) async { |
| + guard card.isOpen, !answering.contains(card.id) else { return } |
| + let signature = "\(card.revision)|\(option.value)" |
| + let key = answerKeys[card.id]?.signature == signature ? answerKeys[card.id]!.key : BaseClient.newKey() |
| + answerKeys[card.id] = (signature, key) |
| + answering.insert(card.id) |
| + defer { answering.remove(card.id) } |
| + do { |
| + let out = try await client.answer(card: card.id, choice: option.value, revision: card.revision, key: key) |
| + answerKeys[card.id] = nil |
| + if phase != .ready { phase = .ready } |
| + if let c = out.card { add(c) } |
| + if let m = out.message { add(m) } |
| + if let t = out.turn { setTurn(t) } |
| + } catch { |
| + if case .server(409, _, let state) = error, state != "norunner", state != "oldrunner" { |
| + answerKeys[card.id] = nil |
| + await load() |
| + return |
| + } |
| + refusedWrite(error, keepsKey: { answerKeys[card.id] = nil }) |
| + } |
| + } |
| + |
| + /// What a refused write shows (ask.js `post`): Ask's own states stand in |
| + /// for the conversation, or add their note; a 409 is stale (the next |
| + /// events show how things are); anything else asks to try again. The |
| + /// key is forgotten once the outcome is known (anything but offline and |
| + /// a 502). |
| + private func refusedWrite(_ error: BaseAPIError, keepsKey forget: () -> Void) { |
| + switch error { |
| + case .unauthenticated: |
| + forget() |
| + case .offline: |
| + status = BaseText.text("ask.not_sent") |
| + case .server(let code, _, let state): |
| + if code != 502 { forget() } |
| + let phase = state.map { AskPhase(server: $0) } |
| + if let phase, [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(phase) { |
| + show(phase) |
| + } else if code != 409 { |
| + status = BaseText.text("ask.not_sent") |
| + } |
| + case .badResponse: |
| + forget() |
| + status = BaseText.text("ask.not_sent") |
| + } |
| + } |
| + |
| + // MARK: Applying what Base says |
| + |
| + /// Draws `/ask/state` afresh (ask.js `load`). |
| + func apply(_ s: AskSnapshot) { |
| + phase = s.state |
| + renewAfter = s.renewAfter |
| + if let origin = s.equipoOrigin { equipoOrigin = origin } |
| + guard phase.chatting else { return } |
| + entries = [] |
| + jobCards = [:] |
| + over = [] |
| + quiet = [] |
| + turn = nil |
| + status = "" |
| + for m in s.messages { add(m) } |
| + for j in s.jobs { |
| + add(j.card) |
| + for c in j.cards { add(c) } |
| + } |
| + for c in s.cards { add(c) } |
| + setTurn(s.turn, line: s.status) |
| + } |
| + |
| + /// One event from the stream (ask.js `listen`). |
| + public func apply(_ event: AskEvent) { |
| + switch event { |
| + case .message(let m): add(m) |
| + case .delta(let d): delta(d) |
| + case .card(let c): add(c) |
| + case .turn(let t): setTurn(t) |
| + case .glance(let g): glance(g) |
| + case .activity(let a): activity(a) |
| + case .state(let s): |
| + stopStream() |
| + phase = s |
| + } |
| + } |
| + |
| + private func index(_ id: String) -> Int? { entries.firstIndex { $0.id == id } } |
| + |
| + /// A message, once. The Assistant's reply takes its draft's or thinking |
| + /// bubble's place; open connect cards waiting for it follow it. |
| + func add(_ m: AskMessage) { |
| + guard index("m:" + m.id) == nil else { return } |
| + if !m.isPerson, !m.turnID.isEmpty, let at = index("d:" + m.turnID) ?? index("t:" + m.turnID) { |
| + entries[at] = .message(m) |
| + } else { |
| + entries.append(.message(m)) |
| + } |
| + if !m.isPerson { reoffer() } |
| + } |
| + |
| + /// A streamed word. The turn's thinking bubble becomes its draft; |
| + /// words whose offset isn't where the draft ends are dropped, as ask.js |
| + /// drops them. |
| + func delta(_ d: AskDelta) { |
| + if let at = index("t:" + d.turnID) { |
| + entries[at] = .draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) |
| + } else if index("d:" + d.turnID) == nil { |
| + // Above the turn's connect button, should it already show. |
| + let draft = Entry.draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) |
| + if let offer = entries.firstIndex(where: { if case .offer(let o) = $0 { o.card.turnID == d.turnID } else { false } }) { |
| + entries.insert(draft, at: offer) |
| + } else { |
| + entries.append(draft) |
| + } |
| + } |
| + guard let at = index("d:" + d.turnID), case .draft(var draft) = entries[at], d.offset == Int64(draft.bytes) else { return } |
| + draft.text += d.text |
| + draft.bytes += d.text.utf8.count |
| + entries[at] = .draft(draft) |
| + } |
| + |
| + /// Equipo's glance: one line on the turn in flight, before its words, |
| + /// in its thinking bubble; never kept. |
| + func glance(_ g: AskLine) { |
| + let text = g.text.trimmingCharacters(in: .whitespacesAndNewlines) |
| + guard !text.isEmpty, !quiet.contains(g.turnID), turn?.id == g.turnID, |
| + let at = index("t:" + g.turnID), case .thinking(var t) = entries[at], !t.glanced else { return } |
| + t.line = text |
| + t.glanced = true |
| + entries[at] = .thinking(t) |
| + } |
| + |
| + /// What the Assistant is doing: in its bubble unless a glance holds it, |
| + /// else in the status line. |
| + func activity(_ a: AskLine) { |
| + guard !a.text.isEmpty, !quiet.contains(a.turnID) else { return } |
| + if let at = index("t:" + a.turnID), case .thinking(var t) = entries[at] { |
| + guard !t.glanced else { return } |
| + t.line = a.text |
| + entries[at] = .thinking(t) |
| + } else if turn?.id == a.turnID { |
| + status = a.text |
| + } |
| + } |
| + |
| + /// A card or a job (ask.js `addCard`, `addJob`). |
| + func add(_ c: AskCard) { |
| + if c.isJob { addJob(c); return } |
| + if c.kind == "connect", c.connectLink != nil || index("o:" + c.id) != nil { |
| + offer(c) |
| + return |
| + } |
| + guard AskCard.drawnKinds.contains(c.kind), c.isOpen || !c.result.isEmpty else { |
| + remove(card: c.id) |
| + jobCards[c.id] = nil |
| + return |
| + } |
| + if let old = card(c.id), old.revision > c.revision { return } |
| + if !c.job.isEmpty { jobCards[c.id] = c } |
| + if !c.job.isEmpty, let at = index("j:" + c.job), case .job(var job) = entries[at] { |
| + removeLoose(c.id) |
| + job.open.removeAll { $0.id == c.id } |
| + job.ended.removeAll { $0.id == c.id } |
| + if c.isOpen { |
| + if let i = job.open.firstIndex(where: { $0.id == c.id }) { job.open[i] = c } else { job.open.append(c) } |
| + } else { |
| + job.ended.append(c) |
| + } |
| + entries[at] = .job(job) |
| + return |
| + } |
| + if let at = index("c:" + c.id) { entries[at] = .card(c) } else { entries.append(.card(c)) } |
| + } |
| + |
| + private func addJob(_ c: AskCard) { |
| + guard c.jobState != nil else { return } |
| + if let at = index("j:" + c.id), case .job(var job) = entries[at] { |
| + guard job.card.revision <= c.revision else { return } |
| + job.card = c |
| + entries[at] = .job(job) |
| + return |
| + } |
| + var job = Job(card: c, open: [], ended: []) |
| + // Its loose cards, drawn before it was, move under it, or into its view. |
| + for entry in entries { |
| + guard case .card(let loose) = entry, loose.job == c.id else { continue } |
| + let latest = jobCards[loose.id] ?? loose |
| + if latest.isOpen { job.open.append(latest) } else { job.ended.append(latest) } |
| + } |
| + entries.removeAll { if case .card(let loose) = $0 { loose.job == c.id } else { false } } |
| + entries.append(.job(job)) |
| + } |
| + |
| + private func card(_ id: String) -> AskCard? { |
| + for entry in entries { |
| + switch entry { |
| + case .card(let c) where c.id == id: return c |
| + case .job(let j): |
| + if let c = j.open.first(where: { $0.id == id }) ?? j.ended.first(where: { $0.id == id }) { return c } |
| + default: continue |
| + } |
| + } |
| + return nil |
| + } |
| + |
| + private func removeLoose(_ id: String) { entries.removeAll { $0.id == "c:" + id } } |
| + |
| + private func remove(card id: String) { |
| + removeLoose(id) |
| + for (at, entry) in entries.enumerated() { |
| + guard case .job(var job) = entry else { continue } |
| + let before = job.open.count + job.ended.count |
| + job.open.removeAll { $0.id == id } |
| + job.ended.removeAll { $0.id == id } |
| + if job.open.count + job.ended.count != before { entries[at] = .job(job) } |
| + } |
| + } |
| + |
| + /// An open connect card ends the Assistant's newest reply; one whose |
| + /// reply is still on its way waits for it (reoffer). Connected, it |
| + /// becomes a quiet line where it is. |
| + private var waitingOffers: [String: AskCard] = [:] |
| + |
| + private func offer(_ c: AskCard) { |
| + if let at = index("o:" + c.id), case .offer(let o) = entries[at], o.card.revision > c.revision { return } |
| + if !c.isOpen { |
| + waitingOffers[c.id] = nil |
| + if let at = index("o:" + c.id) { entries[at] = .offer(Offer(card: c, connected: true)) } |
| + return |
| + } |
| + guard c.connectLink != nil else { return } |
| + if onItsWay(c.turnID) { |
| + if index("o:" + c.id) == nil { waitingOffers[c.id] = c } |
| + return |
| + } |
| + put(c) |
| + } |
| + |
| + private func onItsWay(_ turnID: String) -> Bool { |
| + guard !turnID.isEmpty else { return false } |
| + if entries.contains(where: { if case .message(let m) = $0 { !m.isPerson && m.turnID == turnID } else { false } }) { return false } |
| + return !over.contains(turnID) || index("t:" + turnID) != nil || index("d:" + turnID) != nil |
| + } |
| + |
| + private func reoffer() { |
| + for (id, c) in waitingOffers where !onItsWay(c.turnID) { |
| + waitingOffers[id] = nil |
| + put(c) |
| + } |
| + } |
| + |
| + /// After the newest reply, or at the end with none. |
| + private func put(_ c: AskCard) { |
| + entries.removeAll { $0.id == "o:" + c.id } |
| + let offer = Entry.offer(Offer(card: c, connected: false)) |
| + if let last = entries.lastIndex(where: { if case .message(let m) = $0 { !m.isPerson } else { false } }) { |
| + entries.insert(offer, at: last + 1) |
| + } else { |
| + entries.append(offer) |
| + } |
| + } |
| + |
| + // MARK: Turns |
| + |
| + /// A turn's state (ask.js `setTurn`). A quiet turn shows nothing. One in |
| + /// flight is the turn: waiting says so in the status line, else its |
| + /// thinking bubble shows. One that ends settles its bubble and drafts. |
| + func setTurn(_ t: AskTurn?, line: String = "") { |
| + if let t, t.id.isEmpty || over.contains(t.id) { return } |
| + if let t, t.ended { over.insert(t.id) } |
| + if let t, t.quiet { |
| + quiet.insert(t.id) |
| + if t.ended { settle(t) } |
| + return |
| + } |
| + if let t, !t.ended { |
| + turn = t |
| + if t.state == "waiting" { |
| + drop(t.id) |
| + status = line.isEmpty ? BaseText.text("ask.waiting") : line |
| + } else { |
| + status = "" |
| + think(t.id) |
| + } |
| + return |
| + } |
| + if let t { |
| + unthink(t) |
| + reoffer() |
| + } |
| + if let t, let current = turn, t.id != current.id { return } |
| + turn = nil |
| + status = t?.state == "failed" ? BaseText.text("ask.failed") : "" |
| + settle(t) |
| + } |
| + |
| + private func think(_ id: String) { |
| + guard index("t:" + id) == nil, index("d:" + id) == nil else { return } |
| + entries.append(.thinking(Thinking(turnID: id, line: nil, glanced: false))) |
| + } |
| + |
| + private func drop(_ id: String) { entries.removeAll { $0.id == "t:" + id } } |
| + |
| + /// A replied turn's bubble waits a little for its reply (it may come |
| + /// just after); otherwise, or if it never comes, it goes. |
| + private func unthink(_ t: AskTurn) { |
| + guard index("t:" + t.id) != nil else { return } |
| + if t.state == "replied", t.replyID.isEmpty || index("m:" + t.replyID) == nil { |
| + schedule(.seconds(5)) { [weak self] in self?.drop(t.id) } |
| + return |
| + } |
| + drop(t.id) |
| + } |
| + |
| + /// Ends turn `t`'s drafts (every draft with none): a cancelled or |
| + /// failed turn's go; the rest stay as written, without the caret. |
| + private func settle(_ t: AskTurn?) { |
| + let gone = t.map { $0.state == "cancelled" || $0.state == "failed" } ?? false |
| + entries = entries.compactMap { entry in |
| + guard case .draft(var d) = entry, t == nil || d.turnID == t!.id else { return entry } |
| + if gone { return nil } |
| + d.settled = true |
| + return .draft(d) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/BaseText.swift b/native/apple/Sources/BaseKit/BaseText.swift| index b2b51ab..b4d44f3 100644 |
| --- a/native/apple/Sources/BaseKit/BaseText.swift |
| +++ b/native/apple/Sources/BaseKit/BaseText.swift |
| @@ -20,4 +20,10 @@ public enum BaseText { |
| for (name, value) in values { out = out.replacingOccurrences(of: "{\(name)}", with: value) } |
| return out |
| } |
| + |
| + /// A plural entry (copy review's "Plural in the String Catalog"): the |
| + /// catalog's forms select on `count`, written `%lld` there. |
| + public static func plural(_ key: String, _ count: Int) -> String { |
| + String.localizedStringWithFormat(text(key), count) |
| + } |
| } |
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings| index 4bfdaa7..2a84574 100644 |
| --- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| @@ -1,6 +1,438 @@ |
| { |
| "sourceLanguage": "en", |
| "strings": { |
| + "ask.close": { |
| + "comment": "Base on the web's approved copy. The job view's close button (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Close" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.connect.button": { |
| + "comment": "Base on the web's approved copy. Under it (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Set up Ask Base" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.connect.lede": { |
| + "comment": "Base on the web's approved copy. Ask isn't set up for this person yet (chat.html, state connect).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Set up Ask Base to start asking." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.connect_oficina": { |
| + "comment": "Base on the web's approved copy. The button an open connect card draws (chat.html ask-offer).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Connect Oficina" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.connect_oficina.line": { |
| + "comment": "Base on the web's approved copy. Under it (chat.html ask-offer).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Calendar, Docs, Sheets and more" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.connected": { |
| + "comment": "Base on the web's approved copy. A connect card once connected (ask.js offer).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Connected" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.conversation_a11y": { |
| + "comment": "Base on the web's approved copy. VoiceOver's name for the thread (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Conversation" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.empty": { |
| + "comment": "Base on the web's approved copy. An empty conversation (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask about your work, or ask Base to get something done." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.failed": { |
| + "comment": "Base on the web's approved copy. The status line when a turn fails (ask.js setTurn).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That didn't get an answer. Try again." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.jump": { |
| + "comment": "Base on the web's approved copy. Floats at the conversation's foot when the person has scrolled up and something new arrives (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Jump to latest" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.message_label": { |
| + "comment": "Base on the web's approved copy. VoiceOver's name for the composer (chat.html's hidden label).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Message" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.norunner": { |
| + "comment": "Base on the web's approved copy. Above the composer when the person has no runner that can answer (chat.html, norunner); the link goes to Equipo. Markdown link: keep the brackets and {equipo}.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base isn't set up for you yet. [Finish setting it up]({equipo}), then try again." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.not_sent": { |
| + "comment": "Base on the web's approved copy. The status line when an answer or Stop didn't go through (ask.js post).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That didn't send. Try again." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.oldrunner": { |
| + "comment": "Base on the web's approved copy. Above the composer when the person's runner is too old (chat.html, oldrunner). Markdown link: keep the brackets and {equipo}.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base needs an update first. [Update it]({equipo}), then try again." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.pending.button": { |
| + "comment": "Base on the web's approved copy. Under it (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Finish setting up" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.pending.lede": { |
| + "comment": "Base on the web's approved copy. chat.html, state pending.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "You started setting up Ask Base. Approve it to start asking." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.pill_a11y": { |
| + "comment": "Base on the web's approved copy. VoiceOver's label for a job's pill: its title and status (chat.html's aria-label). Not copy; listed so the order stays.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "{title}, {stage}" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.placeholder": { |
| + "comment": "Base on the web's approved copy. The composer's placeholder (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base anything" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.reconnect.button": { |
| + "comment": "Base on the web's approved copy. Under it (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Set it up again" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.reconnect.lede": { |
| + "comment": "Base on the web's approved copy. chat.html, state reconnect.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base needs setting up again." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.send": { |
| + "comment": "Base on the web's approved copy. The composer's Send button, an arrow (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Send" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.stop": { |
| + "comment": "Base on the web's approved copy. The composer's Stop button, a square, while a turn runs (chat.html).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Stop" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.thinking_a11y": { |
| + "comment": "Base on the web's approved copy. VoiceOver's name for the thinking bubble's dots (ask.js think).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Thinking…" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.unavailable": { |
| + "comment": "Base on the web's approved copy. chat.html, state unavailable.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base isn't answering. Try again in a minute." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.waiting": { |
| + "comment": "Base on the web's approved copy. The status line while a turn waits (ask.js setTurn).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Ask Base can't answer right now. It will as soon as it can." |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.day": { |
| + "comment": "Base on the web's approved copy. {when}: 'Started on 12 November' (the day in Base's time zone, day and month).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "on {day}" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.hour": { |
| + "comment": "Base on the web's approved copy. {when}: 'Started 1 hour ago'.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "1 hour ago" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.hours": { |
| + "comment": "Base on the web's approved copy. {when}: 'Started 3 hours ago'.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "{n} hours ago" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.minute": { |
| + "comment": "Base on the web's approved copy. {when}: 'Started 1 minute ago'.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "1 minute ago" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.minutes": { |
| + "comment": "Base on the web's approved copy. {when}: 'Started 5 minutes ago'.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "{n} minutes ago" |
| + } |
| + } |
| + } |
| + }, |
| + "ask.when.now": { |
| + "comment": "Base on the web's approved copy. {when} in 'Started {when}' (ask.js startedText: 'Started just now').", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "just now" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.paste.command": { |
| + "comment": "Equipo's approved label (EquipoKit, 00d09aa7) over a shell code block in a reply.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Command" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.paste.copied": { |
| + "comment": "Equipo's: a code block's Copy button once pressed.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Copied" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.paste.copy": { |
| + "comment": "Equipo's: a code block's Copy button.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Copy" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.paste.prompt": { |
| + "comment": "Equipo's label over a prompt code block.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Prompt" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.paste.text": { |
| + "comment": "Equipo's label over a text code block.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Text" |
| + } |
| + } |
| + } |
| + }, |
| "native.account.signout": { |
| "comment": "Same menu.", |
| "extractionState": "manual", |
| @@ -44,7 +476,19 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "Ask Base isn't set up for you yet. Finish setting it up in Equipo, then come back." |
| + "value": "Ask Base isn’t set up for you yet. Finish setting it up with your team, then come back." |
| + } |
| + } |
| + } |
| + }, |
| + "native.ask.send.error": { |
| + "comment": "Under a message that failed to send.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Your message wasn’t sent. Check your connection and try again." |
| } |
| } |
| } |
| @@ -92,7 +536,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "{shortcut} opens this anywhere" |
| + "value": "Open Ask Base anywhere with {shortcut}" |
| } |
| } |
| } |
| @@ -104,7 +548,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "You're offline. Base will catch up when you're back." |
| + "value": "You’re offline. Reconnect to send messages." |
| } |
| } |
| } |
| @@ -157,6 +601,54 @@ |
| } |
| } |
| }, |
| + "native.settings.account.signout.confirm.action": { |
| + "comment": "Signs out.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Sign out" |
| + } |
| + } |
| + } |
| + }, |
| + "native.settings.account.signout.confirm.cancel": { |
| + "comment": "Closes the confirmation without signing out.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Cancel" |
| + } |
| + } |
| + } |
| + }, |
| + "native.settings.account.signout.confirm.message": { |
| + "comment": "Under the heading. Same wording as the note on Base's web Settings page.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Apps you’ve opened stay signed in until you sign out of each one." |
| + } |
| + } |
| + } |
| + }, |
| + "native.settings.account.signout.confirm.title": { |
| + "comment": "Asked when the person chooses Sign out, in Settings or the account menu.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Sign out of Base?" |
| + } |
| + } |
| + } |
| + }, |
| "native.settings.account.team": { |
| "comment": "Account tab: beside the team's name, with a Switch team button.", |
| "extractionState": "manual", |
| @@ -308,7 +800,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "Off until you choose one" |
| + "value": "No shortcut set" |
| } |
| } |
| } |
| @@ -374,13 +866,25 @@ |
| } |
| }, |
| "native.sidebar.ask.badge_a11y": { |
| - "comment": "Read by VoiceOver for the badge on the Ask Base row. (Keep {count}; singular form: 1 job needs you)", |
| + "comment": "Read by VoiceOver for the badge on the Ask Base row. (Plural in the String Catalog: one = '1 job needs you', other = '{count} jobs need you')", |
| "extractionState": "manual", |
| "localizations": { |
| "en": { |
| - "stringUnit": { |
| - "state": "translated", |
| - "value": "{count} jobs need you" |
| + "variations": { |
| + "plural": { |
| + "one": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "1 job needs you" |
| + } |
| + }, |
| + "other": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "%lld jobs need you" |
| + } |
| + } |
| + } |
| } |
| } |
| } |
| @@ -421,6 +925,30 @@ |
| } |
| } |
| }, |
| + "native.signin.code.expired": { |
| + "comment": "Under the code boxes when the code is too old; 'Send a new code' is just below.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That code has expired. Send a new one to try again." |
| + } |
| + } |
| + } |
| + }, |
| + "native.signin.code.invalid": { |
| + "comment": "Under the code boxes when the code is wrong.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That code didn’t work. Check it and try again." |
| + } |
| + } |
| + } |
| + }, |
| "native.signin.code.lede": { |
| "comment": "Under 'Check your email'. {email} is the address they typed. (Keep {email})", |
| "extractionState": "manual", |
| @@ -428,7 +956,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "We sent a code to {email}" |
| + "value": "We sent a code to {email}." |
| } |
| } |
| } |
| @@ -440,7 +968,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "Next time, sign in with a passkey: Base offers to make one once you're in." |
| + "value": "Next time, use a passkey to sign in. You can set one up in Base." |
| } |
| } |
| } |
| @@ -469,6 +997,18 @@ |
| } |
| } |
| }, |
| + "native.signin.email.error": { |
| + "comment": "Under the email field when the code couldn't be sent.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "We couldn’t send a code. Check your connection and try again." |
| + } |
| + } |
| + } |
| + }, |
| "native.signin.email.label": { |
| "comment": "Above the email field on the sign-in card.", |
| "extractionState": "manual", |
| @@ -500,7 +1040,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "Use your Oficina ID, the same one as Docs, Sheets and Calls." |
| + "value": "Use your Oficina ID, the same one you use for Docs, Sheets and Calls." |
| } |
| } |
| } |
| @@ -548,7 +1088,7 @@ |
| "en": { |
| "stringUnit": { |
| "state": "translated", |
| - "value": "Sign in to Base on the web once with your Oficina ID, then come back." |
| + "value": "Sign in to Base on the web once with your Oficina ID, then come back here." |
| } |
| } |
| } |
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift| new file mode 100644 |
| index 0000000..100d29b |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| @@ -0,0 +1,120 @@ |
| +import Combine |
| +import Foundation |
| +import Observation |
| +import RastrilloApple |
| + |
| +/// Base's session on this device: Oficina ID through the kit, and once |
| +/// signed in, the client, the member, Home and Ask. |
| +/// |
| +/// - Oficina ID is the kit's `OficinaIDModel` (app "base"): straight in |
| +/// when another Oficina app holds the ID, the kit's onboarding otherwise. |
| +/// `OficinaApp.base` arrives with the kit's next pin; until then the |
| +/// onboarding draws in the kit's default appearance. |
| +/// - The client keeps one transport for the whole session and swaps the |
| +/// kit's session under it when the kit mints a new one (a 401's |
| +/// `sessionRejected()`, a stale one renewed on foreground), so Ask's |
| +/// stream and writes never hold an ended cookie. |
| +/// - Coming forward: `renewIfNeeded()`, then Home and Ask read afresh and |
| +/// Ask listens again (Task 12 adds renewing Ask's own key first). |
| +@MainActor @Observable public final class BaseSession { |
| + public static let configuration = OficinaIDConfiguration(app: "base", appName: "Base") |
| + public static var appGroup: String { |
| + #if os(iOS) |
| + "group.works.oficina" |
| + #else |
| + "9U4A84C4WK.works.oficina" |
| + #endif |
| + } |
| + |
| + public let oficina: OficinaIDModel |
| + public private(set) var signedIn: OficinaSignedIn? |
| + public private(set) var client: BaseClient? |
| + public private(set) var ask: AskModel? |
| + public private(set) var me: Me? |
| + public private(set) var home: HomeData? |
| + |
| + @ObservationIgnored private var transport: SwappableTransport? |
| + @ObservationIgnored private var watching: AnyCancellable? |
| + |
| + public init(oficina: OficinaIDModel) { |
| + self.oficina = oficina |
| + watching = oficina.$step.sink { [weak self] step in |
| + Task { @MainActor in self?.stepChanged(step) } |
| + } |
| + } |
| + |
| + public static func live() -> BaseSession { |
| + BaseSession(oficina: .live(configuration: configuration, appGroup: appGroup)) |
| + } |
| + |
| + /// The kit moved: signed in (perhaps with a fresh session), or out. |
| + func stepChanged(_ step: OficinaIDModel.Step) { |
| + guard case .signedIn(let state) = step else { |
| + if signedIn != nil { signedOut() } |
| + return |
| + } |
| + let http = state.client() |
| + if let transport, let current = signedIn, current.origin == state.origin, current.identity.id == state.identity.id { |
| + transport.swap(http) |
| + signedIn = state |
| + return |
| + } |
| + ask?.pause() |
| + let swappable = SwappableTransport(http) |
| + let oficina = self.oficina |
| + let client = BaseClient(transport: swappable) { await oficina.sessionRejected() } |
| + transport = swappable |
| + self.client = client |
| + signedIn = state |
| + me = nil |
| + home = nil |
| + ask = AskModel(client: client) |
| + Task { await self.refresh() } |
| + } |
| + |
| + private func signedOut() { |
| + ask?.pause() |
| + ask = nil; client = nil; transport = nil |
| + signedIn = nil; me = nil; home = nil |
| + } |
| + |
| + /// Reads the member, Home and Ask afresh. |
| + public func refresh() async { |
| + guard let client else { return } |
| + async let me = try? client.me() |
| + async let home = try? client.home() |
| + await ask?.load() |
| + if let me = await me { self.me = me } |
| + if let home = await home { self.home = home } |
| + } |
| + |
| + /// The app came forward. |
| + public func foreground() async { |
| + await oficina.renewIfNeeded() |
| + await refresh() |
| + } |
| + |
| + /// The app went away: Ask stops listening. |
| + public func background() { ask?.pause() } |
| +} |
| + |
| +/// A transport whose session can be replaced under the requests that use |
| +/// it: each request goes to whichever `NativeHTTP` is current when it starts. |
| +final class SwappableTransport: NativeTransport, @unchecked Sendable { |
| + private let lock = NSLock() |
| + private var inner: NativeTransport |
| + init(_ inner: NativeTransport) { self.inner = inner } |
| + func swap(_ next: NativeTransport) { lock.withLock { inner = next } } |
| + private var current: NativeTransport { lock.withLock { inner } } |
| + |
| + var origin: URL { current.origin } |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + try await current.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| + } |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + try await current.stream(path, onOpen: onOpen, onLine: onLine) |
| + } |
| + func download(_ path: String, to destination: URL) async throws { |
| + try await current.download(path, to: destination) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/AskModelTests.swift b/native/apple/Tests/BaseKitTests/AskModelTests.swift| new file mode 100644 |
| index 0000000..f050773 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/AskModelTests.swift |
| @@ -0,0 +1,231 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| + |
| +/// The thread the model keeps is the one ask.js draws, from the same |
| +/// state and events (fixtures in Task 6's contract shapes). |
| +@MainActor final class AskModelTests: XCTestCase { |
| + var later: [@MainActor () -> Void] = [] |
| + |
| + func model(_ steps: [ScriptedTransport.Step] = []) -> (AskModel, ScriptedTransport) { |
| + let t = ScriptedTransport(steps) |
| + return (AskModel(client: BaseClient(transport: t) {}, schedule: { [unowned self] _, body in self.later.append(body) }), t) |
| + } |
| + |
| + func ids(_ m: AskModel) -> [String] { m.entries.map(\.id) } |
| + |
| + func testStateDrawsTheThreadJobsAndTheirCards() { |
| + let (m, _) = model() |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + XCTAssertEqual(m.phase, .ready) |
| + XCTAssertEqual(ids(m), ["m:m1", "m:m2", "j:j1", "j:j2", "j:j3"]) |
| + guard case .job(let j2) = m.entries[3] else { return XCTFail() } |
| + XCTAssertEqual(j2.open.map(\.id), ["c1"], "the open question hangs under its pill") |
| + XCTAssertEqual(j2.ended.map(\.id), ["c0"], "the answered one is in the job's view") |
| + XCTAssertEqual(m.waitingJobs, 1) |
| + guard case .job(let j3) = m.entries[4] else { return XCTFail() } |
| + XCTAssertEqual(j3.card.go?.label, "Try it") |
| + XCTAssertNotNil(m.renewAfter) |
| + XCTAssertEqual(m.equipoOrigin?.host, "equipo.fennel.example") |
| + } |
| + |
| + func testOutsideReadyNothingIsDrawn() { |
| + let (m, _) = model() |
| + m.apply(Fixture.snapshot("state-connect.json")) |
| + XCTAssertEqual(m.phase, .connect) |
| + XCTAssertTrue(m.entries.isEmpty) |
| + } |
| + |
| + /// A turn thinks, says its glance (and keeps it over activity), streams |
| + /// its words into the bubble's place, and its reply takes that place. |
| + func testATurnThinksStreamsAndReplies() { |
| + let (m, _) = model() |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + m.apply(.message(AskMessage(id: "m3", role: "person", text: "What's on tomorrow?", turnID: "t2"))) |
| + m.apply(.turn(AskTurn(id: "t2", kind: "chat", state: "running"))) |
| + XCTAssertEqual(ids(m).suffix(2), ["m:m3", "t:t2"]) |
| + XCTAssertNotNil(m.turn) |
| + m.apply(.activity(AskLine(turnID: "t2", text: "Reading your calendar"))) |
| + guard case .thinking(let t1) = m.entries.last else { return XCTFail() } |
| + XCTAssertEqual(t1.line, "Reading your calendar") |
| + m.apply(.glance(AskLine(turnID: "t2", text: "Looking at tomorrow"))) |
| + m.apply(.activity(AskLine(turnID: "t2", text: "Still reading"))) |
| + guard case .thinking(let t2) = m.entries.last else { return XCTFail() } |
| + XCTAssertEqual(t2.line, "Looking at tomorrow", "activity leaves a glance be") |
| + m.apply(.delta(AskDelta(turnID: "t2", offset: 0, text: "Three things "))) |
| + m.apply(.delta(AskDelta(turnID: "t2", offset: 99, text: "out of place"))) |
| + m.apply(.delta(AskDelta(turnID: "t2", offset: 13, text: "tomorrow: café"))) |
| + guard case .draft(let d) = m.entries.last else { return XCTFail("\(m.entries)") } |
| + XCTAssertEqual(d.text, "Three things tomorrow: café") |
| + XCTAssertEqual(d.bytes, "Three things tomorrow: café".utf8.count) |
| + m.apply(.delta(AskDelta(turnID: "t2", offset: Int64(d.bytes), text: "!"))) |
| + m.apply(.message(AskMessage(id: "m4", role: "assistant", text: "Three things tomorrow: café!", turnID: "t2"))) |
| + XCTAssertEqual(ids(m).suffix(2), ["m:m3", "m:m4"], "the reply takes the draft's place") |
| + m.apply(.turn(AskTurn(id: "t2", kind: "chat", state: "replied"))) |
| + XCTAssertNil(m.turn) |
| + XCTAssertEqual(m.status, "") |
| + // An old revision of the turn, after it ended, changes nothing. |
| + m.apply(.turn(AskTurn(id: "t2", kind: "chat", state: "running"))) |
| + XCTAssertNil(m.turn) |
| + } |
| + |
| + func testAJobRedrawsInPlaceAndItsAnsweredCardMovesIntoItsView() { |
| + let (m, _) = model() |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + m.apply(.card(AskCard(id: "j2", revision: 6, kind: "job", state: "working", question: "Christmas order form", result: "Making the form"))) |
| + m.apply(.card(AskCard(id: "c1", revision: 2, kind: "question", state: "answered", question: "When should Christmas orders close?", result: "Fri 18 Dec", job: "j2"))) |
| + XCTAssertEqual(ids(m), ["m:m1", "m:m2", "j:j1", "j:j2", "j:j3"]) |
| + guard case .job(let j2) = m.entries[3] else { return XCTFail() } |
| + XCTAssertEqual(j2.state, .working) |
| + XCTAssertEqual(j2.open, []) |
| + XCTAssertEqual(j2.ended.map(\.id), ["c0", "c1"]) |
| + XCTAssertEqual(m.waitingJobs, 0) |
| + // An older revision of the job is ignored. |
| + m.apply(.card(AskCard(id: "j2", revision: 4, kind: "job", state: "stopped"))) |
| + guard case .job(let again) = m.entries[3] else { return XCTFail() } |
| + XCTAssertEqual(again.state, .working) |
| + } |
| + |
| + func testCardsBeforeTheirJobMoveUnderItWhenItComes() { |
| + let (m, _) = model() |
| + m.apply(.card(AskCard(id: "g1", revision: 1, kind: "confirm", state: "open", question: "Publish it?", options: [.init(value: "yes", label: "Publish")], job: "j9"))) |
| + m.apply(.card(AskCard(id: "g0", revision: 1, kind: "confirm", state: "answered", question: "Use the logo?", result: "Yes", job: "j9"))) |
| + XCTAssertEqual(ids(m), ["c:g1", "c:g0"]) |
| + m.apply(.card(AskCard(id: "j9", revision: 1, kind: "job", state: "asking", question: "Bakery website", result: "Ready to publish"))) |
| + XCTAssertEqual(ids(m), ["j:j9"]) |
| + guard case .job(let j) = m.entries[0] else { return XCTFail() } |
| + XCTAssertEqual(j.open.map(\.id), ["g1"]) |
| + XCTAssertEqual(j.ended.map(\.id), ["g0"]) |
| + } |
| + |
| + func testAnEndedCardWithNothingToSayGoes() { |
| + let (m, _) = model() |
| + m.apply(.card(AskCard(id: "q1", revision: 1, kind: "question", state: "open", question: "Which?"))) |
| + m.apply(.card(AskCard(id: "q1", revision: 2, kind: "question", state: "cancelled"))) |
| + XCTAssertTrue(m.entries.isEmpty) |
| + m.apply(.card(AskCard(id: "x1", revision: 1, kind: "poll", state: "open"))) |
| + XCTAssertTrue(m.entries.isEmpty, "a kind Base doesn't draw is not drawn") |
| + } |
| + |
| + func testAConnectOfferWaitsForItsReply() { |
| + let (m, _) = model() |
| + m.apply(.turn(AskTurn(id: "t5", kind: "chat", state: "running"))) |
| + let offer = AskCard(id: "k1", revision: 1, kind: "connect", state: "open", question: "Connect?", |
| + links: [.init(label: "Connect", url: URL(string: "https://fennel.base.example/ask/oficina/connect"), rel: "oficina_connect")], turnID: "t5") |
| + m.apply(.card(offer)) |
| + XCTAssertEqual(ids(m), ["t:t5"], "it waits while the reply is on its way") |
| + m.apply(.message(AskMessage(id: "r5", role: "assistant", text: "Connect Oficina to see your calendar.", turnID: "t5"))) |
| + XCTAssertEqual(ids(m), ["m:r5", "o:k1"]) |
| + var done = offer; done.state = "resolved"; done.revision = 2 |
| + m.apply(.card(done)) |
| + guard case .offer(let o) = m.entries[1] else { return XCTFail() } |
| + XCTAssertTrue(o.connected) |
| + } |
| + |
| + func testWaitingAndFailedTurnsSaySoInTheStatusLine() { |
| + let (m, _) = model() |
| + m.apply(.turn(AskTurn(id: "t6", kind: "chat", state: "running"))) |
| + m.apply(.turn(AskTurn(id: "t6", kind: "chat", state: "waiting"))) |
| + XCTAssertEqual(m.status, BaseText.text("ask.waiting")) |
| + XCTAssertFalse(ids(m).contains("t:t6")) |
| + m.apply(.delta(AskDelta(turnID: "t6", offset: 0, text: "Partly"))) |
| + m.apply(.turn(AskTurn(id: "t6", kind: "chat", state: "failed"))) |
| + XCTAssertEqual(m.status, BaseText.text("ask.failed")) |
| + XCTAssertTrue(m.entries.isEmpty, "a failed turn's draft goes") |
| + } |
| + |
| + func testAQuietTurnShowsNothing() { |
| + let (m, _) = model() |
| + m.apply(.turn(AskTurn(id: "q", kind: "team_update", state: "running"))) |
| + m.apply(.activity(AskLine(turnID: "q", text: "Reading"))) |
| + XCTAssertNil(m.turn) |
| + XCTAssertTrue(m.entries.isEmpty) |
| + XCTAssertEqual(m.status, "") |
| + } |
| + |
| + func testARepliedTurnsBubbleWaitsForItsReply() { |
| + let (m, _) = model() |
| + m.apply(.turn(AskTurn(id: "t7", kind: "chat", state: "running"))) |
| + m.apply(.turn(AskTurn(id: "t7", kind: "chat", state: "replied"))) |
| + XCTAssertEqual(ids(m), ["t:t7"], "the reply may come just after") |
| + XCTAssertEqual(later.count, 1) |
| + later.removeAll() |
| + m.apply(.message(AskMessage(id: "r7", role: "assistant", text: "Done.", turnID: "t7"))) |
| + XCTAssertEqual(ids(m), ["m:r7"]) |
| + } |
| + |
| + // MARK: Writes |
| + |
| + func testSendingUsesAFreshKeyAndAResendReusesIt() async { |
| + let sent = #"{"message":{"id":"m9","role":"person","text":"Hello","turn_id":"t9"},"turn":{"id":"t9","kind":"chat","state":"queued"}}"# |
| + let (m, t) = model([.offline(), .commitThenLoseResponse(), json(200, sent), json(200, sent.replacingOccurrences(of: "9", with: "8"))]) |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + m.text = " Hello " |
| + await m.send() |
| + XCTAssertEqual(m.text, " Hello ", "the text stays to send again") |
| + XCTAssertEqual(m.status, BaseText.text("native.ask.send.error")) |
| + await m.send() |
| + await m.send() |
| + XCTAssertEqual(m.text, "") |
| + XCTAssertEqual(m.status, "") |
| + let keys = t.calls.map { fields($0)["key"]! } |
| + XCTAssertEqual(Set(keys).count, 1, "one message, one key, however often it's resent") |
| + XCTAssertEqual(fields(t.calls[0])["text"], "Hello") |
| + XCTAssertEqual(ids(m).suffix(2), ["m:m9", "t:t9"]) |
| + XCTAssertEqual(m.turn?.id, "t9") |
| + // Stop's turn ends; a new message gets a new key. |
| + m.apply(.turn(AskTurn(id: "t9", kind: "chat", state: "cancelled"))) |
| + m.text = "Again" |
| + await m.send() |
| + XCTAssertNotEqual(fields(t.calls[3])["key"], keys[0]) |
| + } |
| + |
| + func testNoRunnerKeepsTheTextAndShowsTheNote() async { |
| + let (m, _) = model([json(409, #"{"state":"norunner"}"#)]) |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + m.text = "Hello" |
| + await m.send() |
| + XCTAssertEqual(m.phase, .norunner) |
| + XCTAssertTrue(m.phase.chatting) |
| + XCTAssertEqual(m.text, "Hello") |
| + } |
| + |
| + func testEquipoRefusingTheKeyShowsReconnect() async { |
| + let (m, _) = model([json(409, #"{"state":"reconnect"}"#)]) |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + m.text = "Hello" |
| + await m.send() |
| + XCTAssertEqual(m.phase, .reconnect) |
| + } |
| + |
| + func testAnsweringPostsTheRevisionAndAStaleCardRedraws() async throws { |
| + let answered = #"{"card":{"id":"c1","revision":2,"kind":"question","state":"answered","question":"When should Christmas orders close?","result":"Fri 18 Dec","job":"j2"},"message":{"id":"m5","role":"person","text":"Fri 18 Dec","turn_id":"t5"},"turn":{"id":"t5","kind":"chat","state":"queued"}}"# |
| + let (m, t) = model([json(409, #"{"state":"ready"}"#), .respond(status: 200, body: Fixture.data("state-ready.json")), .hang, |
| + json(200, answered)]) |
| + m.apply(Fixture.snapshot("state-ready.json")) |
| + guard case .job(let j2) = m.entries[3], let card = j2.open.first else { return XCTFail() } |
| + await m.answer(card, card.options[0]) |
| + XCTAssertEqual(t.calls[0].path, "/ask/cards/c1/answer") |
| + XCTAssertEqual(fields(t.calls[0])["revision"], "1") |
| + XCTAssertEqual(fields(t.calls[0])["choice"], "fri") |
| + XCTAssertEqual(t.calls[1].path, "/ask/state", "a stale card reads the conversation afresh, never resends") |
| + try await waitUntil { t.calls.count == 3 } |
| + m.pause() |
| + await m.answer(card, card.options[0]) |
| + XCTAssertNotEqual(fields(t.calls[3])["key"], fields(t.calls[0])["key"]) |
| + guard case .job(let after) = m.entries[3] else { return XCTFail() } |
| + XCTAssertEqual(after.ended.last?.result, "Fri 18 Dec") |
| + XCTAssertEqual(m.turn?.id, "t5") |
| + XCTAssertTrue(m.answering.isEmpty) |
| + } |
| + |
| + func testStopCancelsTheTurn() async { |
| + let (m, t) = model([json(200, #"{"state":"ready"}"#)]) |
| + m.apply(.turn(AskTurn(id: "t8", kind: "chat", state: "running"))) |
| + await m.stop() |
| + XCTAssertEqual(t.calls.first?.path, "/ask/turns/t8/cancel") |
| + XCTAssertNotNil(fields(t.calls[0])["key"]) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/CatalogTests.swift b/native/apple/Tests/BaseKitTests/CatalogTests.swift| index 75ff0ed..ec22bac 100644 |
| --- a/native/apple/Tests/BaseKitTests/CatalogTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/CatalogTests.swift |
| @@ -5,6 +5,14 @@ final class CatalogTests: XCTestCase { |
| /// The catalog is in the bundle and answers by copy review's ids. |
| func testCatalogAnswersByID() { |
| XCTAssertEqual(BaseText.text("native.signin.title"), "Sign in to Base") |
| - XCTAssertEqual(BaseText.format("native.signin.code.lede", ["email": "ana@fennel.ie"]), "We sent a code to ana@fennel.ie") |
| + XCTAssertEqual(BaseText.format("native.signin.code.lede", ["email": "ana@fennel.ie"]), "We sent a code to ana@fennel.ie.") |
| + } |
| +} |
| + |
| +final class PluralTests: XCTestCase { |
| + /// Copy review's plural: one = "1 job needs you", other = "{count} jobs need you". |
| + func testTheBadgesPlural() { |
| + XCTAssertEqual(BaseText.plural("native.sidebar.ask.badge_a11y", 1), "1 job needs you") |
| + XCTAssertEqual(BaseText.plural("native.sidebar.ask.badge_a11y", 3), "3 jobs need you") |
| } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/ClientTests.swift b/native/apple/Tests/BaseKitTests/ClientTests.swift| new file mode 100644 |
| index 0000000..3497c57 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/ClientTests.swift |
| @@ -0,0 +1,114 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| + |
| +final class ClientTests: XCTestCase { |
| + func client(_ transport: NativeTransport, _ rejections: Rejections = Rejections()) -> BaseClient { |
| + BaseClient(transport: transport) { rejections.hit() } |
| + } |
| + |
| + /// What really goes on the wire through the kit's NativeHTTP: the |
| + /// session's cookie, Origin (Base's CSRF check), Accept JSON, and Ask's |
| + /// writes as the web's forms. |
| + func testRequestsCarryTheCookieOriginAndAForm() async throws { |
| + let server = try LocalServer { _ in (200, #"{"message":{"id":"m9","role":"person","text":"Hi & bye","turn_id":"t9"},"turn":{"id":"t9","kind":"chat","state":"queued"}}"#) } |
| + let http = NativeHTTP(origin: server.origin, credential: NativeSession(name: "__Host-rastrillo_session", value: "s3cret")) |
| + let sent = try await client(http).send("Hi & bye", key: "k1") |
| + XCTAssertEqual(sent.message?.text, "Hi & bye") |
| + let request = try XCTUnwrap(server.received.first) |
| + let lines = request.lowercased() |
| + XCTAssertTrue(request.hasPrefix("POST /ask/messages HTTP/1.1")) |
| + XCTAssertTrue(lines.contains("cookie: __host-rastrillo_session=s3cret"), request) |
| + XCTAssertTrue(lines.contains("origin: \(server.origin.absoluteString.lowercased())"), request) |
| + XCTAssertTrue(lines.contains("accept: application/json"), request) |
| + XCTAssertTrue(lines.contains("content-type: application/x-www-form-urlencoded"), request) |
| + XCTAssertTrue(request.hasSuffix("text=Hi%20%26%20bye&key=k1"), request) |
| + } |
| + |
| + func testBaseRefusingTheSessionTellsTheKit() async { |
| + let rejections = Rejections() |
| + let c = client(ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#), .respond(status: 303)]), rejections) |
| + await XCTAssertThrows(.unauthenticated) { _ = try await c.me() } |
| + await XCTAssertThrows(.unauthenticated) { _ = try await c.askState() } |
| + XCTAssertEqual(rejections.count, 2) |
| + } |
| + |
| + /// `409 {"state":"reconnect"}` is Equipo refusing Ask's key: Ask's to |
| + /// show, never a reason to sign in again. |
| + func testEquipoRefusingTheKeyIsAsksNotTheSessions() async { |
| + let rejections = Rejections() |
| + let c = client(ScriptedTransport([json(409, #"{"state":"reconnect"}"#)]), rejections) |
| + await XCTAssertThrows(.server(status: 409, code: nil, state: "reconnect")) { _ = try await c.send("hi", key: "k") } |
| + XCTAssertEqual(rejections.count, 0) |
| + } |
| + |
| + func testJSONErrorsAreTyped() async { |
| + let c = client(ScriptedTransport([json(409, #"{"state":"norunner"}"#), json(409, #"{"code":"card_stale","state":"ready"}"#), |
| + json(502, #"{"state":"unavailable"}"#), .respond(status: 400, body: Data("bad request".utf8)), |
| + .offline(), json(200, "not json")])) |
| + await XCTAssertThrows(.server(status: 409, code: nil, state: "norunner")) { _ = try await c.send("a", key: "k") } |
| + await XCTAssertThrows(.server(status: 409, code: "card_stale", state: "ready")) { _ = try await c.answer(card: "c1", choice: "x", revision: 1, key: "k") } |
| + await XCTAssertThrows(.server(status: 502, code: nil, state: "unavailable")) { try await c.cancel(turn: "t1", key: "k") } |
| + await XCTAssertThrows(.server(status: 400, code: nil, state: nil)) { _ = try await c.send("a", key: "k") } |
| + await XCTAssertThrows(.offline) { _ = try await c.home() } |
| + await XCTAssertThrows(.badResponse) { _ = try await c.me() } |
| + } |
| + |
| + func testAnswerAndCancelPostTheirForms() async throws { |
| + let t = ScriptedTransport([json(200, #"{"card":{"id":"c/1","revision":2,"kind":"question","state":"answered","result":"Fri"},"message":null,"turn":null}"#), |
| + json(200, #"{"state":"ready"}"#), |
| + json(200, #"{"state":"ready","renew_after":"2026-11-28T10:00:00Z"}"#)]) |
| + let c = client(t) |
| + let out = try await c.answer(card: "c/1", choice: "fri day", revision: 2, key: "k2") |
| + XCTAssertEqual(out.card?.result, "Fri") |
| + XCTAssertNil(out.message) |
| + try await c.cancel(turn: "t1", key: "k3") |
| + let setup = try await c.connectAsk(assertion: "a", verifier: "v") |
| + XCTAssertEqual(setup.state, .ready) |
| + XCTAssertNotNil(setup.renewAfter) |
| + XCTAssertEqual(t.calls[0].path, "/ask/cards/c%2F1/answer") |
| + XCTAssertEqual(fields(t.calls[0]), ["revision": "2", "choice": "fri day", "key": "k2"]) |
| + XCTAssertEqual(t.calls[1].path, "/ask/turns/t1/cancel") |
| + XCTAssertEqual(fields(t.calls[1]), ["key": "k3"]) |
| + XCTAssertEqual(t.calls[2].path, "/api/v1/ask/oficina") |
| + let body = try JSONSerialization.jsonObject(with: t.calls[2].body!) as? [String: String] |
| + XCTAssertEqual(body, ["assertion": "a", "verifier": "v"]) |
| + } |
| + |
| + func testReadsDecodeTolerantly() async throws { |
| + let c = client(ScriptedTransport([.respond(status: 200, body: Fixture.data("me.json")), .respond(status: 200, body: Fixture.data("home.json"))])) |
| + let me = try await c.me() |
| + XCTAssertEqual(me.member.initials, "PC") |
| + XCTAssertEqual(me.base.name, "Fennel & Rye") |
| + XCTAssertEqual(me.appearance, .dark) |
| + XCTAssertNil(me.equipoOrigin) |
| + XCTAssertEqual(me.base.timeZone?.identifier, "Europe/Dublin") |
| + let home = try await c.home() |
| + XCTAssertEqual(home.steps.map(\.done), [true, true, false]) |
| + XCTAssertEqual(home.apps.map(\.id), ["calendar", "calls", "welcome", "store", "future"]) |
| + XCTAssertEqual(home.apps[1].scheme, "oficina-calls") |
| + XCTAssertEqual(home.apps[0].iconURL, "/static/oficina/calendar.3f2a.svg") |
| + XCTAssertEqual(home.apps[4].kind, .other) |
| + } |
| + |
| + func testKeysAreFreshAndHex() { |
| + let a = BaseClient.newKey(), b = BaseClient.newKey() |
| + XCTAssertNotEqual(a, b) |
| + XCTAssertEqual(a.count, 32) |
| + XCTAssertTrue(a.allSatisfy(\.isHexDigit)) |
| + } |
| +} |
| + |
| +func XCTAssertThrows(_ expected: BaseAPIError, file: StaticString = #filePath, line: UInt = #line, |
| + _ body: () async throws -> Void) async { |
| + do { |
| + try await body() |
| + XCTFail("no error; expected \(expected)", file: file, line: line) |
| + } catch let error as BaseAPIError { |
| + XCTAssertEqual(error, expected, file: file, line: line) |
| + } catch { |
| + XCTFail("\(error); expected \(expected)", file: file, line: line) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/EventsTests.swift b/native/apple/Tests/BaseKitTests/EventsTests.swift| new file mode 100644 |
| index 0000000..d6f005d |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/EventsTests.swift |
| @@ -0,0 +1,108 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| + |
| +final class EventsTests: XCTestCase { |
| + func feed(_ lines: [String]) -> [SSEEvent] { |
| + var parser = SSEParser() |
| + return lines.compactMap { parser.feed($0) } |
| + } |
| + |
| + func testTheParserReadsAsTheStandardDoes() { |
| + let events = feed([ |
| + "retry: 2500", "", // no data: not dispatched, but the retry carries |
| + ": ping", "", |
| + "id: 7", "event: delta", "data: {\"a\":", "data:1}", "", |
| + "data: plain", "", |
| + "event: glance", "data:{\"x\":1}", "", |
| + "id", "data: empty id", "", |
| + "bogus: field", "retry: soon", "data: x", "", |
| + ]) |
| + XCTAssertEqual(events, [ |
| + SSEEvent(id: "7", type: "delta", data: "{\"a\":\n1}", retry: 2500), |
| + SSEEvent(id: nil, type: "message", data: "plain", retry: nil), |
| + SSEEvent(id: nil, type: "glance", data: "{\"x\":1}", retry: nil), |
| + SSEEvent(id: "", type: "message", data: "empty id", retry: nil), |
| + SSEEvent(id: nil, type: "message", data: "x", retry: nil), |
| + ]) |
| + } |
| + |
| + /// Base's stream, as ask_relay.go frames it: every event decodes, a |
| + /// glance has no id, unknown events are skipped, pings say nothing. |
| + func testTheStreamDecodesBasesEvents() async throws { |
| + let transport = ScriptedTransport([.respond(status: 200, body: Fixture.data("events.sse"))]) |
| + let client = BaseClient(transport: transport) {} |
| + let got = Collected() |
| + try await client.events(after: 42, onRetry: { await got.retry($0) }) { event, id in await got.add(event, id) } |
| + XCTAssertEqual(transport.calls.first?.path, "/ask/events?after=42") |
| + let events = await got.events |
| + XCTAssertEqual(events.map(\.1), [43, nil, 44, 45, 46, 47, 48, 49, 50]) |
| + guard case .turn(let t) = events[0].0, case .glance(let g) = events[1].0, case .activity(let a) = events[2].0, |
| + case .delta(let d) = events[4].0, case .message(let m) = events[7].0 else { return XCTFail("\(events)") } |
| + XCTAssertEqual(t.state, "running") |
| + XCTAssertEqual(g.text, "Looking at tomorrow") |
| + XCTAssertEqual(a.text, "Reading your calendar") |
| + XCTAssertEqual(d.offset, 13) |
| + XCTAssertEqual(m.text, "Three things tomorrow:\n- 08:00 Flour delivery") |
| + let retries = await got.retries |
| + XCTAssertEqual(retries, [3000]) |
| + } |
| + |
| + func testAStreamThatCantStartSaysItsState() async throws { |
| + let body = "event: state\ndata: {\"state\":\"reconnect\"}\n\n" |
| + let client = BaseClient(transport: ScriptedTransport([.respond(status: 200, body: Data(body.utf8))])) {} |
| + let got = Collected() |
| + try await client.events(after: nil) { event, id in await got.add(event, id) } |
| + let events = await got.events |
| + XCTAssertEqual(events.map(\.0), [.state(.reconnect)]) |
| + } |
| + |
| + /// The model reconnects from the newest id when Base ends a stream, and |
| + /// reads the state afresh when Base refuses one (any non-200: there is |
| + /// no 410; a 502, a 400 for a bad cursor). |
| + @MainActor func testReconnectsFromTheLastIDAndReloadsOnRefusal() async throws { |
| + let first = "retry: 0\n\nid: 43\nevent: turn\ndata: {\"type\":\"turn\",\"data\":{\"id\":\"t2\",\"kind\":\"chat\",\"state\":\"running\"}}\n\n" |
| + let state = Fixture.data("state-ready.json") |
| + let transport = ScriptedTransport([ |
| + .respond(status: 200, body: state), // load |
| + .respond(status: 200, body: Data(first.utf8)), // events after 42, ends cleanly |
| + .respond(status: 502, body: Data(#"{"state":"unavailable"}"#.utf8)), // events after 43, refused |
| + .respond(status: 200, body: state), // reload |
| + .hang, // events after 42 again |
| + ]) |
| + let model = AskModel(client: BaseClient(transport: transport) {}) |
| + await model.load() |
| + try await waitUntil { transport.calls.count >= 5 } |
| + XCTAssertEqual(transport.calls.map(\.path), ["/ask/state", "/ask/events?after=42", "/ask/events?after=43", "/ask/state", "/ask/events?after=42"]) |
| + model.pause() |
| + } |
| + |
| + @MainActor func testAStateEventStopsListening() async throws { |
| + let body = "event: state\ndata: {\"state\":\"reconnect\"}\n\n" |
| + let transport = ScriptedTransport([.respond(status: 200, body: Fixture.data("state-ready.json")), .respond(status: 200, body: Data(body.utf8))]) |
| + let model = AskModel(client: BaseClient(transport: transport) {}) |
| + await model.load() |
| + try await waitUntil { model.phase == .reconnect } |
| + try await Task.sleep(for: .milliseconds(700)) |
| + XCTAssertEqual(transport.calls.count, 2, "no reconnect after a state event") |
| + } |
| +} |
| + |
| +actor Collected { |
| + var events: [(AskEvent, Int64?)] = [] |
| + var retries: [Int] = [] |
| + func add(_ e: AskEvent, _ id: Int64?) { events.append((e, id)) } |
| + func retry(_ ms: Int) { retries.append(ms) } |
| +} |
| + |
| +struct TimedOut: Error {} |
| + |
| +@MainActor func waitUntil(_ timeout: Duration = .seconds(5), file: StaticString = #filePath, line: UInt = #line, _ condition: () -> Bool) async throws { |
| + let deadline = ContinuousClock.now + timeout |
| + while !condition() { |
| + if ContinuousClock.now > deadline { XCTFail("timed out", file: file, line: line); throw TimedOut() } |
| + try await Task.sleep(for: .milliseconds(20)) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/.keep b/native/apple/Tests/BaseKitTests/Fixtures/.keep| deleted file mode 100644 |
| index e69de29..0000000 |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/events.sse b/native/apple/Tests/BaseKitTests/Fixtures/events.sse| new file mode 100644 |
| index 0000000..5555226 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/events.sse |
| @@ -0,0 +1,43 @@ |
| +retry: 3000 |
| + |
| +: ping |
| + |
| +id: 43 |
| +event: turn |
| +data: {"type":"turn","data":{"id":"t2","kind":"chat","state":"running","reason":""}} |
| + |
| +event: glance |
| +data: {"type":"glance","data":{"turn_id":"t2","text":"Looking at tomorrow"}} |
| + |
| +id: 44 |
| +event: activity |
| +data: {"type":"activity","data":{"turn_id":"t2","label":"Reading your calendar"}} |
| + |
| +id: 45 |
| +event: delta |
| +data: {"type":"delta","data":{"turn_id":"t2","offset":0,"text":"Three things "}} |
| + |
| +id: 46 |
| +event: delta |
| +data: {"type":"delta","data":{"turn_id":"t2","offset":13,"text":"tomorrow:"}} |
| + |
| +id: 47 |
| +event: card |
| +data: {"type":"card","data":{"id":"j2","revision":6,"kind":"job","state":"working","question":"Christmas order form","options":[],"links":[],"result":"Making the form"}} |
| + |
| +id: 48 |
| +event: card |
| +data: {"type":"card","data":{"id":"c1","revision":2,"kind":"question","state":"answered","question":"When should Christmas orders close?","options":[],"links":[],"result":"Fri 18 Dec","job":"j2"}} |
| + |
| +id: 49 |
| +event: message |
| +data: {"type":"message","data":{"id":"m4","role":"assistant","text":"Three things tomorrow:\n- 08:00 Flour delivery","turn_id":"t2","created_at":"2026-11-23T09:10:00Z"}} |
| + |
| +id: 50 |
| +event: turn |
| +data: {"type":"turn","data":{"id":"t2","kind":"chat","state":"replied","reason":""}} |
| + |
| +id: 51 |
| +event: something_new |
| +data: {"type":"something_new","data":{}} |
| + |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/home.json b/native/apple/Tests/BaseKitTests/Fixtures/home.json| new file mode 100644 |
| index 0000000..eebdd77 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/home.json |
| @@ -0,0 +1,6 @@ |
| +{"greeting":"Good morning, Paul","lede":"Here's your team's Base.","steps":[{"label":"Signed in","done":true},{"label":"Invite your team","done":true},{"label":"Install your first app","done":false}], |
| + "apps":[{"id":"calendar","kind":"oficina","name":"Calendar","url":"https://fennel.calendar.oficina.works","icon_url":"/static/oficina/calendar.3f2a.svg","bundle_id":"works.oficina.calendar"}, |
| + {"id":"calls","kind":"oficina","name":"Calls","url":"https://fennel.calls.oficina.works","icon_url":"/static/oficina/calls.9b1c.svg","bundle_id":"works.oficina.calls","scheme":"oficina-calls"}, |
| + {"id":"welcome","kind":"installed","name":"Welcome","url":"https://fennel.base.example/apps/welcome","tint":"amber","icon_svg":"<svg viewBox=\"0 0 24 24\"><path d=\"M4 4h16\"/></svg>"}, |
| + {"id":"store","kind":"own","name":"Store","url":"https://fennel.base.example/store"}, |
| + {"id":"future","kind":"widget","name":"Something new","url":"https://fennel.base.example/new"}]} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/me.json b/native/apple/Tests/BaseKitTests/Fixtures/me.json| new file mode 100644 |
| index 0000000..6fd7831 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/me.json |
| @@ -0,0 +1,3 @@ |
| +{"member":{"id":"mb_1","name":"Paul Campbell","email":"paul@fennel.example","initials":"PC","owner":true}, |
| + "base":{"name":"Fennel & Rye","slug":"fennel","origin":"https://fennel.base.example","timezone":"Europe/Dublin"}, |
| + "appearance":"dark","equipo_origin":null,"later":true} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/state-connect.json b/native/apple/Tests/BaseKitTests/Fixtures/state-connect.json| new file mode 100644 |
| index 0000000..a1aa485 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/state-connect.json |
| @@ -0,0 +1 @@ |
| +{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"renew_after":"","equipo_origin":"https://equipo.fennel.example"} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/state-ready.json b/native/apple/Tests/BaseKitTests/Fixtures/state-ready.json| new file mode 100644 |
| index 0000000..7244283 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/state-ready.json |
| @@ -0,0 +1,17 @@ |
| +{"state":"ready", |
| + "messages":[ |
| + {"id":"m1","role":"person","text":"Make us a website for the bakery","turn_id":"t1","created_at":"2026-11-23T09:00:00.123456789Z"}, |
| + {"id":"m2","role":"assistant","text":"On it. You'll see a first look in a couple of minutes, with the menu from your Sheets.","turn_id":"t1","created_at":"2026-11-23T09:00:04Z"}], |
| + "jobs":[ |
| + {"id":"j1","revision":3,"kind":"job","state":"working","question":"Bakery website","options":[],"links":[{"label":"Open in Equipo","url":"https://equipo.fennel.example/tasks/tk1","rel":"equipo"}],"result":"Building a first look","detail":"Pulling the menu from your Sheets.","started_at":"2026-11-23T09:00:05Z","cards":[]}, |
| + {"id":"j2","revision":5,"kind":"job","state":"asking","question":"Christmas order form","options":[],"links":[],"result":"One question for you","started_at":"2026-11-22T16:20:00Z", |
| + "cards":[{"id":"c1","revision":1,"kind":"question","state":"open","question":"When should Christmas orders close?","options":[{"value":"fri","label":"Fri 18 Dec"},{"value":"tue","label":"Tue 22 Dec"},{"value":"other","label":"Something else"}],"links":[],"result":"","job":"j2"}, |
| + {"id":"c0","revision":2,"kind":"confirm","state":"answered","question":"Use the autumn menu's prices?","options":[],"links":[],"result":"You said yes","job":"j2"}]}, |
| + {"id":"j3","revision":2,"kind":"job","state":"ready","question":"Invoice reminders","options":[],"links":[{"label":"Try it","url":"https://fennel.example/apps/reminders"}],"result":"Ready to try","started_at":"2026-11-21T10:00:00Z","cards":[]}], |
| + "cards":[], |
| + "turn":null, |
| + "status":"", |
| + "cursor":42, |
| + "renew_after":"2026-11-28T10:00:00Z", |
| + "equipo_origin":"https://equipo.fennel.example", |
| + "a_field_from_a_newer_base":{"nested":[1,2,3]}} |
diff --git a/native/apple/Tests/BaseKitTests/Support.swift b/native/apple/Tests/BaseKitTests/Support.swift| new file mode 100644 |
| index 0000000..6167acc |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Support.swift |
| @@ -0,0 +1,85 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import Network |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| + |
| +enum Fixture { |
| + static func data(_ name: String) -> Data { |
| + let url = Bundle.module.url(forResource: "Fixtures/\(name)", withExtension: nil)! |
| + return try! Data(contentsOf: url) |
| + } |
| + static func snapshot(_ name: String) -> AskSnapshot { try! JSONDecoder().decode(AskSnapshot.self, from: data(name)) } |
| +} |
| + |
| +/// Counts the kit's `sessionRejected()` calls. |
| +final class Rejections: @unchecked Sendable { |
| + private let lock = NSLock() |
| + private var n = 0 |
| + var count: Int { lock.withLock { n } } |
| + func hit() { lock.withLock { n += 1 } } |
| +} |
| + |
| +func json(_ status: Int, _ body: String) -> ScriptedTransport.Step { .respond(status: status, body: Data(body.utf8)) } |
| + |
| +/// Form fields of a scripted call's body. |
| +func fields(_ call: ScriptedTransport.Call) -> [String: String] { |
| + guard let body = call.body, let text = String(data: body, encoding: .utf8) else { return [:] } |
| + var out: [String: String] = [:] |
| + for pair in text.split(separator: "&") { |
| + let parts = pair.split(separator: "=", maxSplits: 1).map(String.init) |
| + out[parts[0]] = (parts.count > 1 ? parts[1] : "").replacingOccurrences(of: "+", with: " ").removingPercentEncoding |
| + } |
| + return out |
| +} |
| + |
| +/// One HTTP/1.1 exchange on localhost: records the request NativeHTTP |
| +/// really sends, and answers it. |
| +final class LocalServer: @unchecked Sendable { |
| + let listener: NWListener |
| + private let lock = NSLock() |
| + private var requests: [String] = [] |
| + private let answer: @Sendable (String) -> (Int, String) |
| + var port: UInt16 { listener.port!.rawValue } |
| + var origin: URL { URL(string: "http://localhost:\(port)")! } |
| + var received: [String] { lock.withLock { requests } } |
| + |
| + init(answer: @escaping @Sendable (String) -> (Int, String)) throws { |
| + self.answer = answer |
| + listener = try NWListener(using: .tcp, on: .any) |
| + listener.newConnectionHandler = { [weak self] connection in self?.serve(connection) } |
| + let ready = DispatchSemaphore(value: 0) |
| + listener.stateUpdateHandler = { if case .ready = $0 { ready.signal() } } |
| + listener.start(queue: .global()) |
| + _ = ready.wait(timeout: .now() + 5) |
| + } |
| + |
| + private func serve(_ connection: NWConnection) { |
| + connection.start(queue: .global()) |
| + var buffer = Data() |
| + func read() { |
| + connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, done, _ in |
| + guard let self else { return } |
| + if let data { buffer.append(data) } |
| + let text = String(decoding: buffer, as: UTF8.self) |
| + if let head = text.range(of: "\r\n\r\n") { |
| + let length = text[..<head.lowerBound].split(separator: "\r\n") |
| + .first { $0.lowercased().hasPrefix("content-length:") } |
| + .flatMap { Int($0.split(separator: ":")[1].trimmingCharacters(in: .whitespaces)) } ?? 0 |
| + if buffer.count - text[..<head.upperBound].utf8.count >= length { |
| + self.lock.withLock { self.requests.append(text) } |
| + let (status, body) = self.answer(text) |
| + let reply = "HTTP/1.1 \(status) X\r\nContent-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\nConnection: close\r\n\r\n\(body)" |
| + connection.send(content: Data(reply.utf8), completion: .contentProcessed { _ in connection.cancel() }) |
| + return |
| + } |
| + } |
| + if done { connection.cancel() } else { read() } |
| + } |
| + } |
| + read() |
| + } |
| + |
| + deinit { listener.cancel() } |
| +} |
diff --git a/native/scripts/check-strings.py b/native/scripts/check-strings.py| index feb1ed8..07ef83d 100755 |
| --- a/native/scripts/check-strings.py |
| +++ b/native/scripts/check-strings.py |
| @@ -24,21 +24,29 @@ catalog = json.loads(catalog_path.read_text()) |
| if catalog.get("sourceLanguage") != "en": |
| failures.append("the catalog's source language is not en") |
| texts = {} |
| +plurals = {} |
| for key, entry in catalog["strings"].items(): |
| value = entry.get("localizations", {}).get("en", {}).get("stringUnit", {}).get("value") |
| - variations = entry.get("localizations", {}).get("en", {}).get("variations") |
| - if value is None and variations is None: |
| + plural = entry.get("localizations", {}).get("en", {}).get("variations", {}).get("plural") |
| + if plural: |
| + # Plurals select on %lld; copy review writes it {count}. |
| + forms = {k: v["stringUnit"]["value"].replace("%lld", "{count}") for k, v in plural.items()} |
| + if "other" not in forms: |
| + failures.append(f"{key}: a plural with no 'other' form") |
| + plurals[key] = forms |
| + value = forms.get("other") |
| + if value is None: |
| failures.append(f"{key}: no English text") |
| texts[key] = value |
| # Strings copy review approved for screens later tasks draw (Tasks 12 to |
| # 14). They stay in the catalog so the review's text is the app's text. |
| -WAITING = re.compile(r"^native\.(signin|sidebar|account|menubar|settings|phone|colophon|offline|ask|job)\b") |
| +WAITING = re.compile(r"^native\.(signin|sidebar|account|menubar|settings|phone|colophon|offline|ask|job)\b|^ask\.|^chat\.paste\.") # ask.* and chat.paste.*: Task 11 draws them |
| used = set() |
| for path in sources.rglob("*.swift"): |
| text = path.read_text() |
| - for match in re.finditer(r'BaseText\.(?:text|format)\(\s*"([^"]+)"', text): |
| + for match in re.finditer(r'BaseText\.(?:text|format|plural)\(\s*"([^"]+)"', text): |
| if match.group(1) != "…": used.add(match.group(1)) |
| for match in re.finditer(r'(?:baseKey|textKey):\s*"([^"]+)"', text): |
| used.add(match.group(1)) |
| @@ -61,6 +69,9 @@ if found: |
| failures.append(f"{item['id']}: in copy review but not in the catalog") |
| elif texts[item["id"]] != item["text"]: |
| failures.append(f"{item['id']}: the catalog says {texts[item['id']]!r}, copy review {item['text']!r}") |
| + plural = re.search(r"Plural in the String Catalog: one = '([^']*)', other = '([^']*)'", item.get("notes", "")) |
| + if plural and plurals.get(item["id"]) != {"one": plural.group(1), "other": plural.group(2)}: |
| + failures.append(f"{item['id']}: copy review asks for the plural {plural.groups()}, the catalog has {plurals.get(item['id'])}") |
| print(f"strings: the catalog matches copy review ({found})") |
| else: |
| print("strings: copy review's strings.json is not here (git-ignored); its comparison skipped") |
diff --git a/native/scripts/sync-strings.py b/native/scripts/sync-strings.py| new file mode 100755 |
| index 0000000..27daab5 |
| --- /dev/null |
| +++ b/native/scripts/sync-strings.py |
| @@ -0,0 +1,42 @@ |
| +#!/usr/bin/env python3 |
| +"""Copies copy review's strings into the catalog. |
| + |
| + native/scripts/sync-strings.py [path/to/copy-review/strings.json] |
| + |
| +Every id in copy review's file (git-ignored, in the main checkout's |
| +copy-review/; or $BASE_COPY_REVIEW) becomes, or replaces, the catalog entry |
| +of that key, with its text and its context as the comment. Keys the review |
| +doesn't list (the web's approved Ask copy, `ask.*`) are kept as they are. |
| +An id whose notes ask for a plural ("Plural in the String Catalog: one = |
| +'…', other = '…'") gets plural variations, `{count}` written `%lld`. |
| +check-strings.py then holds the two to each other. |
| +""" |
| +import json, os, pathlib, re, sys |
| + |
| +native = pathlib.Path(__file__).resolve().parent.parent |
| +repo = native.parent |
| +catalog_path = native / "apple/Sources/BaseKit/Resources/Localizable.xcstrings" |
| +given = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("BASE_COPY_REVIEW") |
| +candidates = [pathlib.Path(given)] if given else [repo / "copy-review/strings.json", repo.parent / "base/copy-review/strings.json"] |
| +source = next((p for p in candidates if p.is_file()), None) |
| +if not source: |
| + sys.exit("sync-strings: no copy-review/strings.json; pass its path") |
| + |
| +PLURAL = re.compile(r"Plural in the String Catalog: one = '([^']*)', other = '([^']*)'") |
| +catalog = json.loads(catalog_path.read_text()) |
| +for item in json.loads(source.read_text()): |
| + comment = item["context"] + (f" ({item['notes']})" if item.get("notes") else "") |
| + entry = {"comment": comment, "extractionState": "manual"} |
| + plural = PLURAL.search(item.get("notes", "")) |
| + if plural: |
| + one, other = (s.replace("{count}", "%lld") for s in plural.groups()) |
| + entry["localizations"] = {"en": {"variations": {"plural": { |
| + "one": {"stringUnit": {"state": "translated", "value": one}}, |
| + "other": {"stringUnit": {"state": "translated", "value": other}}, |
| + }}}} |
| + else: |
| + entry["localizations"] = {"en": {"stringUnit": {"state": "translated", "value": item["text"]}}} |
| + catalog["strings"][item["id"]] = entry |
| +catalog["strings"] = dict(sorted(catalog["strings"].items())) |
| +catalog_path.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n") |
| +print(f"sync-strings: {catalog_path.relative_to(repo)} now holds copy review's {source}") |