Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeatureToolStateTests.swift

691 lines25.7 KB

1import Foundation
2import Testing
3@testable import T3Code
4​
5@Suite("Thread tool state")
6struct FeatureToolStateTests {
7 @MainActor
8 @Test("A failed source-control action stops progress before recovery")
9 func failedSourceControlActionStopsProgressBeforeRecovery() async {
10 var phases: [String] = []
11​
12 let result: Result<Void, Error> = await runFeatureSourceControlAction(
13 setRunning: { phases.append($0 ? "running" : "stopped") }
14 ) {
15 throw FeatureCapabilityUnavailable("Source control")
16 }
17​
18 if case .failure = result {
19 phases.append("recovery")
20 }
21​
22 #expect(phases == ["running", "stopped", "recovery"])
23 }
24​
25 private static func vcsLocal(
26 isRepo: Bool = true,
27 hasPrimaryRemote: Bool = true,
28 refName: String? = "feature/cached",
29 files: [String] = []
30 ) -> VCSLocalStatus {
31 VCSLocalStatus(
32 isRepo: isRepo,
33 sourceControlProvider: nil,
34 hasPrimaryRemote: hasPrimaryRemote,
35 isDefaultRef: false,
36 refName: refName,
37 hasWorkingTreeChanges: files.isEmpty == false,
38 workingTree: VCSWorkingTree(
39 files: files.map {
40 VCSWorkingTreeFile(path: $0, insertions: 1, deletions: 0)
41 },
42 insertions: files.count,
43 deletions: 0
44 )
45 )
46 }
47​
48 private static func vcsRemote(
49 aheadCount: Int,
50 behindCount: Int = 0,
51 pullRequest: VCSChangeRequest? = nil
52 ) -> VCSRemoteStatus {
53 VCSRemoteStatus(
54 hasUpstream: true,
55 aheadCount: aheadCount,
56 behindCount: behindCount,
57 aheadOfDefaultCount: nil,
58 pr: pullRequest
59 )
60 }
61​
62 @Test("Cached local status is available before remote status")
63 func cachedLocalStatusArrivesFirst() throws {
64 var accumulator = NativeSourceControlStatusAccumulator()
65​
66 let consumedLocal = accumulator.consume(
67 .snapshot(
68 local: Self.vcsLocal(files: ["App/NativeFeatureClient.swift"]),
69 remote: nil
70 )
71 )
72 let localOnly = try #require(consumedLocal)
73​
74 #expect(localOnly.branch == "feature/cached")
75 #expect(localOnly.files.map(\.path) == ["App/NativeFeatureClient.swift"])
76 #expect(localOnly.aheadCount == 0)
77 #expect(localOnly.pullRequest == nil)
78 #expect(accumulator.isComplete == false)
79 // Ahead/behind are unknown rather than zero, so remote-dependent
80 // actions stay withheld until the remote half lands.
81 #expect(localOnly.isRemoteKnown == false)
82 #expect(localOnly.availableActions.contains(.createPullRequest) == false)
83 #expect(localOnly.availableActions.contains(.commitPushAndCreatePullRequest) == false)
84 #expect(localOnly.availableActions.contains(.commit))
85 }
86​
87 @Test("Remote status combines with the latest local status")
88 func remoteStatusUsesLatestLocalState() throws {
89 var accumulator = NativeSourceControlStatusAccumulator()
90 _ = accumulator.consume(
91 .snapshot(local: Self.vcsLocal(refName: "feature/old"), remote: nil)
92 )
93 _ = accumulator.consume(
94 .localUpdated(Self.vcsLocal(refName: "feature/new", files: ["new.swift"]))
95 )
96 let pullRequest = VCSChangeRequest(
97 number: 42,
98 title: "Cached status",
99 url: "https://example.com/pull/42",
100 baseRef: "main",
101 headRef: "feature/new",
102 state: "OPEN"
103 )
104​
105 let consumedRemote = accumulator.consume(
106 .remoteUpdated(
107 Self.vcsRemote(
108 aheadCount: 2,
109 behindCount: 1,
110 pullRequest: pullRequest
111 )
112 )
113 )
114 let combined = try #require(consumedRemote)
115​
116 #expect(combined.branch == "feature/new")
117 #expect(combined.files.map(\.path) == ["new.swift"])
118 #expect(combined.aheadCount == 2)
119 #expect(combined.behindCount == 1)
120 #expect(combined.pullRequest?.number == 42)
121 #expect(combined.isRemoteKnown)
122 #expect(accumulator.isComplete)
123 }
124​
125 @Test("Remote status is retained across a later local-only update")
126 func localUpdateKeepsKnownRemoteStatus() throws {
127 var accumulator = NativeSourceControlStatusAccumulator()
128 _ = accumulator.consume(
129 .snapshot(
130 local: Self.vcsLocal(refName: "feature/one"),
131 remote: Self.vcsRemote(aheadCount: 4, behindCount: 2)
132 )
133 )
134 #expect(accumulator.isComplete)
135​
136 let consumed = accumulator.consume(
137 .localUpdated(Self.vcsLocal(refName: "feature/one", files: ["later.swift"]))
138 )
139 let updated = try #require(consumed)
140​
141 #expect(updated.files.map(\.path) == ["later.swift"])
142 #expect(updated.aheadCount == 4)
143 #expect(updated.behindCount == 2)
144 #expect(updated.isRemoteKnown)
145 // Completion latches: a local-only update must not reopen the stream.
146 #expect(accumulator.isComplete)
147 }
148​
149 @Test("Remote-before-local ordering retains the remote status")
150 func remoteBeforeLocalIsRetained() throws {
151 var accumulator = NativeSourceControlStatusAccumulator()
152​
153 let remoteBeforeLocal = accumulator.consume(
154 .remoteUpdated(Self.vcsRemote(aheadCount: 9))
155 )
156 #expect(remoteBeforeLocal == nil)
157 #expect(accumulator.isComplete == false)
158​
159 let consumedLocal = accumulator.consume(
160 .localUpdated(Self.vcsLocal(refName: "feature/local"))
161 )
162 let withRetainedRemote = try #require(consumedLocal)
163 let consumedRemote = accumulator.consume(
164 .remoteUpdated(Self.vcsRemote(aheadCount: 3))
165 )
166 let combined = try #require(consumedRemote)
167​
168 #expect(withRetainedRemote.aheadCount == 9)
169 #expect(withRetainedRemote.isRemoteKnown)
170 #expect(combined.branch == "feature/local")
171 #expect(combined.aheadCount == 3)
172 #expect(accumulator.isComplete)
173 }
174​
175 @Test(
176 "Terminal local states do not wait for remote status",
177 arguments: [
178 Self.vcsLocal(isRepo: false, hasPrimaryRemote: false, refName: nil),
179 Self.vcsLocal(hasPrimaryRemote: false, refName: "local-only"),
180 ]
181 )
182 func terminalLocalStatesAreExplicit(local: VCSLocalStatus) throws {
183 var accumulator = NativeSourceControlStatusAccumulator()
184​
185 let consumed = accumulator.consume(.snapshot(local: local, remote: nil))
186 let status = try #require(consumed)
187​
188 #expect(status.isRepository == local.isRepo)
189 #expect(status.branch == local.refName)
190 #expect(status.pullRequest == nil)
191 // No remote will ever arrive, so nothing is left pending.
192 #expect(status.isRemoteKnown)
193 #expect(accumulator.isComplete)
194 }
195​
196 @Test("A stream ending after only a cached local status is a protocol error")
197 func prematureStreamEndIsExplicit() throws {
198 var accumulator = NativeSourceControlStatusAccumulator()
199 _ = accumulator.consume(
200 .snapshot(local: Self.vcsLocal(files: ["pending.swift"]), remote: nil)
201 )
202 #expect(accumulator.isComplete == false)
203​
204 #expect(throws: RPCError.self) { try accumulator.validateEnd() }
205 }
206​
207 @Test("An absent remote half resolves the status instead of leaving it pending")
208 func nilRemotePayloadResolvesTheRemoteHalf() throws {
209 var accumulator = NativeSourceControlStatusAccumulator()
210 _ = accumulator.consume(.snapshot(local: Self.vcsLocal(), remote: nil))
211 #expect(accumulator.isComplete == false)
212​
213 let consumed = accumulator.consume(.remoteUpdated(nil))
214 let resolved = try #require(consumed)
215​
216 // "Known to be absent" is not "still pending": the stream is finished
217 // and the screen must stop claiming it is checking.
218 #expect(resolved.isRemoteKnown)
219 #expect(resolved.aheadCount == 0)
220 #expect(resolved.behindCount == 0)
221 #expect(resolved.pullRequest == nil)
222 #expect(accumulator.isComplete)
223 }
224​
225 @Test("A later snapshot replaces the remote half rather than merging into it")
226 func snapshotReplacesKnownRemoteStatus() throws {
227 var accumulator = NativeSourceControlStatusAccumulator()
228 _ = accumulator.consume(
229 .snapshot(
230 local: Self.vcsLocal(refName: "feature/one"),
231 remote: Self.vcsRemote(aheadCount: 7)
232 )
233 )
234​
235 // Resubscribe after a reconnect: the server prepends a fresh snapshot
236 // carrying whatever its cache holds, so a stale ahead count must not
237 // survive and must not be reported as known.
238 let consumed = accumulator.consume(
239 .snapshot(local: Self.vcsLocal(refName: "feature/one"), remote: nil)
240 )
241 let replaced = try #require(consumed)
242​
243 #expect(replaced.aheadCount == 0)
244 #expect(replaced.isRemoteKnown == false)
245 #expect(accumulator.isComplete == false)
246 }
247​
248 @Test("A fresh snapshot can return a reused monitor to pending")
249 func completionTracksTheCurrentSequence() {
250 var accumulator = NativeSourceControlStatusAccumulator()
251 let events: [VCSStatusEvent] = [
252 .snapshot(local: Self.vcsLocal(refName: "feature/seq"), remote: nil),
253 .localUpdated(Self.vcsLocal(refName: "feature/seq", files: ["a.swift"])),
254 .remoteUpdated(Self.vcsRemote(aheadCount: 1)),
255 .localUpdated(Self.vcsLocal(refName: "feature/seq", files: ["a.swift", "b.swift"])),
256 .remoteUpdated(nil),
257 // A reused monitor can begin a fresh cached-local-first sequence.
258 .snapshot(local: Self.vcsLocal(refName: "feature/seq"), remote: nil),
259 .localUpdated(Self.vcsLocal(refName: "feature/seq")),
260 ]
261​
262 var completionStates: [Bool] = []
263 for event in events {
264 _ = accumulator.consume(event)
265 completionStates.append(accumulator.isComplete)
266 }
267​
268 #expect(completionStates == [false, false, true, true, true, false, false])
269 }
270​
271 @Test("Changing branches discards the prior branch remote status")
272 func branchChangeReturnsRemoteStatusToPending() throws {
273 var accumulator = NativeSourceControlStatusAccumulator()
274 _ = accumulator.consume(
275 .snapshot(
276 local: Self.vcsLocal(refName: "feature/one"),
277 remote: Self.vcsRemote(aheadCount: 4)
278 )
279 )
280​
281 let consumed = accumulator.consume(
282 .localUpdated(Self.vcsLocal(refName: "feature/two"))
283 )
284 let changedBranch = try #require(consumed)
285​
286 #expect(changedBranch.branch == "feature/two")
287 #expect(changedBranch.aheadCount == 0)
288 #expect(changedBranch.pullRequest == nil)
289 #expect(changedBranch.isRemoteKnown == false)
290 #expect(accumulator.isComplete == false)
291 }
292​
293 @Test("A completed stream ends without error")
294 func completedStreamEndIsAccepted() throws {
295 var accumulator = NativeSourceControlStatusAccumulator()
296 _ = accumulator.consume(
297 .snapshot(
298 local: Self.vcsLocal(),
299 remote: Self.vcsRemote(aheadCount: 1)
300 )
301 )
302​
303 try accumulator.validateEnd()
304 }
305​
306 @Test
307 func fileFilteringKeepsDirectoriesFirstAndHonorsHiddenFiles() {
308 let entries = [
309 FeatureFileEntry(path: "z.swift", name: "z.swift", kind: .file),
310 FeatureFileEntry(path: ".env", name: ".env", kind: .file, isHidden: true),
311 FeatureFileEntry(path: "Sources", name: "Sources", kind: .directory),
312 FeatureFileEntry(path: "a.swift", name: "a.swift", kind: .file),
313 ]
314​
315 #expect(entries.featureFiltered(by: "", includesHidden: false).map(\.name) == [
316 "Sources", "a.swift", "z.swift",
317 ])
318 #expect(entries.featureFiltered(by: "env", includesHidden: true).map(\.name) == [".env"])
319 }
320​
321 @Test
322 func filePreviewKindUsesImageMarkdownAndSourceSemantics() {
323 #expect(FeatureFilePreviewKind.infer(path: "art/hero.webp") == .image)
324 #expect(FeatureFilePreviewKind.infer(path: "docs/spec.pdf") == .pdf)
325 #expect(FeatureFilePreviewKind.infer(path: "demo.mov") == .video)
326 #expect(FeatureFilePreviewKind.infer(path: "brief.docx") == .document)
327 #expect(FeatureFilePreviewKind.infer(path: "README.md") == .markdown)
328 #expect(FeatureFilePreviewKind.infer(path: "Package.swift") == .source)
329 #expect(FeatureFilePreviewKind.infer(path: "LICENSE") == .plainText)
330 #expect(FeatureFilePreviewKind.infer(path: "template", language: "html") == .source)
331 }
332​
333 @Test
334 func previewFileNamesDropPathsAndRejectEmptyNames() throws {
335 #expect(try FeatureMediaPreviewFiles.safeFileName("reports/final.pdf") == "final.pdf")
336 #expect(try FeatureMediaPreviewFiles.safeFileName("clip:one.mov") == "clip_one.mov")
337 #expect(throws: FeatureMediaPreviewError.invalidFileName) {
338 try FeatureMediaPreviewFiles.safeFileName(" ")
339 }
340 }
341​
342 @Test
343 func previewDirectoriesHaveUniqueOwnership() throws {
344 let first = try FeatureMediaPreviewFiles.ownedDirectory()
345 let second = try FeatureMediaPreviewFiles.ownedDirectory()
346 defer {
347 try? FileManager.default.removeItem(at: first)
348 try? FileManager.default.removeItem(at: second)
349 }
350 #expect(first != second)
351 #expect(FileManager.default.fileExists(atPath: first.path))
352 #expect(FileManager.default.fileExists(atPath: second.path))
353 }
354​
355 @Test
356 func remotePreviewNeverSharesItsSignedSourceURL() {
357 let signedURL = URL(string: "https://example.com/file.pdf?token=secret")!
358 let downloadedURL = URL(fileURLWithPath: "/tmp/owned/file.pdf")
359 #expect(
360 FeatureMediaPreviewFiles.shareURL(
361 for: .remote(signedURL),
362 downloadedURL: nil
363 ) == nil
364 )
365 #expect(
366 FeatureMediaPreviewFiles.shareURL(
367 for: .remote(signedURL),
368 downloadedURL: downloadedURL
369 ) == downloadedURL
370 )
371 }
372​
373 @Test
374 func typedMediaPreviewRouteKeepsHostPathAndKind() {
375 var components = URLComponents()
376 components.scheme = "t3code"
377 components.host = "media-preview"
378 components.path = "/open"
379 components.queryItems = [
380 URLQueryItem(name: "path", value: "/tmp/output/final image.png"),
381 URLQueryItem(name: "kind", value: "image"),
382 ]
383 #expect(
384 FeatureTypedMediaPreviewRoute.parse(components.url!)
385 == FeatureTypedMediaPreviewRoute(
386 path: "/tmp/output/final image.png",
387 kind: .image
388 )
389 )
390 #expect(
391 FeatureTypedMediaPreviewRoute.parse(
392 URL(string: "t3code://media-preview/open?path=/tmp/a.pdf&kind=pdf")!
393 ) == FeatureTypedMediaPreviewRoute(path: "/tmp/a.pdf", kind: .pdf)
394 )
395 }
396​
397 @Test
398 func previewGenerationRejectsCompletionAfterDismissal() {
399 var generation = FeatureMediaPreviewGeneration()
400 let downloadGeneration = generation.begin()
401 #expect(generation.isCurrent(downloadGeneration))
402 generation.invalidate()
403 #expect(!generation.isCurrent(downloadGeneration))
404 }
405​
406 @Test
407 func sourceHighlighterPreservesTextAndClassifiesStableSpans() {
408 let source = """
409 let count = 42 // total
410 /* first
411 second */ return "done"
412 """
413 let lines = FeatureSourceHighlighter.lines(text: source, language: "swift")
414​
415 #expect(lines.map(\.text).joined(separator: "\n") == source)
416 #expect(lines[0].spans.contains { $0.text == "let" && $0.kind == .keyword })
417 #expect(lines[0].spans.contains { $0.text == "42" && $0.kind == .number })
418 #expect(lines[0].spans.last?.kind == .comment)
419 #expect(lines[1].spans.allSatisfy { $0.kind == .comment })
420 #expect(lines[2].spans.first?.kind == .comment)
421 #expect(lines[2].spans.contains { $0.text.contains("return") && $0.kind == .keyword })
422 #expect(lines[2].spans.last?.kind == .literal)
423 }
424​
425 @Test
426 func sourceHighlighterRecognizesJSONProperties() {
427 let line = FeatureSourceHighlighter.lines(
428 text: #"{"enabled": true, "count": 3}"#,
429 language: "json"
430 )[0]
431​
432 #expect(line.spans.contains { $0.text == #""enabled""# && $0.kind == .property })
433 #expect(line.spans.contains { $0.text == "true" && $0.kind == .literal })
434 #expect(line.spans.contains { $0.text == "3" && $0.kind == .number })
435 }
436​
437 @Test
438 func sourceHighlighterBoundsWorkForLargeMinifiedLines() {
439 let source = String(repeating: #"{"value":42}"#, count: 3_000)
440 let line = FeatureSourceHighlighter.lines(text: source, language: "json")[0]
441​
442 #expect(line.text == source)
443 #expect(line.spans == [FeatureSourceSpan(text: source, kind: .plain)])
444 }
445​
446 @Test
447 func reviewTotalsAggregateAcrossFiles() {
448 let review = FeatureReview(files: [
449 FeatureReviewFile(path: "a.swift", change: .modified, additions: 4, deletions: 1),
450 FeatureReviewFile(path: "b.swift", change: .added, additions: 8, deletions: 0),
451 ])
452​
453 #expect(review.additions == 12)
454 #expect(review.deletions == 1)
455 }
456​
457 @Test
458 func wordDiffHighlightsOnlyChangedTokens() {
459 let result = FeatureDiffWordHighlighter.spans(
460 old: "let color = blue",
461 new: "let color = green"
462 )
463​
464 #expect(result.old.map(\.text).joined() == "let color = blue")
465 #expect(result.new.map(\.text).joined() == "let color = green")
466 #expect(result.old.filter { $0.kind == .changed }.map(\.text) == ["blue"])
467 #expect(result.new.filter { $0.kind == .changed }.map(\.text) == ["green"])
468 }
469​
470 @Test
471 func workspaceReviewMapperPairsReplacementLinesAndCarriesBaseReference() {
472 let preview = ReviewDiffPreview(
473 cwd: "/tmp/project",
474 generatedAt: "2026-08-01T00:00:00Z",
475 sources: [
476 ReviewDiffSource(
477 id: "working-tree",
478 kind: "working-tree",
479 title: "Working tree",
480 baseRef: "main",
481 headRef: nil,
482 diff: """
483 diff --git a/App.swift b/App.swift
484 --- a/App.swift
485 +++ b/App.swift
486 @@ -1,1 +1,1 @@
487 -let color = blue
488 +let color = green
489 """,
490 diffHash: "hash",
491 truncated: false
492 ),
493 ]
494 )
495​
496 let review = NativeWorkspaceMapper.review(preview)
497 let deletion = review.files[0].lines.first { $0.kind == .deletion }
498 let addition = review.files[0].lines.first { $0.kind == .addition }
499​
500 #expect(review.baseReference == "main")
501 #expect(review.files[0].sourceKind == "working-tree")
502 #expect(review.files[0].sourceBaseReference == "main")
503 #expect(deletion?.spans?.filter { $0.kind == .changed }.map(\.text) == ["blue"])
504 #expect(addition?.spans?.filter { $0.kind == .changed }.map(\.text) == ["green"])
505 }
506​
507 @Test
508 func fullDiffHydrationRestoresUnchangedRegionsWithoutLosingPatchRows() {
509 let file = FeatureReviewFile(
510 path: "App.swift",
511 change: .modified,
512 additions: 1,
513 deletions: 1,
514 lines: [
515 .init(id: "hunk", kind: .hunk, text: "@@ -2,2 +2,2 @@"),
516 .init(id: "old", kind: .deletion, oldLine: 2, text: "let color = blue"),
517 .init(id: "new", kind: .addition, newLine: 2, text: "let color = green"),
518 .init(id: "after", kind: .context, oldLine: 3, newLine: 3, text: "render()"),
519 ]
520 )
521​
522 let lines = FeatureFullDiffHydrator.lines(
523 for: file,
524 contents: FeatureReviewFileContents(
525 oldContents: "import SwiftUI\nlet color = blue\nrender()\nfinish()\n",
526 newContents: "import SwiftUI\nlet color = green\nrender()\nfinish()\n"
527 )
528 )
529​
530 #expect(lines.map(\.kind) == [.context, .deletion, .addition, .context, .context])
531 #expect(lines.map(\.text) == [
532 "import SwiftUI",
533 "let color = blue",
534 "let color = green",
535 "render()",
536 "finish()",
537 ])
538 #expect(lines.last?.oldLine == 4)
539 #expect(lines.last?.newLine == 4)
540 }
541​
542 @Test
543 func fullDiffHydrationHandlesWholeAddedAndDeletedFiles() {
544 let added = FeatureFullDiffHydrator.lines(
545 for: FeatureReviewFile(
546 path: "Added.swift",
547 change: .added,
548 additions: 2,
549 deletions: 0
550 ),
551 contents: FeatureReviewFileContents(
552 oldContents: "",
553 newContents: "one\ntwo\n"
554 )
555 )
556 let deleted = FeatureFullDiffHydrator.lines(
557 for: FeatureReviewFile(
558 path: "Deleted.swift",
559 change: .deleted,
560 additions: 0,
561 deletions: 1
562 ),
563 contents: FeatureReviewFileContents(
564 oldContents: "gone\n",
565 newContents: ""
566 )
567 )
568​
569 #expect(added.map(\.kind) == [.addition, .addition])
570 #expect(added.map(\.newLine) == [1, 2])
571 #expect(deleted.map(\.kind) == [.deletion])
572 #expect(deleted.map(\.oldLine) == [1])
573 }
574​
575 @Test
576 func fullDiffHydrationKeepsDeletionAtItsPreviousAnchor() {
577 let file = FeatureReviewFile(
578 path: "App.swift",
579 change: .modified,
580 additions: 1,
581 deletions: 1,
582 lines: [
583 .init(id: "anchor", kind: .context, oldLine: 2, newLine: 2, text: "two"),
584 .init(id: "deleted", kind: .deletion, oldLine: 3, text: "three"),
585 .init(id: "later", kind: .addition, newLine: 7, text: "added later"),
586 ]
587 )
588​
589 let lines = FeatureFullDiffHydrator.lines(
590 for: file,
591 contents: FeatureReviewFileContents(
592 oldContents: "one\ntwo\nthree\nfour\nfive\nsix\nseven\n",
593 newContents: "one\ntwo\nfour\nfive\nsix\nseven\nadded later\n"
594 )
595 )
596​
597 #expect(lines.firstIndex { $0.id == "deleted" } == 2)
598 #expect(lines.prefix(3).map(\.text) == ["one", "two", "three"])
599 }
600​
601 @Test
602 func reviewCommentPromptIncludesActionableFileAndLineContext() {
603 let draft = FeatureReviewCommentDraft(
604 filePath: "Sources/App.swift",
605 line: FeatureReviewLineSelection(side: .new, line: 42),
606 body: " Handle the nil case. "
607 )
608​
609 #expect(draft.prompt.contains("`Sources/App.swift` at new line 42"))
610 #expect(draft.prompt.contains("Handle the nil case."))
611 #expect(!draft.prompt.contains(" Handle the nil case. "))
612 }
613​
614 @Test
615 func sourceControlActionsReflectRepositoryState() {
616 let clean = FeatureSourceControlStatus(branch: "main")
617 #expect(clean.availableActions == [.createPullRequest])
618​
619 let changed = FeatureSourceControlStatus(
620 branch: "feature/native",
621 aheadCount: 2,
622 behindCount: 1,
623 files: [.init(path: "App.swift", state: .modified, isStaged: false)]
624 )
625 #expect(changed.availableActions.contains(.commit))
626 #expect(changed.availableActions.contains(.push))
627 #expect(changed.availableActions.contains(.pull))
628 #expect(changed.availableActions.contains(.commitPushAndCreatePullRequest))
629​
630 var busy = changed
631 busy.isBusy = true
632 #expect(busy.availableActions.isEmpty)
633 }
634​
635 @Test
636 func terminalPlainTextDropsControlSequences() {
637 let prompt = "\u{1B}]0;workspace\u{7}\u{1B}[38;5;221mx\u{8}repo\u{1B}[39m ❯ "
638 #expect(TerminalText.plainText(from: prompt) == "repo ❯ ")
639 }
640​
641 @Test
642 func terminalSessionSelectionPrefersAndAllocatesStableIDs() {
643 let sessions = [
644 FeatureTerminalSnapshot(
645 threadID: "thread",
646 terminalID: "term-2",
647 state: .running,
648 title: "Tests"
649 ),
650 FeatureTerminalSnapshot(
651 threadID: "thread",
652 terminalID: "default",
653 state: .running
654 ),
655 FeatureTerminalSnapshot(
656 threadID: "thread",
657 terminalID: "term-3",
658 state: .exited
659 ),
660 ]
661​
662 #expect(TerminalSessionList.initialID(in: sessions) == "default")
663 #expect(TerminalSessionList.nextID(occupiedIDs: ["default", "term-2", "term-4"]) == "term-3")
664 #expect(TerminalSessionList.displayTitle(for: sessions[0]) == "Terminal 2 · Tests")
665 #expect(TerminalSessionList.displayTitle(for: sessions[1]) == "Terminal 1")
666 #expect(
667 TerminalSessionList.fallbackID(in: sessions, excluding: "default") == "term-2"
668 )
669 }
670​
671 @Test
672 func terminalSnapshotPreservesVTDataForGhostty() {
673 let history = "\u{1B}[31mred\u{1B}[0m\r\n"
674 let snapshot = TerminalSessionSnapshot(
675 threadId: "thread",
676 terminalId: "default",
677 cwd: "/repo",
678 worktreePath: nil,
679 status: .running,
680 pid: 123,
681 history: history,
682 exitCode: nil,
683 exitSignal: nil,
684 label: "Terminal",
685 updatedAt: "2026-08-07T00:00:00Z",
686 sequence: 1
687 )
688​
689 #expect(NativeWorkspaceMapper.terminal(snapshot).buffer == history)
690 }