oficina / equipo Public

native: read the conversation engine, as the web Roster does

A device bearer is answered by the engine's routes, not the OpenAPI
conversation shapes. EquipoKit now reads the snapshot, tasks and
needs-you, follows the event stream from its cursor, answers cards
bound to the revision seen and posts to task threads. Reports carry the
stage track and the Checks, Review and Branch facts in the web's words.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev b0e64dad2877d01bbcaeb1fe516879966eb17ced parent a301063
35 files changed, +1,728 −1,244
  • native/apple/Sources/EquipoKit/API/Client.swift +57 −52
  • native/apple/Sources/EquipoKit/API/Errors.swift +11 −3
  • native/apple/Sources/EquipoKit/API/Models.swift +2 −125
  • native/apple/Sources/EquipoKit/API/Thin.swift +150 −0
  • native/apple/Sources/EquipoKit/API/Transport.swift +37 −1
  • native/apple/Sources/EquipoKit/Presentation/Roster.swift +171 −69
  • native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift +15 −6
  • native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings +391 −61
  • native/apple/Sources/EquipoKit/Session/EquipoSession.swift +154 −153
  • native/apple/Sources/EquipoKit/UI/Components.swift +23 −28
  • native/apple/Sources/EquipoKit/UI/LiveCards.swift +131 −86
  • native/apple/Sources/EquipoKit/UI/RosterViews.swift +120 −5
  • native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift +1 −1
  • native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift +2 −3
  • native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift +11 −7
  • native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift +67 −59
  • native/apple/Sources/EquipoKit/UI/Theme.swift +3 −2
  • native/apple/Sources/EquipoMac/LiveTranscript.swift +64 −74
  • native/apple/Tests/EquipoKitTests/ClientTests.swift +57 −37
  • native/apple/Tests/EquipoKitTests/Fixtures/conversation.json +0 −67
  • native/apple/Tests/EquipoKitTests/Fixtures/message.json +0 −12
  • native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json +0 −67
  • native/apple/Tests/EquipoKitTests/Fixtures/notifications.json +0 −24
  • native/apple/Tests/EquipoKitTests/Fixtures/projects.json +0 −28
  • native/apple/Tests/EquipoKitTests/Fixtures/question.json +0 −23
  • native/apple/Tests/EquipoKitTests/Fixtures/subscription.json +0 −8
  • native/apple/Tests/EquipoKitTests/Fixtures/tasks.json +0 −108
  • native/apple/Tests/EquipoKitTests/Fixtures/thread.json +0 −31
  • native/apple/Tests/EquipoKitTests/LiveTests.swift +9 −6
  • native/apple/Tests/EquipoKitTests/PairingTests.swift +15 −0
  • native/apple/Tests/EquipoKitTests/SessionTests.swift +166 −76
  • native/apple/Tests/EquipoKitTests/Support.swift +16 −1
  • native/scripts/check-fixtures.py +8 −7
  • native/scripts/check-strings.py +4 −1
  • native/scripts/strings.json +43 −13
