Dmitrii Cherviakov

← Back to blog

Published 15 min read

TCA and an AI agent in practice: skills, rules and lessons learned in production

Why LLMs don't know TCA well and how skills fix it, the agent rules I've built up over a year, and what happens to code quality as the app grows. Part 2 of 2.

By · Senior iOS Developer

This is part two of two. In part one I explain why a strict architecture with compiler checks and an exhaustive TestStore gives the agent the best feedback loop.

Part one was theory and basic examples. This one is practice: what gets in the agent's way when it writes TCA, how I deal with it, and which rules have built up over a year of working with an agent.

The downside: LLMs don't know TCA well

I'll be honest and start with the main problem. There are relatively few apps and relatively little code written in TCA, so models don't know much about it. And what they do know is badly outdated: without guidance the agent happily writes WithViewStore, Effect.task, .concatenate and other things that were replaced or deprecated long ago.

What helps a lot is that Point-Free themselves released The Point-Free Way, an official set of skills for all their libraries: TCA, Dependencies, Sharing, testing, navigation and so on. They are available with a Point-Free subscription. A skill is loaded into the agent's context and sets the current conventions: how to declare dependencies, how to write TestStore tests, how to build navigation.

The skills are built around a meta-skill. There is one general skill that knows about all the others, and the agent initially sees only their short descriptions. The full text of a specific skill is loaded only when the task needs it. You write a test, the testing skill gets pulled in, and it in turn points to the skills about dependencies and about comparing state. The library's full API sits one more level down, and the agent opens it only if the skill itself didn't have the answer. That way the context doesn't fill up with things that aren't needed right now.

On my current project the first rule for the agent reads: for any work with iOS code, load the Point-Free skills first. It doesn't matter whether it's reading code, writing, refactoring, testing or reviewing. Without the skills the agent gives advice that breaks the project's conventions: the wrong style of dependency injection, the wrong use of TestStore, hand-written mocks instead of withDependencies.

Personally, I had built up my own set of rules before agents, back when I wrote code by hand. But the official skills are even better, and they noticeably lower the learning curve for new developers: now you can not only read the rules, but also get them from the agent as ready-made code.

The second thing that helps is TCA's releases themselves. In version 1.25 Point-Free marked the APIs that will go away in 2.0, but gently: by default the compiler stays quiet. The strict mode is turned on with a package trait:

swift
// Package.swift. In an Xcode project, package traits are set in project.pbxproj
.package(
    url: "https://github.com/pointfreeco/swift-composable-architecture",
    from: "1.25.0",
    traits: ["ComposableArchitecture2Deprecations"]
)

I turned it on in the project for good. Now, if the agent, going from old memory, chains effects with .concatenate:

swift
return .concatenate(
    .send(.loadingStarted),
    .run { send in
        await send(.itemsLoaded(try? await itemsClient.fetch()))
    }
)

it immediately gets a warning with a hint about what to use instead:

output
warning: 'concatenate' is deprecated: Sequence work directly in a '.run' instead

We took the migration to 1.25 down to zero warnings. It's the same principle as in the whole series: the rule is checked by the compiler, not by me in review.

Rules built up over almost a year

Besides the skills, the project has a memory: a set of short notes the agent adds to on its own when it finds something non-obvious. That can be a bug, a toolchain trap or a team convention. Over almost a year there are about 180 of them. Below are the ones directly related to TCA that, I think, will be useful to anyone writing it with an agent.

Dependencies only through withDependencies

No hand-written mocks of the networking layer. A test overrides exactly the client method it needs, right in withDependencies, and anything not overridden fails as unimplemented.

So that every test doesn't have to list noisy dependencies like analytics, all suites are nested inside a base suite with a .dependencies trait:

swift
/// Base suite: traits are inherited by all nested suites.
@Suite(
    .serialized,
    .dependencies {
        $0.analyticsClient = .noop
        // Screens send ad actions out of the box, so no-op to avoid tripping on unimplemented.
        $0.advClient = .disabled
        // The success popup triggers a haptic; the haptics suite overrides it with a counter itself.
        $0.haptic.success = { }
        $0.appUpdateClient = .upToDate
        // ...
    }
)
struct BaseSuite {}
 
