fix(swift-ios): make mobile delivery resilient
This commit is contained in:
11 files changed
+2209
-116
No files matched your search
@@ -13,9 +13,13 @@ extension FeatureInputAnswer {
|
||||
|
||||
/// Composes the transport-focused Core layer with the UI-focused Features layer.
|
||||
@MainActor
|
||||
final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeatureProjectCreationClient {
|
||||
final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
FeatureProjectCreationClient, FeatureWorkspaceAssetResolving
|
||||
{
|
||||
private let runtime: EnvironmentRuntime
|
||||
private let settingsStore: UserDefaults
|
||||
private let fallbackPollingInitialDelay: Duration
|
||||
private let fallbackPollingInterval: Duration
|
||||
private let stream: AsyncStream<FeatureEvent>
|
||||
private let continuation: AsyncStream<FeatureEvent>.Continuation
|
||||
|
||||
@@ -25,6 +29,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
private var environmentClients: [String: T3Client] = [:]
|
||||
private var shellsByEnvironmentID: [String: OrchestrationShellSnapshot] = [:]
|
||||
private var archivedThreadsByEnvironmentID: [String: [FeatureThread]] = [:]
|
||||
private var archivedShellThreadsByEnvironmentID: [
|
||||
String: [String: OrchestrationThreadShell]
|
||||
] = [:]
|
||||
private var projectEnvironmentIDs: [String: String] = [:]
|
||||
private var projectWireIDs: [String: String] = [:]
|
||||
private var threadEnvironmentIDs: [String: String] = [:]
|
||||
@@ -40,7 +47,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
private var latestDetails: [String: FeatureThreadDetail] = [:]
|
||||
private var detailRenderCaches: [String: NativeDetailRenderCache] = [:]
|
||||
private var attachmentURLs: [AttachmentCacheKey: CachedAttachmentURL] = [:]
|
||||
private var pendingBootstrapSubmission: PendingBootstrapSubmission?
|
||||
private var pendingBootstrapSubmissions: [PendingBootstrapSubmission] = []
|
||||
private var pendingTurnSubmissions: [String: PendingTurnSubmission] = [:]
|
||||
private var attachmentHydrationTasks: [
|
||||
String: (id: UUID, task: Task<Void, Never>)
|
||||
@@ -73,10 +80,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
|
||||
init(
|
||||
runtime: EnvironmentRuntime = EnvironmentRuntime(),
|
||||
settingsStore: UserDefaults = .standard
|
||||
settingsStore: UserDefaults = .standard,
|
||||
fallbackPollingInitialDelay: Duration = .seconds(3),
|
||||
fallbackPollingInterval: Duration = .seconds(2)
|
||||
) {
|
||||
self.runtime = runtime
|
||||
self.settingsStore = settingsStore
|
||||
self.fallbackPollingInitialDelay = fallbackPollingInitialDelay
|
||||
self.fallbackPollingInterval = fallbackPollingInterval
|
||||
let pair = AsyncStream<FeatureEvent>.makeStream()
|
||||
stream = pair.stream
|
||||
continuation = pair.continuation
|
||||
@@ -242,6 +253,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
shellsByEnvironmentID.removeAll()
|
||||
serverConfigsByEnvironmentID.removeAll()
|
||||
archivedThreadsByEnvironmentID.removeAll()
|
||||
archivedShellThreadsByEnvironmentID.removeAll()
|
||||
projectEnvironmentIDs.removeAll()
|
||||
projectWireIDs.removeAll()
|
||||
threadEnvironmentIDs.removeAll()
|
||||
@@ -258,7 +270,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
latestDetails.removeAll()
|
||||
detailRenderCaches.removeAll()
|
||||
attachmentURLs.removeAll()
|
||||
pendingBootstrapSubmission = nil
|
||||
pendingBootstrapSubmissions.removeAll()
|
||||
pendingTurnSubmissions.removeAll()
|
||||
approvalRoutes.removeAll()
|
||||
inputRoutes.removeAll()
|
||||
@@ -303,6 +315,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
return try await client.browseFilesystem(partialPath: partialPath)
|
||||
}
|
||||
|
||||
func workspaceAssetURL(threadID: String, path: String) async throws -> URL {
|
||||
let route = try threadRoute(for: threadID)
|
||||
return try await route.client.resolvedAssetURL(
|
||||
resource: .workspaceFile(threadID: route.wireID, path: path)
|
||||
)
|
||||
}
|
||||
|
||||
func discoverProjectSources(
|
||||
environmentID: String
|
||||
) async throws -> SourceControlDiscoveryResult {
|
||||
@@ -335,7 +354,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
)
|
||||
} catch let error as RPCError {
|
||||
switch error {
|
||||
case .connectionUnavailable, .disconnected:
|
||||
case .connectionUnavailable, .disconnected, .responseTimedOut:
|
||||
// The clone RPC is not receipt-bearing, so a lost reply is
|
||||
// ambiguous. Confirm the requested destination became a Git
|
||||
// repository with a primary remote before moving on to the
|
||||
@@ -558,6 +577,62 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws -> FeatureThread {
|
||||
try await createThreadAndSendResolved(
|
||||
projectID: projectID,
|
||||
prompt: prompt,
|
||||
selection: selection,
|
||||
runtimeMode: runtimeMode,
|
||||
interactionMode: interactionMode,
|
||||
workspaceMode: workspaceMode,
|
||||
branch: branch,
|
||||
worktreePath: worktreePath,
|
||||
startFromOrigin: startFromOrigin,
|
||||
attachments: attachments,
|
||||
submissionIdentity: nil
|
||||
)
|
||||
}
|
||||
|
||||
func createThreadAndSend(
|
||||
projectID: String,
|
||||
prompt: String,
|
||||
selection: FeatureSelection?,
|
||||
runtimeMode: FeatureRuntimeMode,
|
||||
interactionMode: FeatureInteractionMode,
|
||||
workspaceMode: FeatureWorkspaceMode,
|
||||
branch: String?,
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws -> FeatureThread {
|
||||
try await createThreadAndSendResolved(
|
||||
projectID: projectID,
|
||||
prompt: prompt,
|
||||
selection: selection,
|
||||
runtimeMode: runtimeMode,
|
||||
interactionMode: interactionMode,
|
||||
workspaceMode: workspaceMode,
|
||||
branch: branch,
|
||||
worktreePath: worktreePath,
|
||||
startFromOrigin: startFromOrigin,
|
||||
attachments: attachments,
|
||||
submissionIdentity: identity
|
||||
)
|
||||
}
|
||||
|
||||
private func createThreadAndSendResolved(
|
||||
projectID: String,
|
||||
prompt: String,
|
||||
selection: FeatureSelection?,
|
||||
runtimeMode: FeatureRuntimeMode,
|
||||
interactionMode: FeatureInteractionMode,
|
||||
workspaceMode: FeatureWorkspaceMode,
|
||||
branch: String?,
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
submissionIdentity: FeatureSubmissionIdentity?
|
||||
) async throws -> FeatureThread {
|
||||
let route = try projectRoute(for: projectID)
|
||||
let client = route.client
|
||||
@@ -592,19 +667,29 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
attachments: attachments
|
||||
)
|
||||
let pending: PendingBootstrapSubmission
|
||||
if let existing = pendingBootstrapSubmission,
|
||||
existing.signature == signature {
|
||||
let explicitIdentity = submissionIdentity.map { commandIdentity($0) }
|
||||
if let explicitIdentity,
|
||||
let existing = pendingBootstrapSubmissions.first(where: {
|
||||
$0.identity == explicitIdentity
|
||||
}) {
|
||||
pending = existing
|
||||
} else if explicitIdentity == nil,
|
||||
let existing = pendingBootstrapSubmissions.first(where: {
|
||||
$0.signature == signature
|
||||
}) {
|
||||
pending = existing
|
||||
} else {
|
||||
pending = PendingBootstrapSubmission(
|
||||
signature: signature,
|
||||
threadID: UUID().uuidString,
|
||||
identity: CommandIdentity(),
|
||||
threadID: submissionIdentity?.threadID ?? UUID().uuidString,
|
||||
identity: explicitIdentity ?? CommandIdentity(),
|
||||
worktreeBranchName: workspaceMode == .worktree
|
||||
? Self.temporaryWorktreeBranchName()
|
||||
? Self.temporaryWorktreeBranchName(
|
||||
seed: submissionIdentity?.threadID
|
||||
)
|
||||
: nil
|
||||
)
|
||||
pendingBootstrapSubmission = pending
|
||||
pendingBootstrapSubmissions.append(pending)
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -662,9 +747,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
guard isKnownClient(client, environmentID: environment.id, generation: generation) else {
|
||||
throw CancellationError()
|
||||
}
|
||||
if pendingBootstrapSubmission?.identity == pending.identity {
|
||||
pendingBootstrapSubmission = nil
|
||||
}
|
||||
removePendingBootstrap(identity: pending.identity)
|
||||
// Dispatch acceptance is the commit point. A dropped refresh must not
|
||||
// turn a successful first turn into a retry that creates a duplicate.
|
||||
if let shell = try? await client.shellSnapshot() {
|
||||
@@ -783,9 +866,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
try? await client.removeWorktree(cwd: projectCwd, path: path)
|
||||
}
|
||||
|
||||
if pendingBootstrapSubmission?.identity == pending.identity {
|
||||
pendingBootstrapSubmission = nil
|
||||
}
|
||||
removePendingBootstrap(identity: pending.identity)
|
||||
}
|
||||
|
||||
private func removePendingBootstrap(identity: CommandIdentity) {
|
||||
pendingBootstrapSubmissions.removeAll { $0.identity == identity }
|
||||
}
|
||||
|
||||
func renameThread(id: String, title: String) async throws {
|
||||
@@ -928,6 +1013,38 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws {
|
||||
try await sendMessageResolved(
|
||||
threadID: threadID,
|
||||
text: text,
|
||||
selection: selection,
|
||||
attachments: attachments,
|
||||
submissionIdentity: nil
|
||||
)
|
||||
}
|
||||
|
||||
func sendMessage(
|
||||
threadID: String,
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws {
|
||||
try await sendMessageResolved(
|
||||
threadID: threadID,
|
||||
text: text,
|
||||
selection: selection,
|
||||
attachments: attachments,
|
||||
submissionIdentity: identity
|
||||
)
|
||||
}
|
||||
|
||||
private func sendMessageResolved(
|
||||
threadID: String,
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
submissionIdentity: FeatureSubmissionIdentity?
|
||||
) async throws {
|
||||
let route = try threadRoute(for: threadID)
|
||||
let client = route.client
|
||||
@@ -949,20 +1066,26 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
attachments: attachments
|
||||
)
|
||||
let pending: PendingTurnSubmission
|
||||
if let existing = pendingTurnSubmissions[route.uiID],
|
||||
existing.signature == signature {
|
||||
let explicitIdentity = submissionIdentity.map { commandIdentity($0) }
|
||||
if let explicitIdentity,
|
||||
let existing = pendingTurnSubmissions[route.uiID],
|
||||
existing.identity == explicitIdentity {
|
||||
pending = existing
|
||||
} else if explicitIdentity == nil,
|
||||
let existing = pendingTurnSubmissions[route.uiID],
|
||||
existing.signature == signature {
|
||||
pending = existing
|
||||
} else {
|
||||
pending = PendingTurnSubmission(
|
||||
signature: signature,
|
||||
identity: CommandIdentity()
|
||||
identity: explicitIdentity ?? CommandIdentity()
|
||||
)
|
||||
pendingTurnSubmissions[route.uiID] = pending
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try await client.sendTurn(
|
||||
threadID: route.wireID,
|
||||
threadID: submissionIdentity?.threadID ?? route.wireID,
|
||||
text: text,
|
||||
runtimeMode: runtimeMode,
|
||||
interactionMode: interactionMode,
|
||||
@@ -978,7 +1101,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
}
|
||||
guard await messageWasCommitted(
|
||||
client: client,
|
||||
threadID: route.wireID,
|
||||
threadID: submissionIdentity?.threadID ?? route.wireID,
|
||||
messageID: pending.identity.messageID
|
||||
) else {
|
||||
// Keep the stable identity. Retrying the same restored draft
|
||||
@@ -1443,23 +1566,73 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
) {
|
||||
archivedThreadsByEnvironmentID[route.environmentID, default: []]
|
||||
.removeAll { $0.id == route.uiID }
|
||||
if var thread {
|
||||
var archivedShellThreads = archivedShellThreadsByEnvironmentID[
|
||||
route.environmentID,
|
||||
default: [:]
|
||||
]
|
||||
let previouslyArchivedShell = archivedShellThreads.removeValue(
|
||||
forKey: route.wireID
|
||||
)
|
||||
|
||||
if archived, var thread {
|
||||
// Keep the accepted lifecycle transition visible until both live
|
||||
// and archived follow-up reads converge, including when the
|
||||
// owning passive device drops immediately after the command.
|
||||
thread.isArchived = archived
|
||||
thread.isArchived = true
|
||||
archivedThreadsByEnvironmentID[route.environmentID, default: []].append(thread)
|
||||
}
|
||||
if archived {
|
||||
if let shell = shellsByEnvironmentID[route.environmentID] {
|
||||
|
||||
if let shell = shellsByEnvironmentID[route.environmentID] {
|
||||
if archived {
|
||||
if let liveThread = shell.threads.first(where: { $0.id == route.wireID }) {
|
||||
archivedShellThreads[route.wireID] = liveThread
|
||||
}
|
||||
shellsByEnvironmentID[route.environmentID] = OrchestrationShellSnapshot(
|
||||
snapshotSequence: shell.snapshotSequence,
|
||||
projects: shell.projects,
|
||||
threads: shell.threads.filter { $0.id != route.wireID },
|
||||
updatedAt: shell.updatedAt
|
||||
)
|
||||
} else if let previouslyArchivedShell {
|
||||
var threads = shell.threads.filter { $0.id != route.wireID }
|
||||
threads.append(Self.unarchived(previouslyArchivedShell))
|
||||
shellsByEnvironmentID[route.environmentID] = OrchestrationShellSnapshot(
|
||||
snapshotSequence: shell.snapshotSequence,
|
||||
projects: shell.projects,
|
||||
threads: threads,
|
||||
updatedAt: shell.updatedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
archivedShellThreadsByEnvironmentID[route.environmentID] = archivedShellThreads
|
||||
}
|
||||
|
||||
private static func unarchived(
|
||||
_ thread: OrchestrationThreadShell
|
||||
) -> OrchestrationThreadShell {
|
||||
OrchestrationThreadShell(
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: nil,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil,
|
||||
snoozedAt: thread.snoozedAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: thread.latestUserMessageAt,
|
||||
hasPendingApprovals: thread.hasPendingApprovals,
|
||||
hasPendingUserInput: thread.hasPendingUserInput,
|
||||
hasActionableProposedPlan: thread.hasActionableProposedPlan
|
||||
)
|
||||
}
|
||||
|
||||
private func emitCachedSnapshot(for environmentID: String) async {
|
||||
@@ -1617,8 +1790,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
detail: "Live updates paused. Refreshing over HTTP."
|
||||
)
|
||||
}
|
||||
let fallbackPollingInitialDelay = fallbackPollingInitialDelay
|
||||
let fallbackPollingInterval = fallbackPollingInterval
|
||||
fallbackPollingTask = Task { [weak self] in
|
||||
try? await Task.sleep(for: .seconds(3))
|
||||
do {
|
||||
try await Task.sleep(for: fallbackPollingInitialDelay)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
while !Task.isCancelled {
|
||||
guard let self,
|
||||
self.isCurrentSession(
|
||||
@@ -1637,22 +1816,39 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
)
|
||||
do {
|
||||
let shell = try await activeClient.shellSnapshot()
|
||||
guard !Task.isCancelled else { return }
|
||||
await self.consume(
|
||||
guard !Task.isCancelled,
|
||||
self.isCurrentSession(
|
||||
client: activeClient,
|
||||
generation: generation
|
||||
) else {
|
||||
return
|
||||
}
|
||||
await self.consumeFallbackShell(
|
||||
shell: shell,
|
||||
client: activeClient,
|
||||
refreshActiveThread: true
|
||||
generation: generation
|
||||
)
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
guard !Task.isCancelled,
|
||||
self.isCurrentSession(
|
||||
client: activeClient,
|
||||
generation: generation
|
||||
) else {
|
||||
return
|
||||
}
|
||||
self.emitConnection(
|
||||
.reconnecting,
|
||||
detail: "Server unreachable. Retrying automatically."
|
||||
)
|
||||
}
|
||||
}
|
||||
try? await Task.sleep(for: .seconds(2))
|
||||
do {
|
||||
try await Task.sleep(for: fallbackPollingInterval)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
configurationTask = Task { [weak self] in
|
||||
@@ -1773,6 +1969,30 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP fallback refreshes data while preserving the socket's reconnecting
|
||||
/// state. The generation travels through the awaited snapshot publish so a
|
||||
/// task from a previous environment session cannot publish late results.
|
||||
private func consumeFallbackShell(
|
||||
shell: OrchestrationShellSnapshot,
|
||||
client: T3Client,
|
||||
generation: Int
|
||||
) async {
|
||||
guard isCurrentSession(client: client, generation: generation) else { return }
|
||||
shellPublishTask?.cancel()
|
||||
shellPublishTask = nil
|
||||
latestShell = shell
|
||||
await emitSnapshot(
|
||||
shell,
|
||||
markSourceConnected: false,
|
||||
expectedGeneration: generation
|
||||
)
|
||||
guard isCurrentSession(client: client, generation: generation),
|
||||
let threadID = activeThreadID else {
|
||||
return
|
||||
}
|
||||
scheduleDetailRefresh(threadID: threadID, client: client)
|
||||
}
|
||||
|
||||
private func consume(delta: ShellStreamItem, client: T3Client) async {
|
||||
guard let currentClient = self.client, currentClient === client else { return }
|
||||
guard let current = latestShell else {
|
||||
@@ -2198,6 +2418,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
archivedThreadsByEnvironmentID = archivedThreadsByEnvironmentID.filter {
|
||||
savedIDs.contains($0.key)
|
||||
}
|
||||
archivedShellThreadsByEnvironmentID = archivedShellThreadsByEnvironmentID.filter {
|
||||
savedIDs.contains($0.key)
|
||||
}
|
||||
environmentConnectionStates = environmentConnectionStates.filter {
|
||||
savedIDs.contains($0.key)
|
||||
}
|
||||
@@ -2333,6 +2556,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
archivedThreadsByEnvironmentID[environment.id] = archivedShell.threads.map {
|
||||
mapThread($0, environment: environment)
|
||||
}
|
||||
archivedShellThreadsByEnvironmentID[environment.id] = Dictionary(
|
||||
uniqueKeysWithValues: archivedShell.threads.map { ($0.id, $0) }
|
||||
)
|
||||
rebuildEntityIndexes((try? await runtime.environments()) ?? [environment])
|
||||
}
|
||||
await emitSnapshot(shell, environment: environment)
|
||||
@@ -2351,6 +2577,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
self.archivedThreadsByEnvironmentID[environment.id] = archivedShell.threads.map {
|
||||
self.mapThread($0, environment: environment)
|
||||
}
|
||||
self.archivedShellThreadsByEnvironmentID[environment.id] = Dictionary(
|
||||
uniqueKeysWithValues: archivedShell.threads.map { ($0.id, $0) }
|
||||
)
|
||||
self.rebuildEntityIndexes(
|
||||
(try? await self.runtime.environments()) ?? [environment]
|
||||
)
|
||||
@@ -2395,26 +2624,32 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
|
||||
private func emitSnapshot(
|
||||
_ shell: OrchestrationShellSnapshot,
|
||||
environment sourceEnvironment: Environment? = nil
|
||||
environment sourceEnvironment: Environment? = nil,
|
||||
markSourceConnected: Bool = true,
|
||||
expectedGeneration: Int? = nil
|
||||
) async {
|
||||
guard let environment = activeEnvironment else { return }
|
||||
let sourceEnvironment = sourceEnvironment ?? environment
|
||||
let generation = environmentGeneration
|
||||
guard expectedGeneration == nil || expectedGeneration == generation else { return }
|
||||
let environments = (try? await runtime.environments()) ?? [environment]
|
||||
guard generation == environmentGeneration,
|
||||
expectedGeneration == nil || expectedGeneration == environmentGeneration,
|
||||
activeEnvironment?.id == environment.id else {
|
||||
return
|
||||
}
|
||||
shellsByEnvironmentID[sourceEnvironment.id] = shell
|
||||
environmentConnectionStates[sourceEnvironment.id] = .connected
|
||||
environmentConnectionDetails[sourceEnvironment.id] = nil
|
||||
if markSourceConnected {
|
||||
environmentConnectionStates[sourceEnvironment.id] = .connected
|
||||
environmentConnectionDetails[sourceEnvironment.id] = nil
|
||||
}
|
||||
if sourceEnvironment.id == environment.id {
|
||||
latestShell = shell
|
||||
}
|
||||
rebuildEntityIndexes(environments)
|
||||
let connectionState: FeatureConnection.State
|
||||
let connectionDetail: String?
|
||||
if sourceEnvironment.id == environment.id {
|
||||
if sourceEnvironment.id == environment.id, markSourceConnected {
|
||||
connectionState = .connected
|
||||
connectionDetail = nil
|
||||
} else {
|
||||
@@ -3352,7 +3587,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
config: ServerConfigSnapshot?
|
||||
) -> [FeatureProvider] {
|
||||
if let providers = config?.providers, !providers.isEmpty {
|
||||
return providers.map { provider in
|
||||
return Self.normalizedProviders(providers.map { provider in
|
||||
FeatureProvider(
|
||||
id: provider.instanceId,
|
||||
name: provider.displayName ?? providerDisplayName(provider.driver),
|
||||
@@ -3401,7 +3636,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var modelsByProvider: [String: Set<String>] = [:]
|
||||
@@ -3424,6 +3659,32 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
}
|
||||
}
|
||||
|
||||
static func normalizedProviders(
|
||||
_ providers: [FeatureProvider]
|
||||
) -> [FeatureProvider] {
|
||||
var normalized: [FeatureProvider] = []
|
||||
var providerIndexByID: [String: Int] = [:]
|
||||
|
||||
for var provider in providers {
|
||||
var seenModelIDs = Set<String>()
|
||||
provider.models = provider.models.filter {
|
||||
seenModelIDs.insert($0.id).inserted
|
||||
}
|
||||
if let index = providerIndexByID[provider.id] {
|
||||
var existing = normalized[index]
|
||||
var existingModelIDs = Set(existing.models.map(\.id))
|
||||
existing.models.append(contentsOf: provider.models.filter {
|
||||
existingModelIDs.insert($0.id).inserted
|
||||
})
|
||||
normalized[index] = existing
|
||||
} else {
|
||||
providerIndexByID[provider.id] = normalized.count
|
||||
normalized.append(provider)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
private func modelSelection(
|
||||
_ selection: FeatureSelection?,
|
||||
projectID: String,
|
||||
@@ -3445,7 +3706,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
)
|
||||
}
|
||||
|
||||
/// Automatic selection is resolved against the target environment. This
|
||||
/// Fallback selection is resolved against the target environment. This
|
||||
/// matters when a passive machine exposes a different provider catalogue
|
||||
/// than the currently active one.
|
||||
private func fallbackModelSelection(
|
||||
@@ -3846,8 +4107,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
|
||||
return "\(compact.prefix(69).trimmingCharacters(in: .whitespacesAndNewlines))..."
|
||||
}
|
||||
|
||||
private static func temporaryWorktreeBranchName() -> String {
|
||||
"t3code/\(UUID().uuidString.prefix(8).lowercased())"
|
||||
private func commandIdentity(
|
||||
_ identity: FeatureSubmissionIdentity
|
||||
) -> CommandIdentity {
|
||||
CommandIdentity(
|
||||
commandID: identity.commandID,
|
||||
messageID: identity.messageID,
|
||||
createdAt: Self.fractionalDateFormatter.string(from: identity.createdAt)
|
||||
)
|
||||
}
|
||||
|
||||
private static func temporaryWorktreeBranchName(seed: String? = nil) -> String {
|
||||
let suffix = seed ?? UUID().uuidString
|
||||
return "t3code/\(suffix.prefix(8).lowercased())"
|
||||
}
|
||||
|
||||
private func previewText(_ text: String?) -> String? {
|
||||
|
||||
@@ -993,8 +993,18 @@ public actor EnvironmentRuntime {
|
||||
if existing.environment == environment {
|
||||
return existing
|
||||
}
|
||||
clients.removeValue(forKey: environment.id)
|
||||
await existing.disconnect()
|
||||
// Publish the replacement before disconnecting the stale client.
|
||||
// Actor methods are reentrant across that await; removing first
|
||||
// allowed a concurrent caller to construct a second replacement.
|
||||
let replacement = T3Client(
|
||||
environment: environment,
|
||||
credentialStore: credentialStore,
|
||||
httpTransport: httpTransport,
|
||||
webSocketConnector: webSocketConnector
|
||||
)
|
||||
clients[environment.id] = replacement
|
||||
Task { await existing.disconnect() }
|
||||
return replacement
|
||||
}
|
||||
let client = T3Client(
|
||||
environment: environment,
|
||||
|
||||
@@ -92,6 +92,7 @@ private actor URLSessionWebSocketConnection: WebSocketConnection {
|
||||
public enum RPCError: LocalizedError, Sendable {
|
||||
case connectionUnavailable
|
||||
case disconnected
|
||||
case responseTimedOut
|
||||
case remote(String)
|
||||
case protocolViolation(String)
|
||||
|
||||
@@ -100,6 +101,7 @@ public enum RPCError: LocalizedError, Sendable {
|
||||
case .connectionUnavailable:
|
||||
"The live command connection is unavailable."
|
||||
case .disconnected: "The environment disconnected."
|
||||
case .responseTimedOut: "The environment did not answer the command in time."
|
||||
case let .remote(message): message
|
||||
case let .protocolViolation(message): message
|
||||
}
|
||||
@@ -153,6 +155,8 @@ public actor WebSocketRPCClient {
|
||||
private struct UnaryRequest {
|
||||
let envelope: RPCRequestEnvelope
|
||||
var sent: Bool
|
||||
var connectionWaitTask: Task<Void, Never>?
|
||||
var responseDeadlineTask: Task<Void, Never>?
|
||||
let resume: @Sendable (Result<JSONValue, Error>) -> Void
|
||||
}
|
||||
|
||||
@@ -168,6 +172,7 @@ public actor WebSocketRPCClient {
|
||||
private let connector: any WebSocketConnecting
|
||||
private let endpointProvider: EndpointProvider
|
||||
private let connectionWaitTimeout: Duration
|
||||
private let responseTimeout: Duration
|
||||
private var connection: (any WebSocketConnection)?
|
||||
private var loopTask: Task<Void, Never>?
|
||||
private var keepaliveTask: Task<Void, Never>?
|
||||
@@ -180,10 +185,12 @@ public actor WebSocketRPCClient {
|
||||
public init(
|
||||
connector: any WebSocketConnecting = URLSessionWebSocketConnector(),
|
||||
connectionWaitTimeout: Duration = .seconds(4),
|
||||
responseTimeout: Duration = .seconds(30),
|
||||
endpointProvider: @escaping EndpointProvider
|
||||
) {
|
||||
self.connector = connector
|
||||
self.connectionWaitTimeout = connectionWaitTimeout
|
||||
self.responseTimeout = responseTimeout
|
||||
self.endpointProvider = endpointProvider
|
||||
}
|
||||
|
||||
@@ -282,24 +289,22 @@ public actor WebSocketRPCClient {
|
||||
payload: payload,
|
||||
headers: []
|
||||
)
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
unary[id] = UnaryRequest(
|
||||
envelope: envelope,
|
||||
sent: false,
|
||||
resume: { continuation.resume(with: $0) }
|
||||
)
|
||||
if connection != nil {
|
||||
Task { await self.sendUnary(id) }
|
||||
}
|
||||
let timeout = connectionWaitTimeout
|
||||
Task { [weak self] in
|
||||
do {
|
||||
try await Task.sleep(for: timeout)
|
||||
} catch {
|
||||
return
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
unary[id] = UnaryRequest(
|
||||
envelope: envelope,
|
||||
sent: false,
|
||||
connectionWaitTask: nil,
|
||||
responseDeadlineTask: nil,
|
||||
resume: { continuation.resume(with: $0) }
|
||||
)
|
||||
installUnaryDeadlines(id)
|
||||
if connection != nil {
|
||||
Task { await self.sendUnary(id) }
|
||||
}
|
||||
await self?.failUnaryIfUnsent(id)
|
||||
}
|
||||
} onCancel: {
|
||||
Task { await self.cancelUnary(id) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,11 +380,11 @@ public actor WebSocketRPCClient {
|
||||
try await sendControl("Ack", requestID: requestID)
|
||||
case "Exit":
|
||||
guard let requestID = response.requestId, let exit = response.exit else { return }
|
||||
if let request = unary.removeValue(forKey: requestID) {
|
||||
if unary[requestID] != nil {
|
||||
if exit._tag == "Success" {
|
||||
request.resume(.success(exit.value ?? .null))
|
||||
completeUnary(requestID, with: .success(exit.value ?? .null))
|
||||
} else {
|
||||
request.resume(.failure(remoteError(exit)))
|
||||
completeUnary(requestID, with: .failure(remoteError(exit)))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -408,8 +413,7 @@ public actor WebSocketRPCClient {
|
||||
} catch {
|
||||
// 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))
|
||||
completeUnary(id, with: .failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,17 +461,65 @@ public actor WebSocketRPCClient {
|
||||
}
|
||||
|
||||
private func failUnary(_ error: Error, includingUnsent: Bool) {
|
||||
let failed = unary.filter { includingUnsent || $0.value.sent }
|
||||
for (id, request) in failed {
|
||||
unary.removeValue(forKey: id)
|
||||
request.resume(.failure(error))
|
||||
let failedIDs = unary.compactMap { id, request in
|
||||
includingUnsent || request.sent ? id : nil
|
||||
}
|
||||
for id in failedIDs {
|
||||
completeUnary(id, with: .failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func failUnaryIfUnsent(_ id: Int) {
|
||||
guard let request = unary[id], !request.sent else { return }
|
||||
unary.removeValue(forKey: id)
|
||||
request.resume(.failure(RPCError.connectionUnavailable))
|
||||
completeUnary(id, with: .failure(RPCError.connectionUnavailable))
|
||||
}
|
||||
|
||||
private func installUnaryDeadlines(_ id: Int) {
|
||||
guard var request = unary[id] else { return }
|
||||
let connectionWaitTimeout = connectionWaitTimeout
|
||||
let responseTimeout = responseTimeout
|
||||
request.connectionWaitTask = Task { [weak self] in
|
||||
do {
|
||||
try await Task.sleep(for: connectionWaitTimeout)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await self?.failUnaryIfUnsent(id)
|
||||
}
|
||||
request.responseDeadlineTask = Task { [weak self] in
|
||||
do {
|
||||
try await Task.sleep(for: responseTimeout)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await self?.failUnaryOnResponseDeadline(id)
|
||||
}
|
||||
unary[id] = request
|
||||
}
|
||||
|
||||
private func failUnaryOnResponseDeadline(_ id: Int) async {
|
||||
guard let request = unary[id] else { return }
|
||||
let sent = request.sent
|
||||
completeUnary(id, with: .failure(RPCError.responseTimedOut))
|
||||
if sent {
|
||||
try? await sendControl("Interrupt", requestID: id)
|
||||
}
|
||||
}
|
||||
|
||||
private func cancelUnary(_ id: Int) async {
|
||||
guard let request = unary[id] else { return }
|
||||
let sent = request.sent
|
||||
completeUnary(id, with: .failure(CancellationError()))
|
||||
if sent {
|
||||
try? await sendControl("Interrupt", requestID: id)
|
||||
}
|
||||
}
|
||||
|
||||
private func completeUnary(_ id: Int, with result: Result<JSONValue, Error>) {
|
||||
guard let request = unary.removeValue(forKey: id) else { return }
|
||||
request.connectionWaitTask?.cancel()
|
||||
request.responseDeadlineTask?.cancel()
|
||||
request.resume(result)
|
||||
}
|
||||
|
||||
private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError {
|
||||
|
||||
@@ -32,9 +32,19 @@ public final class FeatureRootModel {
|
||||
public var errorMessage: String?
|
||||
|
||||
let client: any FeatureClient
|
||||
private let outboxStore: FeatureOutboxStore
|
||||
private var pendingSubmissionsByID: [String: FeatureQueuedSubmission] = [:]
|
||||
private var pendingThreadsByID: [String: FeatureThread] = [:]
|
||||
private var outboxDrainTask: Task<Void, Never>?
|
||||
private var outboxRetryAttempt = 0
|
||||
private var outboxGeneration: UInt64 = 0
|
||||
|
||||
public init(client: any FeatureClient) {
|
||||
public init(
|
||||
client: any FeatureClient,
|
||||
outboxStore: FeatureOutboxStore = .shared
|
||||
) {
|
||||
self.client = client
|
||||
self.outboxStore = outboxStore
|
||||
}
|
||||
|
||||
public func start() async {
|
||||
@@ -45,7 +55,9 @@ public final class FeatureRootModel {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
await restoreOutbox()
|
||||
isLoading = false
|
||||
scheduleOutboxDrain()
|
||||
|
||||
for await event in client.events() {
|
||||
apply(event)
|
||||
@@ -79,18 +91,29 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
public func removeEnvironment(_ id: String) async {
|
||||
await stopOutboxDrain()
|
||||
await perform {
|
||||
try await client.removeEnvironment(id: id)
|
||||
try? await outboxStore.removeAll(environmentID: id)
|
||||
removePendingSubmissions(environmentID: id)
|
||||
install(try await client.initialSnapshot())
|
||||
clearDetails()
|
||||
}
|
||||
scheduleOutboxDrain()
|
||||
}
|
||||
|
||||
public func disconnect() async {
|
||||
await stopOutboxDrain()
|
||||
isManagingConnections = false
|
||||
await client.disconnect()
|
||||
let disconnectedEnvironments = snapshot.environments.map { environment in
|
||||
var environment = environment
|
||||
environment.connectionState = .disconnected
|
||||
environment.connectionDetail = nil
|
||||
return environment
|
||||
}
|
||||
install(FeatureSnapshot(
|
||||
environments: snapshot.environments,
|
||||
environments: disconnectedEnvironments,
|
||||
settings: snapshot.settings
|
||||
))
|
||||
clearDetails()
|
||||
@@ -134,9 +157,40 @@ public final class FeatureRootModel {
|
||||
guard !prompt.isEmpty || !request.attachments.isEmpty else { return nil }
|
||||
guard request.workspaceMode != .worktree || request.branch != nil else { return nil }
|
||||
|
||||
let environment = currentEnvironmentIdentity
|
||||
var created: FeatureThread?
|
||||
let succeeded = await perform(reportError: false) {
|
||||
guard let project = snapshot.projects.first(where: { $0.id == request.projectID }) else {
|
||||
errorMessage = "That project is no longer available."
|
||||
return nil
|
||||
}
|
||||
let identity = FeatureSubmissionIdentity()
|
||||
let threadID = FeatureScopedID.thread(
|
||||
environmentID: project.environmentID,
|
||||
wireID: identity.threadID
|
||||
)
|
||||
let uploads = request.attachments.map(\.upload)
|
||||
let queued = FeatureQueuedSubmission(
|
||||
environmentID: project.environmentID,
|
||||
identity: identity,
|
||||
threadID: threadID,
|
||||
text: prompt,
|
||||
selection: request.selection,
|
||||
runtimeMode: request.runtimeMode,
|
||||
interactionMode: request.interactionMode,
|
||||
attachments: uploads,
|
||||
creation: FeatureQueuedCreation(
|
||||
projectID: request.projectID,
|
||||
projectName: project.name,
|
||||
workspaceMode: request.workspaceMode,
|
||||
branch: request.branch,
|
||||
worktreePath: request.worktreePath,
|
||||
startFromOrigin: request.startFromOrigin
|
||||
)
|
||||
)
|
||||
guard await enqueue(queued) else { return nil }
|
||||
installPendingCreation(queued, project: project)
|
||||
|
||||
isPerformingAction = true
|
||||
defer { isPerformingAction = false }
|
||||
do {
|
||||
let thread = try await client.createThreadAndSend(
|
||||
projectID: request.projectID,
|
||||
prompt: prompt,
|
||||
@@ -147,15 +201,29 @@ public final class FeatureRootModel {
|
||||
branch: request.branch,
|
||||
worktreePath: request.worktreePath,
|
||||
startFromOrigin: request.startFromOrigin,
|
||||
attachments: request.attachments.map(\.upload)
|
||||
attachments: uploads,
|
||||
identity: identity
|
||||
)
|
||||
guard currentEnvironmentIdentity == environment else {
|
||||
throw CancellationError()
|
||||
await completeQueuedSubmission(queued)
|
||||
if thread.id != queued.threadID {
|
||||
removeThread(id: queued.threadID)
|
||||
removeDetail(id: queued.threadID)
|
||||
}
|
||||
upsert(thread)
|
||||
created = thread
|
||||
return thread
|
||||
} catch {
|
||||
if Self.shouldQueue(error, environmentID: project.environmentID, snapshot: snapshot) {
|
||||
if isEnvironmentConnected(project.environmentID) {
|
||||
scheduleOutboxRetry()
|
||||
}
|
||||
return pendingThreadsByID[threadID]
|
||||
}
|
||||
await discardQueuedSubmission(queued)
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return succeeded ? created : nil
|
||||
}
|
||||
|
||||
public func workspaceBranches(
|
||||
@@ -280,12 +348,29 @@ 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)"
|
||||
guard let thread = snapshot.threads.first(where: { $0.id == submission.threadID }),
|
||||
let environmentID = thread.environmentID else {
|
||||
return false
|
||||
}
|
||||
let identity = FeatureSubmissionIdentity(threadID: thread.wireID ?? thread.id)
|
||||
let uploads = submission.attachments.map(\.upload)
|
||||
let queued = FeatureQueuedSubmission(
|
||||
environmentID: environmentID,
|
||||
identity: identity,
|
||||
threadID: submission.threadID,
|
||||
text: trimmed,
|
||||
selection: submission.selection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
attachments: uploads
|
||||
)
|
||||
guard await enqueue(queued) else { return false }
|
||||
|
||||
let optimistic = FeatureMessage(
|
||||
id: optimisticID,
|
||||
id: identity.messageID,
|
||||
role: .user,
|
||||
text: trimmed,
|
||||
createdAt: identity.createdAt,
|
||||
state: .queued,
|
||||
attachments: submission.attachments.map {
|
||||
FeatureMessageAttachment(
|
||||
@@ -306,21 +391,34 @@ public final class FeatureRootModel {
|
||||
$0.messages.append(optimistic)
|
||||
}
|
||||
|
||||
let sent = await perform(reportError: false) {
|
||||
isPerformingAction = true
|
||||
defer { isPerformingAction = false }
|
||||
do {
|
||||
try await client.sendMessage(
|
||||
threadID: submission.threadID,
|
||||
text: trimmed,
|
||||
selection: submission.selection,
|
||||
attachments: submission.attachments.map(\.upload)
|
||||
attachments: uploads,
|
||||
identity: identity
|
||||
)
|
||||
}
|
||||
if !sent {
|
||||
guard currentEnvironmentIdentity == environment else { return false }
|
||||
mutateDetail(id: submission.threadID) {
|
||||
$0.messages.removeAll { $0.id == optimisticID }
|
||||
await completeQueuedSubmission(queued)
|
||||
return true
|
||||
} catch {
|
||||
if Self.shouldQueue(error, environmentID: environmentID, snapshot: snapshot) {
|
||||
if isEnvironmentConnected(environmentID) {
|
||||
scheduleOutboxRetry()
|
||||
}
|
||||
return true
|
||||
}
|
||||
await discardQueuedSubmission(queued)
|
||||
mutateDetail(id: submission.threadID) {
|
||||
$0.messages.removeAll { $0.id == identity.messageID }
|
||||
}
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
return false
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
public func cancelTurn(threadID: String) async {
|
||||
@@ -421,7 +519,11 @@ public final class FeatureRootModel {
|
||||
guard snapshot.connection != value else { return }
|
||||
snapshot.connection = value
|
||||
homePresentationRevision &+= 1
|
||||
if value.state == .connected {
|
||||
scheduleOutboxDrain()
|
||||
}
|
||||
case let .thread(value):
|
||||
acknowledgeAuthoritativeThread(value.id)
|
||||
upsert(value)
|
||||
mutateDetail(
|
||||
id: value.id,
|
||||
@@ -475,6 +577,18 @@ public final class FeatureRootModel {
|
||||
}
|
||||
|
||||
private func install(_ value: FeatureSnapshot) {
|
||||
var value = value
|
||||
let authoritativeThreadIDs = Set(value.threads.map(\.id))
|
||||
for id in authoritativeThreadIDs {
|
||||
acknowledgeAuthoritativeThread(id)
|
||||
}
|
||||
for pending in pendingThreadsByID.values where !authoritativeThreadIDs.contains(pending.id) {
|
||||
value.threads.append(pending)
|
||||
if let index = value.projects.firstIndex(where: { $0.id == pending.projectID }) {
|
||||
value.projects[index].threadCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
if snapshot.connection != value.connection
|
||||
|| snapshot.environments != value.environments
|
||||
|| snapshot.projects != value.projects
|
||||
@@ -486,6 +600,10 @@ public final class FeatureRootModel {
|
||||
threadCollectionRevision &+= 1
|
||||
}
|
||||
snapshot = value
|
||||
if value.connection.state == .connected
|
||||
|| value.environments.contains(where: { $0.connectionState == .connected }) {
|
||||
scheduleOutboxDrain()
|
||||
}
|
||||
}
|
||||
|
||||
private func mutateThread(
|
||||
@@ -510,6 +628,8 @@ public final class FeatureRootModel {
|
||||
|
||||
private func store(_ incoming: FeatureThreadDetail) {
|
||||
let id = incoming.thread.id
|
||||
acknowledgeDeliveredMessages(incoming.messages)
|
||||
let incoming = addingPendingMessages(to: incoming)
|
||||
let next = details[id].map { current in
|
||||
FeatureThreadDetail(
|
||||
thread: incoming.thread,
|
||||
@@ -525,8 +645,15 @@ public final class FeatureRootModel {
|
||||
|
||||
private func store(_ incoming: FeatureThreadDetail, delta: FeatureDetailDelta) {
|
||||
let id = incoming.thread.id
|
||||
details[id] = incoming
|
||||
bumpDetailRevision(id: id, change: .delta(delta))
|
||||
acknowledgeDeliveredMessages(incoming.messages)
|
||||
let next = addingPendingMessages(to: incoming)
|
||||
details[id] = next
|
||||
let appended = next.messages.dropFirst(incoming.messages.count).map(\.id)
|
||||
let pendingDelta = FeatureDetailDelta(
|
||||
changedMessages: delta.changedMessages + next.messages.dropFirst(incoming.messages.count),
|
||||
appendedMessageIDs: delta.appendedMessageIDs + appended
|
||||
)
|
||||
bumpDetailRevision(id: id, change: .delta(pendingDelta))
|
||||
}
|
||||
|
||||
private func mutateDetail(
|
||||
@@ -578,6 +705,362 @@ public final class FeatureRootModel {
|
||||
result.replaceSubrange(prefixCount..., with: incoming.dropFirst(prefixCount))
|
||||
return result
|
||||
}
|
||||
|
||||
private func restoreOutbox() async {
|
||||
let submissions: [FeatureQueuedSubmission]
|
||||
do {
|
||||
submissions = try await outboxStore.submissions()
|
||||
} catch {
|
||||
errorMessage = "Could not restore queued messages: \(error.localizedDescription)"
|
||||
return
|
||||
}
|
||||
|
||||
for submission in submissions {
|
||||
if let creation = submission.creation {
|
||||
if snapshot.threads.contains(where: { $0.id == submission.threadID }) {
|
||||
try? await outboxStore.remove(id: submission.id)
|
||||
continue
|
||||
}
|
||||
guard let project = snapshot.projects.first(where: {
|
||||
$0.id == creation.projectID && $0.environmentID == submission.environmentID
|
||||
}) else {
|
||||
if isEnvironmentConnected(submission.environmentID) {
|
||||
try? await outboxStore.remove(id: submission.id)
|
||||
} else {
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
}
|
||||
continue
|
||||
}
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
installPendingCreation(submission, project: project)
|
||||
continue
|
||||
}
|
||||
|
||||
guard snapshot.threads.contains(where: { $0.id == submission.threadID }) else {
|
||||
if pendingThreadsByID[submission.threadID] != nil {
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
} else if isEnvironmentConnected(submission.environmentID) {
|
||||
try? await outboxStore.remove(id: submission.id)
|
||||
} else {
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
}
|
||||
continue
|
||||
}
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
if let detail = details[submission.threadID] {
|
||||
store(addingPendingMessages(to: detail))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func enqueue(_ submission: FeatureQueuedSubmission) async -> Bool {
|
||||
do {
|
||||
try await outboxStore.enqueue(submission)
|
||||
pendingSubmissionsByID[submission.id] = submission
|
||||
return true
|
||||
} catch {
|
||||
errorMessage = "Could not safely queue this message: \(error.localizedDescription)"
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func installPendingCreation(
|
||||
_ submission: FeatureQueuedSubmission,
|
||||
project: FeatureProject
|
||||
) {
|
||||
guard let creation = submission.creation else { return }
|
||||
let provider = provider(
|
||||
id: submission.selection?.providerID,
|
||||
environmentID: submission.environmentID
|
||||
)
|
||||
let environmentName = snapshot.environments.first {
|
||||
$0.id == submission.environmentID
|
||||
}?.name
|
||||
let title = submission.text
|
||||
.split(whereSeparator: \.isNewline)
|
||||
.first
|
||||
.map(String.init)?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let thread = FeatureThread(
|
||||
id: submission.threadID,
|
||||
wireID: submission.identity.threadID,
|
||||
projectID: project.id,
|
||||
environmentID: submission.environmentID,
|
||||
environmentName: environmentName,
|
||||
title: title?.isEmpty == false ? title! : "New task",
|
||||
preview: submission.text,
|
||||
branch: creation.branch,
|
||||
worktreePath: creation.worktreePath,
|
||||
createdAt: submission.identity.createdAt,
|
||||
updatedAt: submission.identity.createdAt,
|
||||
state: .queued,
|
||||
providerID: submission.selection?.providerID,
|
||||
providerName: provider?.name,
|
||||
modelID: submission.selection?.modelID,
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard
|
||||
)
|
||||
pendingThreadsByID[thread.id] = thread
|
||||
upsert(thread)
|
||||
store(FeatureThreadDetail(
|
||||
thread: thread,
|
||||
messages: [queuedMessage(for: submission)]
|
||||
))
|
||||
}
|
||||
|
||||
private func provider(id: String?, environmentID: String) -> FeatureProvider? {
|
||||
guard let id else { return nil }
|
||||
let providers = snapshot.providersByEnvironment?[environmentID] ?? snapshot.providers
|
||||
return providers.first { $0.id == id }
|
||||
}
|
||||
|
||||
private func queuedMessage(for submission: FeatureQueuedSubmission) -> FeatureMessage {
|
||||
FeatureMessage(
|
||||
id: submission.identity.messageID,
|
||||
role: .user,
|
||||
text: submission.text,
|
||||
createdAt: submission.identity.createdAt,
|
||||
state: .queued,
|
||||
attachments: submission.attachments.enumerated().map { index, attachment in
|
||||
FeatureMessageAttachment(
|
||||
id: "\(submission.id)-attachment-\(index)",
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.data.count
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func addingPendingMessages(to incoming: FeatureThreadDetail) -> FeatureThreadDetail {
|
||||
let queued = pendingSubmissionsByID.values
|
||||
.filter { $0.threadID == incoming.thread.id }
|
||||
.sorted { $0.identity.createdAt < $1.identity.createdAt }
|
||||
guard !queued.isEmpty else { return incoming }
|
||||
var result = incoming
|
||||
let existing = Set(result.messages.map(\.id))
|
||||
result.messages.append(contentsOf: queued.lazy
|
||||
.filter { !existing.contains($0.identity.messageID) }
|
||||
.map(queuedMessage(for:)))
|
||||
return result
|
||||
}
|
||||
|
||||
private func acknowledgeAuthoritativeThread(_ id: String) {
|
||||
guard pendingThreadsByID.removeValue(forKey: id) != nil,
|
||||
let submission = pendingSubmissionsByID.values.first(where: {
|
||||
$0.threadID == id && $0.creation != nil
|
||||
}) else { return }
|
||||
pendingSubmissionsByID.removeValue(forKey: submission.id)
|
||||
markQueuedMessageDelivered(submission)
|
||||
let store = outboxStore
|
||||
Task { try? await store.remove(id: submission.id) }
|
||||
}
|
||||
|
||||
private func acknowledgeDeliveredMessages(_ messages: [FeatureMessage]) {
|
||||
let messageIDs = Set(messages.map(\.id))
|
||||
let delivered = pendingSubmissionsByID.values.filter {
|
||||
$0.creation == nil && messageIDs.contains($0.identity.messageID)
|
||||
}
|
||||
for submission in delivered {
|
||||
pendingSubmissionsByID.removeValue(forKey: submission.id)
|
||||
let store = outboxStore
|
||||
Task { try? await store.remove(id: submission.id) }
|
||||
}
|
||||
}
|
||||
|
||||
private func completeQueuedSubmission(_ submission: FeatureQueuedSubmission) async {
|
||||
try? await outboxStore.remove(id: submission.id)
|
||||
pendingSubmissionsByID.removeValue(forKey: submission.id)
|
||||
pendingThreadsByID.removeValue(forKey: submission.threadID)
|
||||
markQueuedMessageDelivered(submission)
|
||||
outboxRetryAttempt = 0
|
||||
}
|
||||
|
||||
private func markQueuedMessageDelivered(_ submission: FeatureQueuedSubmission) {
|
||||
mutateDetail(
|
||||
id: submission.threadID,
|
||||
change: .delta(FeatureDetailDelta(changedMessages: []))
|
||||
) { detail in
|
||||
guard let index = detail.messages.firstIndex(where: {
|
||||
$0.id == submission.identity.messageID
|
||||
}) else { return }
|
||||
detail.messages[index].state = .complete
|
||||
}
|
||||
}
|
||||
|
||||
private func discardQueuedSubmission(_ submission: FeatureQueuedSubmission) async {
|
||||
try? await outboxStore.remove(id: submission.id)
|
||||
pendingSubmissionsByID.removeValue(forKey: submission.id)
|
||||
let wasPendingCreation = pendingThreadsByID.removeValue(forKey: submission.threadID) != nil
|
||||
if wasPendingCreation {
|
||||
removeThread(id: submission.threadID)
|
||||
removeDetail(id: submission.threadID)
|
||||
} else {
|
||||
mutateDetail(id: submission.threadID) {
|
||||
$0.messages.removeAll { $0.id == submission.identity.messageID }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func removePendingSubmissions(environmentID: String) {
|
||||
let removed = pendingSubmissionsByID.values.filter {
|
||||
$0.environmentID == environmentID
|
||||
}
|
||||
for submission in removed {
|
||||
pendingSubmissionsByID.removeValue(forKey: submission.id)
|
||||
if pendingThreadsByID.removeValue(forKey: submission.threadID) != nil {
|
||||
removeThread(id: submission.threadID)
|
||||
removeDetail(id: submission.threadID)
|
||||
} else {
|
||||
mutateDetail(id: submission.threadID) {
|
||||
$0.messages.removeAll { $0.id == submission.identity.messageID }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func scheduleOutboxDrain(after delay: Duration = .zero) {
|
||||
guard outboxDrainTask == nil, !pendingSubmissionsByID.isEmpty else { return }
|
||||
let generation = outboxGeneration
|
||||
outboxDrainTask = Task { @MainActor [weak self] in
|
||||
if delay > .zero {
|
||||
try? await Task.sleep(for: delay)
|
||||
}
|
||||
guard !Task.isCancelled,
|
||||
let self,
|
||||
self.outboxGeneration == generation else { return }
|
||||
let needsRetry = await self.drainOutbox(generation: generation)
|
||||
self.outboxDrainTask = nil
|
||||
if needsRetry,
|
||||
!Task.isCancelled,
|
||||
self.outboxGeneration == generation {
|
||||
self.scheduleOutboxRetry()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func stopOutboxDrain() async {
|
||||
outboxGeneration &+= 1
|
||||
guard let task = outboxDrainTask else { return }
|
||||
task.cancel()
|
||||
await task.value
|
||||
outboxDrainTask = nil
|
||||
}
|
||||
|
||||
private func scheduleOutboxRetry() {
|
||||
guard outboxDrainTask == nil else { return }
|
||||
let seconds = min(16, 1 << min(outboxRetryAttempt, 4))
|
||||
outboxRetryAttempt += 1
|
||||
scheduleOutboxDrain(after: .seconds(seconds))
|
||||
}
|
||||
|
||||
private func drainOutbox(generation: UInt64) async -> Bool {
|
||||
let submissions = pendingSubmissionsByID.values.sorted {
|
||||
$0.identity.createdAt < $1.identity.createdAt
|
||||
}
|
||||
var needsRetry = false
|
||||
for submission in submissions where pendingSubmissionsByID[submission.id] != nil {
|
||||
guard !Task.isCancelled, outboxGeneration == generation else { return false }
|
||||
var policySnapshot = snapshot
|
||||
if pendingThreadsByID[submission.threadID] != nil {
|
||||
policySnapshot.threads.removeAll { $0.id == submission.threadID }
|
||||
}
|
||||
switch FeatureOutboxPolicy.decision(
|
||||
for: submission,
|
||||
snapshot: policySnapshot,
|
||||
pendingCreationThreadIDs: Set(pendingThreadsByID.keys)
|
||||
) {
|
||||
case .discard:
|
||||
await discardQueuedSubmission(submission)
|
||||
case .wait:
|
||||
// Connectivity and snapshot events wake the drain immediately.
|
||||
// Avoid a permanent timer while the owning device is offline.
|
||||
continue
|
||||
case .send:
|
||||
do {
|
||||
guard pendingSubmissionsByID[submission.id] != nil,
|
||||
snapshot.environments.contains(where: {
|
||||
$0.id == submission.environmentID
|
||||
}) else {
|
||||
continue
|
||||
}
|
||||
if let creation = submission.creation {
|
||||
let thread = try await client.createThreadAndSend(
|
||||
projectID: creation.projectID,
|
||||
prompt: submission.text,
|
||||
selection: submission.selection,
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
workspaceMode: creation.workspaceMode,
|
||||
branch: creation.branch,
|
||||
worktreePath: creation.worktreePath,
|
||||
startFromOrigin: creation.startFromOrigin,
|
||||
attachments: submission.uploads,
|
||||
identity: submission.identity
|
||||
)
|
||||
guard !Task.isCancelled,
|
||||
outboxGeneration == generation else { return false }
|
||||
await completeQueuedSubmission(submission)
|
||||
if thread.id != submission.threadID {
|
||||
removeThread(id: submission.threadID)
|
||||
removeDetail(id: submission.threadID)
|
||||
}
|
||||
upsert(thread)
|
||||
} else {
|
||||
try await client.sendMessage(
|
||||
threadID: submission.threadID,
|
||||
text: submission.text,
|
||||
selection: submission.selection,
|
||||
attachments: submission.uploads,
|
||||
identity: submission.identity
|
||||
)
|
||||
guard !Task.isCancelled,
|
||||
outboxGeneration == generation else { return false }
|
||||
await completeQueuedSubmission(submission)
|
||||
}
|
||||
} catch {
|
||||
if Self.shouldQueue(
|
||||
error,
|
||||
environmentID: submission.environmentID,
|
||||
snapshot: snapshot
|
||||
) {
|
||||
needsRetry = true
|
||||
} else {
|
||||
await discardQueuedSubmission(submission)
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return needsRetry
|
||||
}
|
||||
|
||||
private func isEnvironmentConnected(_ environmentID: String) -> Bool {
|
||||
guard let environment = snapshot.environments.first(where: { $0.id == environmentID }) else {
|
||||
return false
|
||||
}
|
||||
return environment.connectionState == .connected
|
||||
|| (environment.isActive && snapshot.connection.state == .connected)
|
||||
}
|
||||
|
||||
private static func shouldQueue(
|
||||
_ error: any Error,
|
||||
environmentID: String,
|
||||
snapshot: FeatureSnapshot
|
||||
) -> Bool {
|
||||
if error is CancellationError || error is URLError { return true }
|
||||
if let environment = snapshot.environments.first(where: { $0.id == environmentID }) {
|
||||
let disconnected = environment.connectionState != .connected
|
||||
&& !(environment.isActive && snapshot.connection.state == .connected)
|
||||
if disconnected { return true }
|
||||
}
|
||||
let message = error.localizedDescription.lowercased()
|
||||
return [
|
||||
"cancelled", "canceled", "connection", "network", "offline",
|
||||
"socket", "timed out", "timeout", "transport", "not connected",
|
||||
"request deadline",
|
||||
].contains { message.contains($0) }
|
||||
}
|
||||
}
|
||||
|
||||
private extension FeatureDraftAttachment {
|
||||
|
||||
@@ -34,6 +34,19 @@ public protocol FeatureClient: AnyObject {
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws -> FeatureThread
|
||||
func createThreadAndSend(
|
||||
projectID: String,
|
||||
prompt: String,
|
||||
selection: FeatureSelection?,
|
||||
runtimeMode: FeatureRuntimeMode,
|
||||
interactionMode: FeatureInteractionMode,
|
||||
workspaceMode: FeatureWorkspaceMode,
|
||||
branch: String?,
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws -> FeatureThread
|
||||
func listWorkspaceBranches(
|
||||
projectID: String,
|
||||
refresh: Bool
|
||||
@@ -55,6 +68,13 @@ public protocol FeatureClient: AnyObject {
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws
|
||||
func sendMessage(
|
||||
threadID: String,
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws
|
||||
func cancelTurn(threadID: String) async throws
|
||||
func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws
|
||||
func resolveUserInput(id: String, answers: [String: FeatureInputAnswer]) async throws
|
||||
@@ -168,6 +188,36 @@ public extension FeatureClient {
|
||||
return thread
|
||||
}
|
||||
|
||||
/// Clients that understand stable command identities override this method.
|
||||
/// The compatibility path remains functional but cannot guarantee
|
||||
/// idempotence across a process death after an ambiguous network failure.
|
||||
func createThreadAndSend(
|
||||
projectID: String,
|
||||
prompt: String,
|
||||
selection: FeatureSelection?,
|
||||
runtimeMode: FeatureRuntimeMode,
|
||||
interactionMode: FeatureInteractionMode,
|
||||
workspaceMode: FeatureWorkspaceMode,
|
||||
branch: String?,
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws -> FeatureThread {
|
||||
try await createThreadAndSend(
|
||||
projectID: projectID,
|
||||
prompt: prompt,
|
||||
selection: selection,
|
||||
runtimeMode: runtimeMode,
|
||||
interactionMode: interactionMode,
|
||||
workspaceMode: workspaceMode,
|
||||
branch: branch,
|
||||
worktreePath: worktreePath,
|
||||
startFromOrigin: startFromOrigin,
|
||||
attachments: attachments
|
||||
)
|
||||
}
|
||||
|
||||
func sendMessage(
|
||||
threadID: String,
|
||||
text: String,
|
||||
@@ -180,6 +230,21 @@ public extension FeatureClient {
|
||||
try await sendMessage(threadID: threadID, text: text, selection: selection)
|
||||
}
|
||||
|
||||
func sendMessage(
|
||||
threadID: String,
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
identity: FeatureSubmissionIdentity
|
||||
) async throws {
|
||||
try await sendMessage(
|
||||
threadID: threadID,
|
||||
text: text,
|
||||
selection: selection,
|
||||
attachments: attachments
|
||||
)
|
||||
}
|
||||
|
||||
func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] {
|
||||
throw FeatureCapabilityUnavailable("Files")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import Foundation
|
||||
|
||||
/// Stable wire identities make an outbox retry idempotent across app launches,
|
||||
/// including the ambiguous case where the server committed a command but its
|
||||
/// response never reached the phone.
|
||||
public struct FeatureSubmissionIdentity: Sendable, Equatable, Hashable, Codable {
|
||||
public var threadID: String
|
||||
public var commandID: String
|
||||
public var messageID: String
|
||||
public var createdAt: Date
|
||||
|
||||
public init(
|
||||
threadID: String = UUID().uuidString,
|
||||
commandID: String = UUID().uuidString,
|
||||
messageID: String = UUID().uuidString,
|
||||
createdAt: Date = .now
|
||||
) {
|
||||
self.threadID = threadID
|
||||
self.commandID = commandID
|
||||
self.messageID = messageID
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
}
|
||||
|
||||
public struct FeatureQueuedAttachment: Sendable, Equatable, Codable {
|
||||
public var data: Data
|
||||
public var name: String
|
||||
public var mimeType: String
|
||||
|
||||
public init(data: Data, name: String, mimeType: String) {
|
||||
self.data = data
|
||||
self.name = name
|
||||
self.mimeType = mimeType
|
||||
}
|
||||
|
||||
init(_ attachment: FeatureUploadAttachment) {
|
||||
self.init(
|
||||
data: attachment.data,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType
|
||||
)
|
||||
}
|
||||
|
||||
var upload: FeatureUploadAttachment {
|
||||
FeatureUploadAttachment(data: data, name: name, mimeType: mimeType)
|
||||
}
|
||||
}
|
||||
|
||||
public struct FeatureQueuedCreation: Sendable, Equatable, Codable {
|
||||
public var projectID: String
|
||||
public var projectName: String
|
||||
public var workspaceMode: FeatureWorkspaceMode
|
||||
public var branch: String?
|
||||
public var worktreePath: String?
|
||||
public var startFromOrigin: Bool
|
||||
|
||||
public init(
|
||||
projectID: String,
|
||||
projectName: String,
|
||||
workspaceMode: FeatureWorkspaceMode,
|
||||
branch: String?,
|
||||
worktreePath: String?,
|
||||
startFromOrigin: Bool
|
||||
) {
|
||||
self.projectID = projectID
|
||||
self.projectName = projectName
|
||||
self.workspaceMode = workspaceMode
|
||||
self.branch = branch
|
||||
self.worktreePath = worktreePath
|
||||
self.startFromOrigin = startFromOrigin
|
||||
}
|
||||
}
|
||||
|
||||
public struct FeatureQueuedSubmission: Identifiable, Sendable, Equatable, Codable {
|
||||
public let id: String
|
||||
public var environmentID: String
|
||||
public var identity: FeatureSubmissionIdentity
|
||||
public var threadID: String
|
||||
public var text: String
|
||||
public var selection: FeatureSelection?
|
||||
public var runtimeMode: FeatureRuntimeMode
|
||||
public var interactionMode: FeatureInteractionMode
|
||||
public var attachments: [FeatureQueuedAttachment]
|
||||
public var creation: FeatureQueuedCreation?
|
||||
|
||||
public init(
|
||||
id: String? = nil,
|
||||
environmentID: String,
|
||||
identity: FeatureSubmissionIdentity,
|
||||
threadID: String,
|
||||
text: String,
|
||||
selection: FeatureSelection?,
|
||||
runtimeMode: FeatureRuntimeMode,
|
||||
interactionMode: FeatureInteractionMode,
|
||||
attachments: [FeatureUploadAttachment],
|
||||
creation: FeatureQueuedCreation? = nil
|
||||
) {
|
||||
self.id = id ?? identity.messageID
|
||||
self.environmentID = environmentID
|
||||
self.identity = identity
|
||||
self.threadID = threadID
|
||||
self.text = text
|
||||
self.selection = selection
|
||||
self.runtimeMode = runtimeMode.mobileNormalized
|
||||
self.interactionMode = interactionMode.mobileNormalized
|
||||
self.attachments = attachments.map(FeatureQueuedAttachment.init)
|
||||
self.creation = creation
|
||||
}
|
||||
|
||||
public var uploads: [FeatureUploadAttachment] {
|
||||
attachments.map(\.upload)
|
||||
}
|
||||
}
|
||||
|
||||
public enum FeatureOutboxDeliveryDecision: Equatable {
|
||||
case discard
|
||||
case wait
|
||||
case send
|
||||
}
|
||||
|
||||
public enum FeatureOutboxPolicy {
|
||||
/// Delivery waits for the owning environment. Existing threads accept
|
||||
/// follow-up messages while a turn is running, matching the web queue.
|
||||
/// A creation whose thread already exists was committed before a cleanup
|
||||
/// interruption, so it is removed instead of sent twice.
|
||||
public static func decision(
|
||||
for submission: FeatureQueuedSubmission,
|
||||
snapshot: FeatureSnapshot,
|
||||
pendingCreationThreadIDs: Set<String> = []
|
||||
) -> FeatureOutboxDeliveryDecision {
|
||||
let environment = snapshot.environments.first { $0.id == submission.environmentID }
|
||||
let isConnected = environment?.connectionState == .connected
|
||||
|| (environment?.isActive == true && snapshot.connection.state == .connected)
|
||||
let thread = snapshot.threads.first { $0.id == submission.threadID }
|
||||
|
||||
if submission.creation != nil {
|
||||
if thread != nil { return .discard }
|
||||
let projectExists = snapshot.projects.contains {
|
||||
$0.id == submission.creation?.projectID
|
||||
&& $0.environmentID == submission.environmentID
|
||||
}
|
||||
if isConnected, !projectExists { return .discard }
|
||||
return isConnected ? .send : .wait
|
||||
}
|
||||
|
||||
if pendingCreationThreadIDs.contains(submission.threadID) {
|
||||
return .wait
|
||||
}
|
||||
guard thread != nil else {
|
||||
// A fully synchronized environment proves the thread was deleted.
|
||||
return isConnected ? .discard : .wait
|
||||
}
|
||||
guard isConnected else { return .wait }
|
||||
return .send
|
||||
}
|
||||
}
|
||||
|
||||
public actor FeatureOutboxStore {
|
||||
private struct Document: Codable {
|
||||
var version = 1
|
||||
var submissions: [FeatureQueuedSubmission]
|
||||
}
|
||||
|
||||
public static let shared = FeatureOutboxStore()
|
||||
|
||||
public let fileURL: URL
|
||||
private var cached: [FeatureQueuedSubmission]?
|
||||
|
||||
public init(fileURL: URL? = nil) {
|
||||
if let fileURL {
|
||||
self.fileURL = fileURL
|
||||
} else {
|
||||
let root = FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first!
|
||||
self.fileURL = root
|
||||
.appendingPathComponent("T3CodeSwift", isDirectory: true)
|
||||
.appendingPathComponent("outbox.json", isDirectory: false)
|
||||
}
|
||||
}
|
||||
|
||||
public func submissions() throws -> [FeatureQueuedSubmission] {
|
||||
if let cached { return cached }
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
cached = []
|
||||
return []
|
||||
}
|
||||
let document: Document
|
||||
do {
|
||||
document = try JSONDecoder.t3.decode(
|
||||
Document.self,
|
||||
from: Data(contentsOf: fileURL)
|
||||
)
|
||||
} catch {
|
||||
// Surface the recovery once, but do not permanently brick sending.
|
||||
// The next enqueue atomically replaces the unreadable document.
|
||||
cached = []
|
||||
throw error
|
||||
}
|
||||
cached = document.submissions.sorted {
|
||||
$0.identity.createdAt < $1.identity.createdAt
|
||||
}
|
||||
return cached ?? []
|
||||
}
|
||||
|
||||
public func enqueue(_ submission: FeatureQueuedSubmission) throws {
|
||||
var values = try submissions()
|
||||
values.removeAll { $0.id == submission.id }
|
||||
values.append(submission)
|
||||
values.sort { $0.identity.createdAt < $1.identity.createdAt }
|
||||
try save(values)
|
||||
}
|
||||
|
||||
public func remove(id: String) throws {
|
||||
var values = try submissions()
|
||||
values.removeAll { $0.id == id }
|
||||
try save(values)
|
||||
}
|
||||
|
||||
public func removeAll(environmentID: String) throws {
|
||||
var values = try submissions()
|
||||
values.removeAll { $0.environmentID == environmentID }
|
||||
try save(values)
|
||||
}
|
||||
|
||||
private func save(_ submissions: [FeatureQueuedSubmission]) throws {
|
||||
try FileManager.default.createDirectory(
|
||||
at: fileURL.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
let data = try JSONEncoder.t3.encode(Document(submissions: submissions))
|
||||
try data.write(to: fileURL, options: .atomic)
|
||||
cached = submissions
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,66 @@ import XCTest
|
||||
|
||||
@MainActor
|
||||
final class WebSocketRPCRaceTests: XCTestCase {
|
||||
func testSentUnaryTimesOutAndLateTrafficCannotCompleteItTwice() async throws {
|
||||
let connection = DeadlineWebSocketConnection()
|
||||
let client = WebSocketRPCClient(
|
||||
connector: SequencedConnector(connections: [connection]),
|
||||
connectionWaitTimeout: .seconds(2),
|
||||
responseTimeout: .milliseconds(40),
|
||||
endpointProvider: { URL(string: "wss://studio.example/ws")! }
|
||||
)
|
||||
|
||||
let first = Task {
|
||||
try await client.request("server.neverReplies", as: JSONValue.self)
|
||||
}
|
||||
await connection.waitUntilRequestCount(1)
|
||||
|
||||
do {
|
||||
_ = try await first.value
|
||||
XCTFail("A sent unary request must have a response deadline.")
|
||||
} catch let error as RPCError {
|
||||
guard case .responseTimedOut = error else {
|
||||
await client.stop()
|
||||
return XCTFail("Unexpected RPC error: \(error)")
|
||||
}
|
||||
}
|
||||
await connection.waitUntilInterruptCount(1)
|
||||
|
||||
// A response for the expired request is harmless, and the same socket
|
||||
// remains able to serve a subsequent unary call.
|
||||
try await connection.replyToRequest(at: 0)
|
||||
let second = try await client.request("server.replies", as: JSONValue.self)
|
||||
XCTAssertEqual(second, .object(["ok": .bool(true)]))
|
||||
await client.stop()
|
||||
}
|
||||
|
||||
func testCancellingUnaryRemovesItAndInterruptsSentWork() async throws {
|
||||
let connection = DeadlineWebSocketConnection()
|
||||
let client = WebSocketRPCClient(
|
||||
connector: SequencedConnector(connections: [connection]),
|
||||
connectionWaitTimeout: .seconds(2),
|
||||
responseTimeout: .seconds(2),
|
||||
endpointProvider: { URL(string: "wss://studio.example/ws")! }
|
||||
)
|
||||
|
||||
let request = Task {
|
||||
try await client.request("server.cancelled", as: JSONValue.self)
|
||||
}
|
||||
await connection.waitUntilRequestCount(1)
|
||||
request.cancel()
|
||||
|
||||
do {
|
||||
_ = try await request.value
|
||||
XCTFail("Cancelling the caller must cancel its unary continuation.")
|
||||
} catch is CancellationError {}
|
||||
await connection.waitUntilInterruptCount(1)
|
||||
|
||||
try await connection.replyToRequest(at: 0)
|
||||
let next = try await client.request("server.stillHealthy", as: JSONValue.self)
|
||||
XCTAssertEqual(next, .object(["ok": .bool(true)]))
|
||||
await client.stop()
|
||||
}
|
||||
|
||||
func testDisconnectWhileUnarySendIsSuspendedFailsWithoutReplay() async throws {
|
||||
let first = SuspendedSendConnection()
|
||||
let second = AutoReplyConnection()
|
||||
@@ -53,6 +113,106 @@ final class WebSocketRPCRaceTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
private actor DeadlineWebSocketConnection: WebSocketConnection {
|
||||
private var requestIDs: [Int] = []
|
||||
private var interruptIDs: [Int] = []
|
||||
private var requestWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
|
||||
private var interruptWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) throws {
|
||||
let envelope = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
switch envelope["_tag"]?.stringValue {
|
||||
case "Request":
|
||||
guard case let .number(rawID)? = envelope["id"],
|
||||
let requestID = Int(exactly: rawID) else {
|
||||
return
|
||||
}
|
||||
requestIDs.append(requestID)
|
||||
resumeRequestWaiters()
|
||||
if requestIDs.count > 1 {
|
||||
enqueue(try response(requestID: requestID))
|
||||
}
|
||||
case "Interrupt":
|
||||
guard case let .number(rawID)? = envelope["requestId"],
|
||||
let requestID = Int(exactly: rawID) else {
|
||||
return
|
||||
}
|
||||
interruptIDs.append(requestID)
|
||||
resumeInterruptWaiters()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
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 waitUntilRequestCount(_ count: Int) async {
|
||||
guard requestIDs.count < count else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
requestWaiters.append((count, continuation))
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilInterruptCount(_ count: Int) async {
|
||||
guard interruptIDs.count < count else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
interruptWaiters.append((count, continuation))
|
||||
}
|
||||
}
|
||||
|
||||
func replyToRequest(at index: Int) throws {
|
||||
enqueue(try response(requestID: requestIDs[index]))
|
||||
}
|
||||
|
||||
private func response(requestID: Int) throws -> Data {
|
||||
try JSONEncoder.t3.encode(
|
||||
JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(Double(requestID)),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object(["ok": .bool(true)]),
|
||||
]),
|
||||
])
|
||||
)
|
||||
}
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiver {
|
||||
self.receiver = nil
|
||||
receiver.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
|
||||
private func resumeRequestWaiters() {
|
||||
let ready = requestWaiters.filter { requestIDs.count >= $0.0 }
|
||||
requestWaiters.removeAll { requestIDs.count >= $0.0 }
|
||||
ready.forEach { $0.1.resume() }
|
||||
}
|
||||
|
||||
private func resumeInterruptWaiters() {
|
||||
let ready = interruptWaiters.filter { interruptIDs.count >= $0.0 }
|
||||
interruptWaiters.removeAll { interruptIDs.count >= $0.0 }
|
||||
ready.forEach { $0.1.resume() }
|
||||
}
|
||||
}
|
||||
|
||||
private actor SequencedConnector: WebSocketConnecting {
|
||||
private let connections: [any WebSocketConnection]
|
||||
private var nextIndex = 0
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Durable mobile outbox")
|
||||
struct FeatureOutboxStoreTests {
|
||||
@Test
|
||||
func roundTripPreservesStableWireIdentityAndAttachments() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-feature-outbox-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = FeatureOutboxStore(fileURL: directory.appendingPathComponent("outbox.json"))
|
||||
let identity = FeatureSubmissionIdentity(
|
||||
threadID: "thread-wire",
|
||||
commandID: "command-wire",
|
||||
messageID: "message-wire",
|
||||
createdAt: Date(timeIntervalSince1970: 42)
|
||||
)
|
||||
let submission = FeatureQueuedSubmission(
|
||||
environmentID: "environment-1",
|
||||
identity: identity,
|
||||
threadID: "thread-scoped",
|
||||
text: "Ship it",
|
||||
selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
||||
runtimeMode: .automatic,
|
||||
interactionMode: .plan,
|
||||
attachments: [
|
||||
.init(data: Data([0x01, 0x02]), name: "reference.png", mimeType: "image/png"),
|
||||
]
|
||||
)
|
||||
|
||||
try await store.enqueue(submission)
|
||||
let restored = try await FeatureOutboxStore(
|
||||
fileURL: store.fileURL
|
||||
).submissions()
|
||||
|
||||
#expect(restored.count == 1)
|
||||
#expect(restored[0].identity == identity)
|
||||
#expect(restored[0].runtimeMode == .fullAccess)
|
||||
#expect(restored[0].interactionMode == .standard)
|
||||
#expect(restored[0].attachments.first?.data == Data([0x01, 0x02]))
|
||||
}
|
||||
|
||||
@Test
|
||||
func policySendsFollowUpsWhileWorkingAndWaitsWhenOffline() {
|
||||
let thread = FeatureThread(
|
||||
id: "thread-scoped",
|
||||
projectID: "project-1",
|
||||
environmentID: "environment-1",
|
||||
title: "Working",
|
||||
state: .working
|
||||
)
|
||||
let submission = FeatureQueuedSubmission(
|
||||
environmentID: "environment-1",
|
||||
identity: FeatureSubmissionIdentity(),
|
||||
threadID: thread.id,
|
||||
text: "Queue this next",
|
||||
selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: []
|
||||
)
|
||||
let environment = FeatureEnvironment(
|
||||
id: "environment-1",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
)
|
||||
let connected = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [environment],
|
||||
threads: [thread]
|
||||
)
|
||||
var offline = connected
|
||||
offline.connection.state = .disconnected
|
||||
offline.environments[0].connectionState = .disconnected
|
||||
|
||||
#expect(FeatureOutboxPolicy.decision(for: submission, snapshot: connected) == .send)
|
||||
#expect(FeatureOutboxPolicy.decision(for: submission, snapshot: offline) == .wait)
|
||||
}
|
||||
|
||||
@Test
|
||||
func committedCreationAndDeletedThreadAreDiscarded() {
|
||||
let thread = FeatureThread(
|
||||
id: "thread-scoped",
|
||||
projectID: "project-1",
|
||||
environmentID: "environment-1",
|
||||
title: "Created"
|
||||
)
|
||||
let creation = FeatureQueuedSubmission(
|
||||
environmentID: "environment-1",
|
||||
identity: FeatureSubmissionIdentity(),
|
||||
threadID: thread.id,
|
||||
text: "Create it",
|
||||
selection: .init(providerID: "claude", modelID: "claude-opus-5"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: [],
|
||||
creation: .init(
|
||||
projectID: "project-1",
|
||||
projectName: "Native",
|
||||
workspaceMode: .local,
|
||||
branch: nil,
|
||||
worktreePath: nil,
|
||||
startFromOrigin: false
|
||||
)
|
||||
)
|
||||
var snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "environment-1",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
),
|
||||
],
|
||||
projects: [
|
||||
.init(
|
||||
id: "project-1",
|
||||
environmentID: "environment-1",
|
||||
name: "Native",
|
||||
path: "/native"
|
||||
),
|
||||
],
|
||||
threads: [thread]
|
||||
)
|
||||
|
||||
#expect(FeatureOutboxPolicy.decision(for: creation, snapshot: snapshot) == .discard)
|
||||
|
||||
var followUp = creation
|
||||
followUp.creation = nil
|
||||
snapshot.threads = []
|
||||
#expect(FeatureOutboxPolicy.decision(for: followUp, snapshot: snapshot) == .discard)
|
||||
#expect(
|
||||
FeatureOutboxPolicy.decision(
|
||||
for: followUp,
|
||||
snapshot: snapshot,
|
||||
pendingCreationThreadIDs: [creation.threadID]
|
||||
) == .wait
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -41,12 +41,112 @@ struct FeatureRootModelTests {
|
||||
@Test
|
||||
func disconnectEndsConnectionManagement() async {
|
||||
let client = FeatureClientStub()
|
||||
let model = FeatureRootModel(client: client)
|
||||
client.snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "studio",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected,
|
||||
connectionDetail: "Healthy"
|
||||
),
|
||||
]
|
||||
)
|
||||
let model = testRootModel(client: client)
|
||||
await model.reload()
|
||||
model.setConnectionManagementPresented(true)
|
||||
|
||||
await model.disconnect()
|
||||
|
||||
#expect(!model.isManagingConnections)
|
||||
#expect(model.snapshot.connection.state == .disconnected)
|
||||
#expect(model.snapshot.environments.first?.connectionState == .disconnected)
|
||||
#expect(model.snapshot.environments.first?.connectionDetail == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func restoredFollowUpWaitsForItsQueuedThreadCreation() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-root-dependent-outbox-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = FeatureOutboxStore(fileURL: directory.appendingPathComponent("outbox.json"))
|
||||
let threadID = "environment-1::thread::queued-thread"
|
||||
let creationIdentity = FeatureSubmissionIdentity(
|
||||
threadID: "queued-thread",
|
||||
commandID: "create-command",
|
||||
messageID: "create-message",
|
||||
createdAt: Date(timeIntervalSince1970: 1)
|
||||
)
|
||||
let creation = FeatureQueuedSubmission(
|
||||
environmentID: "environment-1",
|
||||
identity: creationIdentity,
|
||||
threadID: threadID,
|
||||
text: "Create the task",
|
||||
selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: [],
|
||||
creation: .init(
|
||||
projectID: "project-1",
|
||||
projectName: "Native",
|
||||
workspaceMode: .local,
|
||||
branch: nil,
|
||||
worktreePath: nil,
|
||||
startFromOrigin: false
|
||||
)
|
||||
)
|
||||
let followUp = FeatureQueuedSubmission(
|
||||
environmentID: "environment-1",
|
||||
identity: .init(
|
||||
threadID: "queued-thread",
|
||||
commandID: "follow-up-command",
|
||||
messageID: "follow-up-message",
|
||||
createdAt: Date(timeIntervalSince1970: 2)
|
||||
),
|
||||
threadID: threadID,
|
||||
text: "And add tests",
|
||||
selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: []
|
||||
)
|
||||
try await store.enqueue(creation)
|
||||
try await store.enqueue(followUp)
|
||||
|
||||
let client = FeatureClientStub()
|
||||
client.snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "environment-1",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
),
|
||||
],
|
||||
projects: [
|
||||
.init(
|
||||
id: "project-1",
|
||||
environmentID: "environment-1",
|
||||
name: "Native",
|
||||
path: "/native"
|
||||
),
|
||||
]
|
||||
)
|
||||
client.startTaskError = URLError(.timedOut)
|
||||
client.finishEvents()
|
||||
let model = FeatureRootModel(client: client, outboxStore: store)
|
||||
|
||||
await model.start()
|
||||
await model.disconnect()
|
||||
|
||||
let restoredIDs = try await store.submissions().map(\.id)
|
||||
#expect(restoredIDs.count == 2)
|
||||
#expect(Set(restoredIDs) == Set([creation.id, followUp.id]))
|
||||
#expect(client.sendMessageCallCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,7 +165,7 @@ struct FeatureRootModelTests {
|
||||
thread: oldThread,
|
||||
messages: [FeatureMessage(id: "old-message", role: .assistant, text: "Old")]
|
||||
)
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
_ = await model.detail(for: oldThread.id)
|
||||
|
||||
let result = await model.pair(endpoint: "https://studio.example", token: "pair-token")
|
||||
@@ -88,7 +188,7 @@ struct FeatureRootModelTests {
|
||||
modelID: "gpt-5"
|
||||
)
|
||||
client.createdThread = created
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
|
||||
let result = await model.createThread(
|
||||
projectID: "project-1",
|
||||
@@ -103,9 +203,28 @@ struct FeatureRootModelTests {
|
||||
@Test
|
||||
func testSendAddsQueuedMessageBeforeServerEvent() async {
|
||||
let client = FeatureClientStub()
|
||||
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
||||
let thread = FeatureThread(
|
||||
id: "thread-1",
|
||||
projectID: "project-1",
|
||||
environmentID: "environment-1",
|
||||
title: "Thread"
|
||||
)
|
||||
client.snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "environment-1",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
),
|
||||
],
|
||||
threads: [thread]
|
||||
)
|
||||
client.threadDetail = FeatureThreadDetail(thread: thread)
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
await model.reload()
|
||||
_ = await model.detail(for: thread.id)
|
||||
|
||||
let sent = await model.sendMessage(
|
||||
@@ -117,7 +236,7 @@ struct FeatureRootModelTests {
|
||||
#expect(sent)
|
||||
#expect(client.sentText == "ship it")
|
||||
#expect(model.details[thread.id]?.messages.last?.text == "ship it")
|
||||
#expect(model.details[thread.id]?.messages.last?.state == .queued)
|
||||
#expect(model.details[thread.id]?.messages.last?.state == .complete)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -131,7 +250,28 @@ struct FeatureRootModelTests {
|
||||
modelID: "gpt-5.6-sol"
|
||||
)
|
||||
client.createdThread = created
|
||||
let model = FeatureRootModel(client: client)
|
||||
client.snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "environment-1",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
),
|
||||
],
|
||||
projects: [
|
||||
.init(
|
||||
id: "project-1",
|
||||
environmentID: "environment-1",
|
||||
name: "Native",
|
||||
path: "/native"
|
||||
),
|
||||
]
|
||||
)
|
||||
let model = testRootModel(client: client)
|
||||
await model.reload()
|
||||
let attachment = FeatureDraftAttachment(
|
||||
data: Data([0xFF, 0xD8, 0xFF]),
|
||||
filename: "reference.jpg",
|
||||
@@ -169,7 +309,7 @@ struct FeatureRootModelTests {
|
||||
let client = FeatureClientStub()
|
||||
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
||||
client.createdThread = thread
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
_ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil)
|
||||
|
||||
await model.setArchived(thread.id, archived: true)
|
||||
@@ -190,7 +330,7 @@ struct FeatureRootModelTests {
|
||||
]
|
||||
)
|
||||
client.threadDetail = detail
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
_ = await model.detail(for: thread.id)
|
||||
client.loadThreadError = CancellationError()
|
||||
|
||||
@@ -213,7 +353,7 @@ struct FeatureRootModelTests {
|
||||
thread.snoozedAt = oldSnooze
|
||||
thread.attentionAt = Date.now.addingTimeInterval(-300)
|
||||
client.createdThread = thread
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
_ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil)
|
||||
|
||||
await model.setSnoozed(
|
||||
@@ -236,7 +376,7 @@ struct FeatureRootModelTests {
|
||||
questions: []
|
||||
)
|
||||
client.threadDetail = FeatureThreadDetail(thread: thread, userInputs: [request])
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
_ = await model.detail(for: thread.id)
|
||||
|
||||
let answers: [String: FeatureInputAnswer] = [
|
||||
@@ -260,7 +400,7 @@ struct FeatureRootModelTests {
|
||||
path: "/native"
|
||||
)
|
||||
client.snapshot = FeatureSnapshot(projects: [project])
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
let thread = FeatureThread(
|
||||
id: "thread-1",
|
||||
projectID: project.id,
|
||||
@@ -303,7 +443,7 @@ struct FeatureRootModelTests {
|
||||
FeatureMessage(id: "message-2", role: .user, text: "Ship it"),
|
||||
]
|
||||
)
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
|
||||
let run = Task { await model.start() }
|
||||
client.emit(.detail(first))
|
||||
@@ -334,7 +474,7 @@ struct FeatureRootModelTests {
|
||||
messages: [completedMessage, appendedMessage]
|
||||
)
|
||||
client.snapshot = FeatureSnapshot(threads: [thread])
|
||||
let model = FeatureRootModel(client: client)
|
||||
let model = testRootModel(client: client)
|
||||
|
||||
let run = Task { await model.start() }
|
||||
client.emit(.detail(first))
|
||||
@@ -473,6 +613,17 @@ struct FeatureRootModelTests {
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func testRootModel(client: FeatureClientStub) -> FeatureRootModel {
|
||||
FeatureRootModel(
|
||||
client: client,
|
||||
outboxStore: FeatureOutboxStore(
|
||||
fileURL: FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-root-outbox-\(UUID().uuidString).json")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func orchestrationEvent(
|
||||
type: String,
|
||||
sequence: Int,
|
||||
@@ -534,6 +685,7 @@ private final class FeatureClientStub: FeatureClient {
|
||||
var startedFromOrigin = false
|
||||
var createThreadCallCount = 0
|
||||
var sendMessageCallCount = 0
|
||||
var startTaskError: (any Error)?
|
||||
var loadThreadError: (any Error)?
|
||||
var resolvedInputID: String?
|
||||
var resolvedInputAnswers: [String: FeatureInputAnswer]?
|
||||
@@ -585,6 +737,7 @@ private final class FeatureClientStub: FeatureClient {
|
||||
interactionMode: FeatureInteractionMode,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws -> FeatureThread {
|
||||
if let startTaskError { throw startTaskError }
|
||||
startedPrompt = prompt
|
||||
startedAttachments = attachments
|
||||
return createdThread
|
||||
@@ -602,6 +755,7 @@ private final class FeatureClientStub: FeatureClient {
|
||||
startFromOrigin: Bool,
|
||||
attachments: [FeatureUploadAttachment]
|
||||
) async throws -> FeatureThread {
|
||||
if let startTaskError { throw startTaskError }
|
||||
startedPrompt = prompt
|
||||
startedAttachments = attachments
|
||||
startedWorkspaceMode = workspaceMode
|
||||
|
||||
@@ -4,6 +4,78 @@ import XCTest
|
||||
|
||||
@MainActor
|
||||
final class NativeMultiEnvironmentTests: XCTestCase {
|
||||
func testProviderCatalogueUsesStableProviderAndModelIdentities() {
|
||||
let normalized = NativeFeatureClient.normalizedProviders([
|
||||
FeatureProvider(
|
||||
id: "codex-work",
|
||||
name: "Codex",
|
||||
models: [
|
||||
FeatureModel(id: "gpt-5.6", name: "GPT-5.6"),
|
||||
FeatureModel(id: "gpt-5.6", name: "Duplicate GPT-5.6"),
|
||||
]
|
||||
),
|
||||
FeatureProvider(
|
||||
id: "codex-work",
|
||||
name: "Duplicate provider",
|
||||
models: [
|
||||
FeatureModel(id: "gpt-5.6", name: "Duplicate again"),
|
||||
FeatureModel(id: "gpt-5.6-mini", name: "GPT-5.6 mini"),
|
||||
]
|
||||
),
|
||||
])
|
||||
|
||||
XCTAssertEqual(normalized.map(\.id), ["codex-work"])
|
||||
XCTAssertEqual(normalized[0].models.map(\.id), ["gpt-5.6", "gpt-5.6-mini"])
|
||||
}
|
||||
|
||||
func testClientReplacementIsSharedWhileStaleClientDisconnects() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-runtime-race-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let originalEnvironment = Environment(
|
||||
id: "shared-environment",
|
||||
label: "Old endpoint",
|
||||
httpBaseURL: URL(string: "https://old.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://old.example")!
|
||||
)
|
||||
let updatedEnvironment = Environment(
|
||||
id: originalEnvironment.id,
|
||||
label: "New endpoint",
|
||||
httpBaseURL: URL(string: "https://new.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://new.example")!
|
||||
)
|
||||
let store = EnvironmentStore(
|
||||
fileURL: directory.appendingPathComponent("environments.json")
|
||||
)
|
||||
try await store.save([updatedEnvironment])
|
||||
let staleConnection = BlockingRuntimeCloseConnection()
|
||||
let connector = RuntimeReplacementConnector(connection: staleConnection)
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: InMemoryCredentialStore(
|
||||
credentials: [
|
||||
originalEnvironment.id: EnvironmentCredential(accessToken: "token"),
|
||||
]
|
||||
),
|
||||
httpTransport: RuntimeReplacementHTTPTransport(),
|
||||
webSocketConnector: connector
|
||||
)
|
||||
let original = await runtime.client(for: originalEnvironment)
|
||||
await original.connect()
|
||||
await staleConnection.waitUntilReceiving()
|
||||
|
||||
let firstLookup = Task { await runtime.client(for: updatedEnvironment) }
|
||||
await staleConnection.waitUntilCloseStarted()
|
||||
let concurrentLookup = await runtime.client(for: updatedEnvironment)
|
||||
await staleConnection.releaseClose()
|
||||
let replacement = await firstLookup.value
|
||||
|
||||
XCTAssertTrue(
|
||||
replacement === concurrentLookup,
|
||||
"Concurrent lookups must share the replacement cached before stale disconnect."
|
||||
)
|
||||
}
|
||||
|
||||
func testSnapshotMergesEnvironmentsAndRoutesThreadWorkToItsOwner() async throws {
|
||||
let fixture = try await makeFixture()
|
||||
defer { try? FileManager.default.removeItem(at: fixture.directory) }
|
||||
@@ -132,7 +204,93 @@ final class NativeMultiEnvironmentTests: XCTestCase {
|
||||
await fixture.client.disconnect()
|
||||
}
|
||||
|
||||
private func makeFixture(duplicateIDs: Bool = false) async throws -> MultiEnvironmentFixture {
|
||||
func testUnarchiveImmediatelyRestoresLiveThreadWhenRefreshIsUnavailable() async throws {
|
||||
let fixture = try await makeFixture()
|
||||
defer { try? FileManager.default.removeItem(at: fixture.directory) }
|
||||
let initial = try await fixture.client.initialSnapshot()
|
||||
let thread = try XCTUnwrap(
|
||||
initial.threads.first(where: { $0.environmentID == "one" })
|
||||
)
|
||||
let events = fixture.client.events()
|
||||
var iterator = events.makeAsyncIterator()
|
||||
await fixture.transport.setShellReadsEnabled(false, host: "one.example")
|
||||
|
||||
try await fixture.client.setThreadArchived(id: thread.id, archived: true)
|
||||
while let event = await iterator.next() {
|
||||
if case let .thread(candidate) = event,
|
||||
candidate.id == thread.id,
|
||||
candidate.isArchived {
|
||||
break
|
||||
}
|
||||
}
|
||||
try await fixture.client.setThreadArchived(id: thread.id, archived: false)
|
||||
var restored: FeatureThread?
|
||||
while let event = await iterator.next() {
|
||||
if case let .thread(candidate) = event,
|
||||
candidate.id == thread.id,
|
||||
!candidate.isArchived {
|
||||
restored = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertEqual(restored?.id, thread.id)
|
||||
XCTAssertEqual(restored?.isArchived, false)
|
||||
await fixture.client.disconnect()
|
||||
}
|
||||
|
||||
func testHTTPFallbackKeepsLiveConnectionReconnecting() async throws {
|
||||
let fixture = try await makeFixture(
|
||||
fallbackPollingInitialDelay: .milliseconds(40),
|
||||
fallbackPollingInterval: .seconds(2)
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: fixture.directory) }
|
||||
_ = try await fixture.client.initialSnapshot()
|
||||
let current = multiEnvironmentShell(
|
||||
projectID: "project-one",
|
||||
threadID: "thread-one",
|
||||
title: "Local work"
|
||||
)
|
||||
let addedProject = OrchestrationProject(
|
||||
id: "project-fallback",
|
||||
title: "Fallback project",
|
||||
workspaceRoot: "/work/fallback",
|
||||
repositoryIdentity: nil,
|
||||
defaultModelSelection: ModelSelection(instanceId: "codex", model: "gpt-5.4"),
|
||||
scripts: [],
|
||||
createdAt: current.updatedAt,
|
||||
updatedAt: current.updatedAt,
|
||||
deletedAt: nil
|
||||
)
|
||||
await fixture.transport.setShell(
|
||||
OrchestrationShellSnapshot(
|
||||
snapshotSequence: current.snapshotSequence + 1,
|
||||
projects: current.projects + [addedProject],
|
||||
threads: current.threads,
|
||||
updatedAt: current.updatedAt
|
||||
),
|
||||
host: "one.example"
|
||||
)
|
||||
let events = fixture.client.events()
|
||||
var iterator = events.makeAsyncIterator()
|
||||
var refreshed: FeatureSnapshot?
|
||||
while let event = await iterator.next() {
|
||||
if case let .snapshot(snapshot) = event,
|
||||
snapshot.projects.contains(where: { $0.wireID == addedProject.id }) {
|
||||
refreshed = snapshot
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertEqual(refreshed?.connection.state, .reconnecting)
|
||||
await fixture.client.disconnect()
|
||||
}
|
||||
|
||||
private func makeFixture(
|
||||
duplicateIDs: Bool = false,
|
||||
fallbackPollingInitialDelay: Duration = .seconds(3),
|
||||
fallbackPollingInterval: Duration = .seconds(2)
|
||||
) async throws -> MultiEnvironmentFixture {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-native-multi-\(UUID().uuidString)", isDirectory: true)
|
||||
let environments = [
|
||||
@@ -187,7 +345,84 @@ final class NativeMultiEnvironmentTests: XCTestCase {
|
||||
return MultiEnvironmentFixture(
|
||||
directory: directory,
|
||||
transport: transport,
|
||||
client: NativeFeatureClient(runtime: runtime, settingsStore: settings)
|
||||
client: NativeFeatureClient(
|
||||
runtime: runtime,
|
||||
settingsStore: settings,
|
||||
fallbackPollingInitialDelay: fallbackPollingInitialDelay,
|
||||
fallbackPollingInterval: fallbackPollingInterval
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private actor RuntimeReplacementConnector: WebSocketConnecting {
|
||||
let connection: BlockingRuntimeCloseConnection
|
||||
|
||||
init(connection: BlockingRuntimeCloseConnection) {
|
||||
self.connection = connection
|
||||
}
|
||||
|
||||
func connect(to _: URL) -> any WebSocketConnection {
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
private actor BlockingRuntimeCloseConnection: WebSocketConnection {
|
||||
private var receiveContinuation: CheckedContinuation<Data, Error>?
|
||||
private var receiveWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var closeContinuation: CheckedContinuation<Void, Never>?
|
||||
private var closeWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
func send(_: Data) {}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
let waiters = receiveWaiters
|
||||
receiveWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiveContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() async {
|
||||
receiveContinuation?.resume(throwing: CancellationError())
|
||||
receiveContinuation = nil
|
||||
let waiters = closeWaiters
|
||||
closeWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
await withCheckedContinuation { continuation in
|
||||
closeContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilReceiving() async {
|
||||
guard receiveContinuation == nil else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
receiveWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilCloseStarted() async {
|
||||
guard closeContinuation == nil else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
closeWaiters.append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
func releaseClose() {
|
||||
closeContinuation?.resume()
|
||||
closeContinuation = nil
|
||||
}
|
||||
}
|
||||
|
||||
private actor RuntimeReplacementHTTPTransport: HTTPTransport {
|
||||
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
|
||||
guard request.url?.path == "/api/auth/websocket-ticket" else {
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
return (
|
||||
Data("{\"ticket\":\"ticket\",\"expiresAt\":\"2026-08-01T12:05:00.000Z\"}".utf8),
|
||||
multiEnvironmentResponse(request)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -200,14 +435,16 @@ private struct MultiEnvironmentFixture {
|
||||
|
||||
private actor MultiEnvironmentHTTPTransport: HTTPTransport {
|
||||
private let shells: [String: OrchestrationShellSnapshot]
|
||||
private let shellData: [String: Data]
|
||||
private var shellData: [String: Data]
|
||||
private var reachableHosts: Set<String>
|
||||
private var shellReadsEnabledHosts: Set<String>
|
||||
private var dispatched: [MultiEnvironmentDispatchRecord] = []
|
||||
|
||||
init(shells: [String: OrchestrationShellSnapshot]) {
|
||||
self.shells = shells
|
||||
shellData = shells.mapValues { try! JSONEncoder.t3.encode($0) }
|
||||
reachableHosts = Set(shells.keys)
|
||||
shellReadsEnabledHosts = Set(shells.keys)
|
||||
}
|
||||
|
||||
func setReachable(_ reachable: Bool, host: String) {
|
||||
@@ -218,6 +455,18 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
|
||||
}
|
||||
}
|
||||
|
||||
func setShellReadsEnabled(_ enabled: Bool, host: String) {
|
||||
if enabled {
|
||||
shellReadsEnabledHosts.insert(host)
|
||||
} else {
|
||||
shellReadsEnabledHosts.remove(host)
|
||||
}
|
||||
}
|
||||
|
||||
func setShell(_ shell: OrchestrationShellSnapshot, host: String) {
|
||||
shellData[host] = try! JSONEncoder.t3.encode(shell)
|
||||
}
|
||||
|
||||
func dispatchHosts() -> [String] {
|
||||
dispatched.map(\.host)
|
||||
}
|
||||
@@ -232,7 +481,9 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
|
||||
throw URLError(.cannotConnectToHost)
|
||||
}
|
||||
let path = request.url?.path ?? ""
|
||||
if path == "/api/orchestration/shell", let data = shellData[host] {
|
||||
if path == "/api/orchestration/shell",
|
||||
shellReadsEnabledHosts.contains(host),
|
||||
let data = shellData[host] {
|
||||
return (data, multiEnvironmentResponse(request))
|
||||
}
|
||||
if path.hasPrefix("/api/orchestration/threads/") {
|
||||
|
||||
@@ -4,7 +4,67 @@ import XCTest
|
||||
|
||||
@MainActor
|
||||
final class NativeRetryIdentityTests: XCTestCase {
|
||||
func testAmbiguousFailuresReuseStableTurnAndBootstrapIdentities() async throws {
|
||||
func testConcurrentBootstrapRetriesKeepIndependentStableIdentities() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-native-concurrent-retry-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let environment = Environment(
|
||||
id: "environment-concurrent-retry",
|
||||
label: "Concurrent retry",
|
||||
httpBaseURL: URL(string: "https://concurrent-retry.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://concurrent-retry.example")!
|
||||
)
|
||||
let store = EnvironmentStore(
|
||||
fileURL: directory.appendingPathComponent("environments.json")
|
||||
)
|
||||
try await store.save([environment])
|
||||
try await store.setActiveEnvironment(id: environment.id)
|
||||
let transport = ConcurrentBootstrapHTTPTransport(shell: retryShellSnapshot())
|
||||
let connection = ConcurrentBootstrapWebSocketConnection()
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: InMemoryCredentialStore(
|
||||
credentials: [environment.id: EnvironmentCredential(accessToken: "token")]
|
||||
),
|
||||
httpTransport: transport,
|
||||
webSocketConnector: ConcurrentBootstrapWebSocketConnector(connection: connection)
|
||||
)
|
||||
let client = NativeFeatureClient(
|
||||
runtime: runtime,
|
||||
settingsStore: UserDefaults(
|
||||
suiteName: "t3-native-concurrent-retry-\(UUID().uuidString)"
|
||||
)!
|
||||
)
|
||||
_ = try await client.initialSnapshot()
|
||||
await connection.waitUntilConnected()
|
||||
await transport.rejectShellReads()
|
||||
|
||||
async let firstAttempt = failedBootstrap(client: client, prompt: "First task")
|
||||
async let secondAttempt = failedBootstrap(client: client, prompt: "Second task")
|
||||
_ = await (firstAttempt, secondAttempt)
|
||||
await connection.waitUntilDispatchCount(2)
|
||||
|
||||
await failedBootstrap(client: client, prompt: "First task")
|
||||
await failedBootstrap(client: client, prompt: "Second task")
|
||||
|
||||
let commands = await connection.dispatchCommands()
|
||||
XCTAssertEqual(commands.count, 4)
|
||||
for prompt in ["First task", "Second task"] {
|
||||
let matching = commands.filter {
|
||||
$0["message"]?["text"]?.stringValue == prompt
|
||||
}
|
||||
XCTAssertEqual(matching.count, 2, "Expected an initial attempt and one retry.")
|
||||
XCTAssertEqual(matching.first?["threadId"], matching.last?["threadId"])
|
||||
XCTAssertEqual(matching.first?["commandId"], matching.last?["commandId"])
|
||||
XCTAssertEqual(
|
||||
matching.first?["message"]?["messageId"],
|
||||
matching.last?["message"]?["messageId"]
|
||||
)
|
||||
}
|
||||
await client.disconnect()
|
||||
}
|
||||
|
||||
func testTurnRetriesStayStableAndConfirmedBootstrapFailureResetsIdentity() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-native-retry-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
@@ -41,12 +101,20 @@ final class NativeRetryIdentityTests: XCTestCase {
|
||||
XCTAssertEqual(initial.threads.first?.interactionMode, .standard)
|
||||
await connection.waitUntilConnected()
|
||||
|
||||
let turnIdentity = FeatureSubmissionIdentity(
|
||||
threadID: "thread-existing",
|
||||
commandID: "persisted-turn-command",
|
||||
messageID: "persisted-turn-message",
|
||||
createdAt: Date(timeIntervalSince1970: 1_750_000_000)
|
||||
)
|
||||
for _ in 0..<2 {
|
||||
do {
|
||||
try await client.sendMessage(
|
||||
threadID: "thread-existing",
|
||||
text: "Retry without duplicating",
|
||||
selection: nil
|
||||
selection: nil,
|
||||
attachments: [],
|
||||
identity: turnIdentity
|
||||
)
|
||||
XCTFail("The synthetic dispatch should fail ambiguously.")
|
||||
} catch {}
|
||||
@@ -69,9 +137,19 @@ final class NativeRetryIdentityTests: XCTestCase {
|
||||
let commands = await connection.dispatchCommands()
|
||||
XCTAssertEqual(commands.count, 4)
|
||||
assertStableIdentity(commands[0], commands[1], includesThreadID: false)
|
||||
assertStableIdentity(commands[2], commands[3], includesThreadID: true)
|
||||
XCTAssertEqual(commands[0]["commandId"]?.stringValue, turnIdentity.commandID)
|
||||
XCTAssertEqual(
|
||||
commands[0]["message"]?["messageId"]?.stringValue,
|
||||
turnIdentity.messageID
|
||||
)
|
||||
XCTAssertNotEqual(commands[2]["commandId"], commands[3]["commandId"])
|
||||
XCTAssertNotEqual(
|
||||
commands[2]["message"]?["messageId"],
|
||||
commands[3]["message"]?["messageId"]
|
||||
)
|
||||
XCTAssertNotEqual(commands[2]["threadId"], commands[3]["threadId"])
|
||||
for command in commands {
|
||||
XCTAssertEqual(command["runtimeMode"]?.stringValue, "auto")
|
||||
XCTAssertEqual(command["runtimeMode"]?.stringValue, "full-access")
|
||||
XCTAssertEqual(command["interactionMode"]?.stringValue, "default")
|
||||
}
|
||||
await client.disconnect()
|
||||
@@ -112,13 +190,24 @@ final class NativeRetryIdentityTests: XCTestCase {
|
||||
_ = try await client.initialSnapshot()
|
||||
await connection.waitUntilConnected()
|
||||
|
||||
let identity = FeatureSubmissionIdentity(
|
||||
threadID: "persisted-bootstrap-thread",
|
||||
commandID: "persisted-bootstrap-command",
|
||||
messageID: "persisted-bootstrap-message",
|
||||
createdAt: Date(timeIntervalSince1970: 1_750_000_000)
|
||||
)
|
||||
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: []
|
||||
workspaceMode: .local,
|
||||
branch: nil,
|
||||
worktreePath: nil,
|
||||
startFromOrigin: false,
|
||||
attachments: [],
|
||||
identity: identity
|
||||
)
|
||||
|
||||
let commands = await connection.dispatchCommands()
|
||||
@@ -126,6 +215,12 @@ final class NativeRetryIdentityTests: XCTestCase {
|
||||
XCTAssertNotNil(commands[0]["bootstrap"])
|
||||
XCTAssertNil(commands[1]["bootstrap"])
|
||||
assertStableIdentity(commands[0], commands[1], includesThreadID: true)
|
||||
XCTAssertEqual(commands[0]["threadId"]?.stringValue, identity.threadID)
|
||||
XCTAssertEqual(commands[0]["commandId"]?.stringValue, identity.commandID)
|
||||
XCTAssertEqual(
|
||||
commands[0]["message"]?["messageId"]?.stringValue,
|
||||
identity.messageID
|
||||
)
|
||||
let wireID = try XCTUnwrap(commands[0]["threadId"]?.stringValue)
|
||||
XCTAssertEqual(created.wireID, wireID)
|
||||
XCTAssertEqual(
|
||||
@@ -147,6 +242,140 @@ final class NativeRetryIdentityTests: XCTestCase {
|
||||
XCTAssertEqual(first["threadId"], second["threadId"])
|
||||
}
|
||||
}
|
||||
|
||||
private func failedBootstrap(client: NativeFeatureClient, prompt: String) async {
|
||||
do {
|
||||
_ = try await client.createThreadAndSend(
|
||||
projectID: "project-1",
|
||||
prompt: prompt,
|
||||
selection: FeatureSelection(providerID: "codex", modelID: "gpt-5.4"),
|
||||
runtimeMode: .fullAccess,
|
||||
interactionMode: .standard,
|
||||
attachments: []
|
||||
)
|
||||
XCTFail("The synthetic dispatch should fail ambiguously.")
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ConcurrentBootstrapWebSocketConnector: WebSocketConnecting {
|
||||
let connection: ConcurrentBootstrapWebSocketConnection
|
||||
|
||||
func connect(to _: URL) -> any WebSocketConnection {
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
private actor ConcurrentBootstrapWebSocketConnection: WebSocketConnection {
|
||||
private var commands: [JSONValue] = []
|
||||
private var initialFailures: [CheckedContinuation<Void, Error>] = []
|
||||
private var dispatchWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
|
||||
private var didConnect = false
|
||||
private var connectionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) async 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.serverGetConfig.rawValue,
|
||||
let response = try retryConfigResponse(for: request) {
|
||||
enqueue(response)
|
||||
return
|
||||
}
|
||||
guard request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue,
|
||||
let payload = request["payload"] else {
|
||||
return
|
||||
}
|
||||
commands.append(payload)
|
||||
let ready = dispatchWaiters.filter { commands.count >= $0.0 }
|
||||
dispatchWaiters.removeAll { commands.count >= $0.0 }
|
||||
ready.forEach { $0.1.resume() }
|
||||
guard commands.count <= 2 else {
|
||||
throw URLError(.networkConnectionLost)
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
initialFailures.append(continuation)
|
||||
guard initialFailures.count == 2 else { return }
|
||||
let failures = initialFailures
|
||||
initialFailures.removeAll()
|
||||
failures.forEach { $0.resume(throwing: URLError(.networkConnectionLost)) }
|
||||
}
|
||||
}
|
||||
|
||||
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 waitUntilDispatchCount(_ count: Int) async {
|
||||
guard commands.count < count else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
dispatchWaiters.append((count, 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 actor ConcurrentBootstrapHTTPTransport: HTTPTransport {
|
||||
private let shellData: Data
|
||||
private var acceptsShellReads = true
|
||||
|
||||
init(shell: OrchestrationShellSnapshot) {
|
||||
shellData = try! JSONEncoder.t3.encode(shell)
|
||||
}
|
||||
|
||||
func rejectShellReads() {
|
||||
acceptsShellReads = false
|
||||
}
|
||||
|
||||
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
|
||||
switch request.url?.path {
|
||||
case "/api/orchestration/shell" where acceptsShellReads:
|
||||
(shellData, retryHTTPResponse(request))
|
||||
case "/api/auth/websocket-ticket":
|
||||
(
|
||||
Data(
|
||||
"{\"ticket\":\"ticket\",\"expiresAt\":\"2026-08-01T12:05:00.000Z\"}".utf8
|
||||
),
|
||||
retryHTTPResponse(request)
|
||||
)
|
||||
default:
|
||||
throw URLError(.networkConnectionLost)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func retryShellSnapshot() -> OrchestrationShellSnapshot {
|
||||
@@ -280,6 +509,7 @@ private struct PartialBootstrapWebSocketConnector: WebSocketConnecting {
|
||||
|
||||
private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection {
|
||||
private var commands: [JSONValue] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var didConnect = false
|
||||
private var connectionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
@@ -291,6 +521,11 @@ private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection {
|
||||
connectionWaiters.forEach { $0.resume() }
|
||||
connectionWaiters.removeAll()
|
||||
}
|
||||
if request["tag"]?.stringValue == RPCMethod.serverGetConfig.rawValue,
|
||||
let response = try retryConfigResponse(for: request) {
|
||||
enqueue(response)
|
||||
return
|
||||
}
|
||||
if request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue,
|
||||
let payload = request["payload"] {
|
||||
commands.append(payload)
|
||||
@@ -299,7 +534,10 @@ private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection {
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
if !queuedResponses.isEmpty {
|
||||
return queuedResponses.removeFirst()
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
receiver = continuation
|
||||
}
|
||||
}
|
||||
@@ -319,6 +557,15 @@ private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection {
|
||||
func dispatchCommands() -> [JSONValue] {
|
||||
commands
|
||||
}
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiver {
|
||||
self.receiver = nil
|
||||
receiver.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private actor PartialBootstrapWebSocketConnection: WebSocketConnection {
|
||||
@@ -337,6 +584,10 @@ private actor PartialBootstrapWebSocketConnection: WebSocketConnection {
|
||||
}
|
||||
guard request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue,
|
||||
let payload = request["payload"] else {
|
||||
if request["tag"]?.stringValue == RPCMethod.serverGetConfig.rawValue,
|
||||
let response = try retryConfigResponse(for: request) {
|
||||
enqueue(response)
|
||||
}
|
||||
return
|
||||
}
|
||||
commands.append(payload)
|
||||
@@ -390,6 +641,20 @@ private actor PartialBootstrapWebSocketConnection: WebSocketConnection {
|
||||
}
|
||||
}
|
||||
|
||||
private func retryConfigResponse(for request: JSONValue) throws -> Data? {
|
||||
guard case let .number(requestID)? = request["id"] else { return nil }
|
||||
return try JSONEncoder.t3.encode(
|
||||
JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(requestID),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object(["providers": .array([])]),
|
||||
]),
|
||||
])
|
||||
)
|
||||
}
|
||||
|
||||
private func retryEmptyThreadDetail(id: String) -> OrchestrationThreadDetailSnapshot {
|
||||
let timestamp = "2026-07-30T12:00:00.000Z"
|
||||
return OrchestrationThreadDetailSnapshot(
|
||||
|
||||
Reference in new issue
Block a user