Open History to see the last commit
1import Foundation
2import Testing
3@testable import T3Code
4
5@MainActor
6@Suite("Native thread metadata")
7struct NativeThreadMetadataTests {
8 @Test
9 func multiplePRLinksUpdateWithoutReloadAndHideDismissedStackMembers() throws {
10 let link = ThreadPullRequestLink(host: "github.com", repository: "test/repo", number: 2,
11 url: "https://github.com/test/repo/pull/2", source: "manual",
12 linkedAt: "2026-09-06T20:00:00Z", snapshot: nil, stack: nil)
13 let linked = NativeThreadDetailReducer.apply(event(type: "thread.pull-request-linked",
14 payload: ["link": try JSONValue.encode(link)]), to: thread())
15 guard case let .updated(withLink) = linked.result else {
16 Issue.record("Expected a local PR link update")
17 return
18 }
19 #expect(withLink.pullRequests == [link])
20 let state = ThreadPullRequestSnapshot(state: .merged, title: "Finished PR", headBranch: "task",
21 baseBranch: "main", isDraft: false, updatedAt: nil, syncedAt: "2026-09-06T20:00:00Z")
22 let key: [String: JSONValue] = ["host": .string("GITHUB.COM"), "repository": .string("TEST/REPO"), "number": .number(2)]
23 let synced = NativeThreadDetailReducer.apply(event(type: "thread.pull-request-synced",
24 payload: key.merging(["snapshot": try JSONValue.encode(state), "stack": .null]) { _, next in next }), to: withLink)
25 guard case let .updated(withState) = synced.result else {
26 Issue.record("Expected a local PR state update")
27 return
28 }
29 #expect(withState.pullRequests?.first?.snapshot?.state == .merged)
30 #expect(HomeThreadPullRequestPresentation.resolve(links: withState.pullRequests ?? [])?.state == .merged)
31 let removed = NativeThreadDetailReducer.apply(event(type: "thread.pull-request-unlinked", payload: key), to: withState)
32 guard case let .updated(withoutLink) = removed.result else {
33 Issue.record("Expected a local PR unlink")
34 return
35 }
36 #expect(withoutLink.pullRequests == [])
37
38 var dismissed = link
39 dismissed.source = "stack-dismissed"
40 let feature = FeatureThread(id: "thread", projectID: "project", title: "Task", pullRequests: [dismissed])
41 #expect(feature.effectivePullRequest == nil)
42 #expect(ThreadPullRequestDestination.resolve(thread: feature, branchPullRequest: nil) == nil)
43 #expect(HomeThreadPullRequestPresentation.resolve(links: [dismissed]) == nil)
44 }
45
46 @Test
47 func multiplePRSnapshotsReachThreadSearchAndExternalLinks() {
48 let link = ThreadPullRequestLink(host: "github.example.com", repository: "test/other", number: 24,
49 url: "https://github.example.com/test/other/pull/24", source: "manual",
50 linkedAt: "2026-09-06T20:00:00Z", snapshot: nil, stack: nil)
51 let feature = FeatureThread(id: "thread", projectID: "project", title: "Task", pullRequests: [link])
52 #expect(ThreadPullRequestDestination.resolve(thread: feature, branchPullRequest: nil)?.url.absoluteString == link.url)
53 #expect(ThreadPullRequests.searchTerms(feature.pullRequests, legacy: nil).contains("test/other#24"))
54 var changed = feature
55 changed.pullRequests = []
56 #expect(HomeOrderKey(feature) != HomeOrderKey(changed))
57 #expect(feature.pullRequestObservationIdentity == feature.pullRequestObservationIdentity)
58 #expect(feature.pullRequestObservationIdentity != changed.pullRequestObservationIdentity)
59 }
60
61 @Test
62 func snapshotsDecodeServerPRAndOrderWithoutRequiringThemFromOlderServers() throws {
63 let base = try JSONValue.encode(thread())
64 guard case var .object(fields) = base else {
65 Issue.record("Expected an encoded thread")
66 return
67 }
68 fields.removeValue(forKey: "branchPullRequest")
69 fields.removeValue(forKey: "activeOrderKey")
70 fields.removeValue(forKey: "pullRequests")
71 let older = try JSONValue.object(fields).decode(OrchestrationThread.self)
72 #expect(older.branchPullRequest == nil)
73 #expect(older.activeOrderKey == nil)
74 #expect(older.pullRequests == nil)
75
76 fields["branchPullRequest"] = try JSONValue.encode(reference())
77 fields["activeOrderKey"] = .string("nm")
78 fields["pullRequests"] = .array([])
79 let current = try JSONValue.object(fields).decode(OrchestrationThread.self)
80 #expect(current.branchPullRequest == reference())
81 #expect(current.activeOrderKey == "nm")
82 #expect(current.pullRequests == [])
83
84 fields["latestUserMessageAt"] = .null
85 fields["hasPendingApprovals"] = .bool(false)
86 fields["hasPendingUserInput"] = .bool(false)
87 fields["hasActionableProposedPlan"] = .bool(false)
88 let shell = try JSONValue.object(fields).decode(OrchestrationThreadShell.self)
89 #expect(shell.branchPullRequest == reference())
90 #expect(shell.activeOrderKey == "nm")
91 #expect(shell.pullRequests == [])
92 }
93
94 @Test
95 func branchPRAndActiveOrderUpdatesDoNotReloadTheThread() throws {
96 let branchUpdate = try reduce(
97 ["branchPullRequest": JSONValue.encode(reference())],
98 thread: thread()
99 )
100 #expect(branchUpdate.branchPullRequest == reference())
101 #expect(branchUpdate.linkedPullRequest == nil)
102
103 let reordered = try reduce(["activeOrderKey": .string("nm")], thread: branchUpdate)
104 #expect(reordered.branchPullRequest == reference())
105 #expect(reordered.activeOrderKey == "nm")
106
107 let cleared = try reduce([
108 "branchPullRequest": .null,
109 "activeOrderKey": .null,
110 ], thread: reordered)
111 #expect(cleared.branchPullRequest == nil)
112 #expect(cleared.activeOrderKey == nil)
113 }
114
115 @Test
116 func settlingClearsManualOrderButKeepsPRMetadata() throws {
117 var source = thread()
118 source.branchPullRequest = reference()
119 source.activeOrderKey = "nm"
120 let result = NativeThreadDetailReducer.apply(event(
121 type: "thread.settled",
122 payload: ["settledAt": .string("2026-09-06T20:00:00Z")]
123 ), to: source)
124 guard case let .updated(settled) = result.result else {
125 Issue.record("Expected settlement without a reload")
126 return
127 }
128 #expect(settled.activeOrderKey == nil)
129 #expect(settled.branchPullRequest == reference())
130 }
131
132 @Test
133 func settlingAndMetadataUpdatesKeepAnActiveTitleRegeneration() throws {
134 var source = thread()
135 source.titleRegeneration = ThreadTitleRegeneration(
136 requestId: "command-regenerate", startedAt: "2026-09-06T19:30:00Z"
137 )
138 let settled = NativeThreadDetailReducer.apply(event(
139 type: "thread.settled",
140 payload: ["settledAt": .string("2026-09-06T20:00:00Z")]
141 ), to: source)
142 guard case let .updated(afterSettle) = settled.result else {
143 Issue.record("Expected settlement without a reload")
144 return
145 }
146 #expect(afterSettle.titleRegeneration == source.titleRegeneration)
147
148 let reordered = try reduce(["activeOrderKey": .string("nm")], thread: afterSettle)
149 #expect(reordered.titleRegeneration == source.titleRegeneration)
150 }
151
152 @Test
153 func ordinaryThreadEventsPreservePRAndManualOrder() throws {
154 var source = thread()
155 source.branchPullRequest = reference()
156 source.activeOrderKey = "nm"
157 let result = NativeThreadDetailReducer.apply(event(
158 type: "thread.message-sent",
159 payload: [
160 "messageId": .string("message"),
161 "role": .string("assistant"),
162 "text": .string("Complete"),
163 "streaming": .bool(false),
164 "createdAt": .string("2026-09-06T20:00:00Z"),
165 ]
166 ), to: source)
167 guard case let .updated(updated) = result.result else {
168 Issue.record("Expected the message to update without a reload")
169 return
170 }
171 #expect(updated.branchPullRequest == reference())
172 #expect(updated.activeOrderKey == "nm")
173 #expect(updated.messages.last?.text == "Complete")
174 }
175
176 @Test
177 func invalidMetadataStillRequestsAnAuthoritativeSnapshot() {
178 let payloads: [[String: JSONValue]] = [
179 ["branchPullRequest": .string("invalid")],
180 ["activeOrderKey": .number(10)],
181 ["activeOrderKey": .string(" ")],
182 ["branchPullRequest": .null, "title": .string("Renamed")],
183 ]
184 for payload in payloads {
185 let result = NativeThreadDetailReducer.apply(event(payload: payload), to: thread())
186 #expect(result.result == .refresh)
187 }
188 }
189
190 @Test
191 func serverPRLinksOpenDirectlyAndExplicitLinksTakePriority() throws {
192 var source = FeatureThread(
193 id: "thread", projectID: "project", title: "Task",
194 branchPullRequest: reference()
195 )
196 let branchIdentity = source.pullRequestObservationIdentity
197 #expect(branchIdentity != nil)
198 let branchDestination = try #require(ThreadPullRequestDestination.resolve(
199 thread: source, branchPullRequest: nil
200 ))
201 #expect(branchDestination.url.absoluteString == reference().url)
202 #expect(branchDestination.number == 1)
203
204 source.linkedPullRequest = reference(number: 2)
205 #expect(source.effectivePullRequest == reference(number: 2))
206 #expect(source.pullRequestObservationIdentity != branchIdentity)
207 let linkedDestination = try #require(ThreadPullRequestDestination.resolve(
208 thread: source, branchPullRequest: nil
209 ))
210 #expect(linkedDestination.number == 2)
211 }
212
213 private func reduce(
214 _ payload: [String: JSONValue],
215 thread: OrchestrationThread
216 ) throws -> OrchestrationThread {
217 let reduction = NativeThreadDetailReducer.apply(event(payload: payload), to: thread)
218 #expect(reduction.renderMutation == .metadata)
219 guard case let .updated(updated) = reduction.result else {
220 throw MetadataTestError.expectedLocalUpdate
221 }
222 return updated
223 }
224
225 private func event(
226 type: String = "thread.meta-updated",
227 payload: [String: JSONValue]
228 ) -> JSONValue {
229 .object([
230 "type": .string(type),
231 "sequence": .number(2),
232 "occurredAt": .string("2026-09-06T20:00:00Z"),
233 "payload": .object(payload.merging([
234 "threadId": .string("thread"),
235 "updatedAt": .string("2026-09-06T20:00:00Z"),
236 ]) { _, value in value }),
237 ])
238 }
239
240 private func reference(number: Int = 1) -> ThreadLinkedPullRequest {
241 ThreadLinkedPullRequest(
242 projectId: "project", repository: "test/repo", number: number,
243 url: "https://example.com/pull/\(number)"
244 )
245 }
246
247 private func thread() -> OrchestrationThread {
248 OrchestrationThread(
249 id: "thread", projectId: "project", title: "Task",
250 modelSelection: ModelSelection(instanceId: "codex", model: "gpt-5.6-sol"),
251 runtimeMode: .fullAccess, interactionMode: .default,
252 branch: "task", worktreePath: nil, latestTurn: nil,
253 createdAt: "2026-09-06T19:00:00Z", updatedAt: "2026-09-06T19:00:00Z",
254 archivedAt: nil, settledOverride: nil, settledAt: nil,
255 snoozedUntil: nil, snoozedAt: nil, pinnedAt: nil, deletedAt: nil,
256 messages: [], activities: [], checkpoints: [], session: nil
257 )
258 }
259}
260
261private enum MetadataTestError: Error {
262 case expectedLocalUpdate
263}