Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Fix SwiftUI macro compatibility for Command Line Tools builds (#186)
Andrey Mikhaylov77e8f9c02ec5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7c30cee0..c5d374f1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -39,18 +39,32 @@ jobs:sudo xcode-select -s "$app"- name: Report the toolchainrun: swift --version+ - name: Check SwiftUI macro independence+ run: |+ ruby Scripts/check_swiftui_macros.rb --self-test+ ruby Scripts/tests/swift_macro_probe_test.rb- name: Build release productsrun: swift build -c release+ - name: Build debug and test state compatibility+ run: Scripts/test.sh --filter 'StoredStateTests|AppModelTests|DecodeServiceLaunchPolicyTests'test:if: github.event_name != 'pull_request' || github.event.pull_request.draft == false- runs-on: macos-26+ # macos-26's default SDK does not exercise the new State macro.+ # Official preview runner: actions/runner-images#14404.+ runs-on: xcode-27steps:- uses: actions/checkout@v4- name: Report the toolchainrun: swift --version- - name: Build release products- run: swift build -c release+ - name: Check SwiftUI macro independence+ run: |+ ruby Scripts/check_swiftui_macros.rb --self-test+ ruby Scripts/tests/swift_macro_probe_test.rb --require-sdk-27+ - name: Build release without SwiftUI platform plugins+ run: ruby Scripts/tests/swift_macro_probe_test.rb --require-sdk-27 --build release+ - name: Build debug without SwiftUI platform plugins+ run: ruby Scripts/tests/swift_macro_probe_test.rb --require-sdk-27 --build debug- name: Run serial testsrun: Scripts/test.sh- name: Check for tracked symlinksdiff --git a/AGENTS.md b/AGENTS.mdindex e2cbbe17..bf9a16af 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -40,6 +40,16 @@ not proxy, tunnel, or expose it. A tool call from the local model never bypassesthe client's normal permission policy. Keep the execution session alive whilethe server is needed, and stop only a server you launched.+## SwiftUI state and previews++Use `@StoredState` from `TurboFieldfareMacPresentation` for view-owned state.+It aliases Apple's `SwiftUI.State<Value>` property wrapper, avoiding the State+macro plugin missing from some CLT installations. Keep reference construction+explicit; the wrapper evaluates inline initializers eagerly. Use+`PreviewProvider` for debug previews. Do not introduce direct State attributes+or Preview macros. Run `ruby Scripts/check_swiftui_macros.rb --self-test` and+`ruby Scripts/tests/swift_macro_probe_test.rb` when changing these surfaces.+## Test rulesBefore a model run, require macOS 26+, Swift 6.2+, enough disk, acceptable `memory_pressure -Q`, a completed `scratch/gemma4.gturbo`, and no process from `pgrep -fl 'TurboFieldfareServer|TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'`. If a check fails, inform the user and stop; do not terminate apps or delete or reinstall the model.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ec081fc5..051c9b67 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -17,6 +17,8 @@ Run the release build, serial tests, and Markdown link check:```bashswift build -c releaseScripts/test.sh+ruby Scripts/check_swiftui_macros.rb --self-test+ruby Scripts/tests/swift_macro_probe_test.rbruby Scripts/check_markdown_links.rb```diff --git a/Scripts/check_swiftui_macros.rb b/Scripts/check_swiftui_macros.rbnew file mode 100644index 00000000..5b9773f0--- /dev/null+++ b/Scripts/check_swiftui_macros.rb@@ -0,0 +1,25 @@+#!/usr/bin/env ruby+# Keep the public app buildable without Xcode's SwiftUI platform plugins.+require 'pathname'++forbidden = /@\s*(?:[A-Za-z_]\w*\s*\.\s*)*State\b|\#\s*Preview\b/+if ARGV.delete('--self-test')+ ['@SwiftUICore.State var value = 0', '@Other.State var value = 0', '@State var value = 0', '@SwiftUI.State var value = 0', "@SwiftUI.\nState var value = 0", '#Preview { Text("x") }'].each do |source|+ abort "Missed forbidden macro: #{source}" unless forbidden.match?(source)+ end+ ['@StoredState var value = 0', '@StateObject var model', 'SwiftUI.State<Int>', 'struct Demo: PreviewProvider {}'].each do |source|+ abort "Rejected supported spelling: #{source}" if forbidden.match?(source)+ end+ puts 'SwiftUI source guard self-tests passed'+end+abort 'Usage: ruby Scripts/check_swiftui_macros.rb [--self-test]' unless ARGV.empty?+root = File.expand_path('..', __dir__)+failures = Dir.glob(File.join(root, 'Sources/**/*.swift')).flat_map do |path|+ text = File.read(path)+ text.to_enum(:scan, forbidden).map do+ line = text[0...Regexp.last_match.begin(0)].count("\n") + 1+ "#{Pathname.new(path).relative_path_from(Pathname.new(root))}:#{line}: use StoredState or PreviewProvider; SwiftUI platform macros require Xcode plugins"+ end+end+abort failures.join("\n") unless failures.empty?+puts 'No SwiftUI State or Preview macros in production sources'diff --git a/Scripts/tests/swift_macro_probe_test.rb b/Scripts/tests/swift_macro_probe_test.rbnew file mode 100644index 00000000..cb7d57ce--- /dev/null+++ b/Scripts/tests/swift_macro_probe_test.rb@@ -0,0 +1,139 @@+#!/usr/bin/env ruby+# Compile bounded fixtures with the selected tools, then remove only platform+# plugin discovery from the emitted frontend command to reproduce issue 185.+require 'tmpdir'+require 'open3'+require 'shellwords'+require 'json'++require_sdk_27 = ARGV.delete('--require-sdk-27')+configuration = nil+unless ARGV.empty?+ unless ARGV.length == 2 && ARGV[0] == '--build' && %w[debug release].include?(ARGV[1])+ abort 'Usage: ruby Scripts/tests/swift_macro_probe_test.rb [--build debug|release] [--require-sdk-27]'+ end+ configuration = ARGV[1]+end++fixtures = {+ 'Import' => "import SwiftUI\n",+ 'Observation' => "import Observation\n@Observable final class Model { var count = 0 }\n",+ 'State' => <<~SWIFT,+ import SwiftUI+ struct Probe: View {+ @State private var search: String+ init() { _search = State(initialValue: "") }+ var body: some View {+ TextField("Search", text: $search)+ Button("Clear") { search = "" }+ }+ }+ SWIFT+ 'Preview' => "import SwiftUI\n#Preview { Text(\"Build check\") }\n"+}++alias_source = File.expand_path('../../Sources/TurboFieldfareApp/MacPresentation/StoredState.swift', __dir__)+fixtures['StoredState'] = fixtures['State'].gsub('@State', '@StoredState').sub('_search = State(', '_search = StoredState(')+fixtures['StoredState'] = fixtures['StoredState'].sub(' var body:', " @StoredState private var optional: UUID?\n @StoredState private var flag = false\n var body:")+fixtures['PreviewProvider'] = 'import SwiftUI; struct Preview: PreviewProvider { static var previews: some View { Text("Build check") } }'++sdk, diagnostic, status = Open3.capture3('/usr/bin/xcrun', '--show-sdk-version')+abort diagnostic unless status.success?+abort "Cannot parse SDK version: #{sdk}" unless sdk.match?(/\A\d+\.\d+/)+platform_macros = sdk.to_i >= 27+abort 'The State macro regression gate requires macOS SDK 27 or newer' if require_sdk_27 && !platform_macros+Dir.mktmpdir('tff-real-macro-tests.') do |directory|+ fixtures.each do |name, source|+ file = File.join(directory, "#{name}.swift")+ File.write(file, File.read(alias_source) + "\n" + source)+ driver = ['/usr/bin/xcrun', 'swiftc', '-typecheck', '-swift-version', '6',+ '-target', 'arm64-apple-macosx26.0', '-module-name', 'MacroProbe', file]+ output, status = Open3.capture2e(*driver)+ missing = { 'State' => 'SwiftUIMacros', 'Preview' => 'PreviewsMacros' }[name]+ unless status.success? || (missing && output.include?("plugin for module '#{missing}' not found"))+ abort "#{name}: selected-tool baseline failed\n#{output}"+ end+ puts "PASS #{name}: selected tools (#{status.success? ? 'compiles' : 'expected missing platform plugin'})"+ next unless platform_macros++ output, status = Open3.capture2e(*driver, '-###')+ abort output unless status.success?+ commands = output.lines.map { |line| Shellwords.split(line) }+ frontend = commands.find { |argv| argv.include?('-frontend') }+ abort 'Cannot find compiler frontend command' unless frontend+ stripped = []+ removed = 0+ until frontend.empty?+ argument = frontend.shift+ if argument == '-external-plugin-path'+ abort 'Missing plugin path argument' if frontend.empty?+ frontend.shift+ removed += 1+ else+ stripped << argument+ end+ end+ abort 'No platform plugin paths found; negative fixture cannot be validated' if removed.zero?+ output, status = Open3.capture2e(*stripped)+ if missing+ unless !status.success? && output.include?("plugin for module '#{missing}' not found")+ abort "#{name}: expected missing #{missing}, got exit #{status.exitstatus}\n#{output}"+ end+ else+ abort "#{name}: unexpectedly failed without platform plugins\n#{output}" unless status.success?+ end+ puts "PASS #{name}: platform discovery removed (#{missing || 'still compiles'})"+ end+ if configuration+ # Exercise every Swift source, including future framework dependencies, with+ # fresh package objects and platform search paths absent from each frontend.+ frontend, status = Open3.capture2('/usr/bin/xcrun', '--find', 'swift-frontend')+ abort 'Cannot find swift-frontend' unless status.success?+ info, status = Open3.capture2('/usr/bin/xcrun', 'swiftc', '-print-target-info')+ abort 'Cannot read compiler resource directory' unless status.success?+ resources = JSON.parse(info).fetch('paths').fetch('runtimeResourcePath')+ proxy = File.join(directory, 'frontend')+ audit = File.join(directory, 'removed-paths')+ File.write(audit, '')+ File.write(proxy, <<~CODE)+ #!/usr/bin/ruby+ # Refuse opaque response files rather than accidentally retaining plugin+ # paths in one invocation while other invocations make the audit green.+ abort 'Response-file arguments cannot be validated by the plugin-removal proxy' if ARGV.any? { |arg| arg.start_with?('@') }+ arguments = []+ removed = 0+ until ARGV.empty?+ argument = ARGV.shift+ if argument == '-external-plugin-path'+ abort 'Missing plugin path argument' if ARGV.empty?+ ARGV.shift+ removed += 1+ else+ arguments << argument+ end+ end+ File.open(#{audit.dump}, 'a') { |file| file.puts(removed) }+ exec(#{frontend.strip.dump}, *arguments)+ CODE+ File.chmod(0755, proxy)+ response = File.join(directory, 'response')+ File.write(response, '-external-plugin-path /unexpected/plugin')+ output, status = Open3.capture2e(proxy, "@#{response}")+ unless !status.success? && output.include?('Response-file arguments cannot be validated')+ abort 'Plugin-removal proxy accepted an opaque response file'+ end+ puts 'PASS plugin-removal proxy rejects response files'+ root = File.expand_path('../..', __dir__)+ # SwiftBuild's integrated driver does not support replacing its frontend+ # consistently (missing ABI sidecars); use SwiftPM's external-driver path.+ success = system('/usr/bin/xcrun', 'swift', 'build', '--build-system', 'native', '--package-path', root,+ '--scratch-path', File.join(directory, 'build'), '-c', configuration,+ '-Xswiftc', '-driver-use-frontend-path', '-Xswiftc', proxy,+ '-Xswiftc', '-resource-dir', '-Xswiftc', resources)+ abort 'Full package build without platform plugins failed' unless success+ removed = File.readlines(audit).sum(&:to_i)+ abort 'Negative build did not exercise plugin-path removal' if platform_macros && removed.zero?+ puts "PASS full #{configuration} package build: #{removed} platform plugin paths removed"+ end+end+puts 'SKIP platform-plugin removal: this fixture requires macOS SDK 27+' unless platform_macrosdiff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex 87b20042..96c08487 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -4,7 +4,7 @@ import SwiftUIstruct RootView: View {let model: AppModel- @State private var conversationChromeHeight: CGFloat = 0+ @StoredState private var conversationChromeHeight: CGFloat = 0var body: some View {// Three columns in one HStack, not a NavigationSplitView. The splitdiff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex 0528f069..8f945f03 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -85,14 +85,14 @@ private final class ForegroundAppDelegate: NSObject, NSApplicationDelegate {@mainstruct TurboFieldfareMacApp: App {@NSApplicationDelegateAdaptor private var appDelegate: ForegroundAppDelegate- @State private var model: AppModel+ @StoredState private var model: AppModelinit() {let model = AppModel(client: DecodeServiceInferenceClient(),visionRuntimeSupported: AppModel.currentDeviceSupportsVisionRuntime,settingsPersistenceEnabled: true)- _model = State(initialValue: model)+ _model = StoredState(initialValue: model)MainActor.assumeIsolated { ForegroundAppDelegate.model = model }}diff --git a/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift b/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swiftindex 923e4974..bf14a5e3 100644--- a/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift@@ -1,3 +1,4 @@+import TurboFieldfareMacPresentationimport SwiftUI/// An `info.circle` that both hovers and clicks: the tooltip alone was@@ -7,7 +8,7 @@ struct InfoPopoverButton: View {let subject: Stringlet text: Stringvar arrowEdge: Edge = .trailing- @State private var isShowingPopover = false+ @StoredState private var isShowingPopover = falsevar body: some View {Button {diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swiftindex 0057a8f5..43789f8a 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift@@ -243,7 +243,7 @@ private struct StripControlButton: View {let help: Stringlet identifier: AccessibilityIDlet action: () -> Void- @State private var isHovering = false+ @StoredState private var isHovering = false@Environment(\.isEnabled) private var isEnabledvar body: some View {diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftindex 90aaffe4..29fa3ba2 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -6,7 +6,7 @@ import SwiftUIstruct OutputPaneView: View {let model: AppModel- @State private var responseCopyFeedbackID: UUID?+ @StoredState private var responseCopyFeedbackID: UUID?var body: some View {Group {@@ -181,7 +181,7 @@ struct OutputPaneView: View {struct SubmittedImageThumbnail: View {let attachment: ChatImagelet maximumSize: CGSize- @State private var image: NSImage?+ @StoredState private var image: NSImage?init(attachment: ChatImage,@@ -282,7 +282,7 @@ private struct EmptyPlaceholderIcon: View {private struct LoadingModelText: View {@Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var animationStart = Date()+ @StoredState private var animationStart = Date()var body: some View {if reduceMotion {@@ -900,47 +900,65 @@ private struct TranscriptPreview: View {}}-#Preview("Empty") {- VStack(spacing: 8) {- Image(systemName: "cube.transparent")- .font(.title2)- .foregroundStyle(.quaternary)- Text("Start a chat, or choose a predefined example.")- .font(.headline)- Text("Each message keeps the ones before it in context.")- .foregroundStyle(.secondary)+private struct EmptyOutputPreview: PreviewProvider {+ static var previews: some View {+ VStack(spacing: 8) {+ Image(systemName: "cube.transparent")+ .font(.title2)+ .foregroundStyle(.quaternary)+ Text("Start a chat, or choose a predefined example.")+ .font(.headline)+ Text("Each message keeps the ones before it in context.")+ .foregroundStyle(.secondary)+ }+ .frame(width: 720, height: 420)+ .previewDisplayName("Empty")}- .frame(width: 720, height: 420)}-#Preview("Streaming") {- TranscriptPreview(- response: "A response arriving one readable piece at a time...",- isTerminal: false)+private struct StreamingOutputPreview: PreviewProvider {+ static var previews: some View {+ TranscriptPreview(+ response: "A response arriving one readable piece at a time...",+ isTerminal: false)+ .previewDisplayName("Streaming")+ }}-#Preview("Prefilling") {- TranscriptPreview(- response: "",- isTerminal: false,- showsPrefillPlaceholder: true)+private struct PrefillingOutputPreview: PreviewProvider {+ static var previews: some View {+ TranscriptPreview(+ response: "",+ isTerminal: false,+ showsPrefillPlaceholder: true)+ .previewDisplayName("Prefilling")+ }}-#Preview("Completed prose") {- TranscriptPreview(- response: "# A clear answer\n\nHere is a concise explanation with **useful emphasis**.\n\n- First point\n- Second point",- isTerminal: true)+private struct CompletedProseOutputPreview: PreviewProvider {+ static var previews: some View {+ TranscriptPreview(+ response: "# A clear answer\n\nHere is a concise explanation with **useful emphasis**.\n\n- First point\n- Second point",+ isTerminal: true)+ .previewDisplayName("Completed prose")+ }}-#Preview("Completed code") {- TranscriptPreview(- response: "Use `fibonacci(7)`:\n\n```python\ndef fibonacci(n: int) -> list[int]:\n return []\n```",- isTerminal: true)+private struct CompletedCodeOutputPreview: PreviewProvider {+ static var previews: some View {+ TranscriptPreview(+ response: "Use `fibonacci(7)`:\n\n```python\ndef fibonacci(n: int) -> list[int]:\n return []\n```",+ isTerminal: true)+ .previewDisplayName("Completed code")+ }}-#Preview("Incomplete Markdown fallback") {- TranscriptPreview(- response: "The partial answer remains readable.\n\n```python\nprint('unfinished')",- isTerminal: true)+private struct IncompleteMarkdownFallbackOutputPreview: PreviewProvider {+ static var previews: some View {+ TranscriptPreview(+ response: "The partial answer remains readable.\n\n```python\nprint('unfinished')",+ isTerminal: true)+ .previewDisplayName("Incomplete Markdown fallback")+ }}#endifdiff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex 1d34dd3b..6253aaa9 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -9,8 +9,8 @@ struct PromptComposerView: View {@Bindable var model: AppModelvar availableHeight: CGFloat = .infinity@FocusState private var promptFocused: Bool- @State private var showingImagePicker = false- @State private var isImageDropTargeted = false+ @StoredState private var showingImagePicker = false+ @StoredState private var isImageDropTargeted = falsevar body: some View {VStack(alignment: .leading, spacing: 8) {diff --git a/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swift b/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swiftindex 99854678..905dba41 100644--- a/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swift+++ b/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swift@@ -19,10 +19,10 @@ import TurboFieldfareMacPresentation/// refusing to be selected.struct ConversationSidebarView: View {let model: AppModel- @State private var search = ""- @State private var renameTarget: ConversationMeta?- @State private var renameText = ""- @State private var deleteTarget: ConversationMeta?+ @StoredState private var search = ""+ @StoredState private var renameTarget: ConversationMeta?+ @StoredState private var renameText = ""+ @StoredState private var deleteTarget: ConversationMeta?var body: some View {VStack(spacing: 0) {diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swiftindex 6f9df9f4..9bf3cb90 100644--- a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift@@ -4,7 +4,7 @@ import SwiftUIstruct ModelInstallView: View {let model: AppModel- @State private var showingDiscardConfirmation = false+ @StoredState private var showingDiscardConfirmation = falsevar body: some View {ScrollView {diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex ea4c9bd8..342ebdce 100644--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {// Most users build from a clone, where there is no Info.plist to read a// version from, so this constant is what they see. Scripts/check_app_version.rb// fails CI when it falls behind the newest published release.- public static let fallbackShortVersion = "0.9.0"+ public static let fallbackShortVersion = "0.9.1"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareApp/MacPresentation/StoredState.swift b/Sources/TurboFieldfareApp/MacPresentation/StoredState.swiftnew file mode 100644index 00000000..0ea4e6ae--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/StoredState.swift@@ -0,0 +1,7 @@+import SwiftUI++/// Selects Apple's property-wrapper type without expanding the SDK's State+/// macro, whose plugin is absent from some Command Line Tools installations.+/// Initial values are evaluated eagerly; keep expensive reference construction+/// outside view bodies and never combine an inline default with init assignment.+public typealias StoredState<Value> = SwiftUI.State<Value>diff --git a/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift b/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swiftnew file mode 100644index 00000000..230c6fc7--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift@@ -0,0 +1,369 @@+import AppKit+import Observation+import SwiftUI+import Testing+import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@Suite(.serialized) @MainActor struct StoredStateTests {+ @Test func bindingsAndValueMutationRedrawTheMountedView() async throws {+ let driver = StateDriver()+ let bridge = StateBridge()+ let host = StateHost(driver: driver, bridge: bridge)+ defer { host.close() }+ try await rendered { bridge.value?.text == "initial" }+ #expect(bridge.value?.selection == nil)+ #expect(bridge.value?.flag == false)+ let binding = try #require(bridge.binding)+ binding.wrappedValue = "child edit"+ try await rendered { bridge.value?.text == "child edit" }+ bridge.mutate?()+ try await rendered { bridge.value?.items == [7] }+ #expect(bridge.value?.text == "child edit!")+ #expect(binding.wrappedValue == "child edit!")+ #expect(bridge.value?.selection == driver.selection)+ #expect(bridge.value?.flag == true)+ #expect(bridge.value?.height == 42)+ }++ @Test func stableIdentityKeepsEditsAndAnimationOriginWhenParentChanges() async throws {+ let driver = StateDriver()+ let bridge = StateBridge()+ let host = StateHost(driver: driver, bridge: bridge)+ defer { host.close() }+ try await rendered { bridge.value != nil }+ bridge.mutate?()+ try await rendered { bridge.value?.items == [7] }+ let before = try #require(bridge.value)+ driver.seed = "new parent input"+ driver.revision += 1+ try await rendered { bridge.revision == 1 }+ #expect(bridge.value == before)+ }++ @Test func changedIdentityAndReinsertionResetOnlyThatView() async throws {+ let driver = StateDriver()+ let bridge = StateBridge()+ let host = StateHost(driver: driver, bridge: bridge)+ defer { host.close() }+ try await rendered { bridge.value != nil }+ bridge.mutate?()+ try await rendered { bridge.value?.flag == true }+ let retiredBinding = try #require(bridge.binding)+ driver.seed = "replacement"+ driver.identity += 1+ try await rendered { bridge.value?.text == "replacement" }+ #expect(bridge.value?.flag == false)+ #expect(bridge.value?.selection == nil)+ #expect(bridge.value?.items.isEmpty == true)+ // A late image/copy task holding the old binding cannot edit a new identity.+ retiredBinding.wrappedValue = "late old completion"+ driver.revision += 1+ try await rendered { bridge.revision == 1 }+ #expect(bridge.value?.text == "replacement")+ driver.visible = false+ try await rendered("conditional removal") { !bridge.mounted }+ driver.seed = "reinserted"+ driver.visible = true+ try await rendered { bridge.value?.text == "reinserted" }+ #expect(bridge.value?.items.isEmpty == true)+ }++ @Test func separateViewInstancesNeverShareState() async throws {+ let first = StateBridge()+ let second = StateBridge()+ let a = StateHost(driver: StateDriver(), bridge: first)+ let b = StateHost(driver: StateDriver(), bridge: second)+ defer { a.close(); b.close() }+ try await rendered { first.value != nil && second.value != nil }+ first.mutate?()+ try await rendered { first.value?.flag == true }+ #expect(second.value?.text == "initial")+ #expect(second.value?.flag == false)+ }++ @Test func observableReferenceKeepsIdentityAndNestedChangesRedraw() async throws {+ let driver = StateDriver()+ let original = driver.model+ let bridge = StateBridge()+ let host = StateHost(driver: driver, bridge: bridge)+ defer { host.close() }+ try await rendered { bridge.model === original }+ original.count = 9+ try await rendered { bridge.modelCount == 9 }+ driver.model = StateReference()+ driver.revision += 1+ try await rendered { bridge.revision == 1 }+ #expect(bridge.model === original)+ #expect(bridge.modelCount == 9)+ driver.identity += 1+ try await rendered { bridge.model === driver.model }+ #expect(bridge.modelCount == 0)+ }++ @Test func stateReferenceIsReleasedAfterItsHostAndBindingsAreReleased() async throws {+ weak var retained: StateReference?+ do {+ let driver = StateDriver()+ retained = driver.model+ let bridge = StateBridge()+ let host = StateHost(driver: driver, bridge: bridge)+ try await rendered { bridge.model != nil }+ driver.model = StateReference()+ driver.revision += 1+ try await rendered { bridge.revision == 1 }+ host.close()+ bridge.binding = nil+ bridge.mutate = nil+ bridge.model = nil+ }+ try await rendered("reference teardown") { retained == nil }+ }++ @Test func appModelKeepsItsExplicitReferenceAndHistoryAcrossRedraws() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer {+ do { try FileManager.default.removeItem(at: directory) }+ catch { Issue.record("Could not remove isolated model fixture: \(error)") }+ }+ let delegateModel = AppModel(+ modelDirectory: directory.appendingPathComponent("missing.gturbo"),+ client: NoGenerationClient(), visionRuntimeSupported: false,+ settingsPersistenceEnabled: true)+ defer { delegateModel.shutdownForTermination() }+ let driver = StateDriver()+ let bridge = AppModelBridge()+ let host = StateHost(rootView: AppModelRoot(model: delegateModel, driver: driver, bridge: bridge))+ defer { host.close() }+ try await rendered { bridge.model === delegateModel }+ let history = delegateModel.history+ delegateModel.promptText = "draft"+ try await rendered { bridge.text == "draft" }+ driver.revision += 1+ try await rendered { bridge.revision == 1 }+ #expect(bridge.model === delegateModel)+ #expect(bridge.model?.history === history)+ #expect(delegateModel.modelPathText == directory.appendingPathComponent("missing.gturbo").path)+ }++ @Test func wrapperInitializationIsEagerAndExplicitInitialValueIsRetained() {+ var constructions = 0+ func makeReference() -> StateReference {+ constructions += 1+ return StateReference()+ }+ let first = StoredState(wrappedValue: makeReference())+ let second = StoredState(wrappedValue: makeReference())+ #expect(constructions == 2)+ #expect(first.wrappedValue !== second.wrappedValue)+ let reference = StateReference()+ let explicit = StoredState(initialValue: reference)+ #expect(explicit.wrappedValue === reference)+ }++ private func rendered(_ label: String = "state update", _ predicate: () -> Bool) async throws {+ let deadline = ContinuousClock.now + .seconds(3)+ while !predicate(), ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(predicate(), "Mounted SwiftUI view did not reach the expected state: \(label)")+ }+}++@MainActor @Observable private final class StateReference {+ var count = 0+}++@MainActor @Observable private final class StateDriver {+ var seed = "initial"+ var revision = 0+ var identity = 0+ var visible = true+ var model = StateReference()+ let selection = UUID()+}++private struct StateValue: Equatable {+ var text: String+ var flag: Bool+ var selection: UUID?+ var height: CGFloat+ var items: [Int]+ var origin: Date+}++@MainActor private final class StateBridge {+ var value: StateValue?+ var binding: Binding<String>?+ var mutate: (() -> Void)?+ var model: StateReference?+ var modelCount = -1+ var revision = -1+ var mounted = false+}++@MainActor private final class StateHost {+ private let window: NSWindow++ convenience init(driver: StateDriver, bridge: StateBridge) {+ self.init(rootView: StateRoot(driver: driver, bridge: bridge))+ }++ init<Content: View>(rootView: Content) {+ _ = NSApplication.shared+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 100, height: 100),+ styleMask: .borderless, backing: .buffered, defer: false)+ window.isReleasedWhenClosed = false+ window.contentView = NSHostingView(rootView: rootView)+ window.orderFront(nil)+ }++ func close() {+ window.orderOut(nil)+ window.contentView = nil+ window.close()+ }+}++private struct StateRoot: View {+ let driver: StateDriver+ let bridge: StateBridge++ var body: some View {+ if driver.visible {+ StateFixture(seed: driver.seed, revision: driver.revision,+ selection: driver.selection, model: driver.model, bridge: bridge)+ .id(driver.identity)+ .onAppear { bridge.mounted = true }+ .onDisappear { bridge.mounted = false }+ }+ }+}++private struct StateFixture: View {+ let revision: Int+ let selection: UUID+ let bridge: StateBridge+ @StoredState private var text: String+ @StoredState private var flag = false+ @StoredState private var selected: UUID?+ @StoredState private var height: CGFloat = 0+ @StoredState private var items: [Int] = []+ @StoredState private var origin = Date()+ @StoredState private var model: StateReference+ @StoredState private var image: NSImage?+ @FocusState private var focused: Bool++ init(seed: String, revision: Int, selection: UUID, model: StateReference, bridge: StateBridge) {+ self.revision = revision+ self.selection = selection+ self.bridge = bridge+ _text = StoredState(initialValue: seed)+ _model = StoredState(initialValue: model)+ }++ var body: some View {+ StateBindingChild(+ text: $text,+ value: StateValue(text: text, flag: flag, selection: selected,+ height: height, items: items, origin: origin),+ model: model, count: model.count, revision: revision, bridge: bridge,+ mutate: {+ text += "!"+ flag.toggle()+ selected = selection+ height = 42+ items.append(7)+ })+ }+}++private struct StateBindingChild: View {+ @Binding var text: String+ let value: StateValue+ let model: StateReference+ let count: Int+ let revision: Int+ let bridge: StateBridge+ let mutate: () -> Void++ var body: some View {+ StateRecorder(value: value, binding: $text, model: model, count: count,+ revision: revision, bridge: bridge, mutate: mutate)+ }+}++private struct StateRecorder: NSViewRepresentable {+ let value: StateValue+ let binding: Binding<String>+ let model: StateReference+ let count: Int+ let revision: Int+ let bridge: StateBridge+ let mutate: () -> Void++ func makeCoordinator() -> StateBridge { bridge }+ func makeNSView(context: Context) -> NSView { NSView() }+ func updateNSView(_ view: NSView, context: Context) {+ bridge.value = value+ bridge.binding = binding+ bridge.mutate = mutate+ bridge.model = model+ bridge.modelCount = count+ bridge.revision = revision+ }+}++private struct NoGenerationClient: AppInferenceClient {+ func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {+ Issue.record("The state ownership fixture must not generate")+ return AsyncThrowingStream { $0.finish() }+ }+ func cancel() {}+}++@MainActor private final class AppModelBridge {+ var model: AppModel?+ var text = ""+ var revision = -1+}++private struct AppModelRoot: View {+ let model: AppModel+ let driver: StateDriver+ let bridge: AppModelBridge++ var body: some View {+ AppModelFixture(model: model, revision: driver.revision, bridge: bridge)+ }+}++private struct AppModelFixture: View {+ @StoredState private var model: AppModel+ let revision: Int+ let bridge: AppModelBridge++ init(model: AppModel, revision: Int, bridge: AppModelBridge) {+ self.revision = revision+ self.bridge = bridge+ _model = StoredState(initialValue: model)+ }++ var body: some View {+ AppModelRecorder(model: model, text: model.promptText, revision: revision, bridge: bridge)+ }+}++private struct AppModelRecorder: NSViewRepresentable {+ let model: AppModel+ let text: String+ let revision: Int+ let bridge: AppModelBridge++ func makeNSView(context: Context) -> NSView { NSView() }+ func updateNSView(_ view: NSView, context: Context) {+ bridge.model = model+ bridge.text = text+ bridge.revision = revision+ }+}