fix(ios): scope native multi-device routing

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:50 -07:00
1 parent e6fdb7bebc
commit ddebf960b8
11 files changed
+1030 -260

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -52,6 +52,9 @@ public struct ThreadDetailView: View {
selection = currentSelection
isLoading = false
}
.onDisappear {
model.releaseThread(thread.id)
}
.sheet(item: $toolSurface) { surface in
NavigationStack {
switch surface {
@@ -231,6 +231,11 @@ public final class FeatureRootModel {
}
}
/// Ends any selected-thread transport work when its detail view closes.
public func releaseThread(_ id: String) {
client.releaseThread(id: id)
}
public func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async -> Bool {
await sendMessage(
FeatureMessageSubmission(
@@ -31,6 +31,7 @@ public protocol FeatureClient: AnyObject {
func deleteThread(id: String) async throws
func loadThread(id: String) async throws -> FeatureThreadDetail
func releaseThread(id: String)
func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws
func sendMessage(
threadID: String,
@@ -72,6 +73,7 @@ public extension FeatureClient {
func removeEnvironment(id: String) async throws {}
func disconnect() async {}
func addProject(path: String) async throws {}
func releaseThread(id: String) {}
func resolveUserInput(id: String, answers: [String: FeatureInputAnswer]) async throws {}
/// Keeps simple text-only callers source-compatible while the typed API
@@ -55,6 +55,9 @@ public struct FeatureEnvironment: Identifiable, Sendable, Equatable, Hashable, C
public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codable {
public let id: String
/// The environment-local identifier sent over the wire. Native aggregate
/// snapshots scope `id` by environment so cloned databases remain distinct.
public var wireID: String?
public var environmentID: String
public var name: String
public var path: String
@@ -63,6 +66,7 @@ public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codab
public init(
id: String,
wireID: String? = nil,
environmentID: String,
name: String,
path: String,
@@ -70,6 +74,7 @@ public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codab
defaultSelection: FeatureSelection? = nil
) {
self.id = id
self.wireID = wireID
self.environmentID = environmentID
self.name = name
self.path = path
@@ -102,6 +107,8 @@ public enum FeatureInteractionMode: String, CaseIterable, Sendable, Codable {
public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codable {
public let id: String
/// The environment-local identifier sent over the wire.
public var wireID: String?
public var projectID: String
public var environmentID: String?
public var environmentName: String?
@@ -131,6 +138,7 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
public init(
id: String,
wireID: String? = nil,
projectID: String,
environmentID: String? = nil,
environmentName: String? = nil,
@@ -159,6 +167,7 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
interactionMode: FeatureInteractionMode = .standard
) {
self.id = id
self.wireID = wireID
self.projectID = projectID
self.environmentID = environmentID
self.environmentName = environmentName
@@ -274,13 +283,23 @@ public enum FeatureApprovalKind: String, Sendable, Codable {
public struct FeatureApproval: Identifiable, Sendable, Equatable, Hashable, Codable {
public let id: String
/// The provider request identifier sent over the wire.
public var wireID: String?
public var threadID: String
public var kind: FeatureApprovalKind
public var title: String
public var detail: String
public init(id: String, threadID: String, kind: FeatureApprovalKind, title: String, detail: String) {
public init(
id: String,
wireID: String? = nil,
threadID: String,
kind: FeatureApprovalKind,
title: String,
detail: String
) {
self.id = id
self.wireID = wireID
self.threadID = threadID
self.kind = kind
self.title = title
@@ -383,16 +402,48 @@ public struct FeatureInputQuestion: Identifiable, Sendable, Equatable, Hashable,
public struct FeatureUserInput: Identifiable, Sendable, Equatable, Hashable, Codable {
public let id: String
/// The provider request identifier sent over the wire.
public var wireID: String?
public var threadID: String
public var questions: [FeatureInputQuestion]
public init(id: String, threadID: String, questions: [FeatureInputQuestion]) {
public init(
id: String,
wireID: String? = nil,
threadID: String,
questions: [FeatureInputQuestion]
) {
self.id = id
self.wireID = wireID
self.threadID = threadID
self.questions = questions
}
}
/// Stable UI identity for entities merged from independent environments.
/// Length-prefixing avoids separator collisions without requiring IDs to be parsed.
enum FeatureScopedID {
static func project(environmentID: String, wireID: String) -> String {
make(kind: "project", environmentID: environmentID, wireID: wireID)
}
static func thread(environmentID: String, wireID: String) -> String {
make(kind: "thread", environmentID: environmentID, wireID: wireID)
}
static func approval(environmentID: String, wireID: String) -> String {
make(kind: "approval", environmentID: environmentID, wireID: wireID)
}
static func input(environmentID: String, wireID: String) -> String {
make(kind: "input", environmentID: environmentID, wireID: wireID)
}
private static func make(kind: String, environmentID: String, wireID: String) -> String {
"\(kind):\(environmentID.utf8.count):\(environmentID)\(wireID)"
}
}
public struct FeatureThreadDetail: Sendable, Equatable, Codable {
public var thread: FeatureThread
public var messages: [FeatureMessage]
@@ -74,6 +74,63 @@ public struct FeatureMessageSubmission: Sendable, Equatable {
}
}
enum DailyUXCreationContext {
static func projects(in snapshot: FeatureSnapshot) -> [FeatureProject] {
guard !snapshot.environments.isEmpty else { return snapshot.projects }
let availableEnvironmentIDs = Set(
snapshot.environments.compactMap { environment in
let state = environment.isActive
? snapshot.connection.state
: environment.connectionState
return state == .disconnected ? nil : environment.id
}
)
return snapshot.projects.filter {
availableEnvironmentIDs.contains($0.environmentID)
}
}
static func providers(
for project: FeatureProject?,
in snapshot: FeatureSnapshot
) -> [FeatureProvider] {
guard let project,
let activeID = snapshot.environments.first(where: \.isActive)?.id,
project.environmentID != activeID else {
return snapshot.providers
}
guard let selection = project.defaultSelection else { return [] }
return [
FeatureProvider(
id: selection.providerID,
name: selection.providerID,
driver: selection.providerID,
models: [
FeatureModel(
id: selection.modelID,
name: selection.modelID,
isDefault: true
),
]
),
]
}
static func initialSelection(
for project: FeatureProject?,
in snapshot: FeatureSnapshot
) -> FeatureSelection? {
if let projectDefault = project?.defaultSelection {
return projectDefault
}
return DailyUXModelOptions.initialSelection(
projectDefault: nil,
appDefault: snapshot.settings.defaultSelection,
providers: providers(for: project, in: snapshot)
)
}
}
struct DailyUXSidebarIndex {
let active: [FeatureThread]
let snoozed: [FeatureThread]
@@ -145,7 +202,12 @@ struct DailyUXSidebarIndex {
) -> [FeatureThread] {
let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedQuery.isEmpty else { return [] }
let projectByID = Dictionary(uniqueKeysWithValues: snapshot.projects.map { ($0.id, $0) })
// Aggregate snapshots can include legacy fixtures with duplicate raw IDs.
// Native projects are environment-scoped, while this defensive reduce
// keeps search non-crashing for older callers during migration.
let projectByID = snapshot.projects.reduce(into: [String: FeatureProject]()) {
$0[$1.id] = $1
}
return candidates.filter { thread in
let project = projectByID[thread.projectID]
return [
@@ -42,8 +42,8 @@ public struct NewThreadView: View {
text: $prompt,
selection: $selection,
attachments: $attachments,
providers: model.snapshot.providers,
threadSelection: initialSelection,
providers: creationProviders,
threadSelection: nil,
isSending: isSubmitting,
isWorking: false,
focused: $promptFocused,
@@ -147,10 +147,7 @@ public struct NewThreadView: View {
}
private var creationProjects: [FeatureProject] {
guard let activeID = model.snapshot.environments.first(where: \.isActive)?.id else {
return model.snapshot.projects
}
return model.snapshot.projects.filter { $0.environmentID == activeID }
DailyUXCreationContext.projects(in: model.snapshot)
}
private var environmentName: String {
@@ -162,13 +159,18 @@ public struct NewThreadView: View {
}
private var initialSelection: FeatureSelection? {
DailyUXModelOptions.initialSelection(
projectDefault: selectedProject?.defaultSelection,
appDefault: model.snapshot.settings.defaultSelection,
providers: model.snapshot.providers
DailyUXCreationContext.initialSelection(
for: selectedProject,
in: model.snapshot
)
}
/// Provider catalogues are active-device-only. For a passive project, keep
/// its own default selectable without leaking models from another machine.
private var creationProviders: [FeatureProvider] {
DailyUXCreationContext.providers(for: selectedProject, in: model.snapshot)
}
private var canSubmit: Bool {
!isSubmitting
&& !projectID.isEmpty
@@ -183,7 +185,7 @@ public struct NewThreadView: View {
private var imagesAllowed: Bool {
DailyUXModelOptions.supportsImages(
selection: selection,
providers: model.snapshot.providers
providers: creationProviders
)
}
@@ -26,6 +26,83 @@ struct DailyUXNewTaskTests {
#expect(request.attachments.first?.byteCount == 3)
}
@Test
func passiveProjectsKeepTheirOwnModelCatalogAndDefault() throws {
let passiveDefault = FeatureSelection(
providerID: "claudeAgent",
modelID: "claude-opus-4-1"
)
let activeProject = FeatureProject(
id: "active-project",
environmentID: "active",
name: "Active",
path: "/active"
)
let passiveProject = FeatureProject(
id: "passive-project",
environmentID: "passive",
name: "Passive",
path: "/passive",
defaultSelection: passiveDefault
)
let snapshot = FeatureSnapshot(
connection: .init(state: .connected),
environments: [
.init(
id: "active",
name: "Active",
endpoint: "https://active.example",
isActive: true,
connectionState: .connected
),
.init(
id: "passive",
name: "Passive",
endpoint: "https://passive.example",
connectionState: .connected
),
.init(
id: "offline",
name: "Offline",
endpoint: "https://offline.example",
connectionState: .disconnected
),
],
projects: [
activeProject,
passiveProject,
.init(
id: "offline-project",
environmentID: "offline",
name: "Offline",
path: "/offline"
),
],
providers: [
.init(
id: "codex",
name: "Codex",
models: [.init(id: "gpt-5.6-sol", name: "GPT-5.6")]
),
]
)
#expect(
DailyUXCreationContext.projects(in: snapshot).map(\.id)
== ["active-project", "passive-project"]
)
let passiveProviders = DailyUXCreationContext.providers(
for: passiveProject,
in: snapshot
)
#expect(passiveProviders.map(\.id) == ["claudeAgent"])
#expect(passiveProviders.first?.models.map(\.id) == ["claude-opus-4-1"])
#expect(
DailyUXCreationContext.initialSelection(for: passiveProject, in: snapshot)
== passiveDefault
)
}
@Test @MainActor
func imageProcessorDownsamplesUploadAndBuildsSmallThumbnail() throws {
let source = UIGraphicsImageRenderer(size: CGSize(width: 2_400, height: 1_200))
@@ -167,6 +167,78 @@ struct DailyUXSidebarTests {
#expect(searched.searchResults.map(\.id) == ["server"])
}
@Test
func searchHandlesScopedClonesAndLegacyDuplicateProjectIDs() {
let localProjectID = FeatureScopedID.project(
environmentID: "local",
wireID: "project-shared"
)
let remoteProjectID = FeatureScopedID.project(
environmentID: "remote",
wireID: "project-shared"
)
let projects = [
FeatureProject(
id: localProjectID,
wireID: "project-shared",
environmentID: "local",
name: "Mobile",
path: "/work/mobile"
),
FeatureProject(
id: remoteProjectID,
wireID: "project-shared",
environmentID: "remote",
name: "Server",
path: "/work/server"
),
]
let local = thread(
id: "local-thread",
projectID: localProjectID,
title: "Polish",
created: -10,
updated: -5
)
let remote = thread(
id: "remote-thread",
projectID: remoteProjectID,
title: "Compression",
created: -20,
updated: -5
)
let scoped = FeatureSnapshot(projects: projects, threads: [local, remote])
#expect(
DailyUXSidebarIndex(snapshot: scoped, query: "server", now: now)
.searchResults.map(\.id) == ["remote-thread"]
)
let legacyDuplicates = FeatureSnapshot(
projects: projects.map {
FeatureProject(
id: "project-shared",
environmentID: $0.environmentID,
name: $0.name,
path: $0.path
)
},
threads: [
thread(
id: "legacy",
projectID: "project-shared",
title: "Legacy",
created: -10,
updated: -5
),
]
)
#expect(
DailyUXSidebarIndex(snapshot: legacyDuplicates, query: "server", now: now)
.searchResults.map(\.id) == ["legacy"]
)
}
@Test
func attentionScopesRemainFocusedSubsetsOfActive() {
let approval = thread(
@@ -11,9 +11,12 @@ final class NativeMultiEnvironmentTests: XCTestCase {
let snapshot = try await fixture.client.initialSnapshot()
XCTAssertEqual(Set(snapshot.projects.map(\.environmentID)), ["one", "two"])
XCTAssertEqual(Set(snapshot.threads.map(\.id)), ["thread-one", "thread-two"])
XCTAssertEqual(Set(snapshot.threads.compactMap(\.wireID)), ["thread-one", "thread-two"])
let remoteThread = try XCTUnwrap(
snapshot.threads.first(where: { $0.environmentID == "two" })
)
XCTAssertEqual(
snapshot.threads.first(where: { $0.id == "thread-two" })?.environmentName,
remoteThread.environmentName,
"Steam Box"
)
XCTAssertEqual(
@@ -21,13 +24,13 @@ final class NativeMultiEnvironmentTests: XCTestCase {
.connected
)
let detail = try await fixture.client.loadThread(id: "thread-two")
let detail = try await fixture.client.loadThread(id: remoteThread.id)
XCTAssertEqual(detail.thread.environmentID, "two")
XCTAssertEqual(detail.thread.environmentName, "Steam Box")
try await fixture.client.renameThread(id: "thread-two", title: "Remote rename")
try await fixture.client.renameThread(id: remoteThread.id, title: "Remote rename")
try await fixture.client.sendMessage(
threadID: "thread-two",
threadID: remoteThread.id,
text: "Run this on Steam Box",
selection: nil
)
@@ -45,7 +48,10 @@ final class NativeMultiEnvironmentTests: XCTestCase {
await fixture.transport.setReachable(false, host: "two.example")
let passiveFailure = try await fixture.client.initialSnapshot()
XCTAssertEqual(Set(passiveFailure.threads.map(\.id)), ["thread-one", "thread-two"])
XCTAssertEqual(
Set(passiveFailure.threads.compactMap(\.wireID)),
["thread-one", "thread-two"]
)
XCTAssertEqual(passiveFailure.connection.state, .connected)
XCTAssertEqual(
passiveFailure.environments.first(where: { $0.id == "two" })?.connectionState,
@@ -56,7 +62,10 @@ final class NativeMultiEnvironmentTests: XCTestCase {
await fixture.transport.setReachable(true, host: "two.example")
let activeFailure = try await fixture.client.initialSnapshot()
XCTAssertEqual(Set(activeFailure.threads.map(\.id)), ["thread-one", "thread-two"])
XCTAssertEqual(
Set(activeFailure.threads.compactMap(\.wireID)),
["thread-one", "thread-two"]
)
XCTAssertEqual(activeFailure.connection.state, .disconnected)
XCTAssertEqual(activeFailure.connection.environmentName, "Left Book")
XCTAssertEqual(
@@ -66,7 +75,64 @@ final class NativeMultiEnvironmentTests: XCTestCase {
await fixture.client.disconnect()
}
private func makeFixture() async throws -> MultiEnvironmentFixture {
func testDuplicateWireIDsRemainDistinctAndRouteByEnvironment() async throws {
let fixture = try await makeFixture(duplicateIDs: true)
defer { try? FileManager.default.removeItem(at: fixture.directory) }
let snapshot = try await fixture.client.initialSnapshot()
XCTAssertEqual(snapshot.projects.count, 2)
XCTAssertEqual(snapshot.threads.count, 2)
XCTAssertEqual(Set(snapshot.projects.map(\.id)).count, 2)
XCTAssertEqual(Set(snapshot.threads.map(\.id)).count, 2)
XCTAssertEqual(Set(snapshot.projects.compactMap(\.wireID)), ["project-shared"])
XCTAssertEqual(Set(snapshot.threads.compactMap(\.wireID)), ["thread-shared"])
let remote = try XCTUnwrap(
snapshot.threads.first(where: { $0.environmentID == "two" })
)
_ = try await fixture.client.loadThread(id: remote.id)
try await fixture.client.renameThread(id: remote.id, title: "Remote only")
let hosts = await fixture.transport.dispatchHosts()
XCTAssertEqual(hosts, ["two.example"])
await fixture.client.disconnect()
}
func testPassiveCreateUsesOwningProjectDefaultAndFallbackRemainsRoutable() async throws {
let fixture = try await makeFixture()
defer { try? FileManager.default.removeItem(at: fixture.directory) }
let snapshot = try await fixture.client.initialSnapshot()
let remoteProject = try XCTUnwrap(
snapshot.projects.first(where: { $0.environmentID == "two" })
)
let created = try await fixture.client.createThread(
projectID: remoteProject.id,
title: "Passive task",
selection: nil
)
XCTAssertEqual(created.environmentID, "two")
XCTAssertEqual(created.projectID, remoteProject.id)
XCTAssertNotNil(created.wireID)
try await fixture.client.renameThread(id: created.id, title: "Fallback routed")
let records = await fixture.transport.dispatchRecords()
XCTAssertEqual(records.map(\.host), ["two.example", "two.example"])
XCTAssertEqual(records[0].command["type"]?.stringValue, "thread.create")
XCTAssertEqual(records[0].command["projectId"]?.stringValue, "project-two")
XCTAssertEqual(
records[0].command["modelSelection"]?["instanceId"]?.stringValue,
"claudeAgent"
)
XCTAssertEqual(
records[1].command["threadId"]?.stringValue,
created.wireID
)
await fixture.client.disconnect()
}
private func makeFixture(duplicateIDs: Bool = false) async throws -> MultiEnvironmentFixture {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("t3-native-multi-\(UUID().uuidString)", isDirectory: true)
let environments = [
@@ -91,14 +157,16 @@ final class NativeMultiEnvironmentTests: XCTestCase {
let transport = MultiEnvironmentHTTPTransport(
shells: [
"one.example": multiEnvironmentShell(
projectID: "project-one",
threadID: "thread-one",
projectID: duplicateIDs ? "project-shared" : "project-one",
threadID: duplicateIDs ? "thread-shared" : "thread-one",
title: "Local work"
),
"two.example": multiEnvironmentShell(
projectID: "project-two",
threadID: "thread-two",
title: "Remote work"
projectID: duplicateIDs ? "project-shared" : "project-two",
threadID: duplicateIDs ? "thread-shared" : "thread-two",
title: "Remote work",
providerID: "claudeAgent",
modelID: "claude-opus-4-1"
),
]
)
@@ -131,11 +199,13 @@ private struct MultiEnvironmentFixture {
}
private actor MultiEnvironmentHTTPTransport: HTTPTransport {
private let shells: [String: OrchestrationShellSnapshot]
private let shellData: [String: Data]
private var reachableHosts: Set<String>
private var dispatchedToHosts: [String] = []
private var dispatched: [MultiEnvironmentDispatchRecord] = []
init(shells: [String: OrchestrationShellSnapshot]) {
self.shells = shells
shellData = shells.mapValues { try! JSONEncoder.t3.encode($0) }
reachableHosts = Set(shells.keys)
}
@@ -149,7 +219,11 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
}
func dispatchHosts() -> [String] {
dispatchedToHosts
dispatched.map(\.host)
}
func dispatchRecords() -> [MultiEnvironmentDispatchRecord] {
dispatched
}
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
@@ -163,7 +237,9 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
}
if path.hasPrefix("/api/orchestration/threads/") {
let threadID = request.url?.lastPathComponent.removingPercentEncoding ?? "thread"
let projectID = threadID == "thread-two" ? "project-two" : "project-one"
let projectID = shells[host]?.threads
.first(where: { $0.id == threadID })?
.projectId ?? shells[host]?.projects.first?.id ?? "project"
return (
try JSONEncoder.t3.encode(
multiEnvironmentDetail(projectID: projectID, threadID: threadID)
@@ -172,7 +248,13 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
)
}
if path == "/api/orchestration/dispatch" {
dispatchedToHosts.append(host)
guard let body = request.httpBody else { throw URLError(.badServerResponse) }
dispatched.append(
MultiEnvironmentDispatchRecord(
host: host,
command: try JSONDecoder.t3.decode(JSONValue.self, from: body)
)
)
return (
try JSONEncoder.t3.encode(DispatchResult(sequence: 2)),
multiEnvironmentResponse(request)
@@ -192,6 +274,11 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
}
}
private struct MultiEnvironmentDispatchRecord: Sendable {
let host: String
let command: JSONValue
}
private struct UnavailableMultiEnvironmentWebSocketConnector: WebSocketConnecting {
func connect(to _: URL) async throws -> any WebSocketConnection {
throw URLError(.cannotConnectToHost)
@@ -201,10 +288,12 @@ private struct UnavailableMultiEnvironmentWebSocketConnector: WebSocketConnectin
private func multiEnvironmentShell(
projectID: String,
threadID: String,
title: String
title: String,
providerID: String = "codex",
modelID: String = "gpt-5.6-sol"
) -> OrchestrationShellSnapshot {
let timestamp = "2026-07-31T12:00:00.000Z"
let model = ModelSelection(instanceId: "codex", model: "gpt-5.6-sol")
let model = ModelSelection(instanceId: providerID, model: modelID)
return OrchestrationShellSnapshot(
snapshotSequence: 1,
projects: [
@@ -120,7 +120,12 @@ final class NativeRetryIdentityTests: XCTestCase {
XCTAssertNotNil(commands[0]["bootstrap"])
XCTAssertNil(commands[1]["bootstrap"])
assertStableIdentity(commands[0], commands[1], includesThreadID: true)
XCTAssertEqual(created.id, commands[0]["threadId"]?.stringValue)
let wireID = try XCTUnwrap(commands[0]["threadId"]?.stringValue)
XCTAssertEqual(created.wireID, wireID)
XCTAssertEqual(
created.id,
FeatureScopedID.thread(environmentID: environment.id, wireID: wireID)
)
await client.disconnect()
}