extension BaseSuite {
    // @MainActor goes on every nested suite: global actors aren't inherited through traits.
    @MainActor @Suite struct ComplainFeatureTests {
        // ...
    }
}

Business dependencies, meaning networking and storage, don't go here. Each test sets them explicitly, and that's the right call: it shows what the feature actually interacts with. Same principle for non-deterministic values: if a feature uses @Dependency(\.uuid), the test has to set $0.uuid = .incrementing.

Keep timeouts in the client, not in the reducer

Many tests use an "instant" clock: $0.continuousClock = ImmediateClock(). Any sleep on such a clock finishes right away, so the test doesn't have to wait on intentional delays like a debounce.

The problem appeared when a timeout was written right in the reducer, as a race between two tasks: the request against clock.sleep(for:). In the app the request almost always wins. But in a test the clock is instant, and the timeout branch finishes first: the feature decides it never got a response, even though the overridden client would have answered immediately. Worst of all, it didn't show up everywhere. One test passed, a neighboring one on the same feature failed, and from the outside it looked like flakiness.

Before, with the timeout in the reducer on the clock from dependencies:

swift
return .run { send in
    let items = await withTaskGroup(of: [Item]?.self) { group in
        group.addTask { try? await itemsClient.fetch() }
        group.addTask { try? await clock.sleep(for: .seconds(8)); return nil }
        let first = await group.next() ?? nil
        group.cancelAll()
        return first
    }
    await send(.itemsLoaded(items))
}

The rule: the timeout lives inside the liveValue of the corresponding @DependencyClient and uses the real clock, and the reducer just waits for the client. In tests the client is replaced entirely, so the timeout never comes into play:

swift
// Reducer: no race, just a call to the client
return .run { send in
    await send(.itemsLoaded(try? await itemsClient.fetch()))
}
 
// Client: the timeout runs on ContinuousClock, test clocks don't touch it
extension ItemsClient: DependencyKey {
    static var liveValue: Self {
        Self(fetch: {
            try await withTimeout(.seconds(8)) { try await api.fetchItems() }
        })
    }
}

withTimeout itself is the same race of two tasks here, only on ContinuousClock() instead of the clock from @Dependency. And the test checks what actually matters for the feature: what it does with the client's response and with its error.

.merge doesn't guarantee order, and @Presents cancels effects

A classic trap the agent reproduced more than once. A child feature inside @Presents, say a question screen, makes a request when "Delete" is tapped and tells the parent it can close:

swift
// The request gets cancelled: on the delegate the parent nils out state.details,
// and TCA cancels all of the child feature's effects
case .deleteButtonTapped:
    return .merge(
        .run { [id = state.id] send in
            await send(.deleteResponse(Result { try await networking.deleteQuestion(id) }))
        },
        .send(.delegate(.didDelete))
    )

.merge runs both effects in parallel. .send fires immediately, the parent responds to the delegate by setting state.details = nil, and TCA cancels all of the child feature's in-flight effects, including the request. The screen closes, but the request never reaches the server: the network log shows it as cancelled. The fix: the delegate is sent only from the response to the request, once the deletion has gone through:

swift
case .deleteButtonTapped:
    return .run { [id = state.id] send in
        await send(.deleteResponse(Result { try await networking.deleteQuestion(id) }))
    }
 
case .deleteResponse(.success):
    return .send(.delegate(.didDelete))
 
case .deleteResponse(.failure):
    // Nothing was deleted, so the screen stays open
    return .none

An ordinary parent test on TestStore catches this, as long as the overridden client behaves like a real request and doesn't run after cancellation. With .merge the request is, as a rule, cancelled before it reaches the client, and the test fails. When the delegate is sent from the response, the order is strict and the test is green:

swift
@MainActor @Test func deleteRemovesQuestionThenCloses() async {
    let questionID = 7
    let deleted = LockIsolated<[Int]>([])
    let store = TestStore(initialState: Questions.State(details: QuestionDetails.State(id: questionID))) {
        Questions()
    } withDependencies: {
        $0.networking.deleteQuestion = { id in
            try Task.checkCancellation()  // like a real request: a cancelled one never reaches the server
            deleted.withValue { $0.append(id) }
        }
    }
 
    await store.send(.details(.presented(.deleteButtonTapped)))
    await store.receive(\.details.presented.deleteResponse)
    await store.receive(\.details.presented.delegate.didDelete) {
        $0.details = nil
    }
    expectNoDifference(deleted.value, [questionID])
}

The same trap works with dismiss() in the child feature and with .cancel(id:) in the parent. The general rule: anything that has to finish before the child screen closes has to finish before the delegate that closes it. And if effects have to run strictly in order, they are written as a single .run with sequential await send: .concatenate is deprecated.

Every exit from .run resets the flag

If a reducer sets a flag like isLoading = true or activeUploadID = id before an effect, every exit path from .run has to send an action that resets that flag. A silent return, a swallowed error, a .failure branch with no handling, and the screen thinks forever that work is still in progress.

For us this turned into a real deadlock in the media upload queue. Only a successful response reset the flag. As long as there was no guard against re-running on top of the flag, the leak went unnoticed. As soon as the guard was added, any silent error stopped the queue for good: the next file waited for an upload that would never finish.

Before:

swift
case .uploadNext:
    guard state.activeUploadID == nil, let item = state.queue.first else { return .none }
    state.activeUploadID = item.id
    return .run { send in
        guard let data = item.data else { return }  // flag stays set
        guard let remoteID = try? await networking.upload(data) else { return }  // here too
        await send(.uploadFinished(item.id, remoteID))
    }

After: every error branch has its own action, and it resets the flag:

swift
case .uploadNext:
    // ...the same check and flag setup
    return .run { send in
        guard
            let data = item.data,
            let remoteID = try? await networking.upload(data)
        else {
            await send(.uploadFailed(item.id))
            return
        }
        await send(.uploadFinished(item.id, remoteID))
    }
 
case .uploadFailed(let id):
    if state.activeUploadID == id { state.activeUploadID = nil }
    return .none

cancelInFlight: true doesn't help here: it only kicks in when the same effect is started again, and it won't be started again while the flag is stuck. What catches it is a test on the error branch. An exhaustive TestStore won't let the test finish until the action that resets the flag has been received:

swift
@MainActor @Test func failedUploadReleasesQueue() async {
    let photoID = 1
    let store = TestStore(initialState: MediaUpload.State(queue: [.photo(id: photoID)])) {
        MediaUpload()
    } withDependencies: {
        $0.networking.upload = { _ in throw UploadError() }
    }
 
    await store.send(.uploadNext) {
        $0.activeUploadID = photoID
    }
    await store.receive(\.uploadFailed) {
        $0.activeUploadID = nil
    }
}

Parent and child integration test

TestStore checks not just an isolated feature, but the whole wiring too. Here is a test of the user profile, which opens the report dialog from part one:

