Sample CodeiOS, iPadOS, Mac Catalyst, macOSReviewed 2026-11-01View on Apple Developer

Origami: Crafting a dynamic tutorial for Apple Intelligence

At a glance

Item Summary
Purpose Turn a person’s craft photos into brainstormed ideas, a streamed step-by-step tutorial, photo-based coaching, and tap-to-explain terminology, all through Foundation Models.
App architecture SwiftUI over SwiftData. Each open project gets one Orchestrator that owns a single LanguageModelSession and four feature models (BrainstormModel, TutorialGenerationModel, CoachModel, TermModel). Views send typed OrchestratorEvents. A reduce step returns OrchestratorEffects that run in one cancellable task.
Main patterns Reducer-style event dispatch (send → reduce → execute), SwiftUI environment injection of the orchestrator, and bindings into @Bindable SwiftData models.
Project style One app target. Folders follow product features (Brainstorm/, Tutorial/, Coach/, Terms/, Projects/) plus shared Models/ and UI/. Each feature folder pairs a model, a view, and an …Instructions file with its prompts.
Execution model The target sets SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, so unannotated types such as Orchestrator and the feature models are main-actor isolated. Model calls are awaited inside unstructured tasks created from that context.
State/event model @Observable models hold UI state. SwiftData @Model types persist projects, photos, generated JSON, and term lookups. Model output arrives as ResponseStream partials that the feature models fold into state.
Key frameworks/packages FoundationModels, SwiftUI, SwiftData, PhotosUI, Observation, os. The project declares no Swift package.

Platform boundary