diff --git a/native/apple/Sources/EquipoKit/API/Client.swift b/native/apple/Sources/EquipoKit/API/Client.swift
index e9d0de49..827cda86 100644
--- a/native/apple/Sources/EquipoKit/API/Client.swift
+++ b/native/apple/Sources/EquipoKit/API/Client.swift
@@ -25,60 +25,51 @@ public struct EquipoClient: Sendable {
}
public var origin: URL { transport.origin }
- // MARK: Reads
+ // MARK: Reads (the conversation engine, as a device bearer reads it)
public func me() async throws -> Me { try await get("/me") }
- public func conversation(cursor: String? = nil, limit: Int = 50) async throws -> ConversationPage {
- try await get("/conversation", page(cursor, limit))
- }
- public func tasks(cursor: String? = nil, limit: Int = 100) async throws -> Page<EquipoTask> { try await get("/tasks", page(cursor, limit)) }
- public func needsYou(cursor: String? = nil, limit: Int = 100) async throws -> Page<EquipoTask> { try await get("/needs-you", page(cursor, limit)) }
- public func task(_ id: String) async throws -> EquipoTask { try await get("/tasks/\(escape(id))") }
- public func thread(_ taskID: String, cursor: String? = nil, limit: Int = 50) async throws -> ConversationPage {
- try await get("/tasks/\(escape(taskID))/thread", page(cursor, limit))
- }
- public func question(_ id: String) async throws -> Question { try await get("/questions/\(escape(id))") }
- public func projects(cursor: String? = nil, limit: Int = 100) async throws -> Page<Project> { try await get("/projects", page(cursor, limit)) }
+ public func snapshot() async throws -> Snapshot { try await get("/snapshot") }
+ public func olderMessages(before: String, limit: Int = 50) async throws -> MessagePage {
+ try await get("/messages", [URLQueryItem(name: "before", value: before), URLQueryItem(name: "limit", value: String(min(max(limit, 1), 200)))])
+ }
+ public func tasks() async throws -> ThinList<ThinTask> { try await get("/tasks") }
+ public func needsYou() async throws -> ThinList<ThinTask> { try await get("/needs-you") }
+ public func task(_ id: String) async throws -> ThinTask { try await get("/tasks/\(escape(id))") }
+ public func projects() async throws -> ThinList<ThinProject> { try await get("/projects") }
public func devices() async throws -> Page<Device> { try await get("/auth/devices") }
- public func notifications(cursor: String?) async throws -> Page<EquipoNotification> {
- try await get("/notifications", cursor.map { [URLQueryItem(name: "cursor", value: $0)] } ?? [])
+
+ /// The conversation's events after `cursor`, as Server-Sent Event lines.
+ public func events(after cursor: Int64) async throws -> AsyncThrowingStream<String, Error> {
+ try await transport.lines(APIRequest("GET", "/events", query: [URLQueryItem(name: "after", value: String(cursor))], bearer: token))
}
// MARK: Writes. Each takes a PendingWrite so a retry is the same request.
- public static func message(_ body: String) throws -> PendingWrite { try .json(["body": body]) }
- public func sendMessage(_ write: PendingWrite) async throws -> Message { try await post("/conversation/messages", write) }
- public func sendThreadMessage(task taskID: String, _ write: PendingWrite) async throws -> Message {
- try await post("/tasks/\(escape(taskID))/thread/messages", write)
- }
-
- /// An answer to a clarification: one option, or the person's own words.
- public enum Answer: Sendable, Equatable {
- case option(String)
- case text(String)
+ /// A message; the engine takes its key in the body as well as the header.
+ public static func message(_ text: String) throws -> PendingWrite {
+ let key = UUID().uuidString.lowercased()
+ return PendingWrite(body: try EquipoJSON.encoder.encode(["text": text, "idempotency_key": key]), key: key)
}
- /// The answer, bound to the question revision the person saw.
- public static func answer(_ answer: Answer, to question: Question) throws -> PendingWrite {
- switch answer {
- case .option(let id): return try .json(["kind": "clarification", "option_id": id], ifMatch: question.revision)
- case .text(let text): return try .json(["kind": "clarification", "text": text], ifMatch: question.revision)
- }
- }
- public func answer(question id: String, _ write: PendingWrite) async throws -> Ack {
- guard write.ifMatch != nil else { throw EquipoAPIError.status(428) }
- return try await post("/questions/\(escape(id))/answer", write)
+ public func send(_ write: PendingWrite) async throws -> Sent { try await post("/messages", write) }
+ public func postThread(task taskID: String, _ write: PendingWrite) async throws -> ThreadEntry {
+ try await post("/tasks/\(escape(taskID))/thread", write)
}
- public func subscribe(device deviceID: String, _ write: PendingWrite) async throws -> NotificationSubscription {
- try await post("/notification-subscriptions", write)
+ /// An answer to a card, bound to the card revision the person saw.
+ public static func answer(_ choice: String, note: String? = nil, to card: ThinCard) throws -> PendingWrite {
+ var body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision)]
+ if let note, !note.isEmpty { body["note"] = .init(note) }
+ return PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision)
}
- public static func subscription(device: String) throws -> PendingWrite { try .json(["device_id": device]) }
- public func acknowledge(subscription id: String, _ write: PendingWrite) async throws -> Ack {
- try await post("/notification-subscriptions/\(escape(id))/ack", write)
+ public func answer(card id: String, _ write: PendingWrite) async throws -> Answered {
+ guard write.ifMatch != nil else { throw EquipoAPIError.status(428) }
+ return try await post("/cards/\(escape(id))/answer", write)
}
- public static func acknowledgement(_ notificationID: String, revision: Int64) throws -> PendingWrite {
- try .json(["notification_id": notificationID], ifMatch: revision)
+ /// Stops the coordinator's turn; only that turn.
+ public func cancelTurn(_ id: String) async throws {
+ let _: EmptyResponse = try await post("/turns/\(escape(id))/cancel", PendingWrite(body: Data("{}".utf8)))
}
+
public func revokeDevice(_ id: String, _ write: PendingWrite) async throws -> Ack {
try await send(APIRequest("DELETE", "/auth/devices/\(escape(id))", body: write.body, bearer: token,
idempotencyKey: write.key, ifMatch: write.ifMatch))
@@ -96,11 +87,6 @@ public struct EquipoClient: Sendable {
// MARK: Plumbing
- private func page(_ cursor: String?, _ limit: Int) -> [URLQueryItem] {
- var q = [URLQueryItem(name: "limit", value: String(min(max(limit, 1), 100)))]
- if let cursor, !cursor.isEmpty { q.append(URLQueryItem(name: "cursor", value: cursor)) }
- return q
- }
private func escape(_ id: String) -> String {
id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? id
}
@@ -111,14 +97,33 @@ public struct EquipoClient: Sendable {
try await send(APIRequest("POST", path, body: write.body, bearer: token, idempotencyKey: write.key, ifMatch: write.ifMatch))
}
func send<T: Decodable>(_ request: APIRequest) async throws -> T {
- let response = try await transport.send(request)
- guard (200..<300).contains(response.status) else {
- if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: response.data) {
- throw EquipoAPIError.server(status: response.status, body: body)
- }
- throw EquipoAPIError.status(response.status)
+ if T.self == EmptyResponse.self {
+ let response = try await transport.send(request)
+ guard (200..<300).contains(response.status) else { throw Self.error(response) }
+ return EmptyResponse() as! T
}
+ let response = try await transport.send(request)
+ guard (200..<300).contains(response.status) else { throw Self.error(response) }
do { return try EquipoJSON.decoder.decode(T.self, from: response.data) }
catch { throw EquipoAPIError.undecodable }
}
+
+ static func error(_ response: APIResponse) -> EquipoAPIError {
+ if let conflict = try? EquipoJSON.decoder.decode(CardConflict.self, from: response.data) {
+ return .card(status: response.status, code: conflict.code, card: conflict.card)
+ }
+ if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: response.data) {
+ return .server(status: response.status, body: body)
+ }
+ return .status(response.status)
+ }
+}
+
+public struct EmptyResponse: Decodable, Sendable { public init() {} }
+
+/// Lets one JSON body mix strings and numbers.
+public struct AnyEncodable: Encodable, Sendable {
+ private let encodeValue: @Sendable (Encoder) throws -> Void
+ public init<T: Encodable & Sendable>(_ value: T) { encodeValue = { try value.encode(to: $0) } }
+ public func encode(to encoder: Encoder) throws { try encodeValue(encoder) }
}
diff --git a/native/apple/Sources/EquipoKit/API/Errors.swift b/native/apple/Sources/EquipoKit/API/Errors.swift
index 9fce2efb..e28e150d 100644
--- a/native/apple/Sources/EquipoKit/API/Errors.swift
+++ b/native/apple/Sources/EquipoKit/API/Errors.swift
@@ -8,21 +8,29 @@ public enum EquipoAPIError: Error, Sendable, Equatable {
case server(status: Int, body: APIErrorBody)
/// The server answered with an error but no readable body.
case status(Int)
+ /// A card the person tried to answer changed or was already answered.
+ case card(status: Int, code: String, card: ThinCard)
case tooLarge
case undecodable
case badOrigin
case signedOut
- public var code: String? { if case .server(_, let body) = self { return body.code }; return nil }
+ public var code: String? {
+ switch self {
+ case .server(_, let body): return body.code
+ case .card(_, let code, _): return code
+ default: return nil
+ }
+ }
public var status: Int? {
switch self {
- case .server(let s, _), .status(let s): return s
+ case .server(let s, _), .status(let s), .card(let s, _, _): return s
default: return nil
}
}
/// The session is over: sign in again.
public var endsSession: Bool { status == 401 || self == .signedOut }
/// The resource changed: fetch it before deciding again.
- public var isStale: Bool { code == "revision_conflict" }
+ public var isStale: Bool { ["revision_conflict", "card_stale", "card_answered"].contains(code ?? "") }
public var currentRevision: Int64? { if case .server(_, let body) = self { return body.currentRevision }; return nil }
}
diff --git a/native/apple/Sources/EquipoKit/API/Models.swift b/native/apple/Sources/EquipoKit/API/Models.swift
index 459aff29..0fb3119a 100644
--- a/native/apple/Sources/EquipoKit/API/Models.swift
+++ b/native/apple/Sources/EquipoKit/API/Models.swift
@@ -1,6 +1,7 @@
import Foundation
-// The person API's responses, from docs/api/equipo-v1.openapi.json. Field
+// The person API's pairing, device and error shapes, from
+// docs/api/equipo-v1.openapi.json. The conversation is in Thin.swift. Field
// names follow the wire (snake_case is converted by `EquipoJSON.decoder`).
// Optional numbers mean unknown, never zero.
@@ -24,123 +25,16 @@ public struct Page<Item: Codable & Sendable>: Codable, Sendable {
public var revision: Int64
}
-public struct Project: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var name: String
- public var repository: String
- public var defaultBranch: String
- public var kind: String
- public var revision: Int64
-}
-public struct Usage: Codable, Sendable, Equatable {
- public var calls: Int64
- public var inputTokens: Int64
- public var outputTokens: Int64
-}
-public struct Step: Codable, Sendable, Equatable {
- public var key: String
- public var category: String
- public var action: String
- public var state: String
- public var model: String
- public var account: String
- public var actual: String
- public var reason: String
- public var usage: Usage?
- public var allowanceRemaining: Int64?
-}
-public struct EquipoTask: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var projectId: Int64
- public var requester: String
- public var description: String
- public var kind: String
- public var state: String
- public var revision: Int64
- public var planRevision: Int64
- public var replacementId: String
- public var canCancel: Bool
- public var canMerge: Bool
- public var needsYou: Bool
- public var steps: [Step]?
- public var usage: Usage?
-}
-public struct SourceRef: Codable, Sendable, Equatable {
- public var kind: String
- public var id: String
- public var hash: String
- public var revision: Int64
-}
-public struct Message: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var conversationId: String
- public var threadId: String
- public var authorKind: String
- public var authorId: String
- public var body: String
- public var sequence: Int64
- public var revision: Int64
- public var createdAt: Date
- public var sources: [SourceRef]?
- public var isOwn: Bool { authorKind == "person" }
-}
-public struct Card: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var kind: String
- public var resourceId: String
- public var taskId: String
- public var revision: Int64
- public var copyKey: String
- public var actions: [String]?
- public var waitingTaskId: String
-}
-public struct ConversationPage: Codable, Sendable {
- public var messages: [Message]?
- public var cards: [Card]?
- public var nextCursor: String
- public var revision: Int64
-}
-public struct QuestionOption: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var label: String
-}
-public struct QuestionField: Codable, Sendable, Equatable {
- public var key: String
- public var prompt: String
-}
-/// A clarification or a native permission question. Only clarifications are
-/// answered in slice 1; a native question opens the web app.
-public struct Question: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var kind: String
- public var taskId: String
- public var text: String
- public var state: String
- public var revision: Int64
- public var canAnswer: Bool
- public var canAllow: Bool
- public var options: [QuestionOption]?
- public var fields: [QuestionField]?
- public var allowText: Bool
- public var expiresAt: Date?
-
- /// Whether this person may answer it now. The server still decides.
- public func isAnswerable(now: Date = Date()) -> Bool {
- guard kind == "clarification", state == "open", canAnswer else { return false }
- if let expiresAt, expiresAt <= now { return false }
- return true
- }
-}
public struct Ack: Codable, Sendable, Equatable {
public var revision: Int64
@@ -174,24 +68,7 @@ public struct Device: Codable, Sendable, Identifiable, Equatable {
public var lastUsedAt: Date?
}
-public struct EquipoNotification: Codable, Sendable, Identifiable, Equatable {
- public var id: String
- public var kind: String
- public var resourceId: String
- public var deepLink: String
- public var resourceRevision: Int64
- public var createdAt: Date
- public var state: String
-}
-public struct NotificationSubscription: Codable, Sendable, Equatable {
- public var id: String
- public var deviceId: String
- public var cursor: String
- public var revision: Int64
- public var active: Bool
- public var expiresAt: Date
-}
/// The person API's error body.
public struct APIErrorBody: Codable, Sendable, Equatable {
diff --git a/native/apple/Sources/EquipoKit/API/Thin.swift b/native/apple/Sources/EquipoKit/API/Thin.swift
new file mode 100644
index 00000000..ea459388
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/API/Thin.swift
@@ -0,0 +1,150 @@
+import Foundation
+
+// The person API as a device bearer reads it: the conversation engine's
+// routes (internal/equipo/chat/http.go) and the shapes in internal/wire.
+// The web's Roster conversation is drawn from the same engine. Fixtures
+// under Tests/.../Fixtures/thin are this server's own answers, captured and
+// strictly checked by internal/thintest TestNativeFixtures.
+
+public struct ThinMe: Codable, Sendable, Equatable {
+ public var id: String
+ public var address: String
+ public var role: String
+ public var teamId: String
+ public var teamName: String
+ public var revision: Int64
+}
+
+public struct ThinMessage: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var revision: Int64
+ public var role: String
+ public var text: String
+ public var turnId: String
+ public var createdAt: Date
+ public var isOwn: Bool { role == "person" }
+}
+
+public struct ThinTurn: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var revision: Int64
+ public var kind: String
+ public var state: String
+ public var reason: String
+ public var createdAt: Date
+ public var updatedAt: Date
+ /// Queued or running: the coordinator is still on it.
+ public var isLive: Bool { !["replied", "failed", "cancelled"].contains(state) }
+}
+
+public struct ThinCard: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var revision: Int64
+ public var kind: String
+ public var state: String
+ public var turnId: String
+ public var projectId: String
+ public var name: String
+ public var question: String
+ public var options: [String]?
+ public var choice: String
+ public var taskId: String
+ public var createdAt: Date
+ public var updatedAt: Date
+ public var previewUrl: String?
+ /// The person can still act on it (wire.CardOpen and the setup states).
+ public var isOpen: Bool { ["open", "ask"].contains(state) }
+}
+
+public struct ThreadEntry: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var author: String
+ public var text: String
+ public var at: Date
+}
+
+public struct ThinStep: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var specialist: String
+ public var state: String
+ public var reason: String
+ public var summary: String
+ public var headline: String
+ public var verdict: String
+ public var reviewLabel: String
+ public var checks: String
+ public var gate: String
+ public var exitCode: Int?
+ public var startedAt: Date?
+ public var finishedAt: Date?
+}
+
+public struct ThinTask: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var revision: Int64
+ public var projectId: String
+ public var project: String
+ public var title: String
+ public var brief: String
+ public var stage: String
+ public var branch: String
+ public var url: String
+ public var candidateSha: String
+ public var checks: String
+ public var checksReason: String
+ public var verdict: String
+ public var reviewLabel: String
+ /// Why the task waits on the person ("merge", ...); empty when it does not.
+ public var needsYou: String
+ public var steps: [ThinStep]?
+ public var thread: [ThreadEntry]?
+ public var createdAt: Date
+ public var updatedAt: Date
+ public var kind: String?
+ public var waitsOnYou: Bool { !needsYou.isEmpty }
+}
+
+public struct ThinProject: Codable, Sendable, Identifiable, Equatable {
+ public var id: String
+ public var revision: Int64
+ public var repo: String
+ public var name: String
+ public var title: String
+ public var state: String
+ public var displayName: String { title.isEmpty ? name : title }
+}
+
+public struct Snapshot: Codable, Sendable {
+ public var me: ThinMe
+ public var messages: [ThinMessage]?
+ public var turns: [ThinTurn]?
+ public var projects: [ThinProject]?
+ public var cards: [ThinCard]?
+ public var tasks: [ThinTask]?
+ public var cursor: Int64
+}
+
+public struct ThinList<Item: Codable & Sendable>: Codable, Sendable { public var items: [Item]? }
+public struct MessagePage: Codable, Sendable { public var items: [ThinMessage]?; public var before: String }
+public struct Sent: Codable, Sendable { public var message: ThinMessage; public var turn: ThinTurn }
+public struct Answered: Codable, Sendable { public var card: ThinCard }
+public struct CardConflict: Codable, Sendable { public var code: String; public var card: ThinCard }
+
+/// One event from `GET /events`. `data` holds the resource it names.
+public struct ThinEvent: Codable, Sendable {
+ public var cursor: Int64?
+ public var type: String
+ public var resource: String
+ public var id: String
+ public var revision: Int64
+ public var turnId: String?
+}
+
+/// What the coordinator is doing now (an `activity` event's data).
+public struct ThinActivity: Codable, Sendable, Equatable {
+ public var turnId: String
+ public var kind: String
+ public var tool: String
+ public var repo: String
+ public var label: String
+}
diff --git a/native/apple/Sources/EquipoKit/API/Transport.swift b/native/apple/Sources/EquipoKit/API/Transport.swift
index c13db024..5a2ba9ac 100644
--- a/native/apple/Sources/EquipoKit/API/Transport.swift
+++ b/native/apple/Sources/EquipoKit/API/Transport.swift
@@ -53,6 +53,9 @@ public protocol EquipoTransport: Sendable {
/// Returns any status. Throws `EquipoAPIError.offline` when the request
/// never reached the server or its answer never came back.
func send(_ request: APIRequest) async throws -> APIResponse
+ /// The lines of a streamed response (Server-Sent Events). Throws the
+ /// API error when the stream is refused.
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error>
}
/// URLSession, ephemeral: no cookie store, no cache, no redirects. Each
@@ -62,7 +65,8 @@ public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTas
public let origin: URL
public static let maxBytes = 4 * 1024 * 1024
private let session: URLSession
- private let observe: @Sendable (NativeTransportOutcome) -> Void
+ let streamSession: URLSession
+ let observe: @Sendable (NativeTransportOutcome) -> Void
public init(origin: URL, observe: (@Sendable (NativeTransportOutcome) -> Void)? = nil) {
self.origin = origin
@@ -75,6 +79,10 @@ public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTas
self.observe = observe ?? { outcome in Task { @MainActor in NativeConnectivity.shared.record(outcome, origin: origin) } }
let delegate = RedirectRefuser()
self.session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
+ let streaming = config.copy() as! URLSessionConfiguration
+ streaming.timeoutIntervalForRequest = 60
+ streaming.timeoutIntervalForResource = 24 * 60 * 60
+ self.streamSession = URLSession(configuration: streaming, delegate: delegate, delegateQueue: nil)
super.init()
}
@@ -93,6 +101,34 @@ public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTas
}
}
+extension URLSessionTransport {
+ public func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
+ var r = try request.urlRequest(origin: origin)
+ r.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ r.timeoutInterval = 60
+ let (bytes, response): (URLSession.AsyncBytes, URLResponse)
+ do { (bytes, response) = try await streamSession.bytes(for: r) }
+ catch let error as URLError { observe(.offline(error.code)); throw EquipoAPIError.offline }
+ guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline }
+ observe(.responded(status: http.statusCode))
+ guard http.statusCode == 200 else {
+ var data = Data()
+ for try await byte in bytes { data.append(byte); if data.count > 64 * 1024 { break } }
+ if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: data) { throw EquipoAPIError.server(status: http.statusCode, body: body) }
+ throw EquipoAPIError.status(http.statusCode)
+ }
+ return AsyncThrowingStream { continuation in
+ let task = Task {
+ do {
+ for try await line in bytes.lines { continuation.yield(line) }
+ continuation.finish()
+ } catch { continuation.finish(throwing: EquipoAPIError.offline) }
+ }
+ continuation.onTermination = { _ in task.cancel() }
+ }
+ }
+}
+
/// A bearer must never follow a redirect to another place.
private final class RedirectRefuser: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
diff --git a/native/apple/Sources/EquipoKit/Presentation/Roster.swift b/native/apple/Sources/EquipoKit/Presentation/Roster.swift
index 4221e8a2..86dd836f 100644
--- a/native/apple/Sources/EquipoKit/Presentation/Roster.swift
+++ b/native/apple/Sources/EquipoKit/Presentation/Roster.swift
@@ -1,9 +1,10 @@
import Foundation
-// Roster (the web's conversation design, chat.html and chat_roster.go) fed
-// only by the person API. Fields the API does not carry yet (stage, Checks,
-// Review, Branch, a card's time, set aside, the live activity line, the
-// roll-up) are left out, not invented. See docs/native/r7/index.md.
+// Roster (the web's conversation design: chat.html, chat_roster.go) fed by
+// the conversation engine's own data. Rules match chat_roster.go:
+// rosterAuthor (who speaks), rosterTone (amber waits on you, red only for a
+// failure), rosterTrack (five stops) and Compact (a report beside its open
+// decision is one line).
public enum Specialist: String, CaseIterable, Sendable {
case coordinator, engineering, copy, research, checks, review, design
@@ -33,14 +34,12 @@ public enum Specialist: String, CaseIterable, Sendable {
}
}
-/// Amber means waiting on you; red only for a failure; green otherwise.
public enum StageTone: String, Sendable { case positive, warning, negative }
public struct RosterByline: Sendable, Equatable {
public var who: Specialist
public var verb: String
public var project: String?
- /// nil when the API has no time for it (cards).
public var time: Date?
public init(who: Specialist, verb: String, project: String?, time: Date?) {
self.who = who; self.verb = verb; self.project = project; self.time = time
@@ -51,100 +50,203 @@ public struct RosterByline: Sendable, Equatable {
public var spoken: String { [who.name, verb, project, timeText].compactMap { $0 }.joined(separator: " ") }
}
-/// What a task is doing, from its steps: the API's task state is an
-/// internal plan state, not Roster's stage.
-public struct TaskSummary: Sendable, Equatable {
- public var label: String
- public var tone: StageTone
- public var specialist: Specialist?
- public var needsYou: Bool
+// MARK: - Stages
- public init(_ task: EquipoTask) {
- let steps = task.steps ?? []
- needsYou = task.needsYou
- if task.state == "cancelled" || task.state == "cancel_requested" {
- label = String(localized: "task.cancelled", bundle: .module); tone = .positive; specialist = nil; return
+public enum Stage: String, CaseIterable, Sendable {
+ case noted, inProgress = "in_progress", inReview = "in_review", readyToMerge = "ready_to_merge", done
+ public init?(wire: String) {
+ switch wire {
+ case "merging": self = .readyToMerge
+ case "investigated": self = .noted
+ default: self.init(rawValue: wire)
}
- if let failed = steps.first(where: { $0.state == "failed" }) {
- specialist = Specialist(category: failed.category)
- label = String(localized: "task.step_failed \(Specialist(category: failed.category).name)", bundle: .module); tone = .negative; return
+ }
+ public var label: String {
+ switch self {
+ case .noted: return String(localized: "stage.noted", bundle: .module)
+ case .inProgress: return String(localized: "stage.in_progress", bundle: .module)
+ case .inReview: return String(localized: "stage.in_review", bundle: .module)
+ case .readyToMerge: return String(localized: "stage.ready_to_merge", bundle: .module)
+ case .done: return String(localized: "stage.done", bundle: .module)
}
- if task.needsYou {
- let waiting = steps.first { $0.state == "waiting" }
- specialist = waiting.map { Specialist(category: $0.category) }
- label = String(localized: "task.needs_you", bundle: .module); tone = .warning; return
+ }
+}
+public enum StopState: Sendable { case done, current, todo }
+public struct TrackStop: Identifiable, Sendable {
+ public var stage: Stage
+ public var state: StopState
+ public var tone: StageTone?
+ public var id: String { stage.rawValue }
+}
+
+public struct RosterFact: Identifiable, Sendable, Equatable {
+ public var label: String
+ public var value: String
+ public var detail: String?
+ public var code = false
+ public var id: String { label }
+}
+
+/// A task as Roster reports it.
+public struct TaskReport: Sendable, Equatable {
+ public var task: ThinTask
+ public var title: String { task.title }
+ public var stage: Stage? { Stage(wire: task.stage) }
+ public var cancelled: Bool { task.stage == "cancelled" }
+ public var needsYou: Bool { task.waitsOnYou }
+
+ public init(_ task: ThinTask) { self.task = task }
+
+ /// chat_roster.go rosterTone.
+ public var tone: StageTone {
+ if task.checks == "failed" || task.verdict == "changes_requested" { return .negative }
+ return task.waitsOnYou ? .warning : .positive
+ }
+ public var eyebrow: String {
+ if cancelled { return String(localized: "stage.cancelled", bundle: .module) }
+ return stage?.label ?? task.stage
+ }
+ /// chat_roster.go rosterTrack: five stops, merging sits on Ready to merge.
+ public var track: [TrackStop] {
+ let current = Stage.allCases.firstIndex(of: stage ?? .noted) ?? 0
+ return Stage.allCases.enumerated().map { i, s in
+ TrackStop(stage: s, state: i < current ? .done : i == current ? .current : .todo, tone: i == current ? tone : nil)
}
- if let active = steps.first(where: { $0.state == "running" }) {
- specialist = Specialist(category: active.category)
- label = String(localized: "task.step_running \(Specialist(category: active.category).name)", bundle: .module); tone = .positive; return
+ }
+ /// The specialist reporting now: the running or last finished step.
+ public var specialist: Specialist {
+ let steps = task.steps ?? []
+ let active = steps.last { $0.state == "running" || $0.state == "queued" } ?? steps.last { $0.state == "done" }
+ return active.map { Specialist(category: $0.specialist) } ?? .engineering
+ }
+ /// chat_roster.go RosterChecks, RosterReview and their details, in the web's words.
+ public var facts: [RosterFact] {
+ var out: [RosterFact] = []
+ let steps = task.steps ?? []
+ let active = steps.last { $0.state == "running" || $0.state == "queued" }
+ let checksRunning = active?.specialist == "checks"
+ if checksRunning || !task.checks.isEmpty {
+ let value = checksRunning ? "checks.running" : "checks." + task.checks
+ var detail: String?
+ switch task.checks {
+ case "cannot_run":
+ detail = EquipoStrings.text(.init(["needs_macos": "checks.needs_macos", "needs_network": "checks.needs_network",
+ "checks_timeout": "checks.timeout"][task.checksReason] ?? "checks.unavailable"))
+ case "passed", "failed":
+ if let ran = steps.last(where: { $0.specialist == "checks" && $0.state == "done" }), !ran.gate.isEmpty {
+ detail = ran.gate
+ if task.checks == "failed", let code = ran.exitCode {
+ detail = String(localized: "checks.exit \(ran.gate) \(String(code))", bundle: .module)
+ }
+ }
+ default: break
+ }
+ if Self.known.contains(value) {
+ out.append(RosterFact(label: String(localized: "fact.checks", bundle: .module), value: EquipoStrings.text(.init(value)), detail: checksRunning ? nil : detail))
+ }
}
- if let waiting = steps.first(where: { $0.state == "waiting" }) {
- specialist = Specialist(category: waiting.category)
- label = String(localized: "task.step_waiting \(Specialist(category: waiting.category).name)", bundle: .module); tone = .positive; return
+ let reviewRunning = active?.specialist == "review"
+ if reviewRunning || !task.verdict.isEmpty {
+ let value = reviewRunning ? "review.running" : "review." + task.verdict
+ let detail = ["other_family", "same_family", "same_account"].contains(task.reviewLabel) ? EquipoStrings.text(.init("review." + task.reviewLabel)) : nil
+ if Self.known.contains(value) {
+ out.append(RosterFact(label: String(localized: "fact.review", bundle: .module), value: EquipoStrings.text(.init(value)), detail: reviewRunning ? nil : detail))
+ }
}
- specialist = nil
- if !steps.isEmpty, steps.allSatisfy({ $0.state == "done" }) {
- label = String(localized: "task.done", bundle: .module)
- } else {
- label = String(localized: "task.not_started", bundle: .module)
+ if !task.branch.isEmpty {
+ out.append(RosterFact(label: String(localized: "fact.branch", bundle: .module), value: task.branch,
+ detail: task.candidateSha.isEmpty ? nil : String(task.candidateSha.prefix(7)), code: true))
}
- tone = .positive
+ return out
}
+ /// Values with words; anything else is left out, never invented.
+ static let known: Set<String> = ["checks.passed", "checks.failed", "checks.none", "checks.cannot_run", "checks.running",
+ "review.approve", "review.changes_requested", "review.running"]
+ public var amadanURL: URL? { URL(string: task.url).flatMap { $0.scheme == "https" ? $0 : nil } }
}
+// MARK: - The feed
+
/// One thing in the conversation.
public enum FeedItem: Identifiable, Sendable {
- case own(Message)
- case coordinator(Message)
+ case own(ThinMessage)
+ case coordinator(ThinMessage)
case outgoing(EquipoSession.Outgoing)
- /// A task the conversation reports on.
- case report(Card, RosterByline, EquipoTask)
- /// A question to answer here.
- case question(Card, RosterByline, Question?, taskTitle: String?)
- /// A decision slice 1 sends to the web: merges, approvals and the rest.
- case decision(Card, RosterByline, taskTitle: String?)
+ /// A task the conversation reports on; compact while its decision is open.
+ case report(ThinCard, RosterByline, TaskReport, compact: Bool)
+ /// A question the coordinator asks, answered here.
+ case question(ThinCard, RosterByline)
+ /// A decision: merges and the rest. Slice 1 shows it and opens the web.
+ case decision(ThinCard, RosterByline)
+ /// A one-line receipt: a project added, a home set.
+ case receipt(ThinCard, RosterByline)
+ /// The coordinator at work: what it is doing and for how long.
+ case thinking(ThinTurn, activity: String?)
public var id: String {
switch self {
case .own(let m), .coordinator(let m): return m.id
case .outgoing(let o): return "outgoing-" + o.id
- case .report(let c, _, _), .question(let c, _, _, _), .decision(let c, _, _): return c.id
+ case .report(let c, _, _, _), .question(let c, _), .decision(let c, _), .receipt(let c, _): return c.id
+ case .thinking(let t, _): return "thinking-" + t.id
}
}
}
public enum Feed {
- /// The conversation in order: messages by the server's sequence, then
- /// this device's unsent messages, then the cards. The API gives a card
- /// no time or position, so cards follow the messages in the API's order.
+ /// The conversation in time order, as Roster lays it out.
@MainActor public static func build(_ session: EquipoSession) -> [FeedItem] {
- var items: [FeedItem] = session.messages.map { $0.isOwn ? .own($0) : .coordinator($0) }
- items += session.outgoing.filter { $0.taskID == nil }.map { .outgoing($0) }
- for card in session.cards {
- let task = session.task(card.taskId)
- let project = task.flatMap { session.project(for: $0)?.name }
- switch card.kind {
- case "question":
- let question = session.questions[card.resourceId]
- let asker = task.flatMap { $0.steps?.first { $0.state == "waiting" } }.map { Specialist(category: $0.category) } ?? .coordinator
- let byline = RosterByline(who: asker, verb: String(localized: "byline.asks", bundle: .module), project: project, time: nil)
- items.append(.question(card, byline, question, taskTitle: task?.description))
- case "task":
- guard let task else { continue }
- let byline = RosterByline(who: TaskSummary(task).specialist ?? .engineering, verb: String(localized: "byline.reports", bundle: .module), project: project, time: nil)
- items.append(.report(card, byline, task))
- default:
- let byline = RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: nil)
- items.append(.decision(card, byline, taskTitle: task?.description))
+ let deciding = Set(session.cards.filter { $0.isOpen && $0.kind != "task" && !$0.taskId.isEmpty }.map(\.taskId))
+ var timed: [(Date, Int, FeedItem)] = []
+ for (i, m) in session.messages.enumerated() {
+ timed.append((m.createdAt, i, m.isOwn ? .own(m) : .coordinator(m)))
+ }
+ for (i, card) in session.cards.enumerated() {
+ let project = session.project(card.projectId)?.displayName
+ let at = card.createdAt
+ let n = session.messages.count + i
+ if card.kind == "task" {
+ guard let task = session.task(card.taskId) else { continue }
+ let report = TaskReport(task)
+ let byline = RosterByline(who: report.specialist, verb: String(localized: "byline.reports", bundle: .module), project: project, time: at)
+ timed.append((at, n, .report(card, byline, report, compact: deciding.contains(task.id))))
+ } else if isReceipt(card) {
+ timed.append((at, n, .receipt(card, RosterByline(who: .coordinator, verb: "", project: project, time: at))))
+ } else if card.kind == "question" {
+ timed.append((at, n, .question(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at))))
+ } else {
+ timed.append((at, n, .decision(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at))))
}
}
+ var items = timed.sorted { ($0.0, $0.1) < ($1.0, $1.1) }.map(\.2)
+ items += session.outgoing.filter { $0.taskID == nil }.map { .outgoing($0) }
+ if let turn = session.liveTurn {
+ items.append(.thinking(turn, activity: session.activity[turn.id]?.label))
+ }
return items
}
- /// Where a card lives on the web: the conversation, at the card.
- public static func webURL(for card: Card, origin: URL) -> URL {
+ /// The card on the web: the conversation, at the card.
+ public static func webURL(for card: ThinCard, origin: URL) -> URL {
var c = URLComponents(url: origin.appendingPathComponent("conversation"), resolvingAgainstBaseURL: false)!
c.fragment = "card-" + card.id
return c.url!
}
+
+ /// A receipt's line, in the web's words (chat.card.*).
+ public static func receiptLine(_ card: ThinCard) -> String {
+ switch (card.kind, card.state) {
+ case ("project", "added"): return String(localized: "receipt.added \(card.name)", bundle: .module)
+ case ("project", "created"): return String(localized: "receipt.created \(card.name)", bundle: .module)
+ case ("project", _): return String(localized: "receipt.working \(card.name)", bundle: .module)
+ case ("home", _) where card.name.isEmpty: return String(localized: "receipt.home_cleared", bundle: .module)
+ case ("home", _): return String(localized: "receipt.home \(card.name)", bundle: .module)
+ default: return card.question.isEmpty ? card.name : card.question
+ }
+ }
+
+ /// A receipt is a line, not a decision: a project added, a home set.
+ static func isReceipt(_ card: ThinCard) -> Bool {
+ card.kind == "project" || (card.kind == "home" && card.state != "ask")
+ }
}
diff --git a/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift b/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift
index 8c730e85..0b9967a9 100644
--- a/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift
+++ b/native/apple/Sources/EquipoKit/Presentation/ThreadTurn.swift
@@ -1,19 +1,28 @@
import Foundation
-/// One turn of a sub-chat: a task thread or a question's replies.
+/// One turn of a sub-chat: a task's thread ("Talk about this").
public struct ThreadTurn: Identifiable, Sendable, Equatable {
public var id: String
public var who: Specialist? // nil is you
+ /// Someone else on the team, by address; nil for you and for Equipo.
+ public var person: String?
public var text: String
public var time: Date?
public var pending = false
- public var own: Bool { who == nil }
+ public var own: Bool { who == nil && person == nil }
public var timeText: String { time.map { $0.formatted(date: .omitted, time: .shortened) } ?? "" }
- public init(id: String, who: Specialist?, text: String, time: Date?, pending: Bool = false) {
- self.id = id; self.who = who; self.text = text; self.time = time; self.pending = pending
+ public init(id: String, who: Specialist?, person: String? = nil, text: String, time: Date?, pending: Bool = false) {
+ self.id = id; self.who = who; self.person = person; self.text = text; self.time = time; self.pending = pending
}
- public init(_ m: Message) {
- self.init(id: m.id, who: m.isOwn ? nil : .coordinator, text: m.body, time: m.createdAt)
+ /// A thread entry: yours, Equipo's own update (author "equipo"), or a teammate's.
+ public init(_ entry: ThreadEntry, me: String?) {
+ if entry.author == "equipo" {
+ self.init(id: entry.id, who: .coordinator, text: entry.text, time: entry.at)
+ } else if let me, entry.author.caseInsensitiveCompare(me) == .orderedSame {
+ self.init(id: entry.id, who: nil, text: entry.text, time: entry.at)
+ } else {
+ self.init(id: entry.id, who: nil, person: entry.author, text: entry.text, time: entry.at)
+ }
}
}
diff --git a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
index 29dced27..e9ef67cd 100644
--- a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
@@ -233,6 +233,127 @@
}
}
},
+ "card.question": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Question"
+ }
+ }
+ }
+ },
+ "checks.cannot_run": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Can’t run here"
+ }
+ }
+ }
+ },
+ "checks.exit %@ %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%1$@, exit code %2$@"
+ }
+ }
+ }
+ },
+ "checks.failed": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Failed"
+ }
+ }
+ }
+ },
+ "checks.needs_macos": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Needs macOS"
+ }
+ }
+ }
+ },
+ "checks.needs_network": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Needs network access"
+ }
+ }
+ }
+ },
+ "checks.none": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "No checks found"
+ }
+ }
+ }
+ },
+ "checks.passed": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Passed"
+ }
+ }
+ }
+ },
+ "checks.running": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Running"
+ }
+ }
+ }
+ },
+ "checks.timeout": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The checks did not finish in time."
+ }
+ }
+ }
+ },
+ "checks.unavailable": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This runner cannot run the checks."
+ }
+ }
+ }
+ },
"chip.needs_you": {
"extractionState": "manual",
"localizations": {
@@ -299,6 +420,39 @@
}
}
},
+ "fact.branch": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Branch"
+ }
+ }
+ }
+ },
+ "fact.checks": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Checks"
+ }
+ }
+ }
+ },
+ "fact.review": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Review"
+ }
+ }
+ }
+ },
"message.coordinator_spoken %@ %@": {
"extractionState": "manual",
"localizations": {
@@ -673,46 +827,145 @@
}
}
},
- "question.answer_placeholder": {
+ "question.answered %@": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Answer"
+ "value": "You answered: %@"
}
}
}
},
- "question.answered %@": {
+ "question.closed": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "You answered: %@"
+ "value": "This question is no longer open."
}
}
}
},
- "question.closed": {
+ "receipt.added %@": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "This question is no longer open."
+ "value": "Added %@"
+ }
+ }
+ }
+ },
+ "receipt.created %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Created %@"
+ }
+ }
+ }
+ },
+ "receipt.home %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "New projects go to %@"
+ }
+ }
+ }
+ },
+ "receipt.home_cleared": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "New projects go to the best-fitting existing repository"
+ }
+ }
+ }
+ },
+ "receipt.working %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Working in %@"
+ }
+ }
+ }
+ },
+ "review.approve": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Approved"
+ }
+ }
+ }
+ },
+ "review.changes_requested": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Changes requested"
+ }
+ }
+ }
+ },
+ "review.other_family": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "another model family"
+ }
+ }
+ }
+ },
+ "review.running": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Reviewing"
}
}
}
},
- "question.loading": {
+ "review.same_account": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Loading the question…"
+ "value": "same family, same account"
+ }
+ }
+ }
+ },
+ "review.same_family": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "same family"
}
}
}
@@ -805,40 +1058,73 @@
}
}
},
- "tab.conversation": {
+ "stage.cancelled": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Conversation"
+ "value": "Cancelled"
}
}
}
},
- "tab.needs": {
+ "stage.done": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Needs you"
+ "value": "Done"
}
}
}
},
- "tab.tasks": {
+ "stage.in_progress": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Tasks"
+ "value": "In progress"
+ }
+ }
+ }
+ },
+ "stage.in_review": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "In review"
+ }
+ }
+ }
+ },
+ "stage.noted": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Noted"
+ }
+ }
+ }
+ },
+ "stage.ready_to_merge": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ready to merge"
}
}
}
},
- "task.cancelled": {
+ "step.cancelled": {
"extractionState": "manual",
"localizations": {
"en": {
@@ -849,7 +1135,7 @@
}
}
},
- "task.done": {
+ "step.done": {
"extractionState": "manual",
"localizations": {
"en": {
@@ -860,40 +1146,51 @@
}
}
},
- "task.hide_talk": {
+ "step.failed": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Hide the talk"
+ "value": "Stopped"
}
}
}
},
- "task.inspector": {
+ "step.queued": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Show or hide the task"
+ "value": "Queued"
}
}
}
},
- "task.missing": {
+ "step.running": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "This task is not available."
+ "value": "Running"
}
}
}
},
- "task.needs_you": {
+ "tab.conversation": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conversation"
+ }
+ }
+ }
+ },
+ "tab.needs": {
"extractionState": "manual",
"localizations": {
"en": {
@@ -904,145 +1201,156 @@
}
}
},
- "task.none_selected": {
+ "tab.tasks": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Choose a task to see it here."
+ "value": "Tasks"
}
}
}
},
- "task.not_started": {
+ "task.brief": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Not started"
+ "value": "What was asked"
}
}
}
},
- "task.open_hint": {
+ "task.hide_talk": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Opens the task"
+ "value": "Hide the talk"
}
}
}
},
- "task.open_web": {
+ "task.inspector": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Open on the web"
+ "value": "Show or hide the task"
}
}
}
},
- "task.reply": {
+ "task.missing": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Reply"
+ "value": "This task is not available."
}
}
}
},
- "task.step_failed %@": {
+ "task.none_selected": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "%@ stopped"
+ "value": "Choose a task to see it here."
}
}
}
},
- "task.step_running %@": {
+ "task.open": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "%@ is working"
+ "value": "Open the task"
}
}
}
},
- "task.step_waiting %@": {
+ "task.open_hint": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "%@ is waiting"
+ "value": "Opens the task"
}
}
}
},
- "task.steps": {
+ "task.open_web": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Steps"
+ "value": "Open on the web"
}
}
}
},
- "task.talk": {
+ "task.reply": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Talk about this"
+ "value": "Reply"
}
}
}
},
- "task.thread_empty": {
+ "task.steps": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Nothing has been said about this task yet."
+ "value": "Steps"
}
}
}
},
- "task.title": {
+ "task.talk": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Task"
+ "value": "Talk about this"
}
}
}
},
- "task.usage": {
+ "task.thread_empty": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nothing has been said about this task yet."
+ }
+ }
+ }
+ },
+ "task.title": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Used so far"
+ "value": "Task"
}
}
}
@@ -1102,68 +1410,90 @@
}
}
},
- "thread.own_spoken %@": {
+ "thinking.stop": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "You said: %@. Sent"
+ "value": "Stop"
}
}
}
},
- "thread.reading %@": {
+ "thinking.stopping": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "%@ is reading"
+ "value": "Stopping…"
}
}
}
},
- "thread.sent": {
+ "thinking.working": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Sent"
+ "value": "Working…"
}
}
}
},
- "usage.calls": {
+ "thread.own_spoken %@": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Calls"
+ "value": "You said: %@. Sent"
+ }
+ }
+ }
+ },
+ "thread.reading %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ is reading"
+ }
+ }
+ }
+ },
+ "thread.sent": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sent"
}
}
}
},
- "usage.tokens_in": {
+ "track.position %@ %@": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Tokens in"
+ "value": "%1$@ of %2$@"
}
}
}
},
- "usage.tokens_out": {
+ "track.spoken %@": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Tokens out"
+ "value": "Stage: %@"
}
}
}
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
index a554feb5..ba2b7713 100644
--- a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
+++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
@@ -2,14 +2,15 @@ import Foundation
import Observation
import RastrilloNative
-/// One signed-in team: what the screens show, kept current by refreshing and
-/// by the device's notification subscription. Reads reconcile by ID; writes
-/// keep their idempotency key until they have a result.
+/// One signed-in team: what the screens show, kept current by the
+/// conversation's event stream while the app is in front. Reads reconcile
+/// by ID and revision; writes keep their idempotency key until they have a
+/// result.
@MainActor @Observable
public final class EquipoSession {
public enum Status: Equatable, Sendable { case loading, ready, signedOut }
- /// A message this device is sending. It stays, with its key, until the
+ /// Something this device is sending. It stays, with its key, until the
/// server has it; offline it waits and is sent again as itself.
public struct Outgoing: Identifiable, Equatable, Sendable {
public enum State: Equatable, Sendable { case sending, waiting, failed }
@@ -22,33 +23,30 @@ public final class EquipoSession {
public private(set) var status: Status = .loading
public private(set) var account: DeviceAccount
- public private(set) var me: Me?
- public private(set) var projects: [String: Project] = [:]
- public private(set) var messages: [Message] = []
- public private(set) var cards: [Card] = []
- public private(set) var tasks: [EquipoTask] = []
+ public private(set) var me: ThinMe?
+ public private(set) var messages: [ThinMessage] = []
+ public private(set) var turns: [ThinTurn] = []
+ public private(set) var cards: [ThinCard] = []
+ public private(set) var tasks: [ThinTask] = []
/// nil until loaded: an unknown count is not zero.
- public private(set) var needsYou: [EquipoTask]?
- public private(set) var questions: [String: Question] = [:]
- public private(set) var threads: [String: [Message]] = [:]
+ public private(set) var needsYou: [ThinTask]?
+ public private(set) var projects: [String: ThinProject] = [:]
+ /// The latest activity of each live turn, from the event stream.
+ public private(set) var activity: [String: ThinActivity] = [:]
public private(set) var outgoing: [Outgoing] = []
- public private(set) var lastRefresh: Date?
public private(set) var refreshFailed = false
+ public private(set) var cursor: Int64 = 0
public let client: EquipoClient
private let accounts: DeviceAccounts
- private let defaults: UserDefaults
private let runner = CoalescedRunner()
- private var seenNotifications: Set<String> = []
- private var polling: Task<Void, Never>?
+ private var live: Task<Void, Never>?
private let sleep: @Sendable (Duration) async throws -> Void
public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil,
- defaults: UserDefaults = .standard,
sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) {
self.account = account
self.accounts = accounts
- self.defaults = defaults
self.sleep = sleep
self.client = EquipoClient(transport: transport ?? URLSessionTransport(origin: account.origin), token: account.credential?.token)
if !account.isUsable() { status = .signedOut }
@@ -56,6 +54,10 @@ public final class EquipoSession {
public var origin: URL { account.origin }
public var teamName: String { me?.teamName ?? account.teamName ?? origin.host ?? "" }
+ public func task(_ id: String) -> ThinTask? { tasks.first { $0.id == id } ?? needsYou?.first { $0.id == id } }
+ public func project(_ id: String) -> ThinProject? { projects[id] }
+ /// The coordinator's turn in flight, if any.
+ public var liveTurn: ThinTurn? { turns.filter(\.isLive).max { $0.createdAt < $1.createdAt } }
// MARK: Reading
@@ -68,59 +70,123 @@ public final class EquipoSession {
private func refreshPass() async {
let client = self.client
do {
- async let meRead = client.me()
- async let projectRead = client.projects()
- async let conversationRead = client.conversation()
+ async let snapshotRead = client.snapshot()
async let taskRead = client.tasks()
async let needsRead = client.needsYou()
- let (me, projectPage, page, taskPage, needsPage) = try await (meRead, projectRead, conversationRead, taskRead, needsRead)
- self.me = me
- projects = Dictionary(projectPage.items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
- messages = Self.merge(messages, (page.messages ?? []).filter { $0.threadId.isEmpty })
- cards = page.cards ?? []
- tasks = taskPage.items
- needsYou = needsPage.items
- for card in cards where card.kind == "question" {
- if let q = try? await client.question(card.resourceId) { questions[q.id] = q }
- }
+ let (snapshot, taskList, needsList) = try await (snapshotRead, taskRead, needsRead)
+ apply(snapshot)
+ tasks = taskList.items ?? []
+ needsYou = needsList.items ?? []
status = .ready
refreshFailed = false
- lastRefresh = Date()
- if account.teamName != me.teamName {
- account.teamName = me.teamName; account.address = me.person.address
- try? accounts.save(account)
- }
} catch let error as EquipoAPIError where error.endsSession {
endSession()
} catch {
refreshFailed = true
- if status == .loading && !messages.isEmpty { status = .ready }
}
}
- public func loadThread(_ taskID: String) async {
- guard let page = try? await client.thread(taskID) else { return }
- threads[taskID] = Self.merge(threads[taskID] ?? [], page.messages ?? [])
+ func apply(_ snapshot: Snapshot) {
+ me = snapshot.me
+ messages = Self.merge(messages, snapshot.messages ?? [])
+ turns = Self.merge(turns, snapshot.turns ?? [])
+ cards = Self.merge(cards, snapshot.cards ?? [])
+ projects = Dictionary((snapshot.projects ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
+ cursor = max(cursor, snapshot.cursor)
+ let liveIDs = Set(turns.filter(\.isLive).map(\.id))
+ activity = activity.filter { liveIDs.contains($0.key) }
+ if account.teamName != snapshot.me.teamName {
+ account.teamName = snapshot.me.teamName; account.address = snapshot.me.address
+ try? accounts.save(account)
+ }
}
- /// Reconciles by ID; the newer revision wins; ordered by the server's sequence.
- static func merge(_ old: [Message], _ new: [Message]) -> [Message] {
+ /// Reconciles by ID; the newer revision wins.
+ static func merge<T: Identifiable & Sendable>(_ old: [T], _ new: [T]) -> [T] where T.ID == String, T: Revisioned {
var byID = Dictionary(old.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
- for m in new where (byID[m.id]?.revision ?? -1) <= m.revision { byID[m.id] = m }
- return byID.values.sorted { ($0.sequence, $0.id) < ($1.sequence, $1.id) }
+ for item in new where (byID[item.id]?.revision ?? -1) <= item.revision { byID[item.id] = item }
+ return byID.values.sorted { ($0.sortDate, $0.id) < ($1.sortDate, $1.id) }
+ }
+
+ // MARK: Following the conversation
+
+ /// Follows the event stream while the app is in front. An activity
+ /// updates the thinking line; anything else is read again through the
+ /// snapshot. A dropped stream reconnects with backoff.
+ public func startLive() {
+ live?.cancel()
+ live = Task { [weak self] in
+ var backoff = Backoff()
+ while !Task.isCancelled {
+ guard let self, self.status != .signedOut else { return }
+ if self.status == .loading { await self.refresh() }
+ do {
+ let lines = try await self.client.events(after: self.cursor)
+ backoff = Backoff()
+ for try await line in lines {
+ if Task.isCancelled { return }
+ await self.handle(line)
+ }
+ } catch let error as EquipoAPIError {
+ if error.endsSession { self.endSession(); return }
+ if error.code == "cursor_expired" { self.cursor = 0; await self.refresh() }
+ } catch {}
+ if Task.isCancelled { return }
+ try? await self.sleep(.seconds(backoff.next()))
+ await self.refresh()
+ }
+ }
+ }
+ public func stopLive() { live?.cancel(); live = nil }
+
+ /// One line of the stream. A turn's activity moves the thinking line;
+ /// a change to something the screens show reads them again; the rest
+ /// (runners, connections, pings) is not this app's.
+ func handle(_ line: String) async {
+ guard line.hasPrefix("data:") else { return }
+ let json = Data(line.dropFirst(5).trimmingCharacters(in: .whitespaces).utf8)
+ guard let event = try? EquipoJSON.decoder.decode(EventEnvelope.self, from: json) else { return }
+ if let c = event.cursor { cursor = max(cursor, c) }
+ if event.type == "activity" {
+ if event.resource == "turn", let data = event.activity { activity[data.turnId] = data }
+ return
+ }
+ guard Self.shown.contains(event.resource) else { return }
+ await refresh()
+ }
+ static let shown: Set<String> = ["message", "turn", "card", "task", "step", "project", "member"]
+
+ struct EventEnvelope: Decodable {
+ var cursor: Int64?
+ var type: String
+ var resource: String
+ var activity: ThinActivity?
+ enum Keys: String, CodingKey { case cursor, type, resource, data }
+ init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: Keys.self)
+ cursor = try c.decodeIfPresent(Int64.self, forKey: .cursor)
+ type = try c.decode(String.self, forKey: .type)
+ resource = try c.decodeIfPresent(String.self, forKey: .resource) ?? ""
+ activity = type == "activity" && resource == "turn" ? try? c.decode(ThinActivity.self, forKey: .data) : nil
+ }
}
- public func project(for task: EquipoTask) -> Project? { projects[String(task.projectId)] }
- public func task(_ id: String) -> EquipoTask? { tasks.first { $0.id == id } ?? needsYou?.first { $0.id == id } }
+ /// Reconnects quickly at first, then every half minute at most.
+ struct Backoff {
+ private var attempt = 0
+ mutating func next() -> Int {
+ defer { attempt += 1 }
+ return min(30, [2, 4, 8, 15][min(attempt, 3)] * (attempt > 3 ? 2 : 1))
+ }
+ }
// MARK: Sending
public func send(_ text: String, inThreadOf taskID: String? = nil) async {
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty, let write = try? EquipoClient.message(text) else { return }
- let item = Outgoing(id: write.key, text: text, taskID: taskID, state: .sending, write: write)
- outgoing.append(item)
- await deliver(item.id)
+ outgoing.append(Outgoing(id: write.key, text: text, taskID: taskID, state: .sending, write: write))
+ await deliver(write.key)
}
/// Sends one outgoing message again, as itself.
@@ -128,21 +194,26 @@ public final class EquipoSession {
private func deliver(_ id: String) async {
guard let index = outgoing.firstIndex(where: { $0.id == id }) else { return }
- var item = outgoing[index]
- item.state = .sending; outgoing[index] = item
+ outgoing[index].state = .sending
+ let item = outgoing[index]
do {
- let sent: Message
- if let taskID = item.taskID { sent = try await client.sendThreadMessage(task: taskID, item.write) }
- else { sent = try await client.sendMessage(item.write) }
+ if let taskID = item.taskID {
+ let entry = try await client.postThread(task: taskID, item.write)
+ if let i = tasks.firstIndex(where: { $0.id == taskID }) {
+ var thread = tasks[i].thread ?? []
+ if !thread.contains(where: { $0.id == entry.id }) { thread.append(entry) }
+ tasks[i].thread = thread
+ }
+ } else {
+ let sent = try await client.send(item.write)
+ messages = Self.merge(messages, [sent.message])
+ turns = Self.merge(turns, [sent.turn])
+ }
outgoing.removeAll { $0.id == id }
- if let taskID = item.taskID { threads[taskID] = Self.merge(threads[taskID] ?? [], [sent]) }
- else { messages = Self.merge(messages, [sent]) }
await refresh()
} catch let error as EquipoAPIError {
if error.endsSession { endSession(); return }
- if let i = outgoing.firstIndex(where: { $0.id == id }) {
- outgoing[i].state = error == .offline ? .waiting : .failed
- }
+ if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error == .offline ? .waiting : .failed }
} catch {
if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = .failed }
}
@@ -152,134 +223,64 @@ public final class EquipoSession {
public enum AnswerOutcome: Equatable, Sendable {
case answered
- /// The question changed or closed: show the current one; never resend.
+ /// The card changed or was already answered: show it as it is now; never resend.
case changed
case offline
case failed
}
- /// Answers a clarification as the person saw it. The question is read
- /// again first; if its revision moved, nothing is sent.
- public func answer(_ question: Question, with answer: EquipoClient.Answer) async -> AnswerOutcome {
- let current: Question
- do { current = try await client.question(question.id) }
- catch EquipoAPIError.offline { return .offline }
- catch { return .failed }
- questions[current.id] = current
- guard current.revision == question.revision, current.isAnswerable() else { return .changed }
- guard let write = try? EquipoClient.answer(answer, to: current) else { return .failed }
+ /// Answers a card as the person saw it, bound to that revision. A lost
+ /// answer is retried as itself; a stale one is never sent again.
+ public func answer(_ card: ThinCard, choice: String, note: String? = nil) async -> AnswerOutcome {
+ guard card.isOpen, let write = try? EquipoClient.answer(choice, note: note, to: card) else { return .changed }
var attempts = 0
while true {
do {
- _ = try await client.answer(question: current.id, write)
+ let answered = try await client.answer(card: card.id, write)
+ cards = Self.merge(cards, [answered.card])
await refresh()
return .answered
} catch let error as EquipoAPIError {
if error.endsSession { endSession(); return .failed }
- if error.isStale || error.status == 410 { if let q = try? await client.question(current.id) { questions[q.id] = q }; return .changed }
- // A lost answer is retried with its own key, body and revision.
+ if case .card(_, _, let current) = error { cards = Self.merge(cards, [current]); return .changed }
+ if error.isStale { await refresh(); return .changed }
if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue }
return error == .offline ? .offline : .failed
} catch { return .failed }
}
}
- // MARK: Notifications
-
- private var subscriptionKey: String { "equipo.subscription." + origin.absoluteString }
- struct StoredSubscription: Codable, Equatable { var id: String; var revision: Int64; var cursor: String }
-
- /// Polls the device's subscription while the app is in front, with a
- /// periodic full refresh as the fallback.
- public func startPolling(every interval: Duration = .seconds(15)) {
- polling?.cancel()
- polling = Task { [weak self] in
- var ticks = 0
- while !Task.isCancelled {
- guard let self else { return }
- await self.pollOnce()
- ticks += 1
- if ticks % 4 == 0 { await self.refresh() }
- try? await self.sleep(interval)
- }
- }
- }
- public func stopPolling() { polling?.cancel(); polling = nil }
-
- func pollOnce() async {
- guard status != .signedOut, let deviceID = account.credential?.id else { return }
- var sub = storedSubscription()
- if sub == nil {
- guard let created = try? await client.subscribe(device: deviceID, EquipoClient.subscription(device: deviceID)) else { return }
- sub = StoredSubscription(id: created.id, revision: created.revision, cursor: created.cursor)
- store(sub)
- }
- guard var current = sub else { return }
- do {
- let page = try await client.notifications(cursor: current.cursor.isEmpty ? nil : current.cursor)
- let fresh = page.items.filter { !seenNotifications.contains($0.id) }
- for n in page.items where n.state == "unread" {
- seenNotifications.insert(n.id)
- current.revision = await acknowledge(n.id, subscription: current)
- }
- seenNotifications.formUnion(page.items.map(\.id))
- if !page.nextCursor.isEmpty { current.cursor = page.nextCursor }
- store(current)
- if !fresh.isEmpty { await refresh() }
- } catch let error as EquipoAPIError {
- if error.endsSession { endSession(); return }
- switch error.code {
- case "subscription_expired": store(nil)
- case "cursor_expired": current.cursor = ""; store(current); await refresh()
- default: break
- }
- } catch {}
- }
-
- /// Acknowledges one delivered notification and returns the subscription's
- /// new revision. A lost acknowledgement is retried as itself; a stale
- /// revision takes the server's current one and tries once more.
- /// Acknowledging records delivery only: it never answers anything.
- private func acknowledge(_ id: String, subscription: StoredSubscription) async -> Int64 {
- var revision = subscription.revision
- guard var write = try? EquipoClient.acknowledgement(id, revision: revision) else { return revision }
- for _ in 0..<3 {
- do { return try await client.acknowledge(subscription: subscription.id, write).revision }
- catch let error as EquipoAPIError {
- if error == .offline { continue }
- guard error.isStale, let current = error.currentRevision,
- let next = try? EquipoClient.acknowledgement(id, revision: current) else { return revision }
- revision = current; write = next
- } catch { return revision }
- }
- return revision
- }
-
- func storedSubscription() -> StoredSubscription? {
- defaults.data(forKey: subscriptionKey).flatMap { try? JSONDecoder().decode(StoredSubscription.self, from: $0) }
- }
- private func store(_ sub: StoredSubscription?) {
- if let sub, let data = try? JSONEncoder().encode(sub) { defaults.set(data, forKey: subscriptionKey) }
- else { defaults.removeObject(forKey: subscriptionKey) }
+ /// Stops the coordinator's turn in flight: that turn only.
+ public func stop(_ turn: ThinTurn) async {
+ try? await client.cancelTurn(turn.id)
+ await refresh()
}
// MARK: Signing out
private func endSession() {
status = .signedOut
- stopPolling()
+ stopLive()
}
/// Revokes this device on the server, then forgets it here. Forgetting
/// happens even if the server cannot be reached.
public func signOut() async {
- stopPolling()
+ stopLive()
if let id = account.credential?.id, let page = try? await client.devices(),
let device = page.items.first(where: { $0.id == id }) {
_ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision))
}
accounts.remove(origin)
- store(nil)
status = .signedOut
}
}
+
+/// What `merge` needs to reconcile a resource.
+protocol Revisioned {
+ var revision: Int64 { get }
+ var sortDate: Date { get }
+}
+extension ThinMessage: Revisioned { var sortDate: Date { createdAt } }
+extension ThinTurn: Revisioned { var sortDate: Date { createdAt } }
+extension ThinCard: Revisioned { var sortDate: Date { createdAt } }
diff --git a/native/apple/Sources/EquipoKit/UI/Components.swift b/native/apple/Sources/EquipoKit/UI/Components.swift
index c004f26a..e08c24aa 100644
--- a/native/apple/Sources/EquipoKit/UI/Components.swift
+++ b/native/apple/Sources/EquipoKit/UI/Components.swift
@@ -24,18 +24,18 @@ struct StepNode: View {
}.frame(width: 22, height: 22)
}
}
-/// The task's steps as a connected timeline, in plan order.
+/// The task's steps as a connected timeline, in plan order: who ran, how
+/// it went, and the step's own headline.
struct StepsView: View {
- let task: EquipoTask
+ let task: ThinTask
var body: some View {
let steps = task.steps ?? []
VStack(alignment: .leading, spacing: 0) {
- ForEach(Array(steps.enumerated()), id: \.element.key) { index, step in
+ ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in
let last = index == steps.count - 1
- let needsYou = waitsOnYou(step, in: task)
HStack(alignment: .top, spacing: 12) {
VStack(spacing: 4) {
- StepNode(state: step.state, needsYou: needsYou)
+ StepNode(state: step.state, needsYou: false)
if !last {
Capsule().fill(step.state == "done" ? Palette.positive.opacity(0.55) : Palette.border)
.frame(width: 2).frame(maxHeight: .infinity)
@@ -43,19 +43,19 @@ struct StepsView: View {
}.padding(.bottom, last ? 0 : 4)
VStack(alignment: .leading, spacing: 4) {
HStack(alignment: .firstTextBaseline) {
- SpecialistLabel(category: step.category, tone: step.state == "queued" ? Palette.secondary : Palette.text)
+ SpecialistLabel(category: step.specialist, tone: step.state == "queued" ? Palette.secondary : Palette.text)
Spacer(minLength: 8)
- Text(label(step, needsYou: needsYou)).font(Typo.caption)
- .foregroundStyle(needsYou ? Palette.warning : step.state == "done" ? Palette.positive : Palette.secondary)
+ Text(Self.label(step.state)).font(Typo.caption)
+ .foregroundStyle(step.state == "failed" ? Palette.negative : step.state == "done" ? Palette.positive : Palette.secondary)
}
- Text(step.action).font(Typo.secondary)
- .foregroundStyle(step.state == "queued" ? Palette.secondary : Palette.text)
- .fixedSize(horizontal: false, vertical: true)
- if !step.actual.isEmpty { QuietLabel(text: step.actual) }
- else if let reason = ["needs_macos": "Needs a Mac to run", "copy_question": "Waiting for your answer"][step.reason] { QuietLabel(text: reason) }
- if let usage = step.usage {
- Text("\(usage.calls) calls · \(compact(usage.inputTokens)) in · \(compact(usage.outputTokens)) out")
- .font(Typo.caption).monospacedDigit().foregroundStyle(Palette.faint)
+ let line = step.headline.isEmpty ? step.summary : step.headline
+ if !line.isEmpty {
+ Text(line).font(Typo.secondary)
+ .foregroundStyle(step.state == "queued" ? Palette.secondary : Palette.text)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ if let finished = step.finishedAt {
+ Text(finished.formatted(date: .abbreviated, time: .shortened)).font(Typo.caption).foregroundStyle(Palette.faint)
}
}.padding(.bottom, last ? 0 : 20)
}.fixedSize(horizontal: false, vertical: true)
@@ -63,13 +63,13 @@ struct StepsView: View {
}
}
}
- private func label(_ step: Step, needsYou: Bool) -> String {
- if needsYou { return "Waiting for you" }
- switch step.state {
- case "done": return "Done"
- case "running": return "Running"
- case "waiting": return "Waiting"
- default: return "Queued"
+ static func label(_ state: String) -> String {
+ switch state {
+ case "done": return String(localized: "step.done", bundle: .module)
+ case "running": return String(localized: "step.running", bundle: .module)
+ case "failed": return String(localized: "step.failed", bundle: .module)
+ case "cancelled": return String(localized: "step.cancelled", bundle: .module)
+ default: return String(localized: "step.queued", bundle: .module)
}
}
}
@@ -98,8 +98,3 @@ struct StatTile: View {
.accessibilityElement(children: .combine)
}
}
-
-/// A waiting step waits on you only when it is not waiting for a machine.
-func waitsOnYou(_ step: Step, in task: EquipoTask) -> Bool {
- step.state == "waiting" && task.needsYou && step.reason != "needs_macos"
-}
diff --git a/native/apple/Sources/EquipoKit/UI/LiveCards.swift b/native/apple/Sources/EquipoKit/UI/LiveCards.swift
index cd8c26da..7dc805a5 100644
--- a/native/apple/Sources/EquipoKit/UI/LiveCards.swift
+++ b/native/apple/Sources/EquipoKit/UI/LiveCards.swift
@@ -1,74 +1,53 @@
import SwiftUI
-/// A question card: the question as the first turn of its thread, the
-/// options, and the compact composer when the question allows text.
-/// Answering reads the question again first; a changed question is shown,
-/// never answered on the person's behalf.
+/// A question the coordinator asks: its options, answered here, bound to
+/// the revision the person saw. A card that changed underneath is shown as
+/// it is now and never answered on the person's behalf. Words of their own
+/// go in the composer, as a message.
struct LiveQuestionCard: View {
- let card: Card
- let question: Question?
+ let card: ThinCard
let taskTitle: String?
let session: EquipoSession
@State private var phase: Phase = .open
- @State private var draft = ""
- @Environment(\.openURL) private var openURL
- enum Phase: Equatable { case open, sending(String), answered(String), changed, offline, failed }
+ enum Phase: Equatable { case open, sending(String), changed, offline, failed }
var body: some View {
- RaisedCard(flat: phase.isAnswered) {
- if let taskTitle, !(question?.text.contains(taskTitle) ?? false) {
+ RaisedCard(flat: !card.isOpen) {
+ if let taskTitle, !card.question.contains(taskTitle) {
Text(taskTitle).font(Typo.caption).foregroundStyle(Palette.secondary)
}
- Text(question?.text ?? String(localized: "question.loading", bundle: .module))
- .font(Typo.cardLine).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)
- content
- }
- .accessibilityElement(children: .contain)
- }
-
- @ViewBuilder private var content: some View {
- if let question, question.kind != "clarification" {
- openOnWeb
- } else if let question {
- switch phase {
- case .answered(let what):
- Label { Text(String(localized: "question.answered \(what)", bundle: .module)) } icon: { Image(systemName: "checkmark") }
+ CardHead(text: card.question.isEmpty ? String(localized: "card.question", bundle: .module) : card.question)
+ if card.isOpen {
+ choices
+ feedback
+ } else if !card.choice.isEmpty {
+ Label { Text(String(localized: "question.answered \(card.choice)", bundle: .module)) } icon: { Image(systemName: "checkmark") }
.font(Typo.secondaryStrong).foregroundStyle(Palette.positive)
- default:
- if !question.isAnswerable() {
- Text(String(localized: "question.closed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary)
- } else {
- choices(question)
- if question.allowText {
- MiniComposer(placeholder: String(localized: "question.answer_placeholder", bundle: .module), busy: isSending) { text in
- Task { await submit(question, .text(text), shown: text) }
- }
- }
- feedback
- }
+ } else {
+ Text(String(localized: "question.closed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary)
}
- } else {
- ProgressView().controlSize(.small)
}
+ .accessibilityElement(children: .contain)
+ .onChange(of: card.revision) { _, _ in if phase == .changed { phase = .open } }
}
private var isSending: Bool { if case .sending = phase { return true }; return false }
- @ViewBuilder private func choices(_ question: Question) -> some View {
- let options = question.options ?? []
+ @ViewBuilder private var choices: some View {
+ let options = card.options ?? []
if !options.isEmpty {
ViewThatFits(in: .horizontal) {
- HStack(spacing: 10) { optionButtons(question, options, expanded: true) }
- VStack(spacing: 10) { optionButtons(question, options, expanded: true) }
+ HStack(spacing: 10) { optionButtons(options) }
+ VStack(spacing: 10) { optionButtons(options) }
}
}
}
- @ViewBuilder private func optionButtons(_ question: Question, _ options: [QuestionOption], expanded: Bool) -> some View {
- ForEach(options) { option in
- let busy: String? = { if case .sending(let id) = phase, id == option.id { return String(localized: "action.sending", bundle: .module) }; return nil }()
- RosterButton(title: option.label, expanded: expanded, busy: busy) {
- Task { await submit(question, .option(option.id), shown: option.label, sendingID: option.id) }
+ @ViewBuilder private func optionButtons(_ options: [String]) -> some View {
+ ForEach(Array(options.enumerated()), id: \.offset) { index, option in
+ let busy: String? = phase == .sending(option) ? String(localized: "action.sending", bundle: .module) : nil
+ RosterButton(title: option, primary: index == 0, expanded: true, busy: busy) {
+ Task { await submit(option) }
}
.disabled(isSending)
}
@@ -83,16 +62,10 @@ struct LiveQuestionCard: View {
}
}
- private var openOnWeb: some View {
- RosterButton(title: String(localized: "card.open_on_web", bundle: .module)) {
- openURL(Feed.webURL(for: card, origin: session.origin))
- }
- }
-
- private func submit(_ question: Question, _ answer: EquipoClient.Answer, shown: String, sendingID: String = "text") async {
- phase = .sending(sendingID)
- switch await session.answer(question, with: answer) {
- case .answered: phase = .answered(shown)
+ private func submit(_ choice: String) async {
+ phase = .sending(choice)
+ switch await session.answer(card, choice: choice) {
+ case .answered: phase = .open
case .changed: phase = .changed
case .offline: phase = .offline
case .failed: phase = .failed
@@ -100,52 +73,124 @@ struct LiveQuestionCard: View {
}
}
-extension LiveQuestionCard.Phase {
- var isAnswered: Bool { if case .answered = self { return true }; return false }
-}
-
/// A decision this slice does not take natively: merges, approvals and the
/// rest open the web app, where the full context and the must-match
/// behaviour already are (sync proposal, parity rows R-02 and R-03).
struct LiveDecisionCard: View {
- let card: Card
+ let card: ThinCard
let taskTitle: String?
let origin: URL
@Environment(\.openURL) private var openURL
var body: some View {
- RaisedCard {
- Text(taskTitle ?? String(localized: "decision.untitled", bundle: .module))
- .font(Typo.cardLine).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)
- Text(String(localized: "decision.on_web", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary)
- .fixedSize(horizontal: false, vertical: true)
- RosterButton(title: String(localized: "card.open_on_web", bundle: .module), primary: true) {
- openURL(Feed.webURL(for: card, origin: origin))
+ RaisedCard(flat: !card.isOpen) {
+ if let taskTitle, !card.question.contains(taskTitle) {
+ Text(taskTitle).font(Typo.caption).foregroundStyle(Palette.secondary)
+ }
+ CardHead(text: card.question.isEmpty ? (taskTitle ?? String(localized: "decision.untitled", bundle: .module)) : card.question)
+ if card.isOpen {
+ Text(String(localized: "decision.on_web", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ RosterButton(title: String(localized: "card.open_on_web", bundle: .module), primary: true) {
+ openURL(Feed.webURL(for: card, origin: origin))
+ }
+ } else {
+ QuietLink(title: String(localized: "card.open_on_web", bundle: .module), icon: "arrow.up.right") {
+ openURL(Feed.webURL(for: card, origin: origin))
+ }
}
}
}
}
-/// A task report, flat on its rail: the title, what it is doing and the
-/// Needs you chip. Stage, Checks, Review and Branch wait for the API.
-struct LiveReport: View {
- let task: EquipoTask
+/// A task report on its rail: eyebrow, title, the five-stop track and the
+/// facts; one line while its decision is open beside it.
+public struct LiveReport: View {
+ let report: TaskReport
+ var compact = false
+ var wide = false
var onOpen: () -> Void = {}
- var body: some View {
- let summary = TaskSummary(task)
- Button(action: onOpen) {
- FlowLayout(spacing: 8, lineSpacing: 4) {
- Text(task.description).font(Typo.compactTitle).foregroundStyle(Palette.text)
- Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot)
- if summary.needsYou { NeedsChip() }
+ public init(report: TaskReport, compact: Bool = false, wide: Bool = false, onOpen: @escaping () -> Void = {}) {
+ self.report = report; self.compact = compact; self.wide = wide; self.onOpen = onOpen
+ }
+ public var body: some View {
+ VStack(alignment: .leading, spacing: Metric.gap) {
+ if compact {
+ Button(action: onOpen) {
+ FlowLayout(spacing: 8, lineSpacing: 4) {
+ Text(report.title).font(Typo.compactTitle).foregroundStyle(Palette.text)
+ Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow)
+ if report.needsYou { NeedsChip() }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityHint(Text(String(localized: "task.open_hint", bundle: .module)))
+ } else {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .center, spacing: 8) {
+ Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow).lineLimit(1)
+ Spacer(minLength: 0)
+ if report.needsYou { NeedsChip() }
+ }
+ Text(report.title).font(Typo.reportTitle).foregroundStyle(Palette.text)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ if !report.cancelled { StageTrack(track: report.track, allLabels: wide) }
+ if !report.facts.isEmpty { FactsView(facts: report.facts, wide: wide) }
+ QuietLink(title: String(localized: "task.open", bundle: .module), icon: "chevron.right", action: onOpen)
}
- .frame(maxWidth: .infinity, alignment: .leading)
- .contentShape(Rectangle())
}
- .buttonStyle(.plain)
- .padding(.leading, Metric.indent).padding(.bottom, 2)
+ .padding(.leading, Metric.indent).padding(.bottom, compact ? 2 : 4)
.background(alignment: .topLeading) {
+ // The neutral rail hangs from the byline tile's centre.
Capsule().fill(Palette.border).frame(width: 2).padding(.leading, Metric.tile / 2 - 1)
}
- .accessibilityHint(Text(String(localized: "task.open_hint", bundle: .module)))
+ }
+}
+
+/// A one-line receipt: a project added, where new projects go.
+struct LiveReceipt: View {
+ let card: ThinCard
+ var body: some View {
+ HStack(spacing: 0) {
+ CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading)
+ Text(Feed.receiptLine(card)).font(Typo.secondary).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// The coordinator at work: the mark, what it is doing, elapsed time and a
+/// quiet Stop for that turn only.
+public struct ThinkingLine: View {
+ let turn: ThinTurn
+ let activity: String?
+ var onStop: () -> Void
+ @State private var stopping = false
+ public init(turn: ThinTurn, activity: String?, onStop: @escaping () -> Void) {
+ self.turn = turn; self.activity = activity; self.onStop = onStop
+ }
+ public var body: some View {
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ let seconds = max(0, Int(context.date.timeIntervalSince(turn.createdAt)))
+ let doing = activity ?? String(localized: "thinking.working", bundle: .module)
+ HStack(spacing: 0) {
+ CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading)
+ HStack(spacing: 0) {
+ Text(doing).font(Typo.secondaryStrong).foregroundStyle(Palette.text).lineLimit(1).truncationMode(.tail)
+ Text(" · ").foregroundStyle(Palette.faint).accessibilityHidden(true)
+ Text(Duration.seconds(seconds).formatted(.units(allowed: [.minutes, .seconds], width: .narrow)))
+ .monospacedDigit().foregroundStyle(Palette.secondary).fixedSize()
+ }.font(Typo.secondary)
+ Spacer(minLength: 8)
+ QuietLink(title: stopping ? String(localized: "thinking.stopping", bundle: .module) : String(localized: "thinking.stop", bundle: .module)) {
+ guard !stopping else { return }
+ stopping = true
+ onStop()
+ }
+ }
+ .accessibilityElement(children: .combine)
+ }
}
}
diff --git a/native/apple/Sources/EquipoKit/UI/RosterViews.swift b/native/apple/Sources/EquipoKit/UI/RosterViews.swift
index 5ba6f722..f771967d 100644
--- a/native/apple/Sources/EquipoKit/UI/RosterViews.swift
+++ b/native/apple/Sources/EquipoKit/UI/RosterViews.swift
@@ -130,6 +130,79 @@ struct Byline: View {
}
}
+// MARK: - Stage track
+
+/// Five stops edge to edge: four equal spans, the last stop only its dot.
+/// Each label centres under its dot and is only nudged in at the two ends.
+struct StageTrack: View {
+ let track: [TrackStop]
+ var allLabels: Bool
+ private let slot: CGFloat = 11
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Canvas { context, size in
+ let y = size.height / 2
+ let xs = positions(size.width)
+ for i in 0..<(xs.count - 1) {
+ let line = Path(CGRect(x: xs[i], y: y - 1, width: xs[i + 1] - xs[i], height: 2))
+ context.fill(line, with: .color(track[i].state == .done ? Palette.positive : Palette.controlBorder))
+ }
+ for (i, stop) in track.enumerated() {
+ let c = CGPoint(x: xs[i], y: y)
+ switch stop.state {
+ case .done:
+ context.fill(Path(ellipseIn: CGRect(x: c.x - 4, y: c.y - 4, width: 8, height: 8)), with: .color(Palette.positive))
+ case .current:
+ let tone = stop.tone ?? .positive
+ context.fill(Path(ellipseIn: CGRect(x: c.x - 9.5, y: c.y - 9.5, width: 19, height: 19)), with: .color(tone.halo))
+ context.fill(Path(ellipseIn: CGRect(x: c.x - 5.5, y: c.y - 5.5, width: 11, height: 11)), with: .color(tone.dot))
+ case .todo:
+ let dot = Path(ellipseIn: CGRect(x: c.x - 4, y: c.y - 4, width: 8, height: 8))
+ context.fill(dot, with: .color(Palette.surface))
+ context.stroke(dot, with: .color(Palette.lineStrong), lineWidth: 1)
+ }
+ }
+ }
+ .frame(height: 20)
+ TrackLabels(slot: slot) {
+ ForEach(track) { stop in
+ let current = stop.state == .current
+ Text(stop.stage.label)
+ .font(current ? Typo.eyebrow : Typo.factLabel)
+ .foregroundStyle(current ? (stop.tone ?? .positive).text : Palette.secondary)
+ .fixedSize()
+ .opacity(allLabels || current ? 1 : 0)
+ }
+ }
+ }
+ .accessibilityElement()
+ .accessibilityLabel(Text(String(localized: "track.spoken \(currentLabel)", bundle: .module)))
+ .accessibilityValue(Text(String(localized: "track.position \(position) \(total)", bundle: .module)))
+ }
+ private var currentLabel: String { track.first { $0.state == .current }?.stage.label ?? "" }
+ private var position: String { ((track.firstIndex { $0.state == .current } ?? 0) + 1).formatted() }
+ private var total: String { track.count.formatted() }
+ private func positions(_ width: CGFloat) -> [CGFloat] {
+ let r = slot / 2
+ return track.indices.map { r + CGFloat($0) * (width - slot) / CGFloat(max(1, track.count - 1)) }
+ }
+}
+/// Places each label centred on its dot, clamped inside the track's width.
+struct TrackLabels: Layout {
+ let slot: CGFloat
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ CGSize(width: proposal.width ?? 300, height: subviews.map { $0.sizeThatFits(.unspecified).height }.max() ?? 0)
+ }
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ let r = slot / 2
+ for (i, view) in subviews.enumerated() {
+ let size = view.sizeThatFits(.unspecified)
+ let centre = bounds.minX + r + CGFloat(i) * (bounds.width - slot) / CGFloat(max(1, subviews.count - 1))
+ let x = min(max(bounds.minX, centre - size.width / 2), bounds.maxX - size.width)
+ view.place(at: CGPoint(x: x, y: bounds.minY), proposal: .unspecified)
+ }
+ }
+}
extension StageTone {
var dot: Color { self == .warning ? Palette.warning : self == .negative ? Palette.negative : Palette.positive }
var halo: Color { self == .warning ? Palette.warningBackground : self == .negative ? Palette.negativeBackground : Palette.positiveBackground }
@@ -153,6 +226,46 @@ struct NeedsChip: View {
}
}
/// A quiet text link: muted, no underline until hovered.
+struct FactsView: View {
+ let facts: [RosterFact]
+ var wide: Bool
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Hairline()
+ if wide {
+ HStack(alignment: .top, spacing: 0) {
+ ForEach(Array(facts.enumerated()), id: \.element.id) { index, fact in
+ if index > 0 { Rectangle().fill(Palette.border).frame(width: 1) }
+ VStack(alignment: .leading, spacing: 2) {
+ Text(fact.label).font(Typo.factLabel).foregroundStyle(Palette.faint)
+ value(fact)
+ }
+ .padding(.leading, index == 0 ? 0 : 10).padding(.trailing, 10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }.fixedSize(horizontal: false, vertical: true).padding(.top, Metric.gap)
+ } else {
+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 12, verticalSpacing: 8) {
+ ForEach(facts) { fact in
+ GridRow {
+ Text(fact.label).font(Typo.factLabel).foregroundStyle(Palette.faint).frame(width: 64, alignment: .leading)
+ value(fact).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }.padding(.top, Metric.gap)
+ }
+ }
+ }
+ private func value(_ fact: RosterFact) -> some View {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(fact.value).font(fact.code ? Typo.code : Typo.factValue).foregroundStyle(Palette.text)
+ .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
+ if let detail = fact.detail {
+ Text(detail).font(fact.code ? Font.system(.caption, design: .monospaced) : Typo.factLabel).foregroundStyle(Palette.secondary)
+ }
+ }.accessibilityElement(children: .combine)
+ }
+}
struct QuietLink: View {
let title: String
var icon: String?
@@ -298,10 +411,12 @@ struct ThreadBubble: View {
} else {
let who = turn.who ?? .coordinator
HStack(alignment: .top, spacing: 8) {
- Avatar(who: who, size: 24)
+ if turn.person != nil {
+ Image(systemName: "person.crop.circle").font(.system(size: 20)).foregroundStyle(Palette.secondary).frame(width: 24, height: 24)
+ } else { Avatar(who: who, size: 24) }
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 6) {
- Text(who.name).font(Typo.threadWho).foregroundStyle(Palette.secondary)
+ Text(turn.person ?? who.name).font(Typo.threadWho).foregroundStyle(Palette.secondary)
Text(turn.timeText).font(Typo.time).foregroundStyle(Palette.faint)
}
Text(turn.text).font(Typo.thread).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)
@@ -389,19 +504,19 @@ struct SubChatDrawer: View {
// MARK: - Messages, the thinking line and the roll-up
struct CoordinatorMessage: View {
- let message: Message
+ let message: ThinMessage
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 0) {
CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading)
Text(message.createdAt.formatted(date: .omitted, time: .shortened)).font(Typo.time).foregroundStyle(Palette.faint)
}.frame(minHeight: Metric.tile)
- Text(message.body).font(Typo.message).foregroundStyle(Palette.text).lineSpacing(3)
+ Text(message.text).font(Typo.message).foregroundStyle(Palette.text).lineSpacing(3)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
}
.frame(maxWidth: .infinity, alignment: .leading)
.accessibilityElement(children: .combine)
- .accessibilityLabel(Text(String(localized: "message.coordinator_spoken \(message.createdAt.formatted(date: .omitted, time: .shortened)) \(message.body)", bundle: .module)))
+ .accessibilityLabel(Text(String(localized: "message.coordinator_spoken \(message.createdAt.formatted(date: .omitted, time: .shortened)) \(message.text)", bundle: .module)))
}
}
struct OwnMessage: View {
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
index 570352a6..58c87859 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
@@ -12,7 +12,7 @@ public struct AccountScreen: View {
Section(String(localized: "account.team", bundle: .module)) {
LabeledContent(String(localized: "account.team_name", bundle: .module), value: session.teamName)
LabeledContent(String(localized: "account.address", bundle: .module), value: session.origin.host ?? session.origin.absoluteString)
- if let me = session.me { LabeledContent(String(localized: "account.signed_in_as", bundle: .module), value: me.person.displayIdentity) }
+ if let me = session.me { LabeledContent(String(localized: "account.signed_in_as", bundle: .module), value: me.address) }
}
Section(String(localized: "account.device", bundle: .module)) {
LabeledContent(String(localized: "account.device_name", bundle: .module), value: session.account.label)
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
index 9449a914..4c708bc4 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
@@ -47,8 +47,7 @@ public final class EquipoAppModel {
public func foreground() {
NativeConnectivity.shared.foregrounded()
guard let session else { return }
- Task { await session.refresh() }
- session.startPolling()
+ session.startLive()
}
- public func background() { session?.stopPolling() }
+ public func background() { session?.stopLive() }
}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift
index 711d9412..389e83b7 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift
@@ -39,24 +39,28 @@ public struct ConversationScreen: View {
@ViewBuilder private func row(_ item: FeedItem) -> some View {
switch item {
- case .own(let m): OwnMessage(text: m.body)
+ case .own(let m): OwnMessage(text: m.text)
case .coordinator(let m): CoordinatorMessage(message: m)
case .outgoing(let o): OutgoingMessage(item: o) { Task { await session.retry(o.id) } }
- case .report(_, let byline, let task):
+ case .report(_, let byline, let report, let compact):
VStack(alignment: .leading, spacing: 8) {
Byline(byline: byline)
- LiveReport(task: task) { openTask(task.id) }
+ LiveReport(report: report, compact: compact) { openTask(report.task.id) }
}
- case .question(let card, let byline, let question, let title):
+ case .question(let card, let byline):
VStack(alignment: .leading, spacing: 8) {
Byline(byline: byline)
- LiveQuestionCard(card: card, question: question, taskTitle: title, session: session)
+ LiveQuestionCard(card: card, taskTitle: session.task(card.taskId)?.title, session: session)
}
- case .decision(let card, let byline, let title):
+ case .decision(let card, let byline):
VStack(alignment: .leading, spacing: 8) {
Byline(byline: byline)
- LiveDecisionCard(card: card, taskTitle: title, origin: session.origin)
+ LiveDecisionCard(card: card, taskTitle: session.task(card.taskId)?.title, origin: session.origin)
}
+ case .receipt(let card, _):
+ LiveReceipt(card: card)
+ case .thinking(let turn, let activity):
+ ThinkingLine(turn: turn, activity: activity) { Task { await session.stop(turn) } }
}
}
}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift b/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift
index 5dd0b3c4..21756375 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/TaskScreens.swift
@@ -18,14 +18,8 @@ public struct NeedsScreen: View {
}
ForEach(needs) { task in
VStack(alignment: .leading, spacing: 8) {
- TaskRowButton(task: task, project: session.project(for: task)?.name) { openTask(task.id) }
- ForEach(session.cards.filter { $0.taskId == task.id && $0.kind != "task" }) { card in
- if card.kind == "question" {
- LiveQuestionCard(card: card, question: session.questions[card.resourceId], taskTitle: nil, session: session)
- } else {
- LiveDecisionCard(card: card, taskTitle: task.description, origin: session.origin)
- }
- }
+ TaskRowButton(task: task) { openTask(task.id) }
+ TaskCards(session: session, task: task)
}
}
} else {
@@ -46,9 +40,9 @@ public struct TasksScreen: View {
public init(session: EquipoSession, openTask: @escaping (String) -> Void) { self.session = session; self.openTask = openTask }
public var body: some View {
List {
- group(String(localized: "tasks.needs_you", bundle: .module), session.tasks.filter(\.needsYou))
- group(String(localized: "tasks.in_progress", bundle: .module), session.tasks.filter { !$0.needsYou && !Self.finished($0) })
- group(String(localized: "tasks.finished", bundle: .module), session.tasks.filter { !$0.needsYou && Self.finished($0) })
+ group(String(localized: "tasks.needs_you", bundle: .module), session.tasks.filter(\.waitsOnYou))
+ group(String(localized: "tasks.in_progress", bundle: .module), session.tasks.filter { !$0.waitsOnYou && !Self.finished($0) })
+ group(String(localized: "tasks.finished", bundle: .module), session.tasks.filter { !$0.waitsOnYou && Self.finished($0) })
}
.scrollContentBackground(.hidden).background(Palette.background)
.refreshable { await session.refresh() }
@@ -59,15 +53,12 @@ public struct TasksScreen: View {
}
}
}
- static func finished(_ t: EquipoTask) -> Bool {
- let steps = t.steps ?? []
- return t.state == "cancelled" || (!steps.isEmpty && steps.allSatisfy { $0.state == "done" })
- }
- @ViewBuilder private func group(_ title: String, _ tasks: [EquipoTask]) -> some View {
+ static func finished(_ t: ThinTask) -> Bool { t.stage == "done" || t.stage == "cancelled" }
+ @ViewBuilder private func group(_ title: String, _ tasks: [ThinTask]) -> some View {
if !tasks.isEmpty {
Section(title) {
ForEach(tasks) { task in
- TaskRowButton(task: task, project: session.project(for: task)?.name) { openTask(task.id) }
+ TaskRowButton(task: task) { openTask(task.id) }
}
}.listRowBackground(Palette.surface)
}
@@ -75,21 +66,20 @@ public struct TasksScreen: View {
}
struct TaskRowButton: View {
- let task: EquipoTask
- let project: String?
+ let task: ThinTask
var action: () -> Void
var body: some View {
- let summary = TaskSummary(task)
+ let report = TaskReport(task)
Button(action: action) {
HStack(alignment: .center, spacing: 10) {
VStack(alignment: .leading, spacing: 5) {
HStack(spacing: 8) {
- if let project { ProjectChip(name: project) }
+ if !task.project.isEmpty { ProjectChip(name: task.project) }
Spacer(minLength: 8)
- if summary.needsYou { NeedsChip() }
+ if report.needsYou { NeedsChip() }
}
- Text(task.description).font(Typo.cardTitle).foregroundStyle(Palette.text).multilineTextAlignment(.leading)
- Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot)
+ Text(task.title).font(Typo.cardTitle).foregroundStyle(Palette.text).multilineTextAlignment(.leading)
+ Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow)
}
Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.faint)
}
@@ -100,71 +90,88 @@ struct TaskRowButton: View {
}
}
-/// One task: what it is doing, any question or decision, its steps, its
-/// usage and its thread ("Talk about this").
+/// A task's open question or decision cards, as the conversation has them.
+struct TaskCards: View {
+ let session: EquipoSession
+ let task: ThinTask
+ var body: some View {
+ ForEach(session.cards.filter { $0.taskId == task.id && $0.kind != "task" && $0.isOpen }) { card in
+ if card.kind == "question" {
+ LiveQuestionCard(card: card, taskTitle: nil, session: session)
+ } else {
+ LiveDecisionCard(card: card, taskTitle: task.title, origin: session.origin)
+ }
+ }
+ }
+}
+
+/// One task: where it is, any question or decision, the facts, its steps
+/// and its thread ("Talk about this").
public struct TaskScreen: View {
let session: EquipoSession
let taskID: String
@State private var talking = false
+ @State private var loaded: ThinTask?
+ @Environment(\.openURL) private var openURL
public init(session: EquipoSession, taskID: String) { self.session = session; self.taskID = taskID }
+ /// The full task (steps and thread) once read; the list's copy until then.
+ private var task: ThinTask? {
+ guard let listed = session.task(taskID) else { return loaded }
+ guard let loaded, loaded.revision >= listed.revision else { return listed }
+ return loaded
+ }
+
public var body: some View {
Group {
- if let task = session.task(taskID) {
+ if let task {
ScrollView { content(task).padding(16).frame(maxWidth: 760).frame(maxWidth: .infinity) }
} else {
ContentUnavailableView(String(localized: "task.missing", bundle: .module), systemImage: "questionmark.folder")
}
}
.background(Palette.background)
- .task { await session.loadThread(taskID) }
- .refreshable { await session.refresh(); await session.loadThread(taskID) }
+ .task(id: session.task(taskID)?.revision) { await load() }
+ .refreshable { await session.refresh(); await load() }
}
- @ViewBuilder private func content(_ task: EquipoTask) -> some View {
- let summary = TaskSummary(task)
+ private func load() async {
+ if let full = try? await session.client.task(taskID) { loaded = full }
+ }
+
+ @ViewBuilder private func content(_ task: ThinTask) -> some View {
+ let report = TaskReport(task)
VStack(alignment: .leading, spacing: 20) {
VStack(alignment: .leading, spacing: 6) {
HStack {
- if let project = session.project(for: task)?.name { ProjectChip(name: project) }
+ if !task.project.isEmpty { ProjectChip(name: task.project) }
Spacer()
- if summary.needsYou { NeedsChip() }
- }
- Text(task.description).font(Typo.reportTitle).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)
- Text(summary.label).font(Typo.eyebrow).foregroundStyle(summary.tone == .positive ? Palette.secondary : summary.tone.dot)
- }
- ForEach(session.cards.filter { $0.taskId == task.id && $0.kind != "task" }) { card in
- if card.kind == "question" {
- LiveQuestionCard(card: card, question: session.questions[card.resourceId], taskTitle: nil, session: session)
- } else {
- LiveDecisionCard(card: card, taskTitle: task.description, origin: session.origin)
+ if report.needsYou { NeedsChip() }
}
+ Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow)
+ Text(task.title).font(Typo.reportTitle).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)
}
+ if !report.cancelled { StageTrack(track: report.track, allLabels: true) }
+ if !report.facts.isEmpty { FactsView(facts: report.facts, wide: false) }
+ TaskCards(session: session, task: task)
HStack(spacing: 18) {
RosterButton(title: talking ? String(localized: "task.hide_talk", bundle: .module) : String(localized: "task.talk", bundle: .module)) { talking.toggle() }
QuietLink(title: String(localized: "task.open_web", bundle: .module), icon: "arrow.up.right") {
- #if canImport(UIKit)
- UIApplication.shared.open(session.origin.appendingPathComponent("tasks/\(task.id)"))
- #else
- NSWorkspace.shared.open(session.origin.appendingPathComponent("tasks/\(task.id)"))
- #endif
+ openURL(session.origin.appendingPathComponent("tasks/\(task.id)"))
}
}
- if talking { TaskThread(session: session, taskID: task.id) }
+ if talking { TaskThread(session: session, task: task) { loaded = nil; Task { await load() } } }
if !(task.steps ?? []).isEmpty {
VStack(alignment: .leading, spacing: 10) {
SectionTitle(text: String(localized: "task.steps", bundle: .module))
Panel { StepsView(task: task) }
}
}
- if let usage = task.usage {
+ if !task.brief.isEmpty {
VStack(alignment: .leading, spacing: 10) {
- SectionTitle(text: String(localized: "task.usage", bundle: .module))
- HStack(spacing: 10) {
- StatTile(label: String(localized: "usage.calls", bundle: .module), value: usage.calls.formatted())
- StatTile(label: String(localized: "usage.tokens_in", bundle: .module), value: usage.inputTokens.formatted(.number.notation(.compactName)))
- StatTile(label: String(localized: "usage.tokens_out", bundle: .module), value: usage.outputTokens.formatted(.number.notation(.compactName)))
- }
+ SectionTitle(text: String(localized: "task.brief", bundle: .module))
+ Text(task.brief).font(Typo.body).foregroundStyle(Palette.text).textSelection(.enabled)
+ .fixedSize(horizontal: false, vertical: true)
}
}
}
@@ -174,17 +181,18 @@ public struct TaskScreen: View {
/// "Talk about this": the task's own thread, with a compact composer.
struct TaskThread: View {
let session: EquipoSession
- let taskID: String
+ let task: ThinTask
+ var sent: () -> Void = {}
var body: some View {
- let turns = (session.threads[taskID] ?? []).map(ThreadTurn.init)
- + session.outgoing.filter { $0.taskID == taskID }.map { ThreadTurn(id: $0.id, who: nil, text: $0.text, time: nil, pending: true) }
+ let turns = (task.thread ?? []).map { ThreadTurn($0, me: session.me?.address) }
+ + session.outgoing.filter { $0.taskID == task.id }.map { ThreadTurn(id: $0.id, who: nil, text: $0.text, time: nil, pending: true) }
VStack(alignment: .leading, spacing: Metric.gap) {
if turns.isEmpty {
Text(String(localized: "task.thread_empty", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary)
}
ForEach(turns) { ThreadBubble(turn: $0) }
MiniComposer(placeholder: String(localized: "task.reply", bundle: .module)) { text in
- Task { await session.send(text, inThreadOf: taskID) }
+ Task { await session.send(text, inThreadOf: task.id); sent() }
}
}
.padding(12)
diff --git a/native/apple/Sources/EquipoKit/UI/Theme.swift b/native/apple/Sources/EquipoKit/UI/Theme.swift
index d674208a..32f04f6a 100644
--- a/native/apple/Sources/EquipoKit/UI/Theme.swift
+++ b/native/apple/Sources/EquipoKit/UI/Theme.swift
@@ -219,8 +219,9 @@ struct SpecialistLabel: View {
var tone: Color = Palette.text
var body: some View {
HStack(spacing: 6) {
- Image(systemName: specialistIcon(category)).foregroundStyle(Palette.secondary)
- Text(category.capitalized).foregroundStyle(tone)
+ let who = Specialist(category: category)
+ Image(systemName: who.symbol).foregroundStyle(Palette.secondary)
+ Text(who.name).foregroundStyle(tone)
}.font(Typo.secondaryStrong)
}
}
diff --git a/native/apple/Sources/EquipoMac/LiveTranscript.swift b/native/apple/Sources/EquipoMac/LiveTranscript.swift
index 5f89e355..75102c2c 100644
--- a/native/apple/Sources/EquipoMac/LiveTranscript.swift
+++ b/native/apple/Sources/EquipoMac/LiveTranscript.swift
@@ -14,7 +14,6 @@ final class LiveTranscript: NSView {
/// What a question card is doing, kept here across rebuilds.
enum AnswerState: Equatable {
case sending(String)
- case answered(String)
case changed, offline, failed
}
@@ -109,7 +108,7 @@ final class LiveTranscript: NSView {
for item in items {
switch item {
case .own(let message):
- place(ownBubble(message.body, width: width), x: width - ownWidth(message.body, width: width))
+ place(ownBubble(message.text, width: width), x: width - ownWidth(message.text, width: width))
case .coordinator(let message):
place(coordinatorRow(message, width: width))
case .outgoing(let outgoing):
@@ -118,15 +117,20 @@ final class LiveTranscript: NSView {
place(bubble, x: width - bubble.frame.width, gapAfter: 4)
let status = outgoingStatus(outgoing)
place(status, x: width - status.frame.width)
- case .report(_, let byline, let task):
+ case .report(_, let byline, let report, let compact):
place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap)
- place(reportLine(task, width: width), gapAfter: 24)
- case .question(let card, let byline, let question, let taskTitle):
+ place(hosted(LiveReport(report: report, compact: compact, wide: true) { [weak self] in self?.openTask(report.task.id) }, width: width), gapAfter: 24)
+ case .question(let card, let byline):
place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap)
- placeCard(questionCard(card, question, taskTitle: taskTitle, width: content))
- case .decision(let card, let byline, let taskTitle):
+ placeCard(questionCard(card, taskTitle: session.task(card.taskId)?.title, width: content))
+ case .decision(let card, let byline):
place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap)
- placeCard(decisionCard(card, taskTitle: taskTitle, width: content))
+ placeCard(decisionCard(card, taskTitle: session.task(card.taskId)?.title, width: content))
+ case .receipt(let card, _):
+ place(receiptRow(card, width: width))
+ case .thinking(let turn, let activity):
+ let session = self.session
+ place(hosted(ThinkingLine(turn: turn, activity: activity) { Task { await session.stop(turn) } }, width: width))
}
}
// The last item scrolls clear of the composer.
@@ -149,16 +153,33 @@ final class LiveTranscript: NSView {
return card
}
- private func coordinatorRow(_ message: Message, width: CGFloat) -> NSView {
+ /// A SwiftUI Roster view (the report's track and facts, the thinking
+ /// line), sized to the column.
+ private func hosted<V: View>(_ view: V, width: CGFloat) -> NSView {
+ let host = NSHostingView(rootView: view.frame(width: width, alignment: .leading))
+ host.frame.size = NSSize(width: width, height: ceil(host.fittingSize.height))
+ return host
+ }
+
+ private func receiptRow(_ card: ThinCard, width: CGFloat) -> NSView {
+ let row = FlippedView(frame: NSRect(x: 0, y: 0, width: width, height: MacMetric.tile))
+ let mark = sparkleView(); mark.frame.origin = NSPoint(x: 0, y: 4); row.addSubview(mark)
+ let line = makeText(Feed.receiptLine(card), MacType.small, .webSecondary, width: width - MacMetric.gutter)
+ centre(line, x: MacMetric.gutter, row: 0, height: MacMetric.tile); row.addSubview(line)
+ row.setAccessibilityElement(true); row.setAccessibilityLabel(Feed.receiptLine(card))
+ return row
+ }
+
+ private func coordinatorRow(_ message: ThinMessage, width: CGFloat) -> NSView {
let row = FlippedView(frame: NSRect(x: 0, y: 0, width: width, height: 0))
let mark = sparkleView(); mark.frame.origin = NSPoint(x: 0, y: 4); row.addSubview(mark)
let time = message.createdAt.formatted(date: .omitted, time: .shortened)
let timeLabel = makeText(time, MacType.time, .webFaint); centre(timeLabel, x: MacMetric.gutter, row: 0, height: MacMetric.tile); row.addSubview(timeLabel)
- let body = makeText(message.body, MacType.line, .webText, width: min(width - MacMetric.gutter, 620), lineSpacing: 3, selectable: true)
+ let body = makeText(message.text, MacType.line, .webText, width: min(width - MacMetric.gutter, 620), lineSpacing: 3, selectable: true)
body.frame.origin = NSPoint(x: MacMetric.gutter, y: MacMetric.tile + 2); row.addSubview(body)
row.frame.size.height = body.frame.maxY
row.setAccessibilityElement(true); row.setAccessibilityRole(.group)
- row.setAccessibilityLabel("\(Specialist.coordinator.name), \(time). \(message.body)")
+ row.setAccessibilityLabel(EquipoStrings.text("message.coordinator_spoken \(time) \(message.text)"))
return row
}
@@ -177,30 +198,6 @@ final class LiveTranscript: NSView {
}
}
- /// One compact line on the neutral rail: the title, what the task is
- /// doing, and the Needs you chip. Clicking opens the task.
- private func reportLine(_ task: EquipoTask, width: CGFloat) -> NSView {
- let summary = TaskSummary(task)
- let block = FlippedView(frame: NSRect(x: 0, y: 0, width: width, height: 26))
- let x = MacMetric.gutter, w = width - MacMetric.gutter
- let title = makeText(task.description, MacType.compactTitle, .webText, width: w * 0.65, lines: 1)
- centre(title, x: x, row: 0, height: 22); block.addSubview(title)
- let label = makeText(summary.label, MacType.eyebrow, summary.tone.nsEyebrow)
- centre(label, x: title.frame.maxX + 10, row: 0, height: 22); block.addSubview(label)
- if summary.needsYou {
- let chip = needsChipView(); centre(chip, x: label.frame.maxX + 10, row: 0, height: 22); block.addSubview(chip)
- }
- block.addSubview(PaintView(frame: NSRect(x: MacMetric.tile / 2 - 1, y: -2, width: 2, height: 28)) { r in
- NSColor.webLine.setFill(); NSBezierPath(roundedRect: r, xRadius: 1, yRadius: 1).fill()
- }, positioned: .below, relativeTo: nil)
- let open = ActionButton("", style: .row) { [weak self] in self?.openTask(task.id) }
- open.frame = NSRect(x: x - 4, y: 0, width: w + 4, height: 26)
- open.setAccessibilityLabel("\(task.description), \(summary.label)")
- open.setAccessibilityHelp(EquipoStrings.text("task.open_hint"))
- block.addSubview(open, positioned: .below, relativeTo: nil)
- return block
- }
-
// MARK: Cards
private func finish(_ plate: RaisedPlate, height: CGFloat) -> RaisedPlate {
@@ -210,56 +207,43 @@ final class LiveTranscript: NSView {
return plate
}
- private func questionCard(_ card: Card, _ question: Question?, taskTitle: String?, width: CGFloat) -> RaisedPlate {
+ private func questionCard(_ card: ThinCard, taskTitle: String?, width: CGFloat) -> RaisedPlate {
let state = answers[card.id]
- let answered: Bool = { if case .answered = state { return true }; return false }()
- let plate = RaisedPlate(width: width, height: 0, flat: answered)
+ let plate = RaisedPlate(width: width, height: 0, flat: !card.isOpen)
let inner = width - 2 * MacMetric.pad
var y = MacMetric.pad
func add(_ view: NSView, gap: CGFloat = MacMetric.gap) {
view.frame.origin = NSPoint(x: MacMetric.pad, y: y); plate.content.addSubview(view); y = view.frame.maxY + gap
}
- if let taskTitle, !(question?.text.contains(taskTitle) ?? false) {
+ if let taskTitle, !card.question.contains(taskTitle) {
add(makeText(taskTitle, MacType.caption, .webSecondary, width: inner), gap: 4)
}
- add(makeText(question?.text ?? EquipoStrings.text("question.loading"), MacType.line, .webText, width: inner, lineSpacing: 2, selectable: true))
- guard let question else { return finish(plate, height: y - MacMetric.gap + MacMetric.pad) }
- if question.kind != "clarification" {
- add(openOnWeb(card, primary: false))
- return finish(plate, height: y - MacMetric.gap + MacMetric.pad)
- }
- if case .answered(let what) = state {
- add(outcome(EquipoStrings.text("question.answered \(what)"), width: inner))
- return finish(plate, height: y - MacMetric.gap + MacMetric.pad)
- }
- guard question.isAnswerable() else {
- add(makeText(EquipoStrings.text("question.closed"), MacType.small, .webSecondary, width: inner))
+ add(makeText(card.question.isEmpty ? EquipoStrings.text("card.question") : card.question, MacType.line, .webText, width: inner, lineSpacing: 2, selectable: true))
+ guard card.isOpen else {
+ if card.choice.isEmpty {
+ add(makeText(EquipoStrings.text("question.closed"), MacType.small, .webSecondary, width: inner))
+ } else {
+ add(outcome(EquipoStrings.text("question.answered \(card.choice)"), width: inner))
+ }
return finish(plate, height: y - MacMetric.gap + MacMetric.pad)
}
let sending: String? = { if case .sending(let id) = state { return id }; return nil }()
- let options = question.options ?? []
+ let options = card.options ?? []
if !options.isEmpty {
let gap: CGFloat = 10
let w = floor((inner - gap * CGFloat(options.count - 1)) / CGFloat(options.count))
for (index, option) in options.enumerated() {
- let busy = sending == option.id ? EquipoStrings.text("action.sending") : nil
- let b = button(option.label, busy: busy) { [weak self] in
- self?.submit(card: card, question: question, answer: .option(option.id), shown: option.label, sendingID: option.id)
+ let busy = sending == option ? EquipoStrings.text("action.sending") : nil
+ let b = button(option, index == 0 ? .primary : .choice, busy: busy) { [weak self] in
+ self?.submit(card: card, choice: option)
}
- if sending != nil && sending != option.id { b.isEnabled = false }
+ if sending != nil && sending != option { b.isEnabled = false }
b.frame = NSRect(x: MacMetric.pad + CGFloat(index) * (w + gap), y: y, width: w, height: 32)
- b.setAccessibilityLabel(busy ?? option.label)
+ b.setAccessibilityLabel(busy ?? option)
plate.content.addSubview(b)
}
y += 32 + MacMetric.gap
}
- if question.allowText {
- let composer = MiniComposerView(width: inner, placeholder: EquipoStrings.text("question.answer_placeholder"), busy: sending == "text")
- composer.onSend = { [weak self] text in
- self?.submit(card: card, question: question, answer: .text(text), shown: text, sendingID: "text")
- }
- add(composer)
- }
let feedback: String? = {
switch state {
case .changed: return EquipoStrings.text("card.changed")
@@ -277,16 +261,16 @@ final class LiveTranscript: NSView {
return finish(plate, height: y - MacMetric.gap + MacMetric.pad)
}
- private func submit(card: Card, question: Question, answer: EquipoClient.Answer, shown: String, sendingID: String) {
+ private func submit(card: ThinCard, choice: String) {
if case .sending = answers[card.id] { return }
- answers[card.id] = .sending(sendingID)
+ answers[card.id] = .sending(choice)
rebuild()
let session = self.session
Task { [weak self] in
- let outcome = await session.answer(question, with: answer)
+ let outcome = await session.answer(card, choice: choice)
guard let self else { return }
switch outcome {
- case .answered: self.answers[card.id] = .answered(shown)
+ case .answered: self.answers[card.id] = nil
case .changed: self.answers[card.id] = .changed
case .offline: self.answers[card.id] = .offline
case .failed: self.answers[card.id] = .failed
@@ -295,20 +279,26 @@ final class LiveTranscript: NSView {
}
}
- private func decisionCard(_ card: Card, taskTitle: String?, width: CGFloat) -> RaisedPlate {
- let plate = RaisedPlate(width: width, height: 0, flat: false)
+ private func decisionCard(_ card: ThinCard, taskTitle: String?, width: CGFloat) -> RaisedPlate {
+ let plate = RaisedPlate(width: width, height: 0, flat: !card.isOpen)
let inner = width - 2 * MacMetric.pad
var y = MacMetric.pad
func add(_ view: NSView, gap: CGFloat = MacMetric.gap) {
view.frame.origin = NSPoint(x: MacMetric.pad, y: y); plate.content.addSubview(view); y = view.frame.maxY + gap
}
- add(makeText(taskTitle ?? EquipoStrings.text("decision.untitled"), MacType.line, .webText, width: inner, lineSpacing: 2), gap: 4)
- add(makeText(EquipoStrings.text("decision.on_web"), MacType.small, .webSecondary, width: inner))
- add(openOnWeb(card, primary: true))
+ if let taskTitle, !card.question.isEmpty, !card.question.contains(taskTitle) {
+ add(makeText(taskTitle, MacType.caption, .webSecondary, width: inner), gap: 4)
+ }
+ let head = card.question.isEmpty ? (taskTitle ?? EquipoStrings.text("decision.untitled")) : card.question
+ add(makeText(head, MacType.line, .webText, width: inner, lineSpacing: 2, selectable: true), gap: 4)
+ if card.isOpen {
+ add(makeText(EquipoStrings.text("decision.on_web"), MacType.small, .webSecondary, width: inner))
+ }
+ add(openOnWeb(card, primary: card.isOpen))
return finish(plate, height: y - MacMetric.gap + MacMetric.pad)
}
- private func openOnWeb(_ card: Card, primary: Bool) -> ActionButton {
+ private func openOnWeb(_ card: ThinCard, primary: Bool) -> ActionButton {
let url = Feed.webURL(for: card, origin: session.origin)
return button(EquipoStrings.text("card.open_on_web"), primary ? .primary : .choice) { NSWorkspace.shared.open(url) }
}
diff --git a/native/apple/Tests/EquipoKitTests/ClientTests.swift b/native/apple/Tests/EquipoKitTests/ClientTests.swift
index 2067615d..f9af8082 100644
--- a/native/apple/Tests/EquipoKitTests/ClientTests.swift
+++ b/native/apple/Tests/EquipoKitTests/ClientTests.swift
@@ -5,55 +5,76 @@ import Testing
@Suite struct ClientTests {
@Test func everyFixtureDecodes() throws {
_ = try Fixture.decode("me", as: Me.self)
- _ = try Fixture.decode("projects", as: Page<Project>.self)
- let tasks = try Fixture.decode("tasks", as: Page<EquipoTask>.self)
- _ = try Fixture.decode("needs-you", as: Page<EquipoTask>.self)
- let page = try Fixture.decode("conversation", as: ConversationPage.self)
- _ = try Fixture.decode("thread", as: ConversationPage.self)
- _ = try Fixture.decode("message", as: Message.self)
- _ = try Fixture.decode("question", as: Question.self)
_ = try Fixture.decode("ack", as: Ack.self)
_ = try Fixture.decode("device-challenge", as: DeviceChallenge.self)
_ = try Fixture.decode("device-credential", as: DeviceCredential.self)
_ = try Fixture.decode("devices", as: Page<Device>.self)
- _ = try Fixture.decode("subscription", as: NotificationSubscription.self)
- _ = try Fixture.decode("notifications", as: Page<EquipoNotification>.self)
+ // The thin fixtures are the server's own answers (internal/thintest).
+ let snapshot = try Fixture.decode("thin/snapshot", as: Snapshot.self)
+ _ = try Fixture.decode("thin/tasks", as: ThinList<ThinTask>.self)
+ _ = try Fixture.decode("thin/needs-you", as: ThinList<ThinTask>.self)
+ _ = try Fixture.decode("thin/projects", as: ThinList<ThinProject>.self)
+ let task = try Fixture.decode("thin/task", as: ThinTask.self)
+ _ = try Fixture.decode("thin/messages", as: MessagePage.self)
+ _ = try Fixture.decode("thin/sent", as: Sent.self)
+ _ = try Fixture.decode("thin/answered", as: Answered.self)
+ _ = try Fixture.decode("thin/card-conflict", as: CardConflict.self)
+ _ = try Fixture.decode("thin/thread-entry", as: ThreadEntry.self)
// Go writes nanoseconds; they parse.
- #expect(page.messages?[1].createdAt != nil)
- // Unknown usage stays unknown.
- #expect(tasks.items[1].usage == nil)
+ #expect(snapshot.messages?.count == 6)
+ #expect(snapshot.me.teamName.isEmpty == false)
+ #expect(task.steps?.count == 3)
}
@Test func readsCarryTheBearerAndNoCookies() async throws {
- let t = ScriptedTransport(); t.on("GET /me", fixture: "me")
- _ = try await EquipoClient(transport: t, token: "secret-token").me()
+ let t = ScriptedTransport(); t.on("GET /snapshot", fixture: "thin/snapshot")
+ _ = try await EquipoClient(transport: t, token: "secret-token").snapshot()
let r = try #require(t.requests.first)
let url = try r.urlRequest(origin: t.origin)
- #expect(url.url?.absoluteString == "https://oficina.example.test/api/v1/me")
+ #expect(url.url?.absoluteString == "https://oficina.example.test/api/v1/snapshot")
#expect(url.value(forHTTPHeaderField: "Authorization") == "Bearer secret-token")
#expect(url.httpShouldHandleCookies == false)
#expect(url.value(forHTTPHeaderField: "Idempotency-Key") == nil)
}
- @Test func writesCarryKeyAndQuotedRevision() async throws {
- let t = ScriptedTransport(); t.on("POST /questions/question-vat/answer", fixture: "ack")
- let q: Question = try Fixture.decode("question")
- let write = try EquipoClient.answer(.option("vat"), to: q)
- _ = try await EquipoClient(transport: t, token: "tok").answer(question: q.id, write)
+ @Test func anAnswerCarriesKeyAndTheRevisionSeen() async throws {
+ let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
+ let card = try #require(snapshot.cards?.first { $0.kind == "merge" && $0.isOpen })
+ let t = ScriptedTransport(); t.on("POST /cards/\(card.id)/answer", fixture: "thin/answered")
+ let write = try EquipoClient.answer("wait_mac", to: card)
+ _ = try await EquipoClient(transport: t, token: "tok").answer(card: card.id, write)
let url = try t.requests[0].urlRequest(origin: t.origin)
#expect(url.value(forHTTPHeaderField: "Idempotency-Key") == write.key)
- #expect(url.value(forHTTPHeaderField: "If-Match") == "\"7\"")
- let body = try JSONSerialization.jsonObject(with: url.httpBody!) as! [String: String]
- #expect(body == ["kind": "clarification", "option_id": "vat"])
+ #expect(url.value(forHTTPHeaderField: "If-Match") == "\"\(card.revision)\"")
+ let body = try JSONSerialization.jsonObject(with: url.httpBody!) as! [String: Any]
+ #expect(body["choice"] as? String == "wait_mac")
+ #expect((body["revision"] as? NSNumber)?.int64Value == card.revision)
+ #expect(body["note"] == nil)
+ }
+
+ @Test func aMessageCarriesItsKeyInBodyAndHeader() throws {
+ let write = try EquipoClient.message("Fix the README")
+ let body = try JSONSerialization.jsonObject(with: write.body) as! [String: String]
+ #expect(body == ["text": "Fix the README", "idempotency_key": write.key])
}
@Test func anAnswerWithoutARevisionIsNeverSent() async throws {
let t = ScriptedTransport()
let unbound = PendingWrite(body: Data("{}".utf8))
- await #expect(throws: EquipoAPIError.status(428)) { _ = try await EquipoClient(transport: t, token: "t").answer(question: "q", unbound) }
+ await #expect(throws: EquipoAPIError.status(428)) { _ = try await EquipoClient(transport: t, token: "t").answer(card: "c", unbound) }
#expect(t.requests.isEmpty)
}
+ @Test func aCardConflictKeepsTheCardAsItIsNow() async throws {
+ let t = ScriptedTransport(); t.on("POST /cards/c1/answer", status: 409, fixture: "thin/card-conflict")
+ do { _ = try await EquipoClient(transport: t, token: "t").answer(card: "c1", PendingWrite(body: Data("{}".utf8), ifMatch: 1)); Issue.record("no error") }
+ catch let e as EquipoAPIError {
+ #expect(e.isStale); #expect(e.status == 409); #expect(e.code == "card_answered")
+ guard case .card(_, _, let card) = e else { Issue.record("not a card conflict"); return }
+ #expect(card.state == "answered")
+ }
+ }
+
@Test func errorsKeepCodeAndCurrentRevision() async throws {
let t = ScriptedTransport(); t.on("GET /me", status: 409, fixture: "error-revision-conflict")
do { _ = try await EquipoClient(transport: t, token: "t").me(); Issue.record("no error") }
@@ -65,10 +86,18 @@ import Testing
catch let e as EquipoAPIError { #expect(e.endsSession) }
}
- @Test func listLimitsStayInRange() async throws {
- let t = ScriptedTransport(); t.on("GET /tasks", fixture: "tasks")
- _ = try await EquipoClient(transport: t, token: "t").tasks(limit: 500)
- #expect(t.requests[0].query.first { $0.name == "limit" }?.value == "100")
+ @Test func olderMessagesStayInRange() async throws {
+ let t = ScriptedTransport(); t.on("GET /messages", fixture: "thin/messages")
+ _ = try await EquipoClient(transport: t, token: "t").olderMessages(before: "m1", limit: 500)
+ #expect(t.requests[0].query.first { $0.name == "limit" }?.value == "200")
+ }
+
+ @Test func eventsResumeAfterTheCursor() async throws {
+ let t = ScriptedTransport(); t.onStream(.success([]))
+ _ = try await EquipoClient(transport: t, token: "t").events(after: 64)
+ #expect(t.requests[0].path == "/events")
+ #expect(t.requests[0].query.first { $0.name == "after" }?.value == "64")
+ #expect(t.requests[0].bearer == "t")
}
@Test func idsAreEscapedInPaths() async throws {
@@ -76,13 +105,4 @@ import Testing
_ = try? await EquipoClient(transport: t, token: "t").task("a/b?c")
#expect(t.requests[0].path == "/tasks/a%2Fb%3Fc")
}
-
- @Test func questionAnswerability() throws {
- var q: Question = try Fixture.decode("question")
- #expect(q.isAnswerable())
- q.state = "answered"; #expect(!q.isAnswerable())
- q.state = "open"; q.canAnswer = false; #expect(!q.isAnswerable())
- q.canAnswer = true; q.expiresAt = Date(timeIntervalSince1970: 0); #expect(!q.isAnswerable())
- q.expiresAt = nil; q.kind = "native"; #expect(!q.isAnswerable())
- }
}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json b/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json
deleted file mode 100644
index 191876ac..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/conversation.json
+++ /dev/null
@@ -1,67 +0,0 @@
-{
- "messages": [
- {
- "id": "message-1",
- "conversation_id": "conversation-paul",
- "thread_id": "",
- "author_kind": "person",
- "author_id": "paul@example.test",
- "body": "Can you fix the VAT rounding on invoice PDFs?",
- "sequence": 1,
- "revision": 1,
- "created_at": "2026-11-13T09:41:00Z",
- "sources": []
- },
- {
- "id": "message-2",
- "conversation_id": "conversation-paul",
- "thread_id": "",
- "author_kind": "coordinator",
- "author_id": "coordinator",
- "body": "Engineering has fixed the rounding. Copy has one question.",
- "sequence": 2,
- "revision": 1,
- "created_at": "2026-11-13T09:42:00.123456789Z",
- "sources": []
- }
- ],
- "cards": [
- {
- "id": "card-vat-report",
- "kind": "task",
- "resource_id": "task-vat",
- "task_id": "task-vat",
- "revision": 7,
- "copy_key": "chat.card.task",
- "actions": null,
- "waiting_task_id": ""
- },
- {
- "id": "card-vat",
- "kind": "question",
- "resource_id": "question-vat",
- "task_id": "task-vat",
- "revision": 7,
- "copy_key": "questions.clarification",
- "actions": [
- "answer"
- ],
- "waiting_task_id": "task-vat"
- },
- {
- "id": "card-merge",
- "kind": "merge",
- "resource_id": "task-signin",
- "task_id": "task-signin",
- "revision": 4,
- "copy_key": "chat.card.merge_question",
- "actions": [
- "merge",
- "wait"
- ],
- "waiting_task_id": "task-signin"
- }
- ],
- "next_cursor": "",
- "revision": 11
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/message.json b/native/apple/Tests/EquipoKitTests/Fixtures/message.json
deleted file mode 100644
index 008e87d6..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/message.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "id": "message-3",
- "conversation_id": "conversation-paul",
- "thread_id": "",
- "author_kind": "person",
- "author_id": "paul@example.test",
- "body": "Thanks",
- "sequence": 3,
- "revision": 1,
- "created_at": "2026-11-13T12:05:00Z",
- "sources": []
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json b/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json
deleted file mode 100644
index 1cba4aad..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/needs-you.json
+++ /dev/null
@@ -1,67 +0,0 @@
-{
- "items": [
- {
- "id": "task-vat",
- "project_id": 1,
- "requester": "paul@example.test",
- "description": "Fix VAT on invoice PDFs",
- "kind": "bug",
- "state": "waiting",
- "revision": 7,
- "plan_revision": 2,
- "replacement_id": "",
- "can_cancel": true,
- "can_merge": false,
- "needs_you": true,
- "steps": [
- {
- "key": "eng",
- "category": "engineering",
- "action": "Fix the rounding",
- "state": "done",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "Fixed rounding before totals.",
- "reason": "",
- "usage": {
- "calls": 4,
- "input_tokens": 18400,
- "output_tokens": 2600
- },
- "allowance_remaining": null
- },
- {
- "key": "copy",
- "category": "copy",
- "action": "Check the wording",
- "state": "waiting",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "",
- "reason": "copy_question",
- "usage": null,
- "allowance_remaining": null
- },
- {
- "key": "checks",
- "category": "checks",
- "action": "Run invoice tests",
- "state": "queued",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "",
- "reason": "",
- "usage": null,
- "allowance_remaining": null
- }
- ],
- "usage": {
- "calls": 4,
- "input_tokens": 18400,
- "output_tokens": 2600
- }
- }
- ],
- "next_cursor": "",
- "revision": 9
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json b/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json
deleted file mode 100644
index 0eded994..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/notifications.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "items": [
- {
- "id": "n1",
- "kind": "question",
- "resource_id": "question-vat",
- "deep_link": "/questions/question-vat",
- "resource_revision": 7,
- "created_at": "2026-11-18T10:01:00Z",
- "state": "unread"
- },
- {
- "id": "n2",
- "kind": "task_ready",
- "resource_id": "task-signin",
- "deep_link": "/tasks/task-signin",
- "resource_revision": 4,
- "created_at": "2026-11-18T10:02:00Z",
- "state": "acknowledged"
- }
- ],
- "next_cursor": "c2",
- "revision": 3
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/projects.json b/native/apple/Tests/EquipoKitTests/Fixtures/projects.json
deleted file mode 100644
index 83f2f25b..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/projects.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "items": [
- {
- "id": "1",
- "account_id": 1,
- "name": "Equipo",
- "repository": "https://forge.example.test/oficina/equipo",
- "app_name": "equipo",
- "default_branch": "main",
- "kind": "app",
- "owners": [],
- "revision": 1
- },
- {
- "id": "2",
- "account_id": 1,
- "name": "Woodstar",
- "repository": "https://forge.example.test/oficina/woodstar",
- "app_name": "woodstar",
- "default_branch": "main",
- "kind": "app",
- "owners": null,
- "revision": 1
- }
- ],
- "next_cursor": "",
- "revision": 1
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/question.json b/native/apple/Tests/EquipoKitTests/Fixtures/question.json
deleted file mode 100644
index e65a2a13..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/question.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "id": "question-vat",
- "kind": "clarification",
- "task_id": "task-vat",
- "text": "Which tax label should appear on the invoice?",
- "state": "open",
- "revision": 7,
- "can_answer": true,
- "can_allow": false,
- "options": [
- {
- "id": "vat",
- "label": "VAT"
- },
- {
- "id": "sales-tax",
- "label": "Sales tax"
- }
- ],
- "fields": [],
- "allow_text": true,
- "expires_at": "2099-01-01T00:00:00Z"
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json b/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json
deleted file mode 100644
index 8be19334..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/subscription.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "id": "sub_1",
- "device_id": "dev_01JD5Z4Q2X",
- "cursor": "",
- "revision": 1,
- "active": true,
- "expires_at": "2099-01-31T00:00:00Z"
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json b/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json
deleted file mode 100644
index d5b75e4c..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/tasks.json
+++ /dev/null
@@ -1,108 +0,0 @@
-{
- "items": [
- {
- "id": "task-vat",
- "project_id": 1,
- "requester": "paul@example.test",
- "description": "Fix VAT on invoice PDFs",
- "kind": "bug",
- "state": "waiting",
- "revision": 7,
- "plan_revision": 2,
- "replacement_id": "",
- "can_cancel": true,
- "can_merge": false,
- "needs_you": true,
- "steps": [
- {
- "key": "eng",
- "category": "engineering",
- "action": "Fix the rounding",
- "state": "done",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "Fixed rounding before totals.",
- "reason": "",
- "usage": {
- "calls": 4,
- "input_tokens": 18400,
- "output_tokens": 2600
- },
- "allowance_remaining": null
- },
- {
- "key": "copy",
- "category": "copy",
- "action": "Check the wording",
- "state": "waiting",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "",
- "reason": "copy_question",
- "usage": null,
- "allowance_remaining": null
- },
- {
- "key": "checks",
- "category": "checks",
- "action": "Run invoice tests",
- "state": "queued",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "",
- "reason": "",
- "usage": null,
- "allowance_remaining": null
- }
- ],
- "usage": {
- "calls": 4,
- "input_tokens": 18400,
- "output_tokens": 2600
- }
- },
- {
- "id": "task-signin",
- "project_id": 2,
- "requester": "paul@example.test",
- "description": "Check sign-in recovery",
- "kind": "bug",
- "state": "running",
- "revision": 4,
- "plan_revision": 1,
- "replacement_id": "",
- "can_cancel": true,
- "can_merge": false,
- "needs_you": false,
- "steps": [
- {
- "key": "eng",
- "category": "engineering",
- "action": "Fix the recovery link",
- "state": "done",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "The link survives a second request.",
- "reason": "",
- "usage": null,
- "allowance_remaining": null
- },
- {
- "key": "review",
- "category": "review",
- "action": "Review the change",
- "state": "running",
- "model": "fixture-model",
- "account": "connection-claude",
- "actual": "Reading the session tests.",
- "reason": "",
- "usage": null,
- "allowance_remaining": null
- }
- ],
- "usage": null
- }
- ],
- "next_cursor": "",
- "revision": 9
-}
diff --git a/native/apple/Tests/EquipoKitTests/Fixtures/thread.json b/native/apple/Tests/EquipoKitTests/Fixtures/thread.json
deleted file mode 100644
index 65a2ad85..00000000
--- a/native/apple/Tests/EquipoKitTests/Fixtures/thread.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "messages": [
- {
- "id": "message-t1",
- "conversation_id": "conversation-paul",
- "thread_id": "task-signin",
- "author_kind": "person",
- "author_id": "paul@example.test",
- "body": "Does this cover the passkey reset too?",
- "sequence": 1,
- "revision": 1,
- "created_at": "2026-11-13T12:02:00Z",
- "sources": []
- },
- {
- "id": "message-t2",
- "conversation_id": "conversation-paul",
- "thread_id": "task-signin",
- "author_kind": "coordinator",
- "author_id": "coordinator",
- "body": "Not yet.",
- "sequence": 2,
- "revision": 1,
- "created_at": "2026-11-13T12:02:30Z",
- "sources": []
- }
- ],
- "cards": [],
- "next_cursor": "",
- "revision": 2
-}
diff --git a/native/apple/Tests/EquipoKitTests/LiveTests.swift b/native/apple/Tests/EquipoKitTests/LiveTests.swift
index ec536f20..b0d62e15 100644
--- a/native/apple/Tests/EquipoKitTests/LiveTests.swift
+++ b/native/apple/Tests/EquipoKitTests/LiveTests.swift
@@ -46,16 +46,19 @@ struct LiveTests {
let text = "Native slice 1 live check \(UUID().uuidString.prefix(8))"
await session.send(text)
#expect(session.outgoing.isEmpty, "the message was not accepted: \(session.outgoing)")
- #expect(session.messages.contains { $0.isOwn && $0.body == text })
+ #expect(session.messages.contains { $0.isOwn && $0.text == text })
+
+ // The event stream opens with this device's bearer and says something.
+ let stream = try await session.client.events(after: 0)
+ var first: String?
+ for try await line in stream where line.hasPrefix("data:") { first = line; break }
+ #expect(first != nil, "the event stream said nothing")
if let task = session.tasks.first {
- await session.loadThread(task.id)
- print("LIVE thread of \(task.id): \(session.threads[task.id]?.count ?? 0) messages")
+ let full = try await session.client.task(task.id)
+ print("LIVE task \(task.id) at \(full.stage), \(full.steps?.count ?? 0) steps, thread \(full.thread?.count ?? 0)")
}
- await session.pollOnce()
- #expect(session.storedSubscription() != nil, "no notification subscription")
-
await session.signOut()
#expect(accounts.all().isEmpty)
// The credential no longer works: the server revoked it.
diff --git a/native/apple/Tests/EquipoKitTests/PairingTests.swift b/native/apple/Tests/EquipoKitTests/PairingTests.swift
index 1ad28c3c..48730027 100644
--- a/native/apple/Tests/EquipoKitTests/PairingTests.swift
+++ b/native/apple/Tests/EquipoKitTests/PairingTests.swift
@@ -40,6 +40,21 @@ final class Sleeps: @unchecked Sendable {
#expect(begin["public_key"] == (try saved.publicKey()))
}
+ @Test func aServerAskingForFasterPollsStillWaitsFiveSeconds() async throws {
+ let t = ScriptedTransport()
+ let fast = String(decoding: Fixture.data("device-challenge"), as: UTF8.self)
+ .replacingOccurrences(of: "\"poll_interval_seconds\": 5", with: "\"poll_interval_seconds\": 1")
+ #expect(fast.contains("\"poll_interval_seconds\": 1"))
+ t.on("POST /auth/devices", .success(APIResponse(status: 200, data: Data(fast.utf8))))
+ t.on("POST /auth/devices/exchange", err(409, "authorization_pending"), .success(APIResponse(status: 200, data: Fixture.data("device-credential"))))
+ t.on("GET /me", fixture: "me")
+ let sleeps = Sleeps()
+ let model = PairingModel(accounts: DeviceAccounts(store: MemorySecretStore()), makeTransport: { _ in t }, sleep: sleeps.sleep)
+ await model.run(origin: t.origin, label: "Test")
+ #expect(!sleeps.waits.isEmpty)
+ #expect(sleeps.waits.allSatisfy { $0 == .seconds(5) })
+ }
+
@Test func expiredChallengeStops() async throws {
let t = ScriptedTransport()
t.on("POST /auth/devices", fixture: "device-challenge")
diff --git a/native/apple/Tests/EquipoKitTests/SessionTests.swift b/native/apple/Tests/EquipoKitTests/SessionTests.swift
index 325c3569..bb645b9c 100644
--- a/native/apple/Tests/EquipoKitTests/SessionTests.swift
+++ b/native/apple/Tests/EquipoKitTests/SessionTests.swift
@@ -2,21 +2,24 @@ import Foundation
import Testing
@testable import EquipoKit
-@MainActor private func paired(_ t: ScriptedTransport, store: MemorySecretStore = MemorySecretStore(), defaults: UserDefaults? = nil) throws -> EquipoSession {
+@MainActor private func paired(_ t: ScriptedTransport, store: MemorySecretStore = MemorySecretStore()) throws -> EquipoSession {
var account = DeviceAccount.new(origin: t.origin, label: "Test")
account.credential = try Fixture.decode("device-credential")
let accounts = DeviceAccounts(store: store)
try accounts.save(account)
- let d = defaults ?? UserDefaults(suiteName: "equipo-tests-\(UUID().uuidString)")!
- return EquipoSession(account: account, accounts: accounts, transport: t, defaults: d, sleep: { _ in })
+ return EquipoSession(account: account, accounts: accounts, transport: t, sleep: { _ in })
}
+/// The server's own answers, as a device bearer reads them.
private func readable(_ t: ScriptedTransport) {
- t.on("GET /me", fixture: "me"); t.on("GET /projects", fixture: "projects")
- t.on("GET /conversation", fixture: "conversation"); t.on("GET /tasks", fixture: "tasks")
- t.on("GET /needs-you", fixture: "needs-you"); t.on("GET /questions/question-vat", fixture: "question")
+ t.on("GET /snapshot", fixture: "thin/snapshot")
+ t.on("GET /tasks", fixture: "thin/tasks")
+ t.on("GET /needs-you", fixture: "thin/needs-you")
}
+private let waiting = "tkqsrho7oq3n" // Ready to merge, needs you for the merge
+private let merged = "tkyiki7muqby" // Done
+
@MainActor @Suite struct SessionTests {
@Test func refreshFillsEverything() async throws {
let t = ScriptedTransport(); readable(t)
@@ -24,10 +27,12 @@ private func readable(_ t: ScriptedTransport) {
#expect(s.needsYou == nil, "unknown until loaded, never zero")
await s.refresh()
#expect(s.status == .ready)
- #expect(s.messages.map(\.id) == ["message-1", "message-2"])
- #expect(s.needsYou?.map(\.id) == ["task-vat"])
- #expect(s.questions["question-vat"]?.revision == 7)
- #expect(s.project(for: s.tasks[0])?.name == "Equipo")
+ #expect(s.messages.count == 6)
+ #expect(s.needsYou?.map(\.id) == [waiting])
+ #expect(s.tasks.count == 2)
+ #expect(s.cursor == 64)
+ #expect(s.teamName == s.me?.teamName)
+ #expect(s.liveTurn?.state == "running")
#expect(t.requests.allSatisfy { $0.bearer == "equipo.person.v1.TOKENFIXTURE" })
}
@@ -35,13 +40,65 @@ private func readable(_ t: ScriptedTransport) {
let t = ScriptedTransport(); readable(t)
let s = try paired(t); await s.refresh()
let feed = Feed.build(s)
- #expect(feed.map(\.id) == ["message-1", "message-2", "card-vat-report", "card-vat", "card-merge"])
- guard case .question(_, let byline, let q, _) = feed[3] else { Issue.record("not a question"); return }
- #expect(byline.who == .copy)
- #expect(byline.project == "Equipo")
- #expect(byline.time == nil, "the API gives cards no time")
- #expect(q?.id == "question-vat")
- guard case .decision = feed[4] else { Issue.record("merges go to the web"); return }
+ var reports: [String: Bool] = [:]
+ var decisions = 0, receipts = 0
+ for item in feed {
+ switch item {
+ case .report(_, let byline, let report, let compact):
+ reports[report.task.id] = compact
+ #expect(byline.time != nil, "cards carry their time")
+ #expect(byline.project == "Woodstar")
+ case .decision: decisions += 1
+ case .receipt(let card, _): receipts += 1; #expect(Feed.receiptLine(card).hasPrefix("Added "))
+ default: break
+ }
+ }
+ #expect(reports[waiting] == true, "a report beside its open decision is one line")
+ #expect(reports[merged] == false)
+ #expect(decisions == 3, "merges go to the web, open or answered")
+ #expect(receipts == 1)
+ guard case .thinking(let turn, _) = feed.last else { Issue.record("the live turn comes last"); return }
+ #expect(turn.state == "running")
+ let times = feed.compactMap { item -> Date? in
+ switch item {
+ case .own(let m), .coordinator(let m): return m.createdAt
+ case .report(let c, _, _, _), .question(let c, _), .decision(let c, _), .receipt(let c, _): return c.createdAt
+ default: return nil
+ }
+ }
+ #expect(times == times.sorted(), "messages and cards interleave by time")
+ }
+
+ @Test func reportsUseTheWebsWords() throws {
+ let tasks: ThinList<ThinTask> = try Fixture.decode("thin/tasks")
+ let ready = TaskReport(try #require(tasks.items?.first { $0.id == waiting }))
+ #expect(ready.tone == .warning)
+ #expect(ready.eyebrow == "Ready to merge")
+ #expect(ready.track.map(\.state) == [.done, .done, .done, .current, .todo])
+ #expect(ready.facts.map(\.label) == ["Checks", "Review", "Branch"])
+ #expect(ready.facts[0].value == "Can’t run here")
+ #expect(ready.facts[0].detail == "Needs macOS")
+ #expect(ready.facts[1].value == "Approved")
+ #expect(ready.facts[1].detail == "same family")
+ #expect(ready.facts[2].detail == "2222222")
+ var failed = ready.task; failed.checks = "failed"
+ #expect(TaskReport(failed).tone == .negative)
+ var merging = ready.task; merging.stage = "merging"
+ #expect(TaskReport(merging).track[3].state == .current)
+ var unknown = ready.task; unknown.checks = "something_new"; unknown.verdict = ""
+ #expect(TaskReport(unknown).facts.map(\.label) == ["Branch"], "a value without words is left out, never invented")
+ #expect(Specialist.coordinator.name == "Coordinator")
+ }
+
+ /// Facts look their words up by a key made from the wire value: each one resolves.
+ @Test func everyFactValueHasWords() {
+ for key in ["checks.passed", "checks.failed", "checks.none", "checks.cannot_run", "checks.running",
+ "checks.needs_macos", "checks.needs_network", "checks.timeout", "checks.unavailable",
+ "review.approve", "review.changes_requested", "review.running",
+ "review.other_family", "review.same_family", "review.same_account"] {
+ #expect(EquipoStrings.text(.init(key)) != key, "no words for \(key)")
+ }
+ #expect(TaskReport.known.allSatisfy { EquipoStrings.text(.init($0)) != $0 })
}
@Test func coordinatorIsUnnamedOnScreen() {
@@ -50,90 +107,120 @@ private func readable(_ t: ScriptedTransport) {
#expect(b.spoken.hasPrefix(Specialist.coordinator.name))
}
- @Test func mergeKeepsTheNewerRevision() {
- let old = Message(id: "m", conversationId: "c", threadId: "", authorKind: "coordinator", authorId: "c", body: "old", sequence: 2, revision: 2, createdAt: .now, sources: nil)
- var newer = old; newer.body = "new"; newer.revision = 3
- var stale = old; stale.body = "stale"; stale.revision = 1
- #expect(EquipoSession.merge([old], [newer]).first?.body == "new")
- #expect(EquipoSession.merge([newer], [stale]).first?.body == "new")
+ @Test func mergeKeepsTheNewerRevision() throws {
+ let page: MessagePage = try Fixture.decode("thin/messages")
+ let old = try #require(page.items?.first)
+ var newer = old; newer.text = "new"; newer.revision = old.revision + 1
+ var stale = old; stale.text = "stale"; stale.revision = old.revision - 1
+ #expect(EquipoSession.merge([old], [newer]).first?.text == "new")
+ #expect(EquipoSession.merge([newer], [stale]).first?.text == "new")
}
@Test func aLostMessageIsResentAsItself() async throws {
let t = ScriptedTransport(); readable(t)
- t.on("POST /conversation/messages", .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("message"))))
+ t.on("POST /messages", .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/sent"))))
let s = try paired(t)
await s.send("Thanks")
#expect(s.outgoing.first?.state == .waiting)
await s.retry(s.outgoing[0].id)
#expect(s.outgoing.isEmpty)
- let posts = t.sent("POST /conversation/messages")
+ let posts = t.sent("POST /messages")
#expect(posts.count == 2)
#expect(posts[0].idempotencyKey == posts[1].idempotencyKey)
#expect(posts[0].body == posts[1].body)
- #expect(s.messages.contains { $0.id == "message-3" })
+ #expect(s.messages.contains { $0.id == "m_44dpx26rcepdguk24oyk5ovfxx" })
}
- @Test func aChangedQuestionIsNotAnswered() async throws {
+ @Test func aThreadReplyIsResentAsItself() async throws {
let t = ScriptedTransport(); readable(t)
+ t.on("POST /tasks/\(waiting)/thread", .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/thread-entry"))))
let s = try paired(t); await s.refresh()
- var seen = s.questions["question-vat"]!
- seen.revision = 6
- #expect(await s.answer(seen, with: .option("vat")) == .changed)
- #expect(t.sent("POST /questions/question-vat/answer").isEmpty)
+ await s.send("Does this cover the iPad too?", inThreadOf: waiting)
+ #expect(s.outgoing.first?.taskID == waiting)
+ await s.retry(s.outgoing[0].id)
+ let posts = t.sent("POST /tasks/\(waiting)/thread")
+ #expect(posts.count == 2)
+ #expect(posts[0].idempotencyKey == posts[1].idempotencyKey)
+ #expect(posts[0].body == posts[1].body)
+ #expect(s.outgoing.isEmpty)
+ #expect(t.sent("POST /messages").isEmpty, "a thread reply is not a conversation message")
+ }
+
+ @Test func aClosedCardIsNotAnswered() async throws {
+ let t = ScriptedTransport(); readable(t)
+ let s = try paired(t); await s.refresh()
+ let answered = try #require(s.cards.first { $0.kind == "merge" && !$0.isOpen })
+ #expect(await s.answer(answered, choice: "merge") == .changed)
+ #expect(t.sent("POST /cards/\(answered.id)/answer").isEmpty)
}
@Test func aStaleAnswerIsNeverRetried() async throws {
let t = ScriptedTransport(); readable(t)
- t.on("POST /questions/question-vat/answer", status: 409, fixture: "error-revision-conflict")
let s = try paired(t); await s.refresh()
- #expect(await s.answer(s.questions["question-vat"]!, with: .text("VAT, with the rate")) == .changed)
- #expect(t.sent("POST /questions/question-vat/answer").count == 1)
+ let card = try #require(s.cards.first { $0.kind == "merge" && $0.isOpen })
+ t.on("POST /cards/\(card.id)/answer", status: 409, fixture: "thin/card-conflict")
+ #expect(await s.answer(card, choice: "wait_mac") == .changed)
+ #expect(t.sent("POST /cards/\(card.id)/answer").count == 1)
+ #expect(s.cards.first { $0.id == card.id }?.state == "answered", "the card shows as it is now")
}
@Test func answeringSendsTheRevisionSeen() async throws {
let t = ScriptedTransport(); readable(t)
- t.on("POST /questions/question-vat/answer", fixture: "ack")
let s = try paired(t); await s.refresh()
- #expect(await s.answer(s.questions["question-vat"]!, with: .option("vat")) == .answered)
- #expect(t.sent("POST /questions/question-vat/answer").first?.ifMatch == 7)
+ let card = try #require(s.cards.first { $0.kind == "merge" && $0.isOpen })
+ t.on("POST /cards/\(card.id)/answer", fixture: "thin/answered")
+ #expect(await s.answer(card, choice: "wait_mac") == .answered)
+ #expect(t.sent("POST /cards/\(card.id)/answer").first?.ifMatch == card.revision)
+ }
+
+ @Test func aLostAnswerIsResentAsItself() async throws {
+ let t = ScriptedTransport(); readable(t)
+ let s = try paired(t); await s.refresh()
+ let card = try #require(s.cards.first { $0.kind == "merge" && $0.isOpen })
+ t.on("POST /cards/\(card.id)/answer", .failure(.offline), .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/answered"))))
+ #expect(await s.answer(card, choice: "wait_mac") == .answered)
+ let posts = t.sent("POST /cards/\(card.id)/answer")
+ #expect(posts.count == 3)
+ #expect(Set(posts.map(\.idempotencyKey)).count == 1)
+ #expect(Set(posts.compactMap(\.body)).count == 1)
}
@Test func unauthorisedEndsTheSession() async throws {
let t = ScriptedTransport()
- t.on("GET /projects", fixture: "projects"); t.on("GET /conversation", fixture: "conversation")
- t.on("GET /tasks", fixture: "tasks"); t.on("GET /needs-you", fixture: "needs-you")
- t.on("GET /me", .success(APIResponse(status: 401, data: Data(#"{"code":"unauthenticated","copy_key":"api.unauthenticated","request_id":"r"}"#.utf8))))
+ t.on("GET /tasks", fixture: "thin/tasks"); t.on("GET /needs-you", fixture: "thin/needs-you")
+ t.on("GET /snapshot", .success(APIResponse(status: 401, data: Data(#"{"code":"unauthenticated","copy_key":"api.unauthenticated","request_id":"r"}"#.utf8))))
let s = try paired(t); await s.refresh()
#expect(s.status == .signedOut)
}
- @Test func notificationsAreAcknowledgedOnceAndOnlyWhenUnread() async throws {
+ @Test func activityMovesTheThinkingLineWithoutARead() async throws {
let t = ScriptedTransport(); readable(t)
- t.on("POST /notification-subscriptions", fixture: "subscription")
- t.on("GET /notifications", fixture: "notifications")
- t.on("POST /notification-subscriptions/sub_1/ack", fixture: "ack")
- let defaults = UserDefaults(suiteName: "equipo-tests-\(UUID().uuidString)")!
- let s = try paired(t, defaults: defaults)
- await s.pollOnce()
- await s.pollOnce()
- let acks = t.sent("POST /notification-subscriptions/sub_1/ack")
- #expect(acks.count == 2, "the unread one, once per poll it is still unread; never the acknowledged one")
- #expect(acks.allSatisfy { String(decoding: $0.body!, as: UTF8.self).contains("\"n1\"") })
- #expect(acks[0].ifMatch == 1)
- #expect(acks[1].ifMatch == 8, "the revision the last acknowledgement returned")
- #expect(t.sent("POST /notification-subscriptions").count == 1, "one subscription, reused")
- #expect(s.storedSubscription()?.cursor == "c2")
- }
-
- @Test func anExpiredSubscriptionIsReplaced() async throws {
+ let s = try paired(t); await s.refresh()
+ let turn = try #require(s.liveTurn)
+ let reads = t.sent("GET /snapshot").count
+ await s.handle(#"data: {"cursor":70,"type":"activity","resource":"turn","id":"\#(turn.id)","revision":0,"data":{"turn_id":"\#(turn.id)","attempt":1,"kind":"tool","tool":"read_file","repo":"sample","label":"Reading README.md"}}"#)
+ #expect(s.activity[turn.id]?.label == "Reading README.md")
+ guard case .thinking(_, let label) = Feed.build(s).last else { Issue.record("no thinking line"); return }
+ #expect(label == "Reading README.md")
+ await s.handle(#"data: {"cursor":71,"type":"runner","resource":"runner","id":"r","revision":2,"data":{}}"#)
+ await s.handle(": ping")
+ #expect(t.sent("GET /snapshot").count == reads, "activity, runners and pings read nothing")
+ #expect(s.cursor == 71)
+ await s.handle(#"data: {"cursor":72,"type":"card","resource":"card","id":"c","revision":3,"data":{}}"#)
+ #expect(t.sent("GET /snapshot").count == reads + 1, "a card change reads the conversation again")
+ }
+
+ @Test func theStreamResumesAfterItsCursor() async throws {
let t = ScriptedTransport(); readable(t)
- t.on("POST /notification-subscriptions", fixture: "subscription")
- t.on("GET /notifications", .success(APIResponse(status: 410, data: Data(#"{"code":"subscription_expired","copy_key":"api.not_found","request_id":"r"}"#.utf8))), .success(APIResponse(status: 200, data: Fixture.data("notifications"))))
- let s = try paired(t)
- await s.pollOnce()
- #expect(s.storedSubscription() == nil)
- await s.pollOnce()
- #expect(t.sent("POST /notification-subscriptions").count == 2)
+ t.onStream(.success([#"data: {"cursor":80,"type":"message","resource":"message","id":"m","revision":1,"data":{}}"#]))
+ let s = try paired(t); await s.refresh()
+ s.startLive()
+ for _ in 0..<200 where t.sent("GET /events").count < 2 { try await Task.sleep(for: .milliseconds(5)) }
+ s.stopLive()
+ let streams = t.sent("GET /events")
+ #expect(streams.count >= 2)
+ #expect(streams[0].query.first { $0.name == "after" }?.value == "64")
+ #expect(streams[1].query.first { $0.name == "after" }?.value == "80", "a reconnect picks up where the stream left off")
}
@Test func signOutRevokesThenForgets() async throws {
@@ -149,16 +236,19 @@ private func readable(_ t: ScriptedTransport) {
#expect(s.status == .signedOut)
}
- @Test func taskSummaryFromSteps() throws {
- let tasks: Page<EquipoTask> = try Fixture.decode("tasks")
- #expect(TaskSummary(tasks.items[0]).tone == .warning)
- #expect(TaskSummary(tasks.items[0]).specialist == .copy)
- #expect(TaskSummary(tasks.items[1]).specialist == .review)
- // The catalog resolves: a missing key would show the key itself.
- #expect(TaskSummary(tasks.items[1]).label == "Review is working")
- #expect(TaskSummary(tasks.items[0]).label == "Needs you")
- #expect(Specialist.coordinator.name == "Coordinator")
- var failed = tasks.items[1]; failed.steps?[1].state = "failed"
- #expect(TaskSummary(failed).tone == .negative)
+ @Test func threadTurnsKnowWhoSpoke() throws {
+ let entry: ThreadEntry = try Fixture.decode("thin/thread-entry")
+ #expect(ThreadTurn(entry, me: "OWNER@example.com").own)
+ let other = ThreadTurn(entry, me: "someone@example.com")
+ #expect(!other.own); #expect(other.person == "owner@example.com")
+ var equipo = entry; equipo.author = "equipo"
+ #expect(ThreadTurn(equipo, me: "owner@example.com").who == .coordinator)
+ }
+
+ @Test func decisionsOpenAtTheCardOnTheWeb() throws {
+ let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
+ let card = try #require(snapshot.cards?.first { $0.kind == "merge" })
+ let url = Feed.webURL(for: card, origin: URL(string: "https://team.example.test")!)
+ #expect(url.absoluteString == "https://team.example.test/conversation#card-\(card.id)")
}
}
diff --git a/native/apple/Tests/EquipoKitTests/Support.swift b/native/apple/Tests/EquipoKitTests/Support.swift
index 9d478d17..030df1cb 100644
--- a/native/apple/Tests/EquipoKitTests/Support.swift
+++ b/native/apple/Tests/EquipoKitTests/Support.swift
@@ -28,11 +28,26 @@ final class ScriptedTransport: EquipoTransport, @unchecked Sendable {
return try answer.get()
}
func sent(_ route: String) -> [APIRequest] { lock.withLock { requests.filter { $0.method + " " + $0.path == route } } }
+
+ /// Event streams, one per call to `lines`; with none left the stream is refused as offline.
+ private var streams: [Result<[String], EquipoAPIError>] = []
+ func onStream(_ answers: Result<[String], EquipoAPIError>...) { lock.withLock { streams += answers } }
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
+ let next: Result<[String], EquipoAPIError>? = lock.withLock {
+ requests.append(request)
+ return streams.isEmpty ? nil : streams.removeFirst()
+ }
+ let lines = try (next ?? .failure(.offline)).get()
+ return AsyncThrowingStream { c in lines.forEach { c.yield($0) }; c.finish() }
+ }
}
enum Fixture {
+ /// "snapshot" or "thin/snapshot": the thin ones are the server's own answers.
static func data(_ name: String) -> Data {
- let url = Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures")!
+ let parts = name.split(separator: "/").map(String.init)
+ let dir = (["Fixtures"] + parts.dropLast()).joined(separator: "/")
+ let url = Bundle.module.url(forResource: parts.last!, withExtension: "json", subdirectory: dir)!
return try! Data(contentsOf: url)
}
static func decode<T: Decodable>(_ name: String, as: T.Type = T.self) throws -> T {
diff --git a/native/scripts/check-fixtures.py b/native/scripts/check-fixtures.py
index 4e8e4995..104450e0 100755
--- a/native/scripts/check-fixtures.py
+++ b/native/scripts/check-fixtures.py
@@ -1,9 +1,13 @@
#!/usr/bin/env python3
"""Validate the native test fixtures against the person API schema.
-Every fixture under native/apple/Tests/EquipoKitTests/Fixtures is a response
-the API could send: it must match its schema exactly, with no invented
-field. Runs anywhere Python runs; Linux CI included."""
+Every pairing, device and error fixture under
+native/apple/Tests/EquipoKitTests/Fixtures is a response the person API could
+send: it must match its schema exactly, with no invented field. The
+conversation fixtures under Fixtures/thin are the server's own answers,
+captured and strictly decoded into internal/wire by Go
+(internal/thintest TestNativeFixtures), so they are not checked here.
+Runs anywhere Python runs; Linux CI included."""
import json, re, sys
from pathlib import Path
@@ -11,11 +15,8 @@ root = Path(__file__).resolve().parents[2]
spec = json.loads((root / 'docs/api/equipo-v1.openapi.json').read_text())
fixtures = root / 'native/apple/Tests/EquipoKitTests/Fixtures'
contracts = {
- 'me': 'Me', 'projects': 'ProjectPage', 'tasks': 'TaskPage', 'needs-you': 'TaskPage',
- 'conversation': 'ConversationPage', 'thread': 'ConversationPage', 'message': 'Message',
- 'question': 'Question', 'ack': 'Ack', 'device-challenge': 'PersonDeviceChallenge',
+ 'me': 'Me', 'ack': 'Ack', 'device-challenge': 'PersonDeviceChallenge',
'device-credential': 'PersonCredential', 'devices': 'DevicePage',
- 'subscription': 'NotificationSubscription', 'notifications': 'NotificationPage',
'error-revision-conflict': 'Error', 'error-pending': 'Error',
}
diff --git a/native/scripts/check-strings.py b/native/scripts/check-strings.py
index 84ee7257..9a9ebbd2 100755
--- a/native/scripts/check-strings.py
+++ b/native/scripts/check-strings.py
@@ -41,5 +41,8 @@ elif json.loads(catalog_path.read_text()) != catalog():
problems.append('the catalog is out of date: run native/scripts/check-strings.py --write')
for p in problems: print(p)
if problems: sys.exit(1)
-unused = sorted(source.keys() - used_keys())
+# Facts look their words up by a key made from the wire value
+# (TaskReport.facts); FactWordsTests checks each one resolves.
+computed = {k for k in source if k.startswith(('checks.', 'review.'))}
+unused = sorted(source.keys() - used_keys() - computed)
print(f'{len(source)} strings, all used keys present' + (f'; unused: {unused}' if unused else ''))
diff --git a/native/scripts/strings.json b/native/scripts/strings.json
index 679502b0..874201d6 100644
--- a/native/scripts/strings.json
+++ b/native/scripts/strings.json
@@ -20,12 +20,26 @@
"card.failed": "Couldn’t confirm that change. Try again.",
"card.offline": "Couldn’t reach your team, so nothing was sent. Try again.",
"card.open_on_web": "Open in Equipo on the web",
+ "card.question": "Question",
+ "checks.cannot_run": "Can’t run here",
+ "checks.exit %@ %@": "%1$@, exit code %2$@",
+ "checks.failed": "Failed",
+ "checks.needs_macos": "Needs macOS",
+ "checks.needs_network": "Needs network access",
+ "checks.none": "No checks found",
+ "checks.passed": "Passed",
+ "checks.running": "Running",
+ "checks.timeout": "The checks did not finish in time.",
+ "checks.unavailable": "This runner cannot run the checks.",
"chip.needs_you": "Needs you",
"composer.send": "Send",
"conversation.empty": "Say what you want done. Your coordinator picks the project and tells you, and you can change it.",
"conversation.placeholder": "Message",
"decision.on_web": "For now you make this decision on the web, where its full context is.",
"decision.untitled": "A decision",
+ "fact.branch": "Branch",
+ "fact.checks": "Checks",
+ "fact.review": "Review",
"message.coordinator_spoken %@ %@": "Coordinator, %1$@. %2$@",
"message.failed": "Not sent. Try again.",
"message.own_spoken %@": "You said: %@",
@@ -60,10 +74,19 @@
"pairing.welcome_title": "Equipo",
"pairing.your_code": "Your code",
"project.spoken %@": "Project %@",
- "question.answer_placeholder": "Answer",
"question.answered %@": "You answered: %@",
"question.closed": "This question is no longer open.",
- "question.loading": "Loading the question…",
+ "receipt.added %@": "Added %@",
+ "receipt.created %@": "Created %@",
+ "receipt.home %@": "New projects go to %@",
+ "receipt.home_cleared": "New projects go to the best-fitting existing repository",
+ "receipt.working %@": "Working in %@",
+ "review.approve": "Approved",
+ "review.changes_requested": "Changes requested",
+ "review.other_family": "another model family",
+ "review.running": "Reviewing",
+ "review.same_account": "same family, same account",
+ "review.same_family": "same family",
"settings.not_paired": "Pair this Mac with a team to see its settings.",
"specialist.checks": "Checks",
"specialist.coordinator": "Coordinator",
@@ -72,37 +95,44 @@
"specialist.engineering": "Engineering",
"specialist.research": "Research",
"specialist.review": "Review",
+ "stage.cancelled": "Cancelled",
+ "stage.done": "Done",
+ "stage.in_progress": "In progress",
+ "stage.in_review": "In review",
+ "stage.noted": "Noted",
+ "stage.ready_to_merge": "Ready to merge",
+ "step.cancelled": "Cancelled",
+ "step.done": "Done",
+ "step.failed": "Stopped",
+ "step.queued": "Queued",
+ "step.running": "Running",
"tab.conversation": "Conversation",
"tab.needs": "Needs you",
"tab.tasks": "Tasks",
- "task.cancelled": "Cancelled",
- "task.done": "Done",
+ "task.brief": "What was asked",
"task.hide_talk": "Hide the talk",
"task.inspector": "Show or hide the task",
"task.missing": "This task is not available.",
- "task.needs_you": "Needs you",
"task.none_selected": "Choose a task to see it here.",
- "task.not_started": "Not started",
+ "task.open": "Open the task",
"task.open_hint": "Opens the task",
"task.open_web": "Open on the web",
"task.reply": "Reply",
- "task.step_failed %@": "%@ stopped",
- "task.step_running %@": "%@ is working",
- "task.step_waiting %@": "%@ is waiting",
"task.steps": "Steps",
"task.talk": "Talk about this",
"task.thread_empty": "Nothing has been said about this task yet.",
"task.title": "Task",
- "task.usage": "Used so far",
"tasks.empty": "Tasks you and your team ask for appear here.",
"tasks.empty_title": "No tasks yet",
"tasks.finished": "Finished",
"tasks.in_progress": "In progress",
"tasks.needs_you": "Needs you",
+ "thinking.stop": "Stop",
+ "thinking.stopping": "Stopping…",
+ "thinking.working": "Working…",
"thread.own_spoken %@": "You said: %@. Sent",
"thread.reading %@": "%@ is reading",
"thread.sent": "Sent",
- "usage.calls": "Calls",
- "usage.tokens_in": "Tokens in",
- "usage.tokens_out": "Tokens out"
+ "track.position %@ %@": "%1$@ of %2$@",
+ "track.spoken %@": "Stage: %@"
}