swift
@MainActor @Test func complainFromProfile() async {
    let userID = 7
    let store = TestStore(initialState: UserProfile.State(userID: userID)) {
        UserProfile()
    } withDependencies: {
        $0.networking.complain = { id in #expect(id == userID) }
    }
 
    await store.send(.complainButtonTapped) {
        $0.complain = ComplainFeature.State(contentID: userID)
    }
    await store.send(.complain(.presented(.submitButtonTapped))) {
        $0.complain?.isSubmitting = true
    }
    await store.receive(\.complain.presented.complainResponse) {
        $0.complain?.isSubmitting = false
    }
    await store.receive(\.complain.presented.delegate.finished) {
        $0.complain = nil
    }
    await store.receive(\.delegate.showSuccessMessage)
}

In part one the feature was simplified. The real one also has a delegate to the parent: on it the parent closes the dialog and shows a message.

Opening, submitting, closing on the delegate and the message in the parent are all checked in one test that the agent writes and fixes on its own. If it breaks navigation between features, you see it not when a tester picks up the device, but in the next test run.

Every bug gets a regression test

Every bug, even in old code, is closed with a test that would have failed before the fix. If the root cause and the visible symptom live at different levels, that's two separate tests. This matters even more with an agent: it often refactors nearby code, and without such a test the old bug quietly comes back.

An example. After a video was uploaded, the rest of the files in the media queue stopped uploading. The root cause was that the picker selection wasn't cleared, and the old item ended up in the queue again. The visible symptom was somewhere else: the queue didn't move on to the next file. So there are two tests. The first checks that the picker is cleared after files are selected. The second checks that a queue of two files gets all the way through. If someone later removes the picker reset, the first one fails. If the queue breaks for some other reason, the second one fails.

If the state is right but the UI isn't, it's not the reducer

The main diagnostic rule. When the state after an action is correct (you can see it in a test or in a log) but the screen shows something else, don't fix the reducer. The problem is lower down: identity in ForEach, caching in lazy containers, or Perception not tracking a read inside an escaping closure. TCA helps here through the separation itself: since the state is verified by a test, the search immediately narrows down to the view.

Without this rule the agent keeps proposing "defensive" changes to the reducer that change nothing. That's what happened on the group management screen. One LazyVStack held two ForEaches: members and search results. The ids of both were numbers from the same space. A user was added to the group, the test showed the correct state, but the screen still showed the search row with an "Invite" button. SwiftUI considered it the same row, since the id matched. The agent spent several rounds changing the reducer, when it was the ids that needed fixing:

swift
ForEach(store.members, id: \.memberRowID) { ... }       // "member-\(id)"
ForEach(store.searchResults, id: \.searchRowID) { ... }  // "search-\(id)"

A special case of this rule, which we stepped on twice, is a custom == that compares only id. The model of a list row had this ==:

swift
struct Row: Equatable, Identifiable {
    let id: Int
    var unit: VolumeUnit
    var error: String?
 
    // Don't: a change to unit or error won't reach the view
    static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id }
}

The reducer changed the unit of measurement, the state was correct, but the old validation error stayed under the row. The reason is that @ObservableState notifies the view only if the new value isn't equal to the old one. And with == by id, the element "didn't change". The fix is simple: remove the custom == and keep the synthesized one.

The sneaky part is that a reducer test doesn't catch this. TestStore compares state with that same ==, and to it rows with the same id are equal, even if the reducer changed nothing. What catches it is a small test on the model itself:

swift
@Test func rowEqualityIncludesAllFields() {
    let original = Row(id: 1, unit: .ml)
    var changed = original
    changed.unit = .gal
    #expect(changed != original)
}

Now this is the first thing the agent checks when part of a row doesn't redraw.

Don't trust a review agent without a test run

A review agent once confidently suggested "simplifying" tests. There was a check that an operation changes nothing in the state:

swift
let unchanged = state
state.refresh(with: sameItems)
expectNoDifference(state, unchanged)

The agent suggested replacing it with expectDifference with an empty changes:, calling it the built-in way to check "nothing changed":

swift
expectDifference(state) {
    state.refresh(with: sameItems)
} changes: { _ in }

The advice sounded plausible. After it, four tests failed. expectDifference checks for a change, and an empty changes: block doesn't mean "no changes" to it. It expects the operation to change something, and if nothing changed, it fails with the message "No difference detected after applying changes". For a "nothing changed" check the right form is the one that was there: a copy and expectNoDifference. Since then the rule is simple: an agent's advice about tests is accepted only after a test run.

Watch out for a false green run

The agent runs targeted tests with xcodebuild test -only-testing:. All our suites are nested inside the base suite, so their full path starts with BaseSuite/. If you skip that prefix, xcodebuild finds zero tests and… exits successfully. The agent sees "tests passed" and moves on:

bash
# Before: 0 tests, yet "** TEST SUCCEEDED **"
xcodebuild test -only-testing:UnitTests/ComplainFeatureTests …
 
# After: the path goes through the base suite, and the report's test count is checked
xcodebuild test -only-testing:UnitTests/BaseSuite/ComplainFeatureTests -resultBundlePath out.xcresult …
xcrun xcresulttool get test-results summary --path out.xcresult   # totalTestCount must be greater than zero

So after a run the agent has to check that the number of executed tests is greater than zero. It's a small thing, but a feedback loop that lies is worse than none at all.

