612 lines
21 KiB
Swift
612 lines
21 KiB
Swift
import Foundation
|
|
import Testing
|
|
@testable import T3Code
|
|
|
|
@MainActor
|
|
@Suite("Feature root model")
|
|
struct FeatureRootModelTests {
|
|
@Test
|
|
func connectionManagementStaysMountedForDisconnectedSavedServers() {
|
|
let savedEnvironment = FeatureEnvironment(
|
|
id: "offline-demo",
|
|
name: "Offline demo",
|
|
endpoint: "https://offline.example",
|
|
connectionState: .disconnected
|
|
)
|
|
let snapshot = FeatureSnapshot(
|
|
connection: .init(state: .disconnected),
|
|
environments: [savedEnvironment]
|
|
)
|
|
|
|
#expect(
|
|
FeatureRootPresentation.showsWorkspace(
|
|
snapshot: snapshot,
|
|
isManagingConnections: true
|
|
)
|
|
)
|
|
#expect(
|
|
!FeatureRootPresentation.showsWorkspace(
|
|
snapshot: snapshot,
|
|
isManagingConnections: false
|
|
)
|
|
)
|
|
#expect(
|
|
!FeatureRootPresentation.showsWorkspace(
|
|
snapshot: FeatureSnapshot(connection: .init(state: .disconnected)),
|
|
isManagingConnections: true
|
|
)
|
|
)
|
|
}
|
|
|
|
@Test
|
|
func disconnectEndsConnectionManagement() async {
|
|
let client = FeatureClientStub()
|
|
let model = FeatureRootModel(client: client)
|
|
model.setConnectionManagementPresented(true)
|
|
|
|
await model.disconnect()
|
|
|
|
#expect(!model.isManagingConnections)
|
|
}
|
|
|
|
@Test
|
|
func testPairReloadsConnectedSnapshot() async {
|
|
let client = FeatureClientStub()
|
|
client.snapshot = FeatureSnapshot(connection: .init(state: .disconnected))
|
|
client.snapshotAfterPair = FeatureSnapshot(
|
|
connection: .init(
|
|
state: .connected,
|
|
environmentName: "Studio",
|
|
endpoint: "https://studio.example"
|
|
)
|
|
)
|
|
let oldThread = FeatureThread(id: "same-id", projectID: "old-project", title: "Old")
|
|
client.threadDetail = FeatureThreadDetail(
|
|
thread: oldThread,
|
|
messages: [FeatureMessage(id: "old-message", role: .assistant, text: "Old")]
|
|
)
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.detail(for: oldThread.id)
|
|
|
|
let result = await model.pair(endpoint: "https://studio.example", token: "pair-token")
|
|
|
|
#expect(result)
|
|
#expect(client.pairEndpoint == "https://studio.example")
|
|
#expect(client.pairToken == "pair-token")
|
|
#expect(model.snapshot.connection.state == .connected)
|
|
#expect(model.details.isEmpty)
|
|
}
|
|
|
|
@Test
|
|
func testCreateThreadOptimisticallyUpsertsIt() async {
|
|
let client = FeatureClientStub()
|
|
let created = FeatureThread(
|
|
id: "thread-1",
|
|
projectID: "project-1",
|
|
title: "Build native app",
|
|
providerID: "codex",
|
|
modelID: "gpt-5"
|
|
)
|
|
client.createdThread = created
|
|
let model = FeatureRootModel(client: client)
|
|
|
|
let result = await model.createThread(
|
|
projectID: "project-1",
|
|
title: created.title,
|
|
selection: .init(providerID: "codex", modelID: "gpt-5")
|
|
)
|
|
|
|
#expect(result == created)
|
|
#expect(model.snapshot.threads == [created])
|
|
}
|
|
|
|
@Test
|
|
func testSendAddsQueuedMessageBeforeServerEvent() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
|
client.threadDetail = FeatureThreadDetail(thread: thread)
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.detail(for: thread.id)
|
|
|
|
let sent = await model.sendMessage(
|
|
threadID: thread.id,
|
|
text: " ship it ",
|
|
selection: nil
|
|
)
|
|
|
|
#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)
|
|
}
|
|
|
|
@Test
|
|
func testNewTaskStartsThreadAndFirstTurnAtomically() async {
|
|
let client = FeatureClientStub()
|
|
let created = FeatureThread(
|
|
id: "thread-atomic",
|
|
projectID: "project-1",
|
|
title: "Ship the native app",
|
|
providerID: "codex",
|
|
modelID: "gpt-5.6-sol"
|
|
)
|
|
client.createdThread = created
|
|
let model = FeatureRootModel(client: client)
|
|
let attachment = FeatureDraftAttachment(
|
|
data: Data([0xFF, 0xD8, 0xFF]),
|
|
filename: "reference.jpg",
|
|
mimeType: "image/jpeg"
|
|
)
|
|
|
|
let result = await model.startTask(
|
|
NewTaskRequest(
|
|
projectID: "project-1",
|
|
prompt: " Ship the native app ",
|
|
selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
|
runtimeMode: .fullAccess,
|
|
interactionMode: .standard,
|
|
attachments: [attachment]
|
|
)
|
|
)
|
|
|
|
#expect(result == created)
|
|
#expect(client.startedPrompt == "Ship the native app")
|
|
#expect(client.startedAttachments.map(\.name) == ["reference.jpg"])
|
|
#expect(client.createThreadCallCount == 0)
|
|
#expect(client.sendMessageCallCount == 0)
|
|
#expect(model.snapshot.threads == [created])
|
|
}
|
|
|
|
@Test
|
|
func testArchiveAndDeleteKeepLocalListsConsistent() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
|
client.createdThread = thread
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil)
|
|
|
|
await model.setArchived(thread.id, archived: true)
|
|
#expect(model.snapshot.threads[0].isArchived)
|
|
|
|
await model.deleteThread(thread.id)
|
|
#expect(model.snapshot.threads.isEmpty)
|
|
}
|
|
|
|
@Test
|
|
func testCancelledDetailRefreshKeepsCachedContentWithoutAlert() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
|
let detail = FeatureThreadDetail(
|
|
thread: thread,
|
|
messages: [
|
|
FeatureMessage(id: "message-1", role: .assistant, text: "Still here"),
|
|
]
|
|
)
|
|
client.threadDetail = detail
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.detail(for: thread.id)
|
|
client.loadThreadError = CancellationError()
|
|
|
|
let refreshed = await model.detail(for: thread.id, force: true)
|
|
|
|
#expect(refreshed == detail)
|
|
#expect(model.errorMessage == nil)
|
|
}
|
|
|
|
@Test
|
|
func testResnoozeRefreshesTheOptimisticSnoozeTimestamp() async {
|
|
let client = FeatureClientStub()
|
|
var thread = FeatureThread(
|
|
id: "thread-1",
|
|
projectID: "project-1",
|
|
title: "Thread",
|
|
state: .failed
|
|
)
|
|
let oldSnooze = Date.now.addingTimeInterval(-600)
|
|
thread.snoozedAt = oldSnooze
|
|
thread.attentionAt = Date.now.addingTimeInterval(-300)
|
|
client.createdThread = thread
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil)
|
|
|
|
await model.setSnoozed(
|
|
thread.id,
|
|
until: Date.now.addingTimeInterval(3_600)
|
|
)
|
|
|
|
let updated = model.snapshot.threads[0]
|
|
#expect(updated.snoozedAt != oldSnooze)
|
|
#expect(updated.snoozedAt! > updated.attentionAt!)
|
|
}
|
|
|
|
@Test
|
|
func testResolveUserInputForwardsTypedAnswersAndClearsTheRequest() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread")
|
|
let request = FeatureUserInput(
|
|
id: "request-1",
|
|
threadID: thread.id,
|
|
questions: []
|
|
)
|
|
client.threadDetail = FeatureThreadDetail(thread: thread, userInputs: [request])
|
|
let model = FeatureRootModel(client: client)
|
|
_ = await model.detail(for: thread.id)
|
|
|
|
let answers: [String: FeatureInputAnswer] = [
|
|
"scope": .selections(["Server", "Web"]),
|
|
"note": .text("Ship it"),
|
|
]
|
|
await model.resolveUserInput(request.id, answers: answers)
|
|
|
|
#expect(client.resolvedInputID == request.id)
|
|
#expect(client.resolvedInputAnswers == answers)
|
|
#expect(model.details[thread.id]?.userInputs.isEmpty == true)
|
|
}
|
|
|
|
@Test
|
|
func granularThreadEventsMaintainCountsAndCollectionRevision() async {
|
|
let client = FeatureClientStub()
|
|
let project = FeatureProject(
|
|
id: "project-1",
|
|
environmentID: "environment-1",
|
|
name: "Native",
|
|
path: "/native"
|
|
)
|
|
client.snapshot = FeatureSnapshot(projects: [project])
|
|
let model = FeatureRootModel(client: client)
|
|
let thread = FeatureThread(
|
|
id: "thread-1",
|
|
projectID: project.id,
|
|
title: "Stream deltas"
|
|
)
|
|
|
|
let run = Task { await model.start() }
|
|
client.emit(.thread(thread))
|
|
client.emit(.thread(thread))
|
|
client.emit(.threadRemoved(id: thread.id))
|
|
let connected = FeatureConnection(state: .connected, environmentName: "Native")
|
|
client.emit(.connection(connected))
|
|
client.emit(.connection(connected))
|
|
client.finishEvents()
|
|
await run.value
|
|
|
|
#expect(model.snapshot.threads.isEmpty)
|
|
#expect(model.snapshot.projects[0].threadCount == 0)
|
|
#expect(model.threadCollectionRevision == 2)
|
|
#expect(model.homePresentationRevision == 4)
|
|
}
|
|
|
|
@Test
|
|
func detailEventsIgnoreDuplicatesAndAdvancePerThreadRevision() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(
|
|
id: "thread-1",
|
|
projectID: "project-1",
|
|
title: "Stream transcript"
|
|
)
|
|
client.snapshot = FeatureSnapshot(threads: [thread])
|
|
let first = FeatureThreadDetail(
|
|
thread: thread,
|
|
messages: [FeatureMessage(id: "message-1", role: .assistant, text: "Hel")]
|
|
)
|
|
let second = FeatureThreadDetail(
|
|
thread: thread,
|
|
messages: [
|
|
FeatureMessage(id: "message-1", role: .assistant, text: "Hello"),
|
|
FeatureMessage(id: "message-2", role: .user, text: "Ship it"),
|
|
]
|
|
)
|
|
let model = FeatureRootModel(client: client)
|
|
|
|
let run = Task { await model.start() }
|
|
client.emit(.detail(first))
|
|
client.emit(.detail(first))
|
|
client.emit(.detail(second))
|
|
client.finishEvents()
|
|
await run.value
|
|
|
|
#expect(model.details[thread.id] == second)
|
|
#expect(model.detailRevision == 2)
|
|
#expect(model.detailRevisions[thread.id] == 2)
|
|
}
|
|
|
|
@Test
|
|
func detailDeltaCarriesAContiguousRenderCursor() async {
|
|
let client = FeatureClientStub()
|
|
let thread = FeatureThread(
|
|
id: "thread-1",
|
|
projectID: "project-1",
|
|
title: "Incremental transcript"
|
|
)
|
|
let firstMessage = FeatureMessage(id: "message-1", role: .assistant, text: "Hel")
|
|
let completedMessage = FeatureMessage(id: "message-1", role: .assistant, text: "Hello")
|
|
let appendedMessage = FeatureMessage(id: "message-2", role: .user, text: "Ship it")
|
|
let first = FeatureThreadDetail(thread: thread, messages: [firstMessage])
|
|
let second = FeatureThreadDetail(
|
|
thread: thread,
|
|
messages: [completedMessage, appendedMessage]
|
|
)
|
|
client.snapshot = FeatureSnapshot(threads: [thread])
|
|
let model = FeatureRootModel(client: client)
|
|
|
|
let run = Task { await model.start() }
|
|
client.emit(.detail(first))
|
|
client.emit(.detailDelta(
|
|
second,
|
|
FeatureDetailDelta(
|
|
changedMessages: [completedMessage, appendedMessage],
|
|
appendedMessageIDs: [appendedMessage.id]
|
|
)
|
|
))
|
|
client.finishEvents()
|
|
await run.value
|
|
|
|
#expect(model.details[thread.id] == second)
|
|
#expect(model.detailRevisions[thread.id] == 2)
|
|
guard let update = model.detailRenderUpdates[thread.id] else {
|
|
Issue.record("Expected an incremental render update")
|
|
return
|
|
}
|
|
#expect(update.baseRevision == 1)
|
|
#expect(update.revision == 2)
|
|
guard case let .delta(delta) = update.change else {
|
|
Issue.record("Expected a detail delta")
|
|
return
|
|
}
|
|
#expect(delta.appendedMessageIDs == [appendedMessage.id])
|
|
#expect(delta.changedMessages == [completedMessage, appendedMessage])
|
|
}
|
|
|
|
@Test
|
|
func detailReducerAppendsStreamingTailAndExposesRenderMutation() {
|
|
let startedAt = "2026-07-31T20:00:00Z"
|
|
let message = OrchestrationMessage(
|
|
id: "message-1",
|
|
role: "assistant",
|
|
text: "Hel",
|
|
attachments: nil,
|
|
turnId: "turn-1",
|
|
streaming: true,
|
|
createdAt: startedAt,
|
|
updatedAt: startedAt
|
|
)
|
|
let thread = orchestrationThread(messages: [message])
|
|
let event = orchestrationEvent(
|
|
type: "thread.message-sent",
|
|
sequence: 12,
|
|
payload: [
|
|
"threadId": .string(thread.id),
|
|
"messageId": .string(message.id),
|
|
"role": .string("assistant"),
|
|
"text": .string("lo"),
|
|
"turnId": .string("turn-1"),
|
|
"streaming": .bool(true),
|
|
"createdAt": .string(startedAt),
|
|
"updatedAt": .string("2026-07-31T20:00:01Z"),
|
|
]
|
|
)
|
|
|
|
let reduction = NativeThreadDetailReducer.apply(event, to: thread)
|
|
|
|
#expect(reduction.sequence == 12)
|
|
guard case let .updated(updated) = reduction.result else {
|
|
Issue.record("Expected a streaming message update")
|
|
return
|
|
}
|
|
#expect(updated.messages[0].text == "Hello")
|
|
#expect(updated.messages[0].updatedAt == startedAt)
|
|
guard case let .message(rendered) = reduction.renderMutation else {
|
|
Issue.record("Expected a message-only render mutation")
|
|
return
|
|
}
|
|
#expect(rendered.text == "Hello")
|
|
}
|
|
|
|
@Test
|
|
func activityReducerKeepsLargeSnapshotHistorySharedAndExposesOnlyTheTail() throws {
|
|
let historical = (0..<1_000).map { (index: Int) in
|
|
OrchestrationActivity(
|
|
id: "history-\(index)",
|
|
tone: "info",
|
|
kind: "tool.completed",
|
|
summary: "Historical work",
|
|
payload: .object([:]),
|
|
turnId: "turn-1",
|
|
sequence: index,
|
|
createdAt: "2026-07-31T20:00:00Z"
|
|
)
|
|
}
|
|
let appended = OrchestrationActivity(
|
|
id: "activity-new",
|
|
tone: "info",
|
|
kind: "tool.completed",
|
|
summary: "New work",
|
|
payload: .object([:]),
|
|
turnId: "turn-1",
|
|
sequence: historical.count,
|
|
createdAt: "2026-07-31T20:00:01Z"
|
|
)
|
|
let thread = orchestrationThread(activities: historical)
|
|
let event = orchestrationEvent(
|
|
type: "thread.activity-appended",
|
|
sequence: 1_001,
|
|
payload: [
|
|
"threadId": .string(thread.id),
|
|
"activity": try JSONValue.encode(appended),
|
|
]
|
|
)
|
|
|
|
let reduction = NativeThreadDetailReducer.apply(event, to: thread)
|
|
|
|
guard case let .updated(updated) = reduction.result else {
|
|
Issue.record("Expected an activity update")
|
|
return
|
|
}
|
|
#expect(updated.activities.count == historical.count)
|
|
guard case let .activity(rendered) = reduction.renderMutation else {
|
|
Issue.record("Expected an activity-tail render mutation")
|
|
return
|
|
}
|
|
#expect(rendered == appended)
|
|
}
|
|
|
|
@Test
|
|
func destructiveDetailEventRequestsAuthoritativeSnapshot() {
|
|
let thread = orchestrationThread()
|
|
let event = orchestrationEvent(
|
|
type: "thread.reverted",
|
|
sequence: 3,
|
|
payload: ["threadId": .string(thread.id)]
|
|
)
|
|
|
|
let reduction = NativeThreadDetailReducer.apply(event, to: thread)
|
|
|
|
#expect(reduction.result == .refresh)
|
|
#expect(reduction.renderMutation == .full)
|
|
}
|
|
}
|
|
|
|
private func orchestrationEvent(
|
|
type: String,
|
|
sequence: Int,
|
|
payload: [String: JSONValue]
|
|
) -> JSONValue {
|
|
.object([
|
|
"type": .string(type),
|
|
"sequence": .number(Double(sequence)),
|
|
"occurredAt": .string("2026-07-31T20:00:02Z"),
|
|
"payload": .object(payload),
|
|
])
|
|
}
|
|
|
|
private func orchestrationThread(
|
|
messages: [OrchestrationMessage] = [],
|
|
activities: [OrchestrationActivity] = []
|
|
) -> OrchestrationThread {
|
|
OrchestrationThread(
|
|
id: "thread-1",
|
|
projectId: "project-1",
|
|
title: "Native detail stream",
|
|
modelSelection: ModelSelection(instanceId: "codex", model: "gpt-5.6-sol"),
|
|
runtimeMode: .fullAccess,
|
|
interactionMode: .default,
|
|
branch: "main",
|
|
worktreePath: "/native",
|
|
latestTurn: nil,
|
|
createdAt: "2026-07-31T20:00:00Z",
|
|
updatedAt: "2026-07-31T20:00:00Z",
|
|
archivedAt: nil,
|
|
settledOverride: nil,
|
|
settledAt: nil,
|
|
snoozedUntil: nil,
|
|
snoozedAt: nil,
|
|
deletedAt: nil,
|
|
messages: messages,
|
|
activities: activities,
|
|
checkpoints: [],
|
|
session: nil
|
|
)
|
|
}
|
|
|
|
@MainActor
|
|
private final class FeatureClientStub: FeatureClient {
|
|
private let eventStream: AsyncStream<FeatureEvent>
|
|
private let eventContinuation: AsyncStream<FeatureEvent>.Continuation
|
|
var snapshot = FeatureSnapshot()
|
|
var snapshotAfterPair: FeatureSnapshot?
|
|
var createdThread = FeatureThread(id: "created", projectID: "project", title: "Created")
|
|
var threadDetail: FeatureThreadDetail?
|
|
var pairEndpoint: String?
|
|
var pairToken: String?
|
|
var sentText: String?
|
|
var startedPrompt: String?
|
|
var startedAttachments: [FeatureUploadAttachment] = []
|
|
var createThreadCallCount = 0
|
|
var sendMessageCallCount = 0
|
|
var loadThreadError: (any Error)?
|
|
var resolvedInputID: String?
|
|
var resolvedInputAnswers: [String: FeatureInputAnswer]?
|
|
|
|
init() {
|
|
let pair = AsyncStream<FeatureEvent>.makeStream()
|
|
eventStream = pair.stream
|
|
eventContinuation = pair.continuation
|
|
}
|
|
|
|
func events() -> AsyncStream<FeatureEvent> {
|
|
eventStream
|
|
}
|
|
|
|
func emit(_ event: FeatureEvent) {
|
|
eventContinuation.yield(event)
|
|
}
|
|
|
|
func finishEvents() {
|
|
eventContinuation.finish()
|
|
}
|
|
|
|
func initialSnapshot() async throws -> FeatureSnapshot {
|
|
if pairEndpoint != nil, let snapshotAfterPair {
|
|
return snapshotAfterPair
|
|
}
|
|
return snapshot
|
|
}
|
|
|
|
func pair(endpoint: String, token: String?) async throws {
|
|
pairEndpoint = endpoint
|
|
pairToken = token
|
|
}
|
|
|
|
func createThread(
|
|
projectID: String,
|
|
title: String?,
|
|
selection: FeatureSelection?
|
|
) async throws -> FeatureThread {
|
|
createThreadCallCount += 1
|
|
return createdThread
|
|
}
|
|
|
|
func createThreadAndSend(
|
|
projectID: String,
|
|
prompt: String,
|
|
selection: FeatureSelection?,
|
|
runtimeMode: FeatureRuntimeMode,
|
|
interactionMode: FeatureInteractionMode,
|
|
attachments: [FeatureUploadAttachment]
|
|
) async throws -> FeatureThread {
|
|
startedPrompt = prompt
|
|
startedAttachments = attachments
|
|
return createdThread
|
|
}
|
|
|
|
func renameThread(id: String, title: String) async throws {}
|
|
func setThreadArchived(id: String, archived: Bool) async throws {}
|
|
func deleteThread(id: String) async throws {}
|
|
|
|
func loadThread(id: String) async throws -> FeatureThreadDetail {
|
|
if let loadThreadError {
|
|
throw loadThreadError
|
|
}
|
|
if let threadDetail {
|
|
return threadDetail
|
|
}
|
|
return FeatureThreadDetail(thread: createdThread)
|
|
}
|
|
|
|
func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws {
|
|
sendMessageCallCount += 1
|
|
sentText = text
|
|
}
|
|
|
|
func cancelTurn(threadID: String) async throws {}
|
|
func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws {}
|
|
func resolveUserInput(
|
|
id: String,
|
|
answers: [String: FeatureInputAnswer]
|
|
) async throws {
|
|
resolvedInputID = id
|
|
resolvedInputAnswers = answers
|
|
}
|
|
func saveSettings(_ settings: FeatureSettings) async throws {}
|
|
}
|