The DocC record lists iOS, iPadOS, Mac Catalyst, and macOS. The project builds natively for iOS and macOS (SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx") and sets SUPPORTS_MACCATALYST = NO (Origami.xcodeproj/project.pbxproj:786).

Project structure

Origami.xcodeproj/                 1 application target, no Swift packages
Origami/
├── OrigamiApp.swift               @main; DataModel and modelContainer
├── Models/
│   ├── Orchestrator.swift         session owner; send / reduce / execute
│   ├── OrchestratorState.swift    Mode, Event, State, Effect enums
│   ├── OrchestratorProfile.swift  DynamicProfile: per-mode instructions and model
│   ├── TranscriptRecorder.swift   debug transcript snapshots
│   └── DataModels/                @Model Project, Photo, TermLookup, TutorialTemplate; DataModel
├── Projects/                      LibraryView, NewProjectView, ProjectDetailView, ProjectModel
├── Brainstorm/                    BrainstormModel, BrainstormView, BrainstormInstructions, @Generable types
├── Tutorial/
│   ├── Intelligence/              TutorialInstructions, OrigamiInstructions, CraftTools, TutorialContent
│   ├── Models/                    TutorialGenerationModel
│   └── Views/                     TutorialView, TutorialStepCard, step text rendering
├── Coach/                         CoachModel, CoachView, CoachInstructions, MovePhotoToStepTool
├── Terms/                         TermModel, TermView, TermInstructions, TermExtractor
└── UI/                            theme, layouts, animation, settings

Structure observations

  • Prompts live beside the feature that uses them. Each …Instructions file defines a DynamicInstructions type and a LanguageModelSession extension with that feature’s prompt methods (Origami/Brainstorm/BrainstormInstructions.swift:12, Origami/Brainstorm/BrainstormInstructions.swift:51).
  • Models/OrchestratorState.swift holds only value types: the mode, the event and effect enums, and the state snapshot (Origami/Models/OrchestratorState.swift:14, Origami/Models/OrchestratorState.swift:45).
  • Generated output is persisted as JSON on the SwiftData Project (tutorialJSON, brainstormJSON) rather than as separate model types (Origami/Models/DataModels/Project.swift:19, Origami/Models/DataModels/Project.swift:24).

Overall architecture

Reference code

Origami/Projects/ProjectDetailView.swift:24 — one orchestrator per project screen

    init(project: Project, modelContext: ModelContext) {
        self.project = project
        let orchestrator = Orchestrator(project: project, modelContext: modelContext)
        _model = State(
            wrappedValue: ProjectModel(project: project, orchestrator: orchestrator)
        )
    }

Interpretation

Observed: ProjectDetailView builds the orchestrator, stores it inside a @State ProjectModel, injects it with .environment(model.orchestrator) (Origami/Projects/ProjectDetailView.swift:76), and sends .started from .task (Origami/Projects/ProjectDetailView.swift:74). It chooses BrainstormView or TutorialView from orchestrator.state.visualMode (Origami/Projects/ProjectDetailView.swift:47).

Inference: the orchestrator is the per-project application core. Views never create sessions. They read feature models through the orchestrator and send events or call its term methods.

Ownership and state

Ownership evidence

Origami/Models/Orchestrator.swift:69 — the orchestrator creates every feature model

    init(project: Project, modelContext: ModelContext) {
        self.project = project
        self.state = OrchestratorState(
            mode: project.tutorialJSON != nil ? .tutorial : .brainstorm
        )
        self.brainstorm = BrainstormModel(
            project: project,
            modelContext: modelContext
        )
        self.tutorial = TutorialGenerationModel(
            project: project,
            modelContext: modelContext
        )
        self.coach = CoachModel()
        self.term = TermModel(
            project: project,
            modelContext: modelContext
        )
    }
Owner Object or state Relationship Mutation authority
OrigamiApp DataModel (SwiftData stack) @State private var dataModel (Origami/OrigamiApp.swift:17); container injected with .modelContainer DataModel.prepareData() seeds on first launch
Orchestrator LanguageModelSession @ObservationIgnored private lazy var session, created with OrchestratorProfile(orchestrator: self) and a starting transcript (Origami/Models/Orchestrator.swift:42) Only the orchestrator; TermModel receives it as a parameter
Orchestrator state: OrchestratorState Stored value (Origami/Models/Orchestrator.swift:28) reduce, execute, and the term methods
Orchestrator currentTask @ObservationIgnored private var (Origami/Models/Orchestrator.swift:59) send(_:) cancels and replaces it
Feature models Their own state enums and display data var state on each @Observable model (Origami/Brainstorm/BrainstormModel.swift:27, Origami/Coach/CoachModel.swift:29) The orchestrator and the model’s own processStream
TermModel Popover state, turns, activeTask private(set) and private (Origami/Terms/TermModel.swift:31, Origami/Terms/TermModel.swift:59) Only TermModel
Project (@Model) tutorialJSON, brainstormJSON, photos, term lookups Persisted properties (Origami/Models/DataModels/Project.swift:19) Written by feature models, then saved through ModelContext

Observed: Orchestrator is not owned by SwiftUI directly. It is a let on ProjectModel, which ProjectDetailView holds in @State (Origami/Projects/ProjectModel.swift:17). The orchestrator’s session is lazy, so the session is created on first use.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Default isolation SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, Swift 6 Unannotated app types, including Orchestrator and the feature models, are main-actor isolated Origami.xcodeproj/project.pbxproj:788, Origami.xcodeproj/project.pbxproj:791
Explicit isolation @MainActor final class DataModel SwiftData stack and seeding Origami/Models/DataModels/DataModel.swift:11
Event task currentTask?.cancel(), then currentTask = Task { for effect in effects { await execute(effect) } } One retained task per event. A new event cancels the previous one. Effects run in order. Origami/Models/Orchestrator.swift:167, Origami/Models/Orchestrator.swift:173
Cancellation handling try Task.checkCancellation() and catch is CancellationError Each stream consumer resets its feature state to .idle on cancellation Origami/Models/Orchestrator.swift:346, Origami/Models/Orchestrator.swift:349
Duplicate suppression coachingInFlight: Set<String> keyed by section and step A second coaching request for the same step returns early Origami/Models/Orchestrator.swift:65, Origami/Models/Orchestrator.swift:584
Orthogonal term task TermModel.activeTask, cancelled on each new turn and on dismiss Term lookups bypass send, so they do not cancel the main event task Origami/Models/Orchestrator.swift:659, Origami/Terms/TermModel.swift:147
Term-extraction task extractionTask with [weak self]; cancelled when a new tutorial is saved Runs a separate on-device LanguageModelSession Origami/Tutorial/Models/TutorialGenerationModel.swift:74, Origami/Terms/TermExtractor.swift:32
Photo loading ProjectModel.photoLoadingTask, cancelled before replacement Loads picker items, appends photos, then sends .photosAdded Origami/Projects/ProjectModel.swift:39
View-scoped loading .task(id: selectedPhotos) SwiftUI cancels the in-flight load when the selection changes or the sheet closes Origami/Projects/NewProjectView.swift:90
Shared static cache TutorialTemplateStore.cache The source comment relies on default main-actor isolation instead of a lock Origami/Models/DataModels/TutorialTemplateStore.swift:15
Tool callbacks MovePhotoToStepTool.call awaits orchestrator.proposeMoveToStep The tool hops to the orchestrator’s isolation to set the pending move Origami/Coach/MovePhotoToStepTool.swift:32

Reference code

Origami/Models/Orchestrator.swift:165 — one cancellable task per event

    func send(_ event: OrchestratorEvent) {
        log("event: \(event)")
        currentTask?.cancel()
        if state.mode == .term {
            dismissTerm()
        }
        let effects = reduce(event)
        guard !effects.isEmpty else { return }
        currentTask = Task {
            for effect in effects {
                await execute(effect)
                snapshotTranscript()
            }
        }
    }

Not established by source: where the model inference itself executes. The app awaits LanguageModelSession APIs and does not choose an executor or queue for them.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Orchestrator to views .environment(model.orchestrator) and @Environment(Orchestrator.self) Feature views read the orchestrator and its child models Origami/Projects/ProjectDetailView.swift:76, Origami/Brainstorm/BrainstormView.swift:12
Streaming output for try await partialResponse in stream Feature models fold partial generations into state Origami/Brainstorm/BrainstormModel.swift:107, Origami/Tutorial/Models/TutorialGenerationModel.swift:104
Mode-driven model choice LanguageModelSession.DynamicProfile switching on orchestrator.mode Selects instructions, model, temperature, reasoning level, and history transform per mode Origami/Models/OrchestratorProfile.swift:12, Origami/Models/OrchestratorProfile.swift:25
Context trimming .historyTransform(shortHistory(_:)) Keeps the last 4 or 15 transcript entries depending on the on-device model variant Origami/Models/OrchestratorProfile.swift:72
Model-to-app callback Tool conformances Template lookup, paper-size and unit math, and a move-photo proposal back to the orchestrator Origami/Tutorial/Intelligence/CraftTools.swift:12, Origami/Coach/MovePhotoToStepTool.swift:12
Persistence SwiftData ModelContext.save() Analysis results, ideas, tutorials, and term lookups are saved by the feature models Origami/Brainstorm/BrainstormModel.swift:59, Origami/Tutorial/Models/TutorialGenerationModel.swift:127
Bindings @Bindable var project, $project.title, $model.showingPhotoPicker Views edit SwiftData and screen-model properties directly Origami/Projects/ProjectDetailView.swift:14, Origami/Projects/ProjectDetailView.swift:36, Origami/Projects/ProjectDetailView.swift:60
Framework import FoundationModels Sessions, profiles, instructions, tools, @Generable Origami/Models/Orchestrator.swift:11
Framework import SwiftData Model container and persisted types Origami/OrigamiApp.swift:9
Framework import PhotosUI Photo picker Origami/Projects/ProjectDetailView.swift:10

Combine is not used. State moves through Observation, SwiftData, and async sequences.

Class and protocol design

Reference code

Origami/Models/OrchestratorProfile.swift:24 — one session, different configuration per mode

    var body: some DynamicProfile {
        switch orchestrator.mode {
        case .brainstorm:
            if !isOnDevice {
                Profile {
                    BrainstormInstructions(orchestrator: orchestrator)
                }
                .model(serverModel)
                .temperature(1.0)
            } else {
                // ...
                Profile {
                    BrainstormInstructions(orchestrator: orchestrator)
                }
                .model(SystemLanguageModel())
            }
        // ...
        case .term:
            Profile {
                TermInstructions(orchestrator: orchestrator)
            }
            .model(SystemLanguageModel())
            .historyTransform(shortHistory(_:))
        }
    }
Type Responsibility Depends on
Orchestrator Owns the session and feature models, maps events to effects, runs effects LanguageModelSession, feature models, Project
OrchestratorProfile Chooses instructions and model settings from the current mode Orchestrator.mode
…Instructions types Instruction text, tool lists, and per-feature prompt methods Orchestrator
BrainstormModel, TutorialGenerationModel, CoachModel, TermModel Fold streamed output into UI state and persist results ModelContext, Project
MovePhotoToStepTool Lets the model propose moving a photo to another step Orchestrator
TermExtractor Stateless enum that runs one on-device extraction pass Its own LanguageModelSession

Observed: the app declares no protocols of its own. Its abstractions are conformances to Foundation Models protocols, and the dependency points from instructions, profile, and tools back to the concrete Orchestrator. TutorialInstructions switches to CoachInstructions when orchestrator.tutorialReady is true (Origami/Tutorial/Intelligence/TutorialInstructions.swift:16), so coaching reuses the tutorial mode’s session configuration.

Access control

Symbol Access Verified effect Likely rationale
Orchestrator.session (Origami/Models/Orchestrator.swift:42) private lazy var Views cannot reach the session directly; term calls go through orchestrator methods Inference: one owner controls prompts and transcript.
Orchestrator.reduce(_:), execute(_:) (Origami/Models/Orchestrator.swift:181, Origami/Models/Orchestrator.swift:283) private The only public entry for the main flow is send(_:) Inference: every state change passes through one dispatch path.
Orchestrator.currentTask, coachingInFlight (Origami/Models/Orchestrator.swift:59, Origami/Models/Orchestrator.swift:65) @ObservationIgnored private var Not observed by SwiftUI and not visible outside the file Inference: task bookkeeping is not UI state.
TermModel state (Origami/Terms/TermModel.swift:31) private(set) Views read popover state but cannot set it Inference: term state changes only through explain, askFollowUp, regenerate, dismiss.
TutorialGenerationModel.extractedTerms (Origami/Tutorial/Models/TutorialGenerationModel.swift:37) private(set) Readable by step views, written only by extraction Same reason.
TutorialTemplateStore.cache (Origami/Models/DataModels/TutorialTemplateStore.swift:17) private static var Only refresh(from:) and template(for:) touch it Inference: a narrow facade around shared mutable state.
BrainstormModel fields (Origami/Brainstorm/BrainstormModel.swift:27) implicit internal var The orchestrator writes state and ideas directly Inference: the feature models are treated as state containers for the orchestrator.

Reference code

Origami/Models/Orchestrator.swift:41 — private, unobserved session and task bookkeeping

final class Orchestrator {
    // ...
    @ObservationIgnored
    private lazy var session = LanguageModelSession(
        profile: OrchestratorProfile(orchestrator: self),
        history: Transcript(
            entries: startHistory
        )
    )
    // ...
    @ObservationIgnored
    private var currentTask: Task<Void, Never>?
    // ...
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Event-to-effect mapping and synchronous state changes Orchestrator.reduce(_:) One switch over OrchestratorEvent (Origami/Models/Orchestrator.swift:181).
Async effect execution Orchestrator.execute(_:) and its private helpers Calls session prompt methods and hands streams to feature models (Origami/Models/Orchestrator.swift:283).
Prompt text LanguageModelSession extensions in …Instructions.swift Keeps prompts beside their feature (Origami/Brainstorm/BrainstormInstructions.swift:52).
Finished-piece handling streamBrainstormIdeas(hasFinishedPiece:) When analysis has tagged a photo as a finished piece, the prompt asks for idea 1 to recreate it and ideas 2 and 3 to be variations (Origami/Brainstorm/BrainstormInstructions.swift:55, Origami/Models/Orchestrator.swift:149).
Folding partial results BrainstormModel.processStream, TutorialGenerationModel.processStream, CoachModel.processStream Each model owns how its partials become UI state (Origami/Brainstorm/BrainstormModel.swift:104).
Term lookups and caching TermModel Hydrates from saved TermLookup records before calling the model (Origami/Terms/TermModel.swift:90).
Photo loading for an open project ProjectModel.photosDidChange() Screen-level helper that ends by sending .photosAdded (Origami/Projects/ProjectModel.swift:35).
Seeding DataModel.prepareData() Runs from the app’s root .task (Origami/Models/DataModels/DataModel.swift:52).

Design patterns

Pattern Source evidence Purpose or tradeoff
Reducer-style event dispatch OrchestratorEvent and OrchestratorEffect (Origami/Models/OrchestratorState.swift:14, Origami/Models/OrchestratorState.swift:45); send → reduce → execute (Origami/Models/Orchestrator.swift:165, Origami/Models/Orchestrator.swift:181, Origami/Models/Orchestrator.swift:283) Typed inputs enter one path. reduce applies synchronous state changes and returns effects, and execute runs them in one cancellable task. reduce also mutates the orchestrator and child models directly, so it is not a pure function.
SwiftUI environment injection .environment(model.orchestrator) (Origami/Projects/ProjectDetailView.swift:76); @Environment(Orchestrator.self) (Origami/Brainstorm/BrainstormView.swift:12) Deep feature views reach the per-project orchestrator without initializer threading
Binding-based state propagation @Bindable var project and $project.title (Origami/Projects/ProjectDetailView.swift:14, Origami/Projects/ProjectDetailView.swift:36) Views edit SwiftData properties in place while the @Model stays the source of truth

Removed: “Central store”. TutorialTemplateStore is a static read-mostly cache of template text for one tool (Origami/Models/DataModels/TutorialTemplateStore.swift:10), not an app-wide state store. No MVVM label is claimed. ProjectModel describes itself as a view model (Origami/Projects/ProjectModel.swift:5), but it only holds picker state and the orchestrator for one screen.

Main application flow

Reference code

Origami/Projects/ProjectModel.swift:35 — load photos, then emit one event

    func photosDidChange() {
        let items = selectedPhotos
        guard !items.isEmpty else { return }
        selectedPhotos = []
        photoLoadingTask?.cancel()
        photoLoadingTask = Task {
            var newItems: [Photo] = []
            for item in items {
                guard !Task.isCancelled else { return }
                if let image = try? await item.loadTransferable(type: PickedImage.self) {
                    newItems.append(Photo(data: image.data))
                }
            }
            guard !Task.isCancelled else { return }
            project.photos.append(contentsOf: newItems)
            orchestrator.send(.photosAdded(newItems))
        }
    }

Origami/Models/Orchestrator.swift:283 — the effect analyzes, then routes by mode

    private func execute(_ effect: OrchestratorEffect) async {
        switch effect {
        case .analyzeAndRoute(let previousMode, let newPhotos):
            await analyzePhotosIfNeeded()
            if previousMode == .brainstorm {
                if brainstorm.ideas.isEmpty {
                    await generateIdeas()
                }
            } else if previousMode == .tutorial, !newPhotos.isEmpty {
                coach.isActive = true
                await startCoaching(
                    with: newPhotos,
                    sectionIndex: coach.activeSectionIndex ?? 0,
                    stepNumber: coach.activeStepNumber ?? 1
                )
            }
        // ...
        }
    }

Origami/Models/Orchestrator.swift:360 — the shared session streams ideas into the brainstorm model

    private func generateIdeas() async {
        log("Current craft is: \(project.description)")
        guard brainstorm.ideas.isEmpty else { return }
        guard !session.isResponding else { return }
        do {
            brainstorm.prepareForRegeneration()
            let stream = session.streamBrainstormIdeas(hasFinishedPiece: hasFinishedPiece)
            try await brainstorm.processStream(stream)
            try Task.checkCancellation()
            brainstorm.state = .idle
        } catch is CancellationError {
            brainstorm.state = .idle
        } catch {
            log("Idea generation failed with error: \(error)")
            brainstorm.state = .error(error.displayMessage)
        }
    }

Observed: if photos arrive while a tutorial is shown, the same effect routes to coaching instead of brainstorming. A finished-piece photo does not skip brainstorming; it changes the brainstorm prompt (see Logic ownership).

Naming conventions

  • Types: feature prefix plus role. BrainstormModel, TutorialGenerationModel, CoachModel, TermModel for observable state. …Instructions for DynamicInstructions. …Tool or verb phrases (FetchOrigamiTemplate, CalculatePaperSize) for Tool conformances. Orchestrator… for the coordinator’s value types (OrchestratorState, OrchestratorEvent, OrchestratorEffect, OrchestratorProfile).
  • Events and effects: events name what happened (photosAdded, brainstormFeedback, progressPhoto). Effects name the work to do (analyzeAndRoute, generateIdeas, streamTutorial, startCoaching).
  • Methods: session prompt methods start with stream… when they return a ResponseStream and use a verb (decideCraftDomain) when they return a value. Feature models expose processStream. Persistence helpers are private (cacheIdeasOnProject, commitIfNeeded).
  • Files: one primary type per file. The orchestrator’s enums are grouped in OrchestratorState.swift.

Architecture takeaways

  • Keep one LanguageModelSession per unit of work (here, a project) and vary its behavior with a DynamicProfile keyed to app mode. The transcript carries context from brainstorm to tutorial to coaching.
  • Route every main-flow action through typed events. Store the running task and cancel it on the next event, and make each stream consumer handle CancellationError.
  • Run side conversations, such as term explanations, outside the main event path so they do not cancel an in-flight generation.
  • Let the model call back into the app through a Tool that only proposes a change (proposeMoveToStep). The UI then asks the person to confirm.
  • Persist generated content as JSON on the SwiftData model, and clear stale caches when newer output replaces them (brainstormJSON = nil after a tutorial is saved, Origami/Tutorial/Models/TutorialGenerationModel.swift:116).

Source map

Source file Relevant symbols
Origami/OrigamiApp.swift OrigamiApp
Origami/Models/DataModels/DataModel.swift DataModel, prepareData()
Origami/Models/Orchestrator.swift Orchestrator, send(_:), reduce(_:), execute(_:), generateIdeas(), startCoaching, explainTerm
Origami/Models/OrchestratorState.swift OrchestratorMode, OrchestratorEvent, OrchestratorState, OrchestratorEffect
Origami/Models/OrchestratorProfile.swift OrchestratorProfile, shortHistory(_:)
Origami/Models/DataModels/Project.swift Project, tutorialJSON, brainstormJSON
Origami/Models/DataModels/TutorialTemplateStore.swift TutorialTemplateStore
Origami/Projects/ProjectDetailView.swift ProjectDetailView
Origami/Projects/ProjectModel.swift ProjectModel, photosDidChange()
Origami/Projects/NewProjectView.swift NewProjectView, .task(id:) photo loading
Origami/Brainstorm/BrainstormInstructions.swift BrainstormInstructions, streamBrainstormIdeas(hasFinishedPiece:)
Origami/Brainstorm/BrainstormModel.swift BrainstormModel, processStream, cacheIdeasOnProject()
Origami/Brainstorm/BrainstormView.swift BrainstormView
Origami/Tutorial/Intelligence/TutorialInstructions.swift TutorialInstructions, streamTutorial(idea:)
Origami/Tutorial/Intelligence/CraftTools.swift FetchOrigamiTemplate, CalculatePaperSize
Origami/Tutorial/Models/TutorialGenerationModel.swift TutorialGenerationModel, processStream, extractTerms(for:)
Origami/Coach/CoachModel.swift CoachModel
Origami/Coach/MovePhotoToStepTool.swift MovePhotoToStepTool
Origami/Terms/TermModel.swift TermModel, runTurn, commitIfNeeded()
Origami/Terms/TermExtractor.swift TermExtractor
Origami.xcodeproj/project.pbxproj SWIFT_DEFAULT_ACTOR_ISOLATION, SUPPORTED_PLATFORMS, SUPPORTS_MACCATALYST