Tests only check the environment they run in

In November we found a crash on launch on iOS 16 and 17. The cause was await send(...) right in the body of withTaskGroup. send in TCA sets task-local values, and before iOS 18 the Swift runtime forbids that inside a task group and terminates the process. Starting with iOS 18 that check was relaxed.

Before:

swift
return .run { send in
    await withTaskGroup(of: Item.self) { group in
        for id in ids { group.addTask { await client.load(id) } }
        for await item in group {
            await send(.itemLoaded(item))  // iOS 16/17: crashes here
        }
    }
}

After: the group runs in its own task and hands results to an AsyncStream, and send is called outside the group:

swift
return .run { send in
    let items = AsyncStream<Item> { continuation in
        let task = Task {
            await withTaskGroup(of: Item.self) { group in
                for id in ids { group.addTask { await client.load(id) } }
                for await item in group { continuation.yield(item) }
            }
            continuation.finish()
        }
        continuation.onTermination = { _ in task.cancel() }
    }
    for await item in items {
        await send(.itemLoaded(item))
    }
}

We didn't have a test that would catch this, and we couldn't have. Unit tests are built for a recent iOS and run on it, and there the check is already relaxed, so all the tests were green. The takeaway matters more than the fix itself: the minimum supported iOS has to be checked separately, on a simulator with that version. No TestStore replaces that. And the agent got a new rule: results leave a task group only through an AsyncStream, and send inside the group is forbidden.

What happens as the app grows

For practically the whole year now I have been writing code with the agent, while I review and steer. My changes are usually about logic: product nuances, edge cases, things the agent couldn't have known. Very few of my changes are about architecture.

Meanwhile the app keeps growing fast. Right now it is about 89 thousand lines of Swift, 75 reducers and more than 1200 tests. The app is in the App Store. And as the number of features grows, I don't see any degradation, either in the quality of the generated code or in maintenance. A new feature doesn't break old ones, because the old ones are covered by tests and the new one is written by the same rules.

I think that is down to the choice of architecture. And it shows directly in the numbers: I measured my speed over two identical six-month windows on the same project. Code output grew by 81%, delivery cadence by 48%, feature throughput by 38%. The month-by-month picture is on the stats page. But something else matters more to me: since the code consistently comes out well, I can focus on the product instead of keeping the codebase in working shape.

The downsides

  • The learning curve. TCA still requires you to rewire how you think. Skills lower the bar, but don't remove it.
  • Models don't know much about it. Without skills the agent writes outdated TCA. You have to plug them in.
  • Macros and the toolchain. @Reducer, @ObservableState, @DependencyClient are macros, and Xcode updates sometimes break the build in ways you have to fix with package versions. In CI you have to enable macros separately.
  • Flaky tests with clocks. ImmediateClock and TestClock are convenient, but races with them have become their own class of problems that eat hours. Some of the rules above come straight from there.
  • Tests only see a recent iOS. Crashes that depend on the runtime version aren't caught by unit tests. The minimum supported version has to be checked separately.

What if you use MVVM?

To be fair: if your team already has good code and architecture guidelines, it's not hard to turn them into a skill, and the agent will write pretty good code too.

But here's what I want to point out: you'll have to build that skill yourselves, running into the same pitfalls. MVVM, popular as it is right now, can look completely different from team to team, and there is no single source of rules for it. You have to come up with strict enough rules and then maintain them. In TCA those rules are already part of the architecture and checked by the compiler, and the current conventions are maintained by its authors. If you want to give it a try, I have an open-source TCA starter with tabs, feature composition, dependencies and tests. It's a convenient place to start.

In place of a conclusion

Architecture in iOS has kept evolving one way or another. First there was MVC and, for many teams, VIPER and similar architectures. With Rx came reactive architectures. I think the next step, together with Observation and AI development, is mass adoption not only of MVVM, but of TCA as well. When code is more and more often written by an agent, the architecture that wins is the one where mistakes show up the earliest.

The series starts with part one: why a strict architecture and TestStore give the agent the best feedback loop.

#tca#ai#swift#architecture#testing