fix(ios): polish native daily flows
This commit is contained in:
29 files changed
+2614
-238
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -100,3 +100,8 @@ public struct AssetCreateURLResult: Codable, Equatable, Sendable {
|
||||
/// Unix epoch milliseconds from the server contract.
|
||||
public let expiresAt: Double
|
||||
}
|
||||
|
||||
public struct ResolvedAssetURL: Equatable, Sendable {
|
||||
public let url: URL
|
||||
public let expiresAt: Date
|
||||
}
|
||||
@@ -17,20 +17,6 @@ public struct TokenExchangeResult: Decodable, Sendable {
|
||||
}
|
||||
|
||||
public actor PairingService {
|
||||
public static let standardScopes = [
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
// Startup pairing credentials carry administrative access. Requesting
|
||||
// these scopes preserves that access for native multi-device
|
||||
// management; ordinary pairing links remain bounded by the scopes the
|
||||
// server granted them.
|
||||
"access:read",
|
||||
"access:write",
|
||||
"relay:read",
|
||||
]
|
||||
|
||||
private let transport: any HTTPTransport
|
||||
private let environmentStore: EnvironmentStore
|
||||
private let credentialStore: any CredentialStore
|
||||
@@ -124,7 +110,6 @@ public actor PairingService {
|
||||
name: "requested_token_type",
|
||||
value: "urn:ietf:params:oauth:token-type:access_token"
|
||||
),
|
||||
URLQueryItem(name: "scope", value: Self.standardScopes.joined(separator: " ")),
|
||||
URLQueryItem(name: "client_device_type", value: "mobile"),
|
||||
URLQueryItem(name: "client_os", value: "iOS"),
|
||||
]
|
||||
|
||||
@@ -9,12 +9,16 @@ public actor T3Client {
|
||||
environment: Environment,
|
||||
credentialStore: any CredentialStore,
|
||||
httpTransport: any HTTPTransport = URLSessionHTTPTransport(),
|
||||
webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector()
|
||||
webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector(),
|
||||
rpcConnectionWaitTimeout: Duration = .seconds(4)
|
||||
) {
|
||||
self.environment = environment
|
||||
let api = EnvironmentAPI(transport: httpTransport, credentials: credentialStore)
|
||||
self.api = api
|
||||
self.rpc = WebSocketRPCClient(connector: webSocketConnector) {
|
||||
self.rpc = WebSocketRPCClient(
|
||||
connector: webSocketConnector,
|
||||
connectionWaitTimeout: rpcConnectionWaitTimeout
|
||||
) {
|
||||
let ticket = try await api.webSocketTicket(for: environment)
|
||||
var components = URLComponents(
|
||||
url: environment.webSocketBaseURL,
|
||||
@@ -40,6 +44,10 @@ public actor T3Client {
|
||||
await rpc.stop()
|
||||
}
|
||||
|
||||
public func liveConnectionActive() async -> Bool {
|
||||
await rpc.isConnected()
|
||||
}
|
||||
|
||||
public func shellSnapshot() async throws -> OrchestrationShellSnapshot {
|
||||
try await api.shellSnapshot(for: environment)
|
||||
}
|
||||
@@ -48,6 +56,13 @@ public actor T3Client {
|
||||
try await api.readModel(for: environment)
|
||||
}
|
||||
|
||||
public func archivedShellSnapshot() async throws -> OrchestrationShellSnapshot {
|
||||
try await rpc.request(
|
||||
RPCMethod.getArchivedShellSnapshot.rawValue,
|
||||
as: OrchestrationShellSnapshot.self
|
||||
)
|
||||
}
|
||||
|
||||
public func threadSnapshot(id: String) async throws -> OrchestrationThreadDetailSnapshot {
|
||||
try await api.threadSnapshot(id: id, environment: environment)
|
||||
}
|
||||
@@ -145,7 +160,16 @@ public actor T3Client {
|
||||
|
||||
@discardableResult
|
||||
public func dispatch(_ command: JSONValue) async throws -> DispatchResult {
|
||||
try await api.dispatch(command, environment: environment)
|
||||
guard await rpc.isConnected() else {
|
||||
return try await api.dispatch(command, environment: environment)
|
||||
}
|
||||
do {
|
||||
return try await dispatchOverWebSocket(command)
|
||||
} catch RPCError.connectionUnavailable {
|
||||
// The request provably never crossed the socket, so HTTP is a safe
|
||||
// fallback without risking duplicate side effects.
|
||||
return try await api.dispatch(command, environment: environment)
|
||||
}
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
@@ -155,7 +179,10 @@ public actor T3Client {
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: InteractionMode = .default,
|
||||
model: ModelSelection? = nil,
|
||||
attachments: [UploadChatImageAttachment] = []
|
||||
attachments: [UploadChatImageAttachment] = [],
|
||||
commandID: String = UUID().uuidString,
|
||||
messageID: String = UUID().uuidString,
|
||||
createdAt: String = OrchestrationCommands.now()
|
||||
) async throws -> DispatchResult {
|
||||
try await dispatch(
|
||||
try OrchestrationCommands.sendTurn(
|
||||
@@ -164,7 +191,10 @@ public actor T3Client {
|
||||
runtimeMode: runtimeMode,
|
||||
interactionMode: interactionMode,
|
||||
model: model,
|
||||
attachments: attachments
|
||||
attachments: attachments,
|
||||
commandID: commandID,
|
||||
messageID: messageID,
|
||||
createdAt: createdAt
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -194,8 +224,8 @@ public actor T3Client {
|
||||
)
|
||||
}
|
||||
|
||||
/// Atomically creates a thread and starts its first turn. This is the
|
||||
/// server-supported path for message-first thread creation.
|
||||
/// Creates a thread and starts its first turn through the server-supported
|
||||
/// message-first bootstrap path.
|
||||
@discardableResult
|
||||
public func createThreadAndSend(
|
||||
threadID: String = UUID().uuidString,
|
||||
@@ -207,9 +237,12 @@ public actor T3Client {
|
||||
interactionMode: InteractionMode = .default,
|
||||
branch: String? = nil,
|
||||
worktreePath: String? = nil,
|
||||
attachments: [UploadChatImageAttachment] = []
|
||||
attachments: [UploadChatImageAttachment] = [],
|
||||
commandID: String = UUID().uuidString,
|
||||
messageID: String = UUID().uuidString,
|
||||
createdAt: String = OrchestrationCommands.now()
|
||||
) async throws -> DispatchResult {
|
||||
try await dispatch(
|
||||
try await dispatchOverWebSocket(
|
||||
try OrchestrationCommands.createThreadAndSend(
|
||||
threadID: threadID,
|
||||
projectID: projectID,
|
||||
@@ -220,11 +253,22 @@ public actor T3Client {
|
||||
interactionMode: interactionMode,
|
||||
branch: branch,
|
||||
worktreePath: worktreePath,
|
||||
attachments: attachments
|
||||
attachments: attachments,
|
||||
commandID: commandID,
|
||||
messageID: messageID,
|
||||
createdAt: createdAt
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func dispatchOverWebSocket(_ command: JSONValue) async throws -> DispatchResult {
|
||||
try await rpc.request(
|
||||
RPCMethod.dispatchCommand.rawValue,
|
||||
payload: command,
|
||||
as: DispatchResult.self
|
||||
)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func createProject(
|
||||
projectID: String = UUID().uuidString,
|
||||
@@ -408,6 +452,10 @@ public actor T3Client {
|
||||
}
|
||||
|
||||
public func resolvedAssetURL(resource: AssetResource) async throws -> URL {
|
||||
try await resolvedAsset(resource: resource).url
|
||||
}
|
||||
|
||||
public func resolvedAsset(resource: AssetResource) async throws -> ResolvedAssetURL {
|
||||
let result = try await createAssetURL(resource: resource)
|
||||
guard let url = URL(
|
||||
string: result.relativeUrl,
|
||||
@@ -415,7 +463,10 @@ public actor T3Client {
|
||||
)?.absoluteURL else {
|
||||
throw RPCError.protocolViolation("The server returned an invalid asset URL.")
|
||||
}
|
||||
return url
|
||||
return ResolvedAssetURL(
|
||||
url: url,
|
||||
expiresAt: Date(timeIntervalSince1970: result.expiresAt / 1_000)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: VCS and source control
|
||||
@@ -881,12 +932,12 @@ public actor EnvironmentRuntime {
|
||||
throw RPCError.remote("Environment \(id) is not saved.")
|
||||
}
|
||||
try await environmentStore.setActiveEnvironment(id: id)
|
||||
return client(for: environment)
|
||||
return await client(for: environment)
|
||||
}
|
||||
|
||||
public func activeClient() async throws -> T3Client? {
|
||||
guard let environment = try await activeEnvironment() else { return nil }
|
||||
return client(for: environment)
|
||||
return await client(for: environment)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
@@ -898,7 +949,7 @@ public actor EnvironmentRuntime {
|
||||
)
|
||||
let environment = try await service.pair(url: url, label: clientLabel)
|
||||
try await environmentStore.setActiveEnvironment(id: environment.id)
|
||||
return client(for: environment)
|
||||
return await client(for: environment)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
@@ -914,7 +965,7 @@ public actor EnvironmentRuntime {
|
||||
)
|
||||
let environment = try await service.pair(host: host, code: code, label: clientLabel)
|
||||
try await environmentStore.setActiveEnvironment(id: environment.id)
|
||||
return client(for: environment)
|
||||
return await client(for: environment)
|
||||
}
|
||||
|
||||
public func remove(id: String) async throws {
|
||||
@@ -925,8 +976,14 @@ public actor EnvironmentRuntime {
|
||||
try await environmentStore.remove(id: id)
|
||||
}
|
||||
|
||||
private func client(for environment: Environment) -> T3Client {
|
||||
if let existing = clients[environment.id] { return existing }
|
||||
private func client(for environment: Environment) async -> T3Client {
|
||||
if let existing = clients[environment.id] {
|
||||
if existing.environment == environment {
|
||||
return existing
|
||||
}
|
||||
clients.removeValue(forKey: environment.id)
|
||||
await existing.disconnect()
|
||||
}
|
||||
let client = T3Client(
|
||||
environment: environment,
|
||||
credentialStore: credentialStore,
|
||||
@@ -942,6 +999,7 @@ public enum RPCMethod: String, Sendable {
|
||||
case serverProbe = "server.probe"
|
||||
case serverGetConfig = "server.getConfig"
|
||||
case dispatchCommand = "orchestration.dispatchCommand"
|
||||
case getArchivedShellSnapshot = "orchestration.getArchivedShellSnapshot"
|
||||
case subscribeShell = "orchestration.subscribeShell"
|
||||
case subscribeThread = "orchestration.subscribeThread"
|
||||
case projectsListEntries = "projects.listEntries"
|
||||
@@ -1097,6 +1155,8 @@ public enum OrchestrationCommands {
|
||||
"text": .string(text),
|
||||
"attachments": .array(attachments.map(\.jsonValue)),
|
||||
]),
|
||||
"modelSelection": try .encode(model),
|
||||
"titleSeed": .string(title),
|
||||
"runtimeMode": .string(runtimeMode.rawValue),
|
||||
"interactionMode": .string(interactionMode.rawValue),
|
||||
"bootstrap": .object(["createThread": .object(create)]),
|
||||
|
||||
@@ -90,12 +90,15 @@ private actor URLSessionWebSocketConnection: WebSocketConnection {
|
||||
}
|
||||
|
||||
public enum RPCError: LocalizedError, Sendable {
|
||||
case connectionUnavailable
|
||||
case disconnected
|
||||
case remote(String)
|
||||
case protocolViolation(String)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .connectionUnavailable:
|
||||
"The live command connection is unavailable."
|
||||
case .disconnected: "The environment disconnected."
|
||||
case let .remote(message): message
|
||||
case let .protocolViolation(message): message
|
||||
@@ -164,6 +167,7 @@ public actor WebSocketRPCClient {
|
||||
|
||||
private let connector: any WebSocketConnecting
|
||||
private let endpointProvider: EndpointProvider
|
||||
private let connectionWaitTimeout: Duration
|
||||
private var connection: (any WebSocketConnection)?
|
||||
private var loopTask: Task<Void, Never>?
|
||||
private var keepaliveTask: Task<Void, Never>?
|
||||
@@ -175,9 +179,11 @@ public actor WebSocketRPCClient {
|
||||
|
||||
public init(
|
||||
connector: any WebSocketConnecting = URLSessionWebSocketConnector(),
|
||||
connectionWaitTimeout: Duration = .seconds(4),
|
||||
endpointProvider: @escaping EndpointProvider
|
||||
) {
|
||||
self.connector = connector
|
||||
self.connectionWaitTimeout = connectionWaitTimeout
|
||||
self.endpointProvider = endpointProvider
|
||||
}
|
||||
|
||||
@@ -192,6 +198,10 @@ public actor WebSocketRPCClient {
|
||||
loopTask = Task { await self.connectionLoop() }
|
||||
}
|
||||
|
||||
public func isConnected() -> Bool {
|
||||
connection != nil
|
||||
}
|
||||
|
||||
public func stop() async {
|
||||
desired = false
|
||||
loopTask?.cancel()
|
||||
@@ -281,6 +291,15 @@ public actor WebSocketRPCClient {
|
||||
if connection != nil {
|
||||
Task { await self.sendUnary(id) }
|
||||
}
|
||||
let timeout = connectionWaitTimeout
|
||||
Task { [weak self] in
|
||||
do {
|
||||
try await Task.sleep(for: timeout)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await self?.failUnaryIfUnsent(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,8 +375,7 @@ public actor WebSocketRPCClient {
|
||||
try await sendControl("Ack", requestID: requestID)
|
||||
case "Exit":
|
||||
guard let requestID = response.requestId, let exit = response.exit else { return }
|
||||
if var request = unary.removeValue(forKey: requestID) {
|
||||
request.sent = false
|
||||
if let request = unary.removeValue(forKey: requestID) {
|
||||
if exit._tag == "Success" {
|
||||
request.resume(.success(exit.value ?? .null))
|
||||
} else {
|
||||
@@ -380,13 +398,18 @@ public actor WebSocketRPCClient {
|
||||
|
||||
private func sendUnary(_ id: Int) async {
|
||||
guard let connection, var request = unary[id], !request.sent else { return }
|
||||
// Actor methods are reentrant at the send below. Record that this
|
||||
// command crossed the socket boundary first so a concurrent
|
||||
// disconnect fails it instead of replaying an ambiguous mutation.
|
||||
request.sent = true
|
||||
unary[id] = request
|
||||
do {
|
||||
try await connection.send(JSONEncoder.t3.encode(request.envelope))
|
||||
request.sent = true
|
||||
unary[id] = request
|
||||
} catch {
|
||||
request.resume(.failure(error))
|
||||
unary.removeValue(forKey: id)
|
||||
// A response, disconnect, or stop may have completed the request
|
||||
// while send was suspended. Only its current owner may resume it.
|
||||
guard let failed = unary.removeValue(forKey: id) else { return }
|
||||
failed.resume(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,6 +464,12 @@ public actor WebSocketRPCClient {
|
||||
}
|
||||
}
|
||||
|
||||
private func failUnaryIfUnsent(_ id: Int) {
|
||||
guard let request = unary[id], !request.sent else { return }
|
||||
unary.removeValue(forKey: id)
|
||||
request.resume(.failure(RPCError.connectionUnavailable))
|
||||
}
|
||||
|
||||
private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError {
|
||||
let value = exit.cause?.first?.error
|
||||
let message = value?["message"]?.stringValue
|
||||
|
||||
@@ -47,6 +47,9 @@ struct FeatureComposerView: View {
|
||||
.padding(.trailing, 7)
|
||||
.padding(.bottom, 7)
|
||||
.accessibilityLabel(isWorking && textIsEmpty ? "Stop agent" : "Send")
|
||||
.accessibilityIdentifier(
|
||||
isWorking && textIsEmpty ? "thread-stop" : "message-send"
|
||||
)
|
||||
}
|
||||
.background(T3Colors.input, in: RoundedRectangle(cornerRadius: 18))
|
||||
.overlay {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ImageIO
|
||||
import PhotosUI
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
@@ -37,6 +38,7 @@ struct FeatureImageAttachmentPicker: View {
|
||||
.disabled(!isEnabled || isLoading || attachments.count >= maximumCount)
|
||||
.opacity(isEnabled ? 1 : 0.3)
|
||||
.accessibilityLabel(isLoading ? "Adding images" : "Add images")
|
||||
.accessibilityIdentifier("image-attachment-picker")
|
||||
.accessibilityHint(isEnabled ? "" : "The selected model does not accept images")
|
||||
.onChange(of: selection) {
|
||||
loadSelection()
|
||||
@@ -67,12 +69,13 @@ struct FeatureImageAttachmentPicker: View {
|
||||
guard let data = try await item.loadTransferable(type: Data.self) else {
|
||||
continue
|
||||
}
|
||||
let type = item.supportedContentTypes.first ?? .jpeg
|
||||
let attachment = try FeatureImageProcessor.attachment(
|
||||
from: data,
|
||||
sourceType: type,
|
||||
ordinal: attachments.count + 1
|
||||
)
|
||||
let ordinal = attachments.count + 1
|
||||
let attachment = try await Task.detached(priority: .userInitiated) {
|
||||
try FeatureImageProcessor.attachment(
|
||||
from: data,
|
||||
ordinal: ordinal
|
||||
)
|
||||
}.value
|
||||
attachments.append(attachment)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
@@ -107,11 +110,12 @@ struct FeatureAttachmentStrip: View {
|
||||
private struct FeatureAttachmentThumbnail: View {
|
||||
let attachment: FeatureDraftAttachment
|
||||
let onRemove: () -> Void
|
||||
@State private var image: UIImage?
|
||||
|
||||
var body: some View {
|
||||
ZStack(alignment: .topTrailing) {
|
||||
Group {
|
||||
if let image = UIImage(data: attachment.data) {
|
||||
if let image {
|
||||
Image(uiImage: image)
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
@@ -130,12 +134,23 @@ private struct FeatureAttachmentThumbnail: View {
|
||||
.foregroundStyle(.white)
|
||||
.frame(width: 22, height: 22)
|
||||
.background(.black.opacity(0.78), in: Circle())
|
||||
.frame(
|
||||
width: T3Metrics.minimumTapTarget,
|
||||
height: T3Metrics.minimumTapTarget
|
||||
)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.offset(x: 5, y: -5)
|
||||
.offset(x: 11, y: -11)
|
||||
.accessibilityLabel("Remove \(attachment.filename)")
|
||||
}
|
||||
.padding(.top, 5)
|
||||
.padding(.trailing, 5)
|
||||
.padding(.top, 11)
|
||||
.padding(.trailing, 11)
|
||||
.task(id: attachment.id) {
|
||||
let data = attachment.thumbnailData ?? attachment.data
|
||||
image = await Task.detached(priority: .utility) {
|
||||
UIImage(data: data)
|
||||
}.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,15 +160,25 @@ enum FeatureImageProcessor {
|
||||
|
||||
static func attachment(
|
||||
from sourceData: Data,
|
||||
sourceType _: UTType,
|
||||
ordinal: Int
|
||||
) throws -> FeatureDraftAttachment {
|
||||
guard let sourceImage = UIImage(data: sourceData) else {
|
||||
guard let source = CGImageSourceCreateWithData(sourceData as CFData, nil),
|
||||
let image = CGImageSourceCreateThumbnailAtIndex(
|
||||
source,
|
||||
0,
|
||||
[
|
||||
kCGImageSourceCreateThumbnailFromImageAlways: true,
|
||||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||||
kCGImageSourceThumbnailMaxPixelSize: maximumDimension,
|
||||
kCGImageSourceShouldCacheImmediately: true,
|
||||
] as CFDictionary
|
||||
) else {
|
||||
throw FeatureImageAttachmentError.invalidImage
|
||||
}
|
||||
|
||||
let image = resized(sourceImage)
|
||||
guard let data = image.jpegData(compressionQuality: 0.82) else {
|
||||
let preparedImage = UIImage(cgImage: image)
|
||||
guard let data = preparedImage.jpegData(compressionQuality: 0.82),
|
||||
let thumbnailData = thumbnail(from: preparedImage) else {
|
||||
throw FeatureImageAttachmentError.encodingFailed
|
||||
}
|
||||
guard data.count <= maximumEncodedBytes else {
|
||||
@@ -162,20 +187,25 @@ enum FeatureImageProcessor {
|
||||
|
||||
return FeatureDraftAttachment(
|
||||
data: data,
|
||||
thumbnailData: thumbnailData,
|
||||
filename: "Image \(ordinal).jpg",
|
||||
mimeType: "image/jpeg"
|
||||
)
|
||||
}
|
||||
|
||||
private static func resized(_ image: UIImage) -> UIImage {
|
||||
private static func thumbnail(from image: UIImage) -> Data? {
|
||||
let longestSide = max(image.size.width, image.size.height)
|
||||
guard longestSide > maximumDimension else { return image }
|
||||
let scale = maximumDimension / longestSide
|
||||
let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
|
||||
let renderer = UIGraphicsImageRenderer(size: size)
|
||||
let scale = min(1, 160 / longestSide)
|
||||
let size = CGSize(
|
||||
width: max(1, image.size.width * scale),
|
||||
height: max(1, image.size.height * scale)
|
||||
)
|
||||
let format = UIGraphicsImageRendererFormat()
|
||||
format.scale = 1
|
||||
let renderer = UIGraphicsImageRenderer(size: size, format: format)
|
||||
return renderer.image { _ in
|
||||
image.draw(in: CGRect(origin: .zero, size: size))
|
||||
}
|
||||
}.jpegData(compressionQuality: 0.72)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ public struct ThreadDetailView: View {
|
||||
}
|
||||
.task(id: thread.id) {
|
||||
isLoading = true
|
||||
_ = await model.detail(for: thread.id)
|
||||
_ = await model.detail(for: thread.id, force: true)
|
||||
selection = currentSelection
|
||||
isLoading = false
|
||||
}
|
||||
@@ -233,9 +233,12 @@ public struct ThreadDetailView: View {
|
||||
.padding(.top, 14)
|
||||
.padding(.bottom, 10)
|
||||
}
|
||||
.defaultScrollAnchor(.bottom)
|
||||
.scrollDismissesKeyboard(.interactively)
|
||||
.onChange(of: detail.messages.count) {
|
||||
.task(id: thread.id) {
|
||||
await Task.yield()
|
||||
proxy.scrollTo("timeline-bottom", anchor: .bottom)
|
||||
}
|
||||
.onChange(of: detail.messages.last?.id) {
|
||||
withAnimation(.easeOut(duration: 0.18)) {
|
||||
proxy.scrollTo("timeline-bottom", anchor: .bottom)
|
||||
}
|
||||
@@ -279,8 +282,17 @@ public struct ThreadDetailView: View {
|
||||
)
|
||||
)
|
||||
if !sent {
|
||||
draft = message
|
||||
attachments = pendingAttachments
|
||||
let currentDraft = draft
|
||||
let restoredMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if currentDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
draft = message
|
||||
} else if !restoredMessage.isEmpty {
|
||||
draft = "\(message)\n\(currentDraft)"
|
||||
}
|
||||
let pendingIDs = Set(pendingAttachments.map(\.id))
|
||||
attachments = pendingAttachments + attachments.filter {
|
||||
!pendingIDs.contains($0.id)
|
||||
}
|
||||
sendFailed = true
|
||||
}
|
||||
isSending = false
|
||||
@@ -414,7 +426,8 @@ struct FeatureMessageView: View {
|
||||
.background(Color.white.opacity(0.11), in: RoundedRectangle(cornerRadius: 15))
|
||||
}
|
||||
.accessibilityLabel("You")
|
||||
.accessibilityValue(message.text)
|
||||
.accessibilityValue(accessibilityValue)
|
||||
.accessibilityIdentifier("message-\(message.id)")
|
||||
case .assistant:
|
||||
VStack(alignment: .leading, spacing: 7) {
|
||||
HStack(spacing: 6) {
|
||||
@@ -431,6 +444,7 @@ struct FeatureMessageView: View {
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.accessibilityIdentifier("message-\(message.id)")
|
||||
case .tool:
|
||||
DisclosureGroup {
|
||||
Text(message.text)
|
||||
@@ -444,17 +458,30 @@ struct FeatureMessageView: View {
|
||||
}
|
||||
.padding(11)
|
||||
.background(Color.white.opacity(0.055), in: RoundedRectangle(cornerRadius: 10))
|
||||
.accessibilityIdentifier("message-\(message.id)")
|
||||
case .system:
|
||||
Text(message.text)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .center)
|
||||
.accessibilityIdentifier("message-\(message.id)")
|
||||
}
|
||||
}
|
||||
|
||||
private var accessibilityValue: String {
|
||||
let attachmentSummary = message.attachments.isEmpty
|
||||
? ""
|
||||
: "\(message.attachments.count) image attachment"
|
||||
+ (message.attachments.count == 1 ? "" : "s")
|
||||
return [message.text, attachmentSummary]
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
}
|
||||
|
||||
private struct FeatureMessageAttachmentsView: View {
|
||||
let attachments: [FeatureMessageAttachment]
|
||||
@State private var previewedAttachment: FeatureMessageAttachment?
|
||||
|
||||
var body: some View {
|
||||
if !attachments.isEmpty {
|
||||
@@ -466,19 +493,62 @@ private struct FeatureMessageAttachmentsView: View {
|
||||
spacing: 7
|
||||
) {
|
||||
ForEach(attachments) { attachment in
|
||||
HStack(spacing: 9) {
|
||||
Image(systemName: attachment.mimeType.hasPrefix("image/") ? "photo" : "doc")
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
if attachment.mimeType.hasPrefix("image/") {
|
||||
Group {
|
||||
if let url = attachment.url {
|
||||
AsyncImage(url: url) { phase in
|
||||
switch phase {
|
||||
case let .success(image):
|
||||
image
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
case .failure:
|
||||
attachmentPlaceholder(
|
||||
systemImage: "exclamationmark.triangle"
|
||||
)
|
||||
case .empty:
|
||||
attachmentPlaceholder(systemImage: "photo")
|
||||
@unknown default:
|
||||
attachmentPlaceholder(systemImage: "photo")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
attachmentPlaceholder(systemImage: "photo")
|
||||
}
|
||||
}
|
||||
.frame(height: 160)
|
||||
.frame(maxWidth: .infinity)
|
||||
.background(T3Colors.surfaceRaised)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
|
||||
HStack(spacing: 9) {
|
||||
Image(
|
||||
systemName: attachment.mimeType.hasPrefix("image/")
|
||||
? "photo"
|
||||
: "doc"
|
||||
)
|
||||
.font(.system(size: 16, weight: .medium))
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
.frame(width: 30, height: 30)
|
||||
.background(T3Colors.surfaceRaised, in: RoundedRectangle(cornerRadius: 6))
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(attachment.name)
|
||||
.font(.caption.weight(.medium))
|
||||
.lineLimit(1)
|
||||
Text(ByteCountFormatter.string(fromByteCount: Int64(attachment.sizeBytes), countStyle: .file))
|
||||
.background(
|
||||
T3Colors.surfaceRaised,
|
||||
in: RoundedRectangle(cornerRadius: 6)
|
||||
)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(attachment.name)
|
||||
.font(.caption.weight(.medium))
|
||||
.lineLimit(1)
|
||||
Text(
|
||||
ByteCountFormatter.string(
|
||||
fromByteCount: Int64(attachment.sizeBytes),
|
||||
countStyle: .file
|
||||
)
|
||||
)
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
@@ -488,10 +558,100 @@ private struct FeatureMessageAttachmentsView: View {
|
||||
.stroke(T3Colors.border, lineWidth: 1)
|
||||
}
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityLabel(
|
||||
attachment.mimeType.hasPrefix("image/")
|
||||
? "Image attachment"
|
||||
: "File attachment"
|
||||
)
|
||||
.accessibilityValue(attachmentAccessibilityValue(attachment))
|
||||
.accessibilityIdentifier("attachment-\(attachment.id)")
|
||||
.accessibilityAddTraits(
|
||||
attachment.mimeType.hasPrefix("image/") && attachment.url != nil
|
||||
? .isButton
|
||||
: []
|
||||
)
|
||||
.accessibilityHint(
|
||||
attachment.mimeType.hasPrefix("image/") && attachment.url != nil
|
||||
? "Opens full-screen preview"
|
||||
: ""
|
||||
)
|
||||
.accessibilityAction {
|
||||
if attachment.mimeType.hasPrefix("image/"), attachment.url != nil {
|
||||
previewedAttachment = attachment
|
||||
}
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture {
|
||||
if attachment.mimeType.hasPrefix("image/"), attachment.url != nil {
|
||||
previewedAttachment = attachment
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.fullScreenCover(item: $previewedAttachment) { attachment in
|
||||
FeatureAttachmentPreview(attachment: attachment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func attachmentPlaceholder(systemImage: String) -> some View {
|
||||
Image(systemName: systemImage)
|
||||
.font(.system(size: 22, weight: .medium))
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
private func attachmentAccessibilityValue(
|
||||
_ attachment: FeatureMessageAttachment
|
||||
) -> String {
|
||||
let size = ByteCountFormatter.string(
|
||||
fromByteCount: Int64(attachment.sizeBytes),
|
||||
countStyle: .file
|
||||
)
|
||||
return "\(attachment.name), \(size)"
|
||||
}
|
||||
}
|
||||
|
||||
private struct FeatureAttachmentPreview: View {
|
||||
@SwiftUI.Environment(\.dismiss) private var dismiss
|
||||
let attachment: FeatureMessageAttachment
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
ZStack {
|
||||
Color.black.ignoresSafeArea()
|
||||
if let url = attachment.url {
|
||||
AsyncImage(url: url) { phase in
|
||||
switch phase {
|
||||
case let .success(image):
|
||||
image
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
case .failure:
|
||||
ContentUnavailableView(
|
||||
"Image unavailable",
|
||||
systemImage: "exclamationmark.triangle"
|
||||
)
|
||||
case .empty:
|
||||
ProgressView()
|
||||
@unknown default:
|
||||
ProgressView()
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
}
|
||||
}
|
||||
.navigationTitle(attachment.name)
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("Done") { dismiss() }
|
||||
}
|
||||
}
|
||||
.t3NavigationChrome()
|
||||
}
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
}
|
||||
|
||||
struct StreamingStatusView: View {
|
||||
@@ -510,7 +670,7 @@ struct StreamingStatusView: View {
|
||||
.font(.footnote.weight(.semibold))
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityElement(children: .contain)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ public struct ConnectionOnboardingView: View {
|
||||
@State private var showsPermissionAction = false
|
||||
@State private var showingScanner = false
|
||||
@State private var entryHeading = "Connect manually"
|
||||
@State private var connectionTask: Task<Void, Never>?
|
||||
@State private var connectionAttemptID: UUID?
|
||||
@FocusState private var focusedField: ConnectionField?
|
||||
|
||||
public init(
|
||||
@@ -65,6 +67,16 @@ public struct ConnectionOnboardingView: View {
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button("Close", action: onCancel)
|
||||
}
|
||||
} else if stage == .checking {
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button("Cancel") {
|
||||
connectionTask?.cancel()
|
||||
connectionTask = nil
|
||||
connectionAttemptID = nil
|
||||
model.errorMessage = nil
|
||||
stage = .details
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.fullScreenCover(isPresented: $showingScanner) {
|
||||
@@ -95,6 +107,12 @@ public struct ConnectionOnboardingView: View {
|
||||
errorMessage = nil
|
||||
}
|
||||
}
|
||||
.interactiveDismissDisabled(stage == .connecting)
|
||||
.onDisappear {
|
||||
connectionTask?.cancel()
|
||||
connectionTask = nil
|
||||
connectionAttemptID = nil
|
||||
}
|
||||
}
|
||||
|
||||
private var welcomeView: some View {
|
||||
@@ -509,13 +527,17 @@ public struct ConnectionOnboardingView: View {
|
||||
|
||||
@MainActor
|
||||
private func connect(_ action: ConnectionAction) {
|
||||
connectionTask?.cancel()
|
||||
let attemptID = UUID()
|
||||
connectionAttemptID = attemptID
|
||||
endpoint = action.endpoint
|
||||
errorMessage = nil
|
||||
showsPermissionAction = false
|
||||
stage = .checking
|
||||
|
||||
Task {
|
||||
connectionTask = Task {
|
||||
let readiness = await readinessChecker.check(endpoint: action.endpoint)
|
||||
guard !Task.isCancelled, connectionAttemptID == attemptID else { return }
|
||||
switch readiness {
|
||||
case .ready:
|
||||
stage = .connecting
|
||||
@@ -539,14 +561,19 @@ public struct ConnectionOnboardingView: View {
|
||||
await model.activateEnvironment(id)
|
||||
didConnect = model.snapshot.connection.state == .connected
|
||||
}
|
||||
guard !Task.isCancelled, connectionAttemptID == attemptID else { return }
|
||||
|
||||
if didConnect {
|
||||
connectionAttemptID = nil
|
||||
connectionTask = nil
|
||||
stage = .success
|
||||
onConnected()
|
||||
} else {
|
||||
let rawError = model.errorMessage
|
||||
model.errorMessage = nil
|
||||
errorMessage = ConnectionErrorCopy.message(for: rawError)
|
||||
connectionAttemptID = nil
|
||||
connectionTask = nil
|
||||
stage = .details
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,17 @@ public struct DevicesView: View {
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
} else if let errorMessage, sessions.isEmpty {
|
||||
ContentUnavailableView {
|
||||
Label("Couldn’t load devices", systemImage: "exclamationmark.circle")
|
||||
} description: {
|
||||
Text(errorMessage)
|
||||
} actions: {
|
||||
Button("Try again") {
|
||||
Task { await reload() }
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
} else if sessions.isEmpty {
|
||||
ContentUnavailableView {
|
||||
Label("No devices found", systemImage: "laptopcomputer.and.iphone")
|
||||
|
||||
@@ -20,7 +20,9 @@ public final class FeatureRootModel {
|
||||
do {
|
||||
snapshot = try await client.initialSnapshot()
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
isLoading = false
|
||||
|
||||
@@ -33,13 +35,16 @@ public final class FeatureRootModel {
|
||||
do {
|
||||
snapshot = try await client.initialSnapshot()
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func pair(endpoint: String, token: String?) async -> Bool {
|
||||
await perform {
|
||||
try await client.pair(endpoint: endpoint, token: token)
|
||||
details.removeAll()
|
||||
snapshot = try await client.initialSnapshot()
|
||||
}
|
||||
}
|
||||
@@ -78,6 +83,7 @@ public final class FeatureRootModel {
|
||||
title: String?,
|
||||
selection: FeatureSelection?
|
||||
) async -> FeatureThread? {
|
||||
let environment = currentEnvironmentIdentity
|
||||
var created: FeatureThread?
|
||||
let succeeded = await perform {
|
||||
let thread = try await client.createThread(
|
||||
@@ -85,6 +91,9 @@ public final class FeatureRootModel {
|
||||
title: title,
|
||||
selection: selection
|
||||
)
|
||||
guard currentEnvironmentIdentity == environment else {
|
||||
throw CancellationError()
|
||||
}
|
||||
upsert(thread)
|
||||
created = thread
|
||||
}
|
||||
@@ -95,8 +104,9 @@ public final class FeatureRootModel {
|
||||
let prompt = request.trimmedPrompt
|
||||
guard !prompt.isEmpty || !request.attachments.isEmpty else { return nil }
|
||||
|
||||
let environment = currentEnvironmentIdentity
|
||||
var created: FeatureThread?
|
||||
let succeeded = await perform {
|
||||
let succeeded = await perform(reportError: false) {
|
||||
let thread = try await client.createThreadAndSend(
|
||||
projectID: request.projectID,
|
||||
prompt: prompt,
|
||||
@@ -105,6 +115,9 @@ public final class FeatureRootModel {
|
||||
interactionMode: request.interactionMode,
|
||||
attachments: request.attachments.map(\.upload)
|
||||
)
|
||||
guard currentEnvironmentIdentity == environment else {
|
||||
throw CancellationError()
|
||||
}
|
||||
upsert(thread)
|
||||
created = thread
|
||||
}
|
||||
@@ -112,8 +125,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func renameThread(_ id: String, title: String) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.renameThread(id: id, title: title)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
snapshot.threads[index].title = title
|
||||
details[id]?.thread.title = title
|
||||
@@ -121,8 +136,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func setArchived(_ id: String, archived: Bool) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.setThreadArchived(id: id, archived: archived)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
snapshot.threads[index].isArchived = archived
|
||||
details[id]?.thread.isArchived = archived
|
||||
@@ -130,26 +147,39 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func setSettled(_ id: String, settled: Bool) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.setThreadSettled(id: id, settled: settled)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
snapshot.threads[index].isSettled = settled
|
||||
snapshot.threads[index].keepsActive = !settled
|
||||
snapshot.threads[index].settledAt = settled ? .now : nil
|
||||
details[id]?.thread.isSettled = settled
|
||||
details[id]?.thread.keepsActive = !settled
|
||||
details[id]?.thread.settledAt = settled ? .now : nil
|
||||
}
|
||||
}
|
||||
|
||||
public func setSnoozed(_ id: String, until: Date?) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.setThreadSnoozed(id: id, until: until)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
let snoozedAt = until.map { _ in Date.now }
|
||||
snapshot.threads[index].snoozedUntil = until
|
||||
snapshot.threads[index].snoozedAt = snoozedAt
|
||||
details[id]?.thread.snoozedUntil = until
|
||||
details[id]?.thread.snoozedAt = snoozedAt
|
||||
}
|
||||
}
|
||||
|
||||
public func setRuntimeMode(_ id: String, mode: FeatureRuntimeMode) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.setRuntimeMode(id: id, mode: mode)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
snapshot.threads[index].runtimeMode = mode
|
||||
details[id]?.thread.runtimeMode = mode
|
||||
@@ -157,8 +187,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func setInteractionMode(_ id: String, mode: FeatureInteractionMode) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.setInteractionMode(id: id, mode: mode)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return }
|
||||
snapshot.threads[index].interactionMode = mode
|
||||
details[id]?.thread.interactionMode = mode
|
||||
@@ -166,8 +198,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func deleteThread(_ id: String) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.deleteThread(id: id)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
snapshot.threads.removeAll { $0.id == id }
|
||||
details[id] = nil
|
||||
}
|
||||
@@ -177,14 +211,20 @@ public final class FeatureRootModel {
|
||||
if !force, let cached = details[id] {
|
||||
return cached
|
||||
}
|
||||
let environment = currentEnvironmentIdentity
|
||||
do {
|
||||
let detail = try await client.loadThread(id: id)
|
||||
guard currentEnvironmentIdentity == environment else {
|
||||
return details[id]
|
||||
}
|
||||
details[id] = detail
|
||||
upsert(detail.thread)
|
||||
return detail
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
return nil
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
return details[id]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +242,7 @@ public final class FeatureRootModel {
|
||||
let trimmed = submission.text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty || !submission.attachments.isEmpty else { return false }
|
||||
|
||||
let environment = currentEnvironmentIdentity
|
||||
let optimisticID = "local-\(UUID().uuidString)"
|
||||
let optimistic = FeatureMessage(
|
||||
id: optimisticID,
|
||||
@@ -219,7 +260,7 @@ public final class FeatureRootModel {
|
||||
)
|
||||
details[submission.threadID]?.messages.append(optimistic)
|
||||
|
||||
let sent = await perform {
|
||||
let sent = await perform(reportError: false) {
|
||||
try await client.sendMessage(
|
||||
threadID: submission.threadID,
|
||||
text: trimmed,
|
||||
@@ -228,6 +269,7 @@ public final class FeatureRootModel {
|
||||
)
|
||||
}
|
||||
if !sent {
|
||||
guard currentEnvironmentIdentity == environment else { return false }
|
||||
details[submission.threadID]?.messages.removeAll { $0.id == optimisticID }
|
||||
}
|
||||
return sent
|
||||
@@ -240,8 +282,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func resolveApproval(_ id: String, decision: FeatureApprovalDecision) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.resolveApproval(id: id, decision: decision)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
for key in details.keys {
|
||||
details[key]?.approvals.removeAll { $0.id == id }
|
||||
}
|
||||
@@ -249,8 +293,10 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func resolveUserInput(_ id: String, answers: [String: String]) async {
|
||||
let environment = currentEnvironmentIdentity
|
||||
await perform {
|
||||
try await client.resolveUserInput(id: id, answers: answers)
|
||||
guard currentEnvironmentIdentity == environment else { return }
|
||||
for key in details.keys {
|
||||
details[key]?.userInputs.removeAll { $0.id == id }
|
||||
}
|
||||
@@ -265,14 +311,17 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func perform(_ operation: () async throws -> Void) async -> Bool {
|
||||
private func perform(
|
||||
reportError: Bool = true,
|
||||
_ operation: () async throws -> Void
|
||||
) async -> Bool {
|
||||
isPerformingAction = true
|
||||
defer { isPerformingAction = false }
|
||||
do {
|
||||
try await operation()
|
||||
return true
|
||||
} catch {
|
||||
if !Self.isBenignCancellation(error) {
|
||||
if reportError, !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
return false
|
||||
@@ -287,6 +336,17 @@ public final class FeatureRootModel {
|
||||
return message == "cancelled" || message == "canceled"
|
||||
}
|
||||
|
||||
private var currentEnvironmentIdentity: String {
|
||||
let active = snapshot.environments.first(where: \.isActive)
|
||||
return [
|
||||
active?.id,
|
||||
active?.endpoint,
|
||||
snapshot.connection.endpoint,
|
||||
]
|
||||
.compactMap { $0 }
|
||||
.joined(separator: "|")
|
||||
}
|
||||
|
||||
private func apply(_ event: FeatureEvent) {
|
||||
switch event {
|
||||
case let .snapshot(value):
|
||||
|
||||
@@ -11,7 +11,7 @@ public struct FeatureRootView: View {
|
||||
Group {
|
||||
if model.isLoading {
|
||||
FeatureLoadingView()
|
||||
} else if model.snapshot.connection.state == .connected {
|
||||
} else if model.snapshot.connection.state != .disconnected {
|
||||
WorkspaceView(
|
||||
model: model,
|
||||
submitNewTask: { request in
|
||||
|
||||
@@ -46,13 +46,22 @@ public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codab
|
||||
public var name: String
|
||||
public var path: String
|
||||
public var threadCount: Int
|
||||
public var defaultSelection: FeatureSelection?
|
||||
|
||||
public init(id: String, environmentID: String, name: String, path: String, threadCount: Int = 0) {
|
||||
public init(
|
||||
id: String,
|
||||
environmentID: String,
|
||||
name: String,
|
||||
path: String,
|
||||
threadCount: Int = 0,
|
||||
defaultSelection: FeatureSelection? = nil
|
||||
) {
|
||||
self.id = id
|
||||
self.environmentID = environmentID
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.threadCount = threadCount
|
||||
self.defaultSelection = defaultSelection
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +100,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
public var modelOptions: [FeatureModelOptionSelection]
|
||||
public var isArchived: Bool
|
||||
public var isSettled: Bool
|
||||
public var keepsActive: Bool
|
||||
public var settledAt: Date?
|
||||
public var lastActivityAt: Date?
|
||||
public var snoozedUntil: Date?
|
||||
public var snoozedAt: Date?
|
||||
public var attentionAt: Date?
|
||||
public var latestTurnCompletedAt: Date?
|
||||
public var runtimeMode: FeatureRuntimeMode
|
||||
public var interactionMode: FeatureInteractionMode
|
||||
|
||||
@@ -108,7 +123,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
modelOptions: [FeatureModelOptionSelection] = [],
|
||||
isArchived: Bool = false,
|
||||
isSettled: Bool = false,
|
||||
keepsActive: Bool = false,
|
||||
settledAt: Date? = nil,
|
||||
lastActivityAt: Date? = nil,
|
||||
snoozedUntil: Date? = nil,
|
||||
snoozedAt: Date? = nil,
|
||||
attentionAt: Date? = nil,
|
||||
latestTurnCompletedAt: Date? = nil,
|
||||
runtimeMode: FeatureRuntimeMode = .fullAccess,
|
||||
interactionMode: FeatureInteractionMode = .standard
|
||||
) {
|
||||
@@ -124,7 +145,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
self.modelOptions = modelOptions
|
||||
self.isArchived = isArchived
|
||||
self.isSettled = isSettled
|
||||
self.keepsActive = keepsActive
|
||||
self.settledAt = settledAt
|
||||
self.lastActivityAt = lastActivityAt
|
||||
self.snoozedUntil = snoozedUntil
|
||||
self.snoozedAt = snoozedAt
|
||||
self.attentionAt = attentionAt
|
||||
self.latestTurnCompletedAt = latestTurnCompletedAt
|
||||
self.runtimeMode = runtimeMode
|
||||
self.interactionMode = interactionMode
|
||||
}
|
||||
|
||||
@@ -3,17 +3,20 @@ import Foundation
|
||||
public struct FeatureDraftAttachment: Identifiable, Sendable, Equatable {
|
||||
public let id: UUID
|
||||
public var data: Data
|
||||
public var thumbnailData: Data?
|
||||
public var filename: String
|
||||
public var mimeType: String
|
||||
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
data: Data,
|
||||
thumbnailData: Data? = nil,
|
||||
filename: String,
|
||||
mimeType: String
|
||||
) {
|
||||
self.id = id
|
||||
self.data = data
|
||||
self.thumbnailData = thumbnailData
|
||||
self.filename = filename
|
||||
self.mimeType = mimeType
|
||||
}
|
||||
@@ -73,6 +76,7 @@ public struct FeatureMessageSubmission: Sendable, Equatable {
|
||||
|
||||
struct DailyUXSidebarIndex {
|
||||
let active: [FeatureThread]
|
||||
let snoozed: [FeatureThread]
|
||||
let settled: [FeatureThread]
|
||||
let searchResults: [FeatureThread]
|
||||
|
||||
@@ -85,11 +89,11 @@ struct DailyUXSidebarIndex {
|
||||
let projectByID = Dictionary(uniqueKeysWithValues: snapshot.projects.map { ($0.id, $0) })
|
||||
let visible = snapshot.threads.filter { thread in
|
||||
guard !thread.isArchived else { return false }
|
||||
guard thread.snoozedUntil.map({ $0 > now }) != true else { return false }
|
||||
return projectID == nil || thread.projectID == projectID
|
||||
}
|
||||
let available = visible.filter { !$0.isEffectivelySnoozed(at: now) }
|
||||
|
||||
active = visible
|
||||
active = available
|
||||
.filter { !$0.isEffectivelySettled(at: now) }
|
||||
.sorted { lhs, rhs in
|
||||
if lhs.createdAt != rhs.createdAt {
|
||||
@@ -98,11 +102,22 @@ struct DailyUXSidebarIndex {
|
||||
return lhs.id < rhs.id
|
||||
}
|
||||
|
||||
settled = visible
|
||||
snoozed = visible
|
||||
.filter { $0.isEffectivelySnoozed(at: now) }
|
||||
.sorted { lhs, rhs in
|
||||
let lhsUntil = lhs.snoozedUntil ?? .distantFuture
|
||||
let rhsUntil = rhs.snoozedUntil ?? .distantFuture
|
||||
if lhsUntil != rhsUntil {
|
||||
return lhsUntil < rhsUntil
|
||||
}
|
||||
return lhs.id < rhs.id
|
||||
}
|
||||
|
||||
settled = available
|
||||
.filter { $0.isEffectivelySettled(at: now) }
|
||||
.sorted { lhs, rhs in
|
||||
if lhs.updatedAt != rhs.updatedAt {
|
||||
return lhs.updatedAt > rhs.updatedAt
|
||||
if lhs.settledSortDate != rhs.settledSortDate {
|
||||
return lhs.settledSortDate > rhs.settledSortDate
|
||||
}
|
||||
return lhs.id < rhs.id
|
||||
}
|
||||
@@ -113,7 +128,7 @@ struct DailyUXSidebarIndex {
|
||||
return
|
||||
}
|
||||
|
||||
searchResults = (active + settled).filter { thread in
|
||||
searchResults = (active + snoozed + settled).filter { thread in
|
||||
let project = projectByID[thread.projectID]
|
||||
return [
|
||||
thread.title,
|
||||
@@ -132,15 +147,44 @@ extension FeatureThread {
|
||||
|
||||
func isEffectivelySettled(at now: Date) -> Bool {
|
||||
switch state {
|
||||
case .queued, .working, .waitingForApproval, .waitingForInput, .failed:
|
||||
case .queued, .working, .waitingForApproval, .waitingForInput:
|
||||
return false
|
||||
case .idle, .completed:
|
||||
case .idle, .failed, .completed:
|
||||
break
|
||||
}
|
||||
if isSettled {
|
||||
return true
|
||||
}
|
||||
return now.timeIntervalSince(updatedAt) >= 3 * 24 * 60 * 60
|
||||
if keepsActive {
|
||||
return false
|
||||
}
|
||||
guard let lastActivityAt else {
|
||||
return false
|
||||
}
|
||||
return now.timeIntervalSince(lastActivityAt) >= 3 * 24 * 60 * 60
|
||||
}
|
||||
|
||||
func isEffectivelySnoozed(at now: Date) -> Bool {
|
||||
guard let snoozedUntil, snoozedUntil > now else { return false }
|
||||
if state == .waitingForApproval || state == .waitingForInput {
|
||||
return false
|
||||
}
|
||||
if state == .failed,
|
||||
let snoozedAt,
|
||||
let attentionAt,
|
||||
attentionAt > snoozedAt {
|
||||
return false
|
||||
}
|
||||
if let snoozedAt,
|
||||
let latestTurnCompletedAt,
|
||||
latestTurnCompletedAt > snoozedAt {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var settledSortDate: Date {
|
||||
settledAt ?? lastActivityAt ?? updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +243,16 @@ struct DailyUXModelCatalog {
|
||||
}
|
||||
|
||||
enum DailyUXModelOptions {
|
||||
static func initialSelection(
|
||||
projectDefault: FeatureSelection?,
|
||||
appDefault: FeatureSelection?,
|
||||
providers: [FeatureProvider]
|
||||
) -> FeatureSelection? {
|
||||
validated(projectDefault, in: providers)
|
||||
?? validated(appDefault, in: providers)
|
||||
?? preferredSelection(in: providers)
|
||||
}
|
||||
|
||||
static func validated(
|
||||
_ selection: FeatureSelection?,
|
||||
in providers: [FeatureProvider]
|
||||
|
||||
@@ -98,6 +98,7 @@ public struct NewThreadView: View {
|
||||
.disabled(!canSubmit)
|
||||
.opacity(canSubmit ? 1 : 0.35)
|
||||
.accessibilityLabel(isSubmitting ? "Starting task" : "Start task")
|
||||
.accessibilityIdentifier("new-task-submit")
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
@@ -123,14 +124,13 @@ public struct NewThreadView: View {
|
||||
projectID = model.snapshot.projects.first?.id ?? ""
|
||||
}
|
||||
if selection == nil {
|
||||
selection = DailyUXModelOptions.validated(
|
||||
model.snapshot.settings.defaultSelection,
|
||||
in: model.snapshot.providers
|
||||
)
|
||||
?? DailyUXModelOptions.preferredSelection(in: model.snapshot.providers)
|
||||
selection = initialSelection
|
||||
}
|
||||
promptFocused = true
|
||||
}
|
||||
.onChange(of: projectID) {
|
||||
selection = initialSelection
|
||||
}
|
||||
.alert("Couldn’t start task", isPresented: $submissionFailed) {
|
||||
Button("OK") {}
|
||||
} message: {
|
||||
@@ -212,6 +212,14 @@ public struct NewThreadView: View {
|
||||
model.snapshot.projects.first { $0.id == projectID }
|
||||
}
|
||||
|
||||
private var initialSelection: FeatureSelection? {
|
||||
DailyUXModelOptions.initialSelection(
|
||||
projectDefault: selectedProject?.defaultSelection,
|
||||
appDefault: model.snapshot.settings.defaultSelection,
|
||||
providers: model.snapshot.providers
|
||||
)
|
||||
}
|
||||
|
||||
private var canSubmit: Bool {
|
||||
!isSubmitting
|
||||
&& !projectID.isEmpty
|
||||
|
||||
@@ -15,6 +15,7 @@ public struct WorkspaceView: View {
|
||||
@State private var showingArchived = false
|
||||
@State private var renamingThread: FeatureThread?
|
||||
@State private var renameTitle = ""
|
||||
@State private var sidebarClock = Date.now
|
||||
|
||||
public init(
|
||||
model: FeatureRootModel,
|
||||
@@ -119,6 +120,17 @@ public struct WorkspaceView: View {
|
||||
self.selectedThreadID = nil
|
||||
}
|
||||
}
|
||||
.task(id: sidebarBoundarySignature) {
|
||||
while !Task.isCancelled {
|
||||
sidebarClock = .now
|
||||
let delay = nextSidebarRefreshDelay(from: sidebarClock)
|
||||
do {
|
||||
try await Task.sleep(for: .seconds(delay))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var sidebar: some View {
|
||||
@@ -129,6 +141,7 @@ public struct WorkspaceView: View {
|
||||
if searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
projectFilter
|
||||
activeSection
|
||||
snoozedSection
|
||||
settledSection
|
||||
archiveAction
|
||||
} else {
|
||||
@@ -296,13 +309,27 @@ public struct WorkspaceView: View {
|
||||
} label: {
|
||||
ProjectFilterRow(
|
||||
project: model.snapshot.projects.first { $0.id == selectedProjectID },
|
||||
totalCount: sidebarIndex.active.count + sidebarIndex.settled.count
|
||||
totalCount: sidebarIndex.active.count
|
||||
+ sidebarIndex.snoozed.count
|
||||
+ sidebarIndex.settled.count
|
||||
)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.listRowSeparator(.hidden)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var snoozedSection: some View {
|
||||
if !sidebarIndex.snoozed.isEmpty {
|
||||
Section("Snoozed") {
|
||||
ForEach(sidebarIndex.snoozed) { thread in
|
||||
threadLink(thread, showsProject: selectedProjectID == nil)
|
||||
.opacity(0.76)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var activeSection: some View {
|
||||
Section("Active") {
|
||||
@@ -349,11 +376,23 @@ public struct WorkspaceView: View {
|
||||
Button {
|
||||
showingArchived = true
|
||||
} label: {
|
||||
Label("Archived", systemImage: "archivebox")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
HStack {
|
||||
Label("Archived", systemImage: "archivebox")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
Spacer()
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel("Archived")
|
||||
.accessibilityAddTraits(.isButton)
|
||||
.accessibilityAction {
|
||||
showingArchived = true
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel("Archived")
|
||||
.accessibilityIdentifier("archived-threads-button")
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
@@ -403,13 +442,13 @@ public struct WorkspaceView: View {
|
||||
} label: {
|
||||
Label("Archive", systemImage: "archivebox")
|
||||
}
|
||||
if thread.isSettled {
|
||||
if thread.isEffectivelySettled(at: .now) {
|
||||
Button {
|
||||
Task { await model.setSettled(thread.id, settled: false) }
|
||||
} label: {
|
||||
Label("Reopen", systemImage: "arrow.counterclockwise")
|
||||
}
|
||||
} else if !thread.isEffectivelySettled(at: .now) {
|
||||
} else {
|
||||
Button {
|
||||
Task { await model.setSettled(thread.id, settled: true) }
|
||||
} label: {
|
||||
@@ -417,20 +456,25 @@ public struct WorkspaceView: View {
|
||||
}
|
||||
}
|
||||
Button {
|
||||
let isSnoozed = thread.isEffectivelySnoozed(at: sidebarClock)
|
||||
Task {
|
||||
await model.setSnoozed(
|
||||
thread.id,
|
||||
until: thread.snoozedUntil == nil
|
||||
? Date().addingTimeInterval(60 * 60)
|
||||
: nil
|
||||
until: isSnoozed ? nil : Date().addingTimeInterval(60 * 60)
|
||||
)
|
||||
}
|
||||
} label: {
|
||||
let isSnoozed = thread.isEffectivelySnoozed(at: sidebarClock)
|
||||
Label(
|
||||
thread.snoozedUntil == nil ? "Snooze 1 hour" : "Unsnooze",
|
||||
systemImage: thread.snoozedUntil == nil ? "clock" : "bell"
|
||||
isSnoozed ? "Unsnooze" : "Snooze 1 hour",
|
||||
systemImage: isSnoozed ? "bell" : "clock"
|
||||
)
|
||||
}
|
||||
.disabled(
|
||||
thread.state == .queued
|
||||
|| thread.state == .waitingForApproval
|
||||
|| thread.state == .waitingForInput
|
||||
)
|
||||
Button(role: .destructive) {
|
||||
Task { await model.deleteThread(thread.id) }
|
||||
} label: {
|
||||
@@ -443,10 +487,34 @@ public struct WorkspaceView: View {
|
||||
DailyUXSidebarIndex(
|
||||
snapshot: model.snapshot,
|
||||
query: searchText,
|
||||
projectID: selectedProjectID
|
||||
projectID: selectedProjectID,
|
||||
now: sidebarClock
|
||||
)
|
||||
}
|
||||
|
||||
private var sidebarBoundarySignature: String {
|
||||
model.snapshot.threads.map {
|
||||
[
|
||||
$0.id,
|
||||
$0.state.rawValue,
|
||||
$0.lastActivityAt?.timeIntervalSince1970.description ?? "",
|
||||
$0.snoozedUntil?.timeIntervalSince1970.description ?? "",
|
||||
$0.snoozedAt?.timeIntervalSince1970.description ?? "",
|
||||
$0.attentionAt?.timeIntervalSince1970.description ?? "",
|
||||
].joined(separator: ":")
|
||||
}
|
||||
.joined(separator: "|")
|
||||
}
|
||||
|
||||
private func nextSidebarRefreshDelay(from now: Date) -> TimeInterval {
|
||||
let nextSnoozeBoundary = model.snapshot.threads
|
||||
.compactMap(\.snoozedUntil)
|
||||
.filter { $0 > now }
|
||||
.min()
|
||||
.map { $0.timeIntervalSince(now) }
|
||||
return max(0.25, min(60, nextSnoozeBoundary ?? 60))
|
||||
}
|
||||
|
||||
private var connectionColor: Color {
|
||||
switch model.snapshot.connection.state {
|
||||
case .connected: T3Colors.success
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 338 KiB |
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "AppIcon-1024.png",
|
||||
"idiom": "universal",
|
||||
"platform": "ios",
|
||||
"size": "1024x1024"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
@@ -339,12 +339,13 @@
|
||||
AB0000000000000000000003 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code Swift";
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code";
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||
INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES;
|
||||
@@ -376,6 +377,7 @@
|
||||
AB0000000000000000000004 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
|
||||
@@ -64,6 +64,33 @@ final class CoreContractTests: XCTestCase {
|
||||
XCTAssertEqual(command["runtimeMode"]?.stringValue, "full-access")
|
||||
}
|
||||
|
||||
func testFirstSendCommandCarriesCanonicalBootstrapMetadata() throws {
|
||||
let model = ModelSelection(instanceId: "codex", model: "gpt-5.4")
|
||||
let command = try OrchestrationCommands.createThreadAndSend(
|
||||
threadID: "thread-first-send",
|
||||
projectID: "project-1",
|
||||
title: "Build the native app",
|
||||
text: "Build the native app",
|
||||
model: model,
|
||||
runtimeMode: .fullAccess,
|
||||
commandID: "command-first-send",
|
||||
messageID: "message-first-send",
|
||||
createdAt: "2026-07-30T12:00:00.000Z"
|
||||
)
|
||||
|
||||
XCTAssertEqual(command["type"]?.stringValue, "thread.turn.start")
|
||||
XCTAssertEqual(command["titleSeed"]?.stringValue, "Build the native app")
|
||||
XCTAssertEqual(command["modelSelection"]?["model"]?.stringValue, "gpt-5.4")
|
||||
XCTAssertEqual(
|
||||
command["bootstrap"]?["createThread"]?["projectId"]?.stringValue,
|
||||
"project-1"
|
||||
)
|
||||
XCTAssertEqual(
|
||||
command["bootstrap"]?["createThread"]?["modelSelection"]?["instanceId"]?.stringValue,
|
||||
"codex"
|
||||
)
|
||||
}
|
||||
|
||||
func testEnvironmentStorePersistsSelectionAndClearsRemovedActiveEnvironment() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-swift-core-\(UUID().uuidString)", isDirectory: true)
|
||||
@@ -94,4 +121,42 @@ final class CoreContractTests: XCTestCase {
|
||||
XCTAssertEqual(remaining.map(\.id), [first.id])
|
||||
XCTAssertEqual(fallback, first.id)
|
||||
}
|
||||
|
||||
func testRuntimeReplacesCachedClientWhenSavedEndpointChanges() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-swift-runtime-\(UUID().uuidString)", isDirectory: true)
|
||||
let file = directory.appendingPathComponent("environments.json")
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let store = EnvironmentStore(fileURL: file)
|
||||
let first = Environment(
|
||||
id: "same-server",
|
||||
label: "Studio",
|
||||
httpBaseURL: URL(string: "http://192.168.1.10:3773")!,
|
||||
webSocketBaseURL: URL(string: "ws://192.168.1.10:3773")!
|
||||
)
|
||||
let moved = Environment(
|
||||
id: "same-server",
|
||||
label: "Studio",
|
||||
httpBaseURL: URL(string: "http://192.168.1.20:4773")!,
|
||||
webSocketBaseURL: URL(string: "ws://192.168.1.20:4773")!
|
||||
)
|
||||
try await store.save([first])
|
||||
try await store.setActiveEnvironment(id: first.id)
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: InMemoryCredentialStore()
|
||||
)
|
||||
|
||||
let firstClientValue = try await runtime.activeClient()
|
||||
let firstClient = try XCTUnwrap(firstClientValue)
|
||||
try await store.upsert(moved)
|
||||
let movedClientValue = try await runtime.activeClient()
|
||||
let movedClient = try XCTUnwrap(movedClientValue)
|
||||
let movedEnvironment = await movedClient.environment
|
||||
|
||||
XCTAssertFalse(firstClient === movedClient)
|
||||
XCTAssertEqual(movedEnvironment.httpBaseURL, moved.httpBaseURL)
|
||||
XCTAssertEqual(movedEnvironment.webSocketBaseURL, moved.webSocketBaseURL)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,10 @@ final class PairingServiceTests: XCTestCase {
|
||||
let form = String(data: requests[1].httpBody!, encoding: .utf8)!
|
||||
XCTAssertTrue(form.contains("subject_token=pair-once"))
|
||||
XCTAssertTrue(form.contains("client_device_type=mobile"))
|
||||
// Omitting scope accepts the exact grant carried by the one-time link.
|
||||
// Requesting administrative scopes consumes ordinary links and then
|
||||
// fails with scope_not_granted.
|
||||
XCTAssertFalse(form.contains("scope="))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,133 @@ final class TransportReliabilityTests: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
func testBootstrapUsesCanonicalWebSocketRPCDispatch() async throws {
|
||||
let environment = Environment(
|
||||
id: "environment-1",
|
||||
label: "Studio",
|
||||
httpBaseURL: URL(string: "https://studio.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://studio.example")!
|
||||
)
|
||||
let credentials = InMemoryCredentialStore(
|
||||
credentials: [
|
||||
environment.id: EnvironmentCredential(accessToken: "access-token"),
|
||||
]
|
||||
)
|
||||
let transport = RecordingHTTPTransport { request in
|
||||
let body = """
|
||||
{
|
||||
"ticket": "websocket-ticket",
|
||||
"expiresAt": "2026-07-30T12:05:00.000Z"
|
||||
}
|
||||
"""
|
||||
return (Data(body.utf8), transportResponse(request))
|
||||
}
|
||||
let connection = RecordingWebSocketConnection()
|
||||
let client = T3Client(
|
||||
environment: environment,
|
||||
credentialStore: credentials,
|
||||
httpTransport: transport,
|
||||
webSocketConnector: StaticWebSocketConnector(connection: connection)
|
||||
)
|
||||
|
||||
let result = try await client.createThreadAndSend(
|
||||
threadID: "thread-first-send",
|
||||
projectID: "project-1",
|
||||
title: "Native first send",
|
||||
text: "Start from this message",
|
||||
model: ModelSelection(instanceId: "codex", model: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess,
|
||||
commandID: "stable-command",
|
||||
messageID: "stable-message",
|
||||
createdAt: "2026-07-30T12:00:00.000Z"
|
||||
)
|
||||
await client.disconnect()
|
||||
|
||||
XCTAssertEqual(result.sequence, 42)
|
||||
let requests = await connection.requests()
|
||||
XCTAssertEqual(requests.count, 1)
|
||||
XCTAssertEqual(requests.first?["tag"]?.stringValue, "orchestration.dispatchCommand")
|
||||
XCTAssertEqual(
|
||||
requests.first?["payload"]?["bootstrap"]?["createThread"]?["projectId"]?.stringValue,
|
||||
"project-1"
|
||||
)
|
||||
XCTAssertEqual(requests.first?["payload"]?["commandId"]?.stringValue, "stable-command")
|
||||
XCTAssertEqual(
|
||||
requests.first?["payload"]?["message"]?["messageId"]?.stringValue,
|
||||
"stable-message"
|
||||
)
|
||||
|
||||
let httpRequests = await transport.requests
|
||||
XCTAssertEqual(httpRequests.map(\.url?.path), ["/api/auth/websocket-ticket"])
|
||||
}
|
||||
|
||||
func testUnsentCommandsFallBackToHTTPButBootstrapDoesNot() async throws {
|
||||
let environment = Environment(
|
||||
id: "environment-1",
|
||||
label: "Studio",
|
||||
httpBaseURL: URL(string: "https://studio.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://studio.example")!
|
||||
)
|
||||
let credentials = InMemoryCredentialStore(
|
||||
credentials: [
|
||||
environment.id: EnvironmentCredential(accessToken: "access-token"),
|
||||
]
|
||||
)
|
||||
let transport = RecordingHTTPTransport { request in
|
||||
let body = if request.url?.path == "/api/auth/websocket-ticket" {
|
||||
"""
|
||||
{
|
||||
"ticket": "websocket-ticket",
|
||||
"expiresAt": "2026-07-30T12:05:00.000Z"
|
||||
}
|
||||
"""
|
||||
} else {
|
||||
"""
|
||||
{"sequence": 9}
|
||||
"""
|
||||
}
|
||||
return (Data(body.utf8), transportResponse(request))
|
||||
}
|
||||
let client = T3Client(
|
||||
environment: environment,
|
||||
credentialStore: credentials,
|
||||
httpTransport: transport,
|
||||
webSocketConnector: FailingWebSocketConnector(),
|
||||
rpcConnectionWaitTimeout: .milliseconds(30)
|
||||
)
|
||||
|
||||
let rename = try await client.rename(threadID: "thread-1", title: "Renamed")
|
||||
XCTAssertEqual(rename.sequence, 9)
|
||||
|
||||
do {
|
||||
_ = try await client.createThreadAndSend(
|
||||
threadID: "thread-first-send",
|
||||
projectID: "project-1",
|
||||
title: "Native first send",
|
||||
text: "Start from this message",
|
||||
model: ModelSelection(instanceId: "codex", model: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess
|
||||
)
|
||||
XCTFail("Bootstrap must not use the HTTP endpoint that cannot expand it.")
|
||||
} catch let error as RPCError {
|
||||
guard case .connectionUnavailable = error else {
|
||||
return XCTFail("Unexpected RPC error: \(error)")
|
||||
}
|
||||
}
|
||||
await client.disconnect()
|
||||
|
||||
let requests = await transport.requests
|
||||
let dispatchRequests = requests.filter {
|
||||
$0.url?.path == "/api/orchestration/dispatch"
|
||||
}
|
||||
XCTAssertEqual(dispatchRequests.count, 1)
|
||||
let command = try JSONDecoder.t3.decode(
|
||||
JSONValue.self,
|
||||
from: try XCTUnwrap(dispatchRequests.first?.httpBody)
|
||||
)
|
||||
XCTAssertEqual(command["type"]?.stringValue, "thread.meta.update")
|
||||
}
|
||||
|
||||
/// Set `T3_SWIFT_WS_DEFLATE_ECHO_URL` to a WebSocket endpoint that rejects
|
||||
/// non-deflate handshakes and echoes binary frames. This is intentionally
|
||||
/// opt-in because XCTest does not own a Node process. A successful round
|
||||
@@ -191,3 +318,65 @@ private actor RecordingHTTPTransport: HTTPTransport {
|
||||
return try handler(request)
|
||||
}
|
||||
}
|
||||
|
||||
private struct StaticWebSocketConnector: WebSocketConnecting {
|
||||
let connection: RecordingWebSocketConnection
|
||||
|
||||
func connect(to _: URL) async throws -> any WebSocketConnection {
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
private struct FailingWebSocketConnector: WebSocketConnecting {
|
||||
func connect(to _: URL) async throws -> any WebSocketConnection {
|
||||
throw URLError(.cannotConnectToHost)
|
||||
}
|
||||
}
|
||||
|
||||
private actor RecordingWebSocketConnection: WebSocketConnection {
|
||||
private var recordedRequests: [JSONValue] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) throws {
|
||||
let request = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
recordedRequests.append(request)
|
||||
guard case let .number(rawID) = request["id"] else { return }
|
||||
let response = JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(rawID),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object(["sequence": .number(42)]),
|
||||
]),
|
||||
])
|
||||
enqueue(try JSONEncoder.t3.encode(response))
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
if !queuedResponses.isEmpty {
|
||||
return queuedResponses.removeFirst()
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiver = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
receiver?.resume(throwing: CancellationError())
|
||||
receiver = nil
|
||||
}
|
||||
|
||||
func requests() -> [JSONValue] {
|
||||
recordedRequests
|
||||
}
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiver {
|
||||
self.receiver = nil
|
||||
receiver.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import XCTest
|
||||
@testable import T3Code
|
||||
|
||||
@MainActor
|
||||
final class WebSocketRPCRaceTests: XCTestCase {
|
||||
func testDisconnectWhileUnarySendIsSuspendedFailsWithoutReplay() async throws {
|
||||
let first = SuspendedSendConnection()
|
||||
let second = AutoReplyConnection()
|
||||
let connector = SequencedConnector(connections: [first, second])
|
||||
let client = WebSocketRPCClient(
|
||||
connector: connector,
|
||||
connectionWaitTimeout: .seconds(2),
|
||||
endpointProvider: { URL(string: "wss://studio.example/ws")! }
|
||||
)
|
||||
|
||||
await client.start()
|
||||
await first.waitUntilReceiving()
|
||||
|
||||
let request = Task {
|
||||
do {
|
||||
let value = try await client.request(
|
||||
"thread.rename",
|
||||
as: JSONValue.self
|
||||
)
|
||||
return Result<JSONValue, Error>.success(value)
|
||||
} catch {
|
||||
return Result<JSONValue, Error>.failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
await first.waitUntilSending()
|
||||
await first.failReceive()
|
||||
|
||||
let outcome = await request.value
|
||||
guard case let .failure(error) = outcome,
|
||||
case .disconnected = error as? RPCError
|
||||
else {
|
||||
await client.stop()
|
||||
await first.releaseSend()
|
||||
return XCTFail("An ambiguous unary send must fail as disconnected.")
|
||||
}
|
||||
|
||||
await connector.waitUntilConnectionCount(2)
|
||||
let replayedRequestCount = await second.sentRequestCount()
|
||||
XCTAssertEqual(
|
||||
replayedRequestCount,
|
||||
0,
|
||||
"A unary request that crossed a broken socket must not be replayed."
|
||||
)
|
||||
|
||||
await client.stop()
|
||||
await first.releaseSend()
|
||||
}
|
||||
}
|
||||
|
||||
private actor SequencedConnector: WebSocketConnecting {
|
||||
private let connections: [any WebSocketConnection]
|
||||
private var nextIndex = 0
|
||||
private var countWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
|
||||
|
||||
init(connections: [any WebSocketConnection]) {
|
||||
self.connections = connections
|
||||
}
|
||||
|
||||
func connect(to _: URL) throws -> any WebSocketConnection {
|
||||
guard nextIndex < connections.count else {
|
||||
throw URLError(.cannotConnectToHost)
|
||||
}
|
||||
let connection = connections[nextIndex]
|
||||
nextIndex += 1
|
||||
let completed = countWaiters.filter { nextIndex >= $0.0 }
|
||||
countWaiters.removeAll { nextIndex >= $0.0 }
|
||||
completed.forEach { $0.1.resume() }
|
||||
return connection
|
||||
}
|
||||
|
||||
func waitUntilConnectionCount(_ count: Int) async {
|
||||
guard nextIndex < count else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
countWaiters.append((count, continuation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private actor SuspendedSendConnection: WebSocketConnection {
|
||||
private var sendContinuation: CheckedContinuation<Void, Error>?
|
||||
private var receiveContinuation: CheckedContinuation<Data, Error>?
|
||||
private var sendWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var receiveWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
func send(_: Data) async throws {
|
||||
let waiters = sendWaiters
|
||||
sendWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
sendContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
let waiters = receiveWaiters
|
||||
receiveWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiveContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
receiveContinuation?.resume(throwing: CancellationError())
|
||||
receiveContinuation = nil
|
||||
}
|
||||
|
||||
func waitUntilSending() async {
|
||||
guard sendContinuation == nil else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
sendWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilReceiving() async {
|
||||
guard receiveContinuation == nil else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
receiveWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func failReceive() {
|
||||
receiveContinuation?.resume(throwing: URLError(.networkConnectionLost))
|
||||
receiveContinuation = nil
|
||||
}
|
||||
|
||||
func releaseSend() {
|
||||
sendContinuation?.resume()
|
||||
sendContinuation = nil
|
||||
}
|
||||
}
|
||||
|
||||
private actor AutoReplyConnection: WebSocketConnection {
|
||||
private var sentRequests = 0
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiveContinuation: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) throws {
|
||||
sentRequests += 1
|
||||
let request = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
guard case let .number(requestID) = request["id"] else { return }
|
||||
let response = JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(requestID),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object([:]),
|
||||
]),
|
||||
])
|
||||
enqueue(try JSONEncoder.t3.encode(response))
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
if !queuedResponses.isEmpty {
|
||||
return queuedResponses.removeFirst()
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiveContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
receiveContinuation?.resume(throwing: CancellationError())
|
||||
receiveContinuation = nil
|
||||
}
|
||||
|
||||
func sentRequestCount() -> Int {
|
||||
sentRequests
|
||||
}
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiveContinuation {
|
||||
self.receiveContinuation = nil
|
||||
receiveContinuation.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,10 @@ final class WorkspaceContractTests: XCTestCase {
|
||||
XCTAssertEqual(RPCMethod.projectsListEntries.rawValue, "projects.listEntries")
|
||||
XCTAssertEqual(RPCMethod.vcsRefreshStatus.rawValue, "vcs.refreshStatus")
|
||||
XCTAssertEqual(RPCMethod.reviewDiffPreview.rawValue, "review.getDiffPreview")
|
||||
XCTAssertEqual(
|
||||
RPCMethod.getArchivedShellSnapshot.rawValue,
|
||||
"orchestration.getArchivedShellSnapshot"
|
||||
)
|
||||
XCTAssertEqual(RPCMethod.terminalAttach.rawValue, "terminal.attach")
|
||||
XCTAssertEqual(RPCMethod.subscribeTerminalEvents.rawValue, "subscribeTerminalEvents")
|
||||
}
|
||||
|
||||
@@ -173,4 +173,27 @@ struct DailyUXModelPickerTests {
|
||||
FeatureModelOptionSelection(id: "fast", value: .boolean(true)),
|
||||
])
|
||||
}
|
||||
|
||||
@Test
|
||||
func projectDefaultWinsBeforeAppAndCatalogDefaults() {
|
||||
let providers = [
|
||||
FeatureProvider(
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
models: [
|
||||
.init(id: "project", name: "Project"),
|
||||
.init(id: "app", name: "App"),
|
||||
.init(id: "catalog", name: "Catalog", isDefault: true),
|
||||
]
|
||||
),
|
||||
]
|
||||
|
||||
let selection = DailyUXModelOptions.initialSelection(
|
||||
projectDefault: .init(providerID: "codex", modelID: "project"),
|
||||
appDefault: .init(providerID: "codex", modelID: "app"),
|
||||
providers: providers
|
||||
)
|
||||
|
||||
#expect(selection?.modelID == "project")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Message-first task creation")
|
||||
@@ -24,4 +25,27 @@ struct DailyUXNewTaskTests {
|
||||
#expect(request.interactionMode == .plan)
|
||||
#expect(request.attachments.first?.byteCount == 3)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func imageProcessorDownsamplesUploadAndBuildsSmallThumbnail() throws {
|
||||
let source = UIGraphicsImageRenderer(size: CGSize(width: 2_400, height: 1_200))
|
||||
.image { context in
|
||||
UIColor.systemPink.setFill()
|
||||
context.fill(CGRect(x: 0, y: 0, width: 2_400, height: 1_200))
|
||||
}
|
||||
let sourceData = try #require(source.pngData())
|
||||
|
||||
let attachment = try FeatureImageProcessor.attachment(
|
||||
from: sourceData,
|
||||
ordinal: 1
|
||||
)
|
||||
let prepared = try #require(UIImage(data: attachment.data))
|
||||
let thumbnail = try #require(
|
||||
attachment.thumbnailData.flatMap(UIImage.init(data:))
|
||||
)
|
||||
|
||||
#expect(max(prepared.size.width, prepared.size.height) <= 2_048)
|
||||
#expect(max(thumbnail.size.width, thumbnail.size.height) <= 160)
|
||||
#expect(attachment.mimeType == "image/jpeg")
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,23 @@ struct DailyUXSidebarTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
func snoozedAndArchivedThreadsStayOutOfBothBlocks() {
|
||||
func explicitActiveOverridePreventsAutoSettlement() {
|
||||
var reopened = thread(
|
||||
id: "reopened",
|
||||
created: -400_000,
|
||||
updated: -300_000,
|
||||
state: .idle
|
||||
)
|
||||
reopened.keepsActive = true
|
||||
|
||||
let index = makeIndex([reopened])
|
||||
|
||||
#expect(index.active.map(\.id) == ["reopened"])
|
||||
#expect(index.settled.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func snoozedThreadsHaveAReachableReverseState() {
|
||||
var snoozed = thread(id: "snoozed", created: -20, updated: -10)
|
||||
snoozed.snoozedUntil = now.addingTimeInterval(3_600)
|
||||
var archived = thread(id: "archived", created: -30, updated: -20)
|
||||
@@ -84,9 +100,56 @@ struct DailyUXSidebarTests {
|
||||
let index = makeIndex([snoozed, archived, visible])
|
||||
|
||||
#expect(index.active.map(\.id) == ["visible"])
|
||||
#expect(index.snoozed.map(\.id) == ["snoozed"])
|
||||
#expect(index.settled.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func snoozeExpiresAtTheClockBoundary() {
|
||||
var thread = thread(id: "timed", created: -20, updated: -10)
|
||||
thread.snoozedUntil = now.addingTimeInterval(30)
|
||||
|
||||
#expect(makeIndex([thread]).snoozed.map(\.id) == ["timed"])
|
||||
let expired = DailyUXSidebarIndex(
|
||||
snapshot: FeatureSnapshot(threads: [thread]),
|
||||
query: "",
|
||||
now: now.addingTimeInterval(31)
|
||||
)
|
||||
#expect(expired.active.map(\.id) == ["timed"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func onlyFailuresRaisedAfterSnoozingWakeTheThread() {
|
||||
var acknowledged = thread(
|
||||
id: "acknowledged",
|
||||
created: -30,
|
||||
updated: -10,
|
||||
state: .failed
|
||||
)
|
||||
acknowledged.snoozedUntil = now.addingTimeInterval(3_600)
|
||||
acknowledged.snoozedAt = now.addingTimeInterval(-10)
|
||||
acknowledged.attentionAt = now.addingTimeInterval(-20)
|
||||
|
||||
var fresh = acknowledged
|
||||
fresh = FeatureThread(
|
||||
id: "fresh",
|
||||
projectID: fresh.projectID,
|
||||
title: fresh.title,
|
||||
createdAt: fresh.createdAt,
|
||||
updatedAt: fresh.updatedAt,
|
||||
state: .failed,
|
||||
lastActivityAt: fresh.lastActivityAt,
|
||||
snoozedUntil: fresh.snoozedUntil,
|
||||
snoozedAt: fresh.snoozedAt,
|
||||
attentionAt: now.addingTimeInterval(-5)
|
||||
)
|
||||
|
||||
let index = makeIndex([acknowledged, fresh])
|
||||
|
||||
#expect(index.snoozed.map(\.id) == ["acknowledged"])
|
||||
#expect(index.active.map(\.id) == ["fresh"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func projectFilterAndSearchUseRepositoryContext() {
|
||||
let projects = [
|
||||
@@ -128,7 +191,8 @@ struct DailyUXSidebarTests {
|
||||
createdAt: now.addingTimeInterval(created),
|
||||
updatedAt: now.addingTimeInterval(updated),
|
||||
state: state,
|
||||
isSettled: isSettled
|
||||
isSettled: isSettled,
|
||||
lastActivityAt: now.addingTimeInterval(updated)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,13 @@ struct FeatureRootModelTests {
|
||||
endpoint: "https://studio.example"
|
||||
)
|
||||
)
|
||||
let oldThread = FeatureThread(id: "same-id", projectID: "old-project", title: "Old")
|
||||
client.threadDetail = FeatureThreadDetail(
|
||||
thread: oldThread,
|
||||
messages: [FeatureMessage(id: "old-message", role: .assistant, text: "Old")]
|
||||
)
|
||||
let model = FeatureRootModel(client: client)
|
||||
_ = await model.detail(for: oldThread.id)
|
||||
|
||||
let result = await model.pair(endpoint: "https://studio.example", token: "pair-token")
|
||||
|
||||
@@ -24,6 +30,7 @@ struct FeatureRootModelTests {
|
||||
#expect(client.pairEndpoint == "https://studio.example")
|
||||
#expect(client.pairToken == "pair-token")
|
||||
#expect(model.snapshot.connection.state == .connected)
|
||||
#expect(model.details.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -120,6 +127,53 @@ struct FeatureRootModelTests {
|
||||
await model.deleteThread(thread.id)
|
||||
#expect(model.snapshot.threads.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func testCancelledDetailRefreshKeepsCachedContentWithoutAlert() async {
|
||||
let client = FeatureClientStub()
|
||||
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
||||
let detail = FeatureThreadDetail(
|
||||
thread: thread,
|
||||
messages: [
|
||||
FeatureMessage(id: "message-1", role: .assistant, text: "Still here"),
|
||||
]
|
||||
)
|
||||
client.threadDetail = detail
|
||||
let model = FeatureRootModel(client: client)
|
||||
_ = await model.detail(for: thread.id)
|
||||
client.loadThreadError = CancellationError()
|
||||
|
||||
let refreshed = await model.detail(for: thread.id, force: true)
|
||||
|
||||
#expect(refreshed == detail)
|
||||
#expect(model.errorMessage == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func testResnoozeRefreshesTheOptimisticSnoozeTimestamp() async {
|
||||
let client = FeatureClientStub()
|
||||
var thread = FeatureThread(
|
||||
id: "thread-1",
|
||||
projectID: "project-1",
|
||||
title: "Thread",
|
||||
state: .failed
|
||||
)
|
||||
let oldSnooze = Date.now.addingTimeInterval(-600)
|
||||
thread.snoozedAt = oldSnooze
|
||||
thread.attentionAt = Date.now.addingTimeInterval(-300)
|
||||
client.createdThread = thread
|
||||
let model = FeatureRootModel(client: client)
|
||||
_ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil)
|
||||
|
||||
await model.setSnoozed(
|
||||
thread.id,
|
||||
until: Date.now.addingTimeInterval(3_600)
|
||||
)
|
||||
|
||||
let updated = model.snapshot.threads[0]
|
||||
#expect(updated.snoozedAt != oldSnooze)
|
||||
#expect(updated.snoozedAt! > updated.attentionAt!)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -135,6 +189,7 @@ private final class FeatureClientStub: FeatureClient {
|
||||
var startedAttachments: [FeatureUploadAttachment] = []
|
||||
var createThreadCallCount = 0
|
||||
var sendMessageCallCount = 0
|
||||
var loadThreadError: (any Error)?
|
||||
|
||||
func initialSnapshot() async throws -> FeatureSnapshot {
|
||||
if pairEndpoint != nil, let snapshotAfterPair {
|
||||
@@ -175,6 +230,9 @@ private final class FeatureClientStub: FeatureClient {
|
||||
func deleteThread(id: String) async throws {}
|
||||
|
||||
func loadThread(id: String) async throws -> FeatureThreadDetail {
|
||||
if let loadThreadError {
|
||||
throw loadThreadError
|
||||
}
|
||||
if let threadDetail {
|
||||
return threadDetail
|
||||
}
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import T3Code
|
||||
|
||||
@MainActor
|
||||
final class NativeRetryIdentityTests: XCTestCase {
|
||||
func testAmbiguousFailuresReuseStableTurnAndBootstrapIdentities() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-native-retry-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let environment = Environment(
|
||||
id: "environment-retry",
|
||||
label: "Retry",
|
||||
httpBaseURL: URL(string: "https://retry.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://retry.example")!
|
||||
)
|
||||
let store = EnvironmentStore(
|
||||
fileURL: directory.appendingPathComponent("environments.json")
|
||||
)
|
||||
try await store.save([environment])
|
||||
try await store.setActiveEnvironment(id: environment.id)
|
||||
|
||||
let connection = AmbiguousDispatchWebSocketConnection()
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: InMemoryCredentialStore(
|
||||
credentials: [
|
||||
environment.id: EnvironmentCredential(accessToken: "token"),
|
||||
]
|
||||
),
|
||||
httpTransport: RetryIdentityHTTPTransport(shell: retryShellSnapshot()),
|
||||
webSocketConnector: RetryIdentityWebSocketConnector(connection: connection)
|
||||
)
|
||||
let settings = UserDefaults(
|
||||
suiteName: "t3-native-retry-\(UUID().uuidString)"
|
||||
)!
|
||||
let client = NativeFeatureClient(runtime: runtime, settingsStore: settings)
|
||||
_ = try await client.initialSnapshot()
|
||||
await connection.waitUntilConnected()
|
||||
|
||||
for _ in 0..<2 {
|
||||
do {
|
||||
try await client.sendMessage(
|
||||
threadID: "thread-existing",
|
||||
text: "Retry without duplicating",
|
||||
selection: nil
|
||||
)
|
||||
XCTFail("The synthetic dispatch should fail ambiguously.")
|
||||
} catch {}
|
||||
}
|
||||
|
||||
for _ in 0..<2 {
|
||||
do {
|
||||
_ = try await client.createThreadAndSend(
|
||||
projectID: "project-1",
|
||||
prompt: "Create exactly one task",
|
||||
selection: FeatureSelection(providerID: "codex", modelID: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: []
|
||||
)
|
||||
XCTFail("The synthetic bootstrap should fail ambiguously.")
|
||||
} catch {}
|
||||
}
|
||||
|
||||
let commands = await connection.dispatchCommands()
|
||||
XCTAssertEqual(commands.count, 4)
|
||||
assertStableIdentity(commands[0], commands[1], includesThreadID: false)
|
||||
assertStableIdentity(commands[2], commands[3], includesThreadID: true)
|
||||
await client.disconnect()
|
||||
}
|
||||
|
||||
func testPartialBootstrapRecoversBySendingOnlyTheStableFinalTurn() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-native-partial-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let environment = Environment(
|
||||
id: "environment-partial",
|
||||
label: "Partial",
|
||||
httpBaseURL: URL(string: "https://partial.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://partial.example")!
|
||||
)
|
||||
let store = EnvironmentStore(
|
||||
fileURL: directory.appendingPathComponent("environments.json")
|
||||
)
|
||||
try await store.save([environment])
|
||||
try await store.setActiveEnvironment(id: environment.id)
|
||||
|
||||
let connection = PartialBootstrapWebSocketConnection()
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: InMemoryCredentialStore(
|
||||
credentials: [
|
||||
environment.id: EnvironmentCredential(accessToken: "token"),
|
||||
]
|
||||
),
|
||||
httpTransport: PartialBootstrapHTTPTransport(shell: retryShellSnapshot()),
|
||||
webSocketConnector: PartialBootstrapWebSocketConnector(connection: connection)
|
||||
)
|
||||
let settings = UserDefaults(
|
||||
suiteName: "t3-native-partial-\(UUID().uuidString)"
|
||||
)!
|
||||
let client = NativeFeatureClient(runtime: runtime, settingsStore: settings)
|
||||
_ = try await client.initialSnapshot()
|
||||
await connection.waitUntilConnected()
|
||||
|
||||
let created = try await client.createThreadAndSend(
|
||||
projectID: "project-1",
|
||||
prompt: "Recover the first turn",
|
||||
selection: FeatureSelection(providerID: "codex", modelID: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: []
|
||||
)
|
||||
|
||||
let commands = await connection.dispatchCommands()
|
||||
XCTAssertEqual(commands.count, 2)
|
||||
XCTAssertNotNil(commands[0]["bootstrap"])
|
||||
XCTAssertNil(commands[1]["bootstrap"])
|
||||
assertStableIdentity(commands[0], commands[1], includesThreadID: true)
|
||||
XCTAssertEqual(created.id, commands[0]["threadId"]?.stringValue)
|
||||
await client.disconnect()
|
||||
}
|
||||
|
||||
private func assertStableIdentity(
|
||||
_ first: JSONValue,
|
||||
_ second: JSONValue,
|
||||
includesThreadID: Bool
|
||||
) {
|
||||
XCTAssertEqual(first["commandId"], second["commandId"])
|
||||
XCTAssertEqual(first["message"]?["messageId"], second["message"]?["messageId"])
|
||||
XCTAssertEqual(first["createdAt"], second["createdAt"])
|
||||
if includesThreadID {
|
||||
XCTAssertEqual(first["threadId"], second["threadId"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func retryShellSnapshot() -> OrchestrationShellSnapshot {
|
||||
let timestamp = "2026-07-30T12:00:00.000Z"
|
||||
let model = ModelSelection(instanceId: "codex", model: "gpt-5.4")
|
||||
return OrchestrationShellSnapshot(
|
||||
snapshotSequence: 1,
|
||||
projects: [
|
||||
OrchestrationProject(
|
||||
id: "project-1",
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/work/t3",
|
||||
repositoryIdentity: nil,
|
||||
defaultModelSelection: model,
|
||||
scripts: [],
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
deletedAt: nil
|
||||
),
|
||||
],
|
||||
threads: [
|
||||
OrchestrationThreadShell(
|
||||
id: "thread-existing",
|
||||
projectId: "project-1",
|
||||
title: "Existing",
|
||||
modelSelection: model,
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .default,
|
||||
branch: nil,
|
||||
worktreePath: nil,
|
||||
latestTurn: nil,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: nil,
|
||||
settledOverride: nil,
|
||||
settledAt: nil,
|
||||
snoozedUntil: nil,
|
||||
snoozedAt: nil,
|
||||
session: nil,
|
||||
latestUserMessageAt: nil,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false
|
||||
),
|
||||
],
|
||||
updatedAt: timestamp
|
||||
)
|
||||
}
|
||||
|
||||
private actor RetryIdentityHTTPTransport: HTTPTransport {
|
||||
private let shellData: Data
|
||||
|
||||
init(shell: OrchestrationShellSnapshot) {
|
||||
shellData = try! JSONEncoder.t3.encode(shell)
|
||||
}
|
||||
|
||||
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
|
||||
let path = request.url?.path ?? ""
|
||||
if path == "/api/orchestration/shell" {
|
||||
return (shellData, retryHTTPResponse(request))
|
||||
}
|
||||
if path == "/api/auth/websocket-ticket" {
|
||||
return (
|
||||
Data(
|
||||
"""
|
||||
{
|
||||
"ticket": "ticket",
|
||||
"expiresAt": "2026-07-30T12:05:00.000Z"
|
||||
}
|
||||
""".utf8
|
||||
),
|
||||
retryHTTPResponse(request)
|
||||
)
|
||||
}
|
||||
if path.hasPrefix("/api/orchestration/threads/") {
|
||||
throw URLError(.networkConnectionLost)
|
||||
}
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RetryIdentityWebSocketConnector: WebSocketConnecting {
|
||||
let connection: AmbiguousDispatchWebSocketConnection
|
||||
|
||||
func connect(to _: URL) async throws -> any WebSocketConnection {
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
private actor PartialBootstrapHTTPTransport: HTTPTransport {
|
||||
private let shellData: Data
|
||||
|
||||
init(shell: OrchestrationShellSnapshot) {
|
||||
shellData = try! JSONEncoder.t3.encode(shell)
|
||||
}
|
||||
|
||||
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
|
||||
let path = request.url?.path ?? ""
|
||||
if path == "/api/orchestration/shell" {
|
||||
return (shellData, retryHTTPResponse(request))
|
||||
}
|
||||
if path == "/api/auth/websocket-ticket" {
|
||||
return (
|
||||
Data(
|
||||
"""
|
||||
{
|
||||
"ticket": "ticket",
|
||||
"expiresAt": "2026-07-30T12:05:00.000Z"
|
||||
}
|
||||
""".utf8
|
||||
),
|
||||
retryHTTPResponse(request)
|
||||
)
|
||||
}
|
||||
if path.hasPrefix("/api/orchestration/threads/") {
|
||||
let threadID = request.url?.lastPathComponent.removingPercentEncoding ?? "thread"
|
||||
let snapshot = retryEmptyThreadDetail(id: threadID)
|
||||
return (try JSONEncoder.t3.encode(snapshot), retryHTTPResponse(request))
|
||||
}
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PartialBootstrapWebSocketConnector: WebSocketConnecting {
|
||||
let connection: PartialBootstrapWebSocketConnection
|
||||
|
||||
func connect(to _: URL) async throws -> any WebSocketConnection {
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection {
|
||||
private var commands: [JSONValue] = []
|
||||
private var didConnect = false
|
||||
private var connectionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) throws {
|
||||
let request = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
if !didConnect {
|
||||
didConnect = true
|
||||
connectionWaiters.forEach { $0.resume() }
|
||||
connectionWaiters.removeAll()
|
||||
}
|
||||
if request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue,
|
||||
let payload = request["payload"] {
|
||||
commands.append(payload)
|
||||
throw URLError(.networkConnectionLost)
|
||||
}
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
receiver = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
receiver?.resume(throwing: CancellationError())
|
||||
receiver = nil
|
||||
}
|
||||
|
||||
func waitUntilConnected() async {
|
||||
guard !didConnect else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
connectionWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func dispatchCommands() -> [JSONValue] {
|
||||
commands
|
||||
}
|
||||
}
|
||||
|
||||
private actor PartialBootstrapWebSocketConnection: WebSocketConnection {
|
||||
private var commands: [JSONValue] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
private var didConnect = false
|
||||
private var connectionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
func send(_ data: Data) throws {
|
||||
let request = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
if !didConnect {
|
||||
didConnect = true
|
||||
connectionWaiters.forEach { $0.resume() }
|
||||
connectionWaiters.removeAll()
|
||||
}
|
||||
guard request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue,
|
||||
let payload = request["payload"] else {
|
||||
return
|
||||
}
|
||||
commands.append(payload)
|
||||
if payload["bootstrap"] != nil {
|
||||
throw URLError(.networkConnectionLost)
|
||||
}
|
||||
guard case let .number(requestID) = request["id"] else { return }
|
||||
let response = JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(requestID),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object(["sequence": .number(42)]),
|
||||
]),
|
||||
])
|
||||
enqueue(try JSONEncoder.t3.encode(response))
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
if !queuedResponses.isEmpty {
|
||||
return queuedResponses.removeFirst()
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiver = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
receiver?.resume(throwing: CancellationError())
|
||||
receiver = nil
|
||||
}
|
||||
|
||||
func waitUntilConnected() async {
|
||||
guard !didConnect else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
connectionWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func dispatchCommands() -> [JSONValue] {
|
||||
commands
|
||||
}
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiver {
|
||||
self.receiver = nil
|
||||
receiver.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func retryEmptyThreadDetail(id: String) -> OrchestrationThreadDetailSnapshot {
|
||||
let timestamp = "2026-07-30T12:00:00.000Z"
|
||||
return OrchestrationThreadDetailSnapshot(
|
||||
snapshotSequence: 2,
|
||||
thread: OrchestrationThread(
|
||||
id: id,
|
||||
projectId: "project-1",
|
||||
title: "Recover the first turn",
|
||||
modelSelection: ModelSelection(instanceId: "codex", model: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .default,
|
||||
branch: nil,
|
||||
worktreePath: nil,
|
||||
latestTurn: nil,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: nil,
|
||||
settledOverride: nil,
|
||||
settledAt: nil,
|
||||
snoozedUntil: nil,
|
||||
snoozedAt: nil,
|
||||
deletedAt: nil,
|
||||
messages: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: nil
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func retryHTTPResponse(_ request: URLRequest) -> HTTPURLResponse {
|
||||
HTTPURLResponse(
|
||||
url: request.url!,
|
||||
statusCode: 200,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: ["Content-Type": "application/json"]
|
||||
)!
|
||||
}
|
||||
Reference in new issue
Block a user