Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Add selectable model locations and a self-built Mac app bundle (#191)

Andrey Mikhaylov4d546048c55c
diff --git a/.gitignore b/.gitignore
index ab451b7c..7ec9b4fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,7 @@ xcuserdata/
.DS_Store
# Build artifacts
+/dist/
*.o
*.a
*.dylib
diff --git a/AGENTS.md b/AGENTS.md
index bf9a16af..d4f2f2b2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,6 +20,7 @@ swift run -c release TurboFieldfareRepack --output scratch/gemma4.gturbo
swift run -c release TurboFieldfareRepack --output scratch/gemma4.gturbo --resume
swift build -c release
.build/release/TurboFieldfareMac
+Scripts/build_app.sh
swift run -c release TurboFieldfareCLI \
--model scratch/gemma4.gturbo \
--prompt "The capital of France is" \
@@ -56,6 +57,11 @@ Before a model run, require macOS 26+, Swift 6.2+, enough disk, acceptable `memo
Run package tests through `Scripts/test.sh`. Run only one app, CLI, or model-using test at a time.
+For isolated app checks, set `TURBO_FIELDFARE_APP_DATA_PATH` to a temporary
+directory so settings and history stay separate. `TURBO_FIELDFARE_MODEL_PATH`
+overrides the saved model location and disables location changes in the UI.
+See [Build a Mac app](README.md#build-a-mac-app) for bundle instructions.
+
For performance results, build release once and follow the [community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) exactly. Do not enable experimental controls or profiling.
Do not download a full checkpoint, duplicate the `.gturbo` model, create a worktree, or purge caches just to run tests.
diff --git a/Package.swift b/Package.swift
index f8d9fa28..0c0ff6bf 100644
--- a/Package.swift
+++ b/Package.swift
@@ -163,7 +163,7 @@ let package = Package(
),
.testTarget(
name: "TurboFieldfareMacPresentationTests",
- dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation"],
+ dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation", "TurboFieldfareMac"],
path: "Tests/TurboFieldfareApp/MacPresentation",
resources: [.copy("Fixtures")]
),
diff --git a/README.md b/README.md
index 45cd3d18..848bc681 100644
--- a/README.md
+++ b/README.md
@@ -56,7 +56,7 @@ On the first run, Swift Package Manager downloads and builds the Swift packages
required by the tokenizer. The complete release build includes the foreground
Mac app and its sibling decode-service executable.
-When the app opens, choose **Download** and let TurboFieldfare fetch and repack
+When the app opens, choose **Download Model** and let TurboFieldfare fetch and repack
the pinned model (about 15 GB). Once it is ready, choose **Load Model**, type
your prompt, and press **Generate**.
@@ -101,7 +101,7 @@ The Swift package exposes six products:
- An Apple Silicon Mac; the validated target is an 8 GB M2 MacBook Air
- macOS 26 with Metal 4
-- Xcode 26 and Swift 6.2 or newer
+- Apple Command Line Tools or Xcode with Swift 6.2+ and the macOS 26 SDK or newer
- Enough free storage for the ~14.3 GB model installation
- An internet connection for the first model install
@@ -143,13 +143,30 @@ swift build -c release
```
Build the complete package so the app and its sibling decode service are both
-available. When launched from this checkout, the app stores the model in
-`scratch/gemma4.gturbo`.
+available. New installs from this checkout default to `scratch/gemma4.gturbo`;
+the app remembers a location you choose.
+
+#### Build a Mac app
+
+From the repository root, run:
+
+```bash
+Scripts/build_app.sh
+```
+
+This creates `dist/TurboFieldfare.app`, which you can double-click or move to
+Applications. Add `--install` to also copy it to `~/Applications`.
+The bundle includes the decode service and resources; model weights stay in
+their selected folder. The script uses ad-hoc signing, so no Apple developer
+account is required.
#### Install the model
-On first launch, the app checks the available storage and shows the download
-and installed sizes. Choose **Download** to begin.
+Choose **Download Model** to install, or **Change…** to pick a destination.
+To reuse a model, choose **Use Existing Model…** and select its `.gturbo`
+folder or parent folder. If several models are found, pick one.
+Keep the optional image pack beside its text model: `gemma4.gturbo` and
+`gemma4.vision.gturbo`.
The installer never materializes the full source checkpoint. It streams the
required byte ranges from the pinned Hugging Face revision and repacks them
@@ -188,11 +205,15 @@ sidebar. Every launch opens an empty chat. Only one conversation's model context
Browsing other chats keeps that cache intact; continuing another chat replaces
it. **New Chat** starts fresh.
+Settings and chats live in `~/Library/Application Support/TurboFieldfare/`
+(`mac-app-settings.json` and `conversations/`). A standalone app also uses
+this folder for new model downloads by default. Moving the app does not move
+these files or change a saved model location.
+
### Command-line interface
-The CLI uses an existing `.gturbo` installation. If you installed the model
-through the Mac app, it is already available at `scratch/gemma4.gturbo`.
-Otherwise, install it from the command line:
+The CLI uses an existing `.gturbo` installation. For a model installed through
+the Mac app, pass its location with `--model`. To install from the command line:
```bash
swift run -c release TurboFieldfareRepack \
diff --git a/Scripts/build_app.rb b/Scripts/build_app.rb
new file mode 100644
index 00000000..f7de77f3
--- /dev/null
+++ b/Scripts/build_app.rb
@@ -0,0 +1,195 @@
+#!/usr/bin/env ruby
+require 'fileutils'
+require 'open3'
+require 'tmpdir'
+require 'cgi'
+require 'digest'
+
+module LocalMacApp
+ ROOT = File.expand_path('..', __dir__)
+ RESOURCES = %w[TurboFieldfare_TurboFieldfare.bundle TurboFieldfare_TurboFieldfareAppCore.bundle TurboFieldfare_TurboFieldfareMac.bundle SwiftMath_SwiftMath.bundle swift-transformers_Hub.bundle swift-crypto_Crypto.bundle].freeze
+ PRODUCTS = %w[TurboFieldfareMac TurboFieldfareDecodeService].freeze
+
+ def self.run(*arguments)
+ output, error, status = Open3.capture3(*arguments, chdir: ROOT)
+ raise "#{arguments.first} failed (#{status.exitstatus}): #{error}\n#{output}" unless status.success?
+ output.strip
+ end
+
+ def self.version
+ source = File.read(File.join(ROOT, 'Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift'))
+ source[/fallbackShortVersion\s*=\s*"([0-9]+(?:\.[0-9]+)+)"/, 1] || raise('About fallback version is missing')
+ end
+
+ def self.active?(destination)
+ destination = File.realpath(destination) if File.exist?(destination)
+ processes = run('/bin/ps', '-axww', '-o', 'comm=')
+ processes.lines.any? do |line|
+ executable = line.strip
+ begin
+ executable = File.realpath(executable)
+ rescue Errno::ENOENT, Errno::EACCES
+ # A process may exit during inspection, and other users' executables
+ # may be inaccessible. Their reported path still supports comparison.
+ end
+ executable.start_with?(File.join(destination, 'Contents/MacOS') + '/')
+ end
+ end
+
+ def self.publish(staged, destination)
+ raise "Quit the app and its decode helper before replacing #{destination}. No process was stopped." if active?(destination)
+ if File.exist?(destination)
+ raise "Refusing to replace an unrelated directory at #{destination}" unless File.file?(File.join(destination, 'Contents/Info.plist')) &&
+ File.read(File.join(destination, 'Contents/Info.plist')).include?('<string>com.turbofieldfare.mac</string>')
+ end
+ backup = destination.sub(/\.app\z/, '') + '.previous-' + Time.now.utc.strftime('%Y%m%dT%H%M%S') + '-'+ Process.pid.to_s + '.app'
+ raise "Previous-build archive already exists at #{backup}; retry after moving it aside." if File.exist?(backup)
+ File.rename(destination, backup) if File.exist?(destination)
+ begin
+ File.rename(staged, destination)
+ rescue
+ File.rename(backup, destination) if File.exist?(backup)
+ raise
+ end
+ end
+
+ def self.resource_root(bundle)
+ structured = File.join(bundle, 'Contents/Resources')
+ File.directory?(structured) ? structured : bundle
+ end
+
+ def self.package(bin, stage, mode:, sign: true)
+ raise 'Unknown resource layout' unless %w[standard legacy].include?(mode)
+ PRODUCTS.each { |name| raise "Missing executable: #{name}" unless File.file?(File.join(bin, name)) && File.executable?(File.join(bin, name)) }
+ RESOURCES.each { |name| raise "Missing required resource bundle: #{name}" unless File.directory?(File.join(bin, name)) }
+ required_files = {
+ 'TurboFieldfare_TurboFieldfare.bundle' => 'Metal',
+ 'TurboFieldfare_TurboFieldfareAppCore.bundle' => 'app-prompts.json',
+ 'TurboFieldfare_TurboFieldfareMac.bundle' => 'turbofieldfare-app-icon.png',
+ 'SwiftMath_SwiftMath.bundle' => 'mathFonts.bundle',
+ 'swift-transformers_Hub.bundle' => 'gpt2_tokenizer_config.json'
+ }
+ required_files.each { |bundle, file| raise "Missing resource: #{bundle}/#{file}" unless File.exist?(File.join(resource_root(File.join(bin, bundle)), file)) }
+ RESOURCES.each do |name|
+ Dir.glob(File.join(bin, name, '**', '*'), File::FNM_DOTMATCH).each do |entry|
+ raise "Resource symlink is not portable: #{entry}" if File.symlink?(entry)
+ raise "Model weights cannot be packaged: #{entry}" if entry.match?(/\.(?:gturbo|safetensors|bin|gguf)(?:\/|$)/)
+ end
+ end
+ executables = File.join(stage, 'Contents/MacOS')
+ resources = File.join(stage, 'Contents/Resources')
+ FileUtils.mkdir_p([executables, resources])
+ PRODUCTS.each { |name| FileUtils.cp(File.join(bin, name), executables) }
+ RESOURCES.each { |name| FileUtils.cp_r(File.join(bin, name), resources) }
+ if mode == 'legacy'
+ # Native SwiftPM's accessor uses Bundle.main.bundleURL, which resolves to
+ # the outer app for both packaged executables on the supported local layout.
+ RESOURCES.each do |name|
+ FileUtils.cp_r(File.join(bin, name), stage)
+ end
+ end
+ iconset = File.join(File.dirname(stage), 'TurboFieldfare.iconset')
+ FileUtils.mkdir_p(iconset)
+ source_icon = File.join(resource_root(File.join(resources, 'TurboFieldfare_TurboFieldfareMac.bundle')), 'turbofieldfare-app-icon.png')
+ [16, 32, 128, 256, 512].each do |size|
+ [1, 2].each do |scale|
+ target = File.join(iconset, "icon_#{size}x#{size}#{scale == 2 ? '@2x' : ''}.png")
+ run('/usr/bin/sips', '-z', (size * scale).to_s, (size * scale).to_s, source_icon, '--out', target)
+ end
+ end
+ run('/usr/bin/iconutil', '-c', 'icns', iconset, '-o', File.join(resources, 'TurboFieldfare.icns'))
+ FileUtils.rm_r(iconset)
+ values = {
+ 'CFBundleExecutable' => 'TurboFieldfareMac', 'CFBundleIdentifier' => 'com.turbofieldfare.mac',
+ 'CFBundleName' => 'TurboFieldfare', 'CFBundleDisplayName' => 'TurboFieldfare',
+ 'CFBundlePackageType' => 'APPL', 'CFBundleShortVersionString' => version,
+ 'CFBundleVersion' => version, 'LSMinimumSystemVersion' => '26.0',
+ 'CFBundleIconFile' => 'TurboFieldfare.icns', 'NSHighResolutionCapable' => true
+ }
+ entries = values.map { |key, value| "<key>#{key}</key>" + (value == true ? '<true/>' : "<string>#{CGI.escapeHTML(value)}</string>") }.join("\n")
+ File.write(File.join(stage, 'Contents/Info.plist'), <<~PLIST)
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0"><dict>#{entries}</dict></plist>
+ PLIST
+ run('/usr/bin/plutil', '-lint', File.join(stage, 'Contents/Info.plist'))
+ if sign
+ if mode == 'standard'
+ PRODUCTS.each { |name| run('/usr/bin/codesign', '--force', '--sign', '-', File.join(executables, name)) }
+ run('/usr/bin/codesign', '--force', '--sign', '-', stage)
+ run('/usr/bin/codesign', '--verify', '--strict', stage)
+ else
+ # codesign interprets a main executable inside .app as an outer bundle
+ # check. Native SwiftPM's root resources cannot be sealed; verify each
+ # preserved Mach-O signature outside that bundle and pin identical bytes.
+ Dir.mktmpdir('.signature-check-', File.dirname(stage)) do |verification|
+ PRODUCTS.each do |name|
+ executable = File.join(executables, name)
+ bare = File.join(verification, name)
+ FileUtils.cp(executable, bare)
+ run('/usr/bin/codesign', '--verify', bare)
+ raise "Signature-probe bytes changed for #{name}" unless Digest::SHA256.file(bare).hexdigest == Digest::SHA256.file(executable).hexdigest
+ end
+ end
+ end
+ end
+ end
+
+ def self.main(arguments)
+ install = arguments == ['--install']
+ raise 'Usage: Scripts/build_app.sh [--install]' unless arguments.empty? || install
+ raise 'Apple Silicon is required' unless run('/usr/bin/uname', '-m') == 'arm64'
+ raise 'macOS 26 or newer is required' unless run('/usr/bin/sw_vers', '-productVersion').split('.').first.to_i >= 26
+ compiler = run('/usr/bin/xcrun', 'swift', '--version')[/Swift version (\d+)\.(\d+)/, 0]
+ raise 'Swift 6.2 or newer is required' unless compiler && (compiler[/\d+\.\d+/].split('.').map(&:to_i) <=> [6, 2]) >= 0
+ raise 'macOS SDK 26 or newer is required' unless run('/usr/bin/xcrun', '--sdk', 'macosx', '--show-sdk-version').split('.').first.to_i >= 26
+ PRODUCTS.each { |name| puts "Building #{name}…"; run('/usr/bin/xcrun', 'swift', 'build', '-c', 'release', '--product', name) }
+ bin = run('/usr/bin/xcrun', 'swift', 'build', '-c', 'release', '--show-bin-path')
+ # Inspect only the accessor for this exact build output, never a stale build.
+ native = File.join(bin, 'TurboFieldfareMac.build/DerivedSources/resource_bundle_accessor.swift')
+ swift_build = File.expand_path('../../Intermediates.noindex/TurboFieldfare.build/Release/TurboFieldfareMac-p.build/DerivedSources/resource_bundle_accessor.swift', bin)
+ accessor = [native, swift_build].find { |path| File.file?(path) } || raise('Cannot locate the generated Mac resource accessor for this build')
+ accessor_paths = if accessor == native
+ Dir.glob(File.join(bin, '*.build/DerivedSources/resource_bundle_accessor.swift'))
+ else
+ Dir.glob(File.join(File.expand_path('../../Intermediates.noindex', bin), '**/Release/**/DerivedSources/resource_bundle_accessor.swift'))
+ end
+ required_accessors = RESOURCES.map do |bundle|
+ name = bundle.delete_suffix('.bundle')
+ accessor_paths.find { |path| File.read(path).include?(name) } || raise("Missing resource accessor for #{bundle}")
+ end
+ mode = required_accessors.all? { |path| File.read(path).include?('Bundle.main.resourceURL') } ? 'standard' : 'legacy'
+ output_root = File.join(ROOT, 'dist')
+ FileUtils.mkdir_p(output_root)
+ Dir.mktmpdir('.build-app-', output_root) do |temporary|
+ staged = File.join(temporary, 'TurboFieldfare.app')
+ package(bin, staged, mode: mode)
+ # Deny the generated accessors' build fallback instead of hiding a live build tree.
+ escaped_bin = bin.gsub('\\', '\\\\').gsub('"', '\\"')
+ policy = "(version 1)(allow default)(deny file-read* (subpath \"#{escaped_bin}\"))"
+ PRODUCTS.each do |name|
+ puts run('/usr/bin/sandbox-exec', '-p', policy, File.join(staged, 'Contents/MacOS', name), '--check-resources')
+ end
+ publish(staged, File.join(output_root, 'TurboFieldfare.app'))
+ end
+ puts "Built dist/TurboFieldfare.app (#{mode == 'standard' ? 'standard resources; ad-hoc app signature' : 'local SwiftPM resource layout; verified linker ad-hoc executable signatures'})."
+ return unless install
+ applications = File.join(Dir.home, 'Applications')
+ FileUtils.mkdir_p(applications)
+ Dir.mktmpdir('.turbofieldfare-install-', applications) do |temporary|
+ staged = File.join(temporary, 'TurboFieldfare.app')
+ FileUtils.cp_r(File.join(output_root, 'TurboFieldfare.app'), staged)
+ publish(staged, File.join(applications, 'TurboFieldfare.app'))
+ end
+ puts 'Installed ~/Applications/TurboFieldfare.app; previous builds retained as TurboFieldfare.previous-*.app when replaced.'
+ end
+end
+
+if $PROGRAM_NAME == __FILE__
+ begin
+ LocalMacApp.main(ARGV)
+ rescue => error
+ warn "App build failed: #{error}"
+ exit 1
+ end
+end
diff --git a/Scripts/build_app.sh b/Scripts/build_app.sh
new file mode 100755
index 00000000..612e371e
--- /dev/null
+++ b/Scripts/build_app.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -euo pipefail
+SCRIPT_DIRECTORY="$(cd "$(dirname "$0")" && pwd)"
+exec ruby "$SCRIPT_DIRECTORY/build_app.rb" "$@"
diff --git a/Scripts/tests/build_app_test.rb b/Scripts/tests/build_app_test.rb
new file mode 100644
index 00000000..3df34d23
--- /dev/null
+++ b/Scripts/tests/build_app_test.rb
@@ -0,0 +1,73 @@
+#!/usr/bin/env ruby
+require 'tmpdir'
+require 'fileutils'
+require_relative '../build_app'
+
+def check(value, message)
+ raise message unless value
+end
+
+def rejects(message)
+ begin
+ yield
+ rescue => error
+ check(error.message.include?(message), "wrong failure: #{error}")
+ return
+ end
+ raise "expected failure: #{message}"
+end
+
+rejects('Usage:') { LocalMacApp.main(['--unknown']) }
+Dir.mktmpdir('tf app packaging тест ') do |root|
+ bin = File.join(root, 'bin')
+ FileUtils.mkdir_p(bin)
+ stage = File.join(root, 'TurboFieldfare.app')
+ rejects('Missing executable') { LocalMacApp.package(bin, stage, mode: 'standard', sign: false) }
+ LocalMacApp::PRODUCTS.each { |name| File.write(File.join(bin, name), '#!/bin/sh\nexit 0\n'); File.chmod(0755, File.join(bin, name)) }
+ rejects('Missing required resource') { LocalMacApp.package(bin, stage, mode: 'standard', sign: false) }
+ LocalMacApp::RESOURCES.each { |name| FileUtils.mkdir_p(File.join(bin, name)) }
+ FileUtils.mkdir_p(File.join(bin, 'TurboFieldfare_TurboFieldfare.bundle/Metal'))
+ File.write(File.join(bin, 'TurboFieldfare_TurboFieldfareAppCore.bundle/app-prompts.json'), '{}')
+ File.write(File.join(bin, 'swift-transformers_Hub.bundle/gpt2_tokenizer_config.json'), '{}')
+ FileUtils.mkdir_p(File.join(bin, 'SwiftMath_SwiftMath.bundle/mathFonts.bundle'))
+ icon = File.join(LocalMacApp::ROOT, 'Sources/TurboFieldfareApp/Mac/Resources/turbofieldfare-app-icon.png')
+ FileUtils.cp(icon, File.join(bin, 'TurboFieldfare_TurboFieldfareMac.bundle/turbofieldfare-app-icon.png'))
+ File.write(File.join(bin, 'unrelated-tests.bundle'), 'exclude')
+ LocalMacApp.package(bin, stage, mode: 'standard', sign: false)
+ check(File.file?(File.join(stage, 'Contents/MacOS/TurboFieldfareDecodeService')), 'helper missing')
+ check(File.file?(File.join(stage, 'Contents/Resources/TurboFieldfare.icns')), 'icon missing')
+ check(File.read(File.join(stage, 'Contents/Info.plist')).include?(LocalMacApp.version), 'version mismatch')
+ check(!File.exist?(File.join(stage, 'Contents/Resources/unrelated-tests.bundle')), 'test bundle included')
+ destination = File.join(root, 'published.app')
+ LocalMacApp.publish(stage, destination)
+ before = File.read(File.join(destination, 'Contents/Info.plist'))
+ FileUtils.rm(File.join(bin, 'TurboFieldfareDecodeService'))
+ rejects('Missing executable') { LocalMacApp.package(bin, stage, mode: 'standard', sign: false) }
+ check(File.read(File.join(destination, 'Contents/Info.plist')) == before, 'failed build changed output')
+ helper = File.join(destination, 'Contents/MacOS/TurboFieldfareDecodeService')
+ FileUtils.cp('/bin/sleep', helper)
+ LocalMacApp.run('/usr/bin/codesign', '--force', '--sign', '-', helper)
+ process = Process.spawn(helper, '30')
+ begin
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 3
+ until LocalMacApp.active?(destination)
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
+ raise "dummy helper was not detected: #{LocalMacApp.run('/bin/ps', '-p', process.to_s, '-o', 'comm=')}"
+ end
+ sleep 0.01
+ end
+ rejects('Quit the app and its decode helper') { LocalMacApp.publish(stage, destination) }
+ rejects('Quit the app and its decode helper') { LocalMacApp.publish(stage, File.realpath(destination)) }
+ check(File.read(File.join(destination, 'Contents/Info.plist')) == before, 'running helper changed output')
+ ensure
+ Process.kill('TERM', process)
+ Process.wait(process)
+ end
+ FileUtils.mkdir_p(stage)
+ rejects('unrelated directory') { LocalMacApp.publish(stage, bin) }
+ FileUtils.rm_r(stage)
+ FileUtils.cp_r(destination, stage)
+ LocalMacApp.publish(stage, destination)
+ check(Dir.glob(File.join(root, 'published.previous-*.app/Contents/Info.plist')).length == 1, 'previous app not retained')
+end
+puts 'PASS packaging: arguments, missing helper/resources, metadata/icon, exclusions, staged failure, running helper refusal and preserved replacement'
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppBundledResources.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppBundledResources.swift
new file mode 100644
index 00000000..45f5625a
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppBundledResources.swift
@@ -0,0 +1,12 @@
+import Foundation
+import TurboFieldfare
+
+public enum AppBundledResources {
+ /// A model-free relocation probe for the app and its independently launched helper.
+ public static func verify() throws {
+ guard AppPromptPreset.all.count == 7 else {
+ throw AppInferenceError.invalidRequest("Bundled prompt examples could not be read.")
+ }
+ _ = try MetalContext()
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppDataBootstrap.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppDataBootstrap.swift
new file mode 100644
index 00000000..98158611
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppDataBootstrap.swift
@@ -0,0 +1,66 @@
+import Foundation
+import TurboFieldfareRepackCore
+
+struct AppDataBootstrap {
+ var settings = MacAppSettings()
+ var failure: String?
+ var modelChoiceRequired = false
+ var canResetSettings = true
+
+ init(root: URL, legacyModel: URL, environment: [String: String], modelOverride: Bool = false, enabled: Bool) {
+ guard enabled else { return }
+ do {
+ let settingsURL = AppDataLocation.settingsURL(in: root)
+ let central = try MacAppSettingsFileStore.load(at: settingsURL)
+ if let central { settings = central }
+ let history = ConversationStoreLocation.url(forAppDataDirectory: root)
+ do {
+ try ConversationStoreImport.recover(at: history)
+ } catch {
+ canResetSettings = false
+ failure = "Recovering an interrupted history import at \(history.path) failed: \(error). Existing settings and history were preserved. Repair the history recovery files and reopen the app; automatic settings writes are disabled."
+ return
+ }
+ if let central {
+ if central.selectedModelPath != nil || modelOverride
+ || environment["TURBO_FIELDFARE_MODEL_PATH"] != nil { return }
+ }
+ let isolated = environment["TURBO_FIELDFARE_APP_DATA_PATH"] != nil
+ let legacyRoot = isolated ? root : legacyModel.deletingLastPathComponent()
+ let legacySettingsURL = AppDataLocation.settingsURL(in: legacyRoot)
+ if central == nil, legacySettingsURL != settingsURL,
+ let legacySettings = try MacAppSettingsFileStore.load(at: legacySettingsURL) {
+ settings = legacySettings
+ }
+ var selectedLegacy = legacyModel
+ if !modelOverride && environment["TURBO_FIELDFARE_MODEL_PATH"] == nil {
+ let candidates = Array(Set([legacyModel.standardizedFileURL,
+ root.appendingPathComponent("gemma4.gturbo").standardizedFileURL]))
+ let installed = try candidates.filter { candidate in
+ if AppModelInstallationProbe.status(at: candidate) == .complete { return true }
+ return try RemoteStreamingRepacker.inspectPersistentInstall(
+ outputDirectory: candidate.path,
+ repoID: AppModelInstallDescriptor.default.repoID,
+ requestedRevision: AppModelInstallDescriptor.default.revision) != nil
+ }
+ if installed.count > 1 {
+ modelChoiceRequired = true
+ } else {
+ selectedLegacy = installed.first ?? legacyModel
+ settings.selectedModelPath = selectedLegacy.path
+ }
+ }
+ let source = ConversationStoreLocation.url(forModelDirectory: selectedLegacy)
+ let destination = ConversationStoreLocation.url(forAppDataDirectory: root)
+ if !isolated, !modelChoiceRequired, source != destination,
+ !settings.migratedHistorySources.contains(source.path),
+ FileManager.default.fileExists(atPath: source.path) {
+ try ConversationStoreImport.run(from: source, to: destination)
+ settings.migratedHistorySources.append(source.path)
+ }
+ try MacAppSettingsFileStore.save(settings, at: settingsURL)
+ } catch {
+ failure = "Could not initialize app data: \(error). Reveal the settings file and repair it, or explicitly reset settings after keeping a backup. Automatic settings writes are disabled."
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppDataLocation.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppDataLocation.swift
new file mode 100644
index 00000000..7597f996
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppDataLocation.swift
@@ -0,0 +1,19 @@
+import Foundation
+
+public enum AppDataLocation {
+ public static func resolve(explicitURL: URL? = nil,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ applicationSupportURL: URL? = nil) -> URL {
+ if let explicitURL { return explicitURL.standardizedFileURL.resolvingSymlinksInPath() }
+ if let path = environment["TURBO_FIELDFARE_APP_DATA_PATH"], !path.isEmpty {
+ return URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL.resolvingSymlinksInPath()
+ }
+ let support = applicationSupportURL ?? FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support", isDirectory: true)
+ return support.appendingPathComponent("TurboFieldfare", isDirectory: true).standardizedFileURL
+ }
+
+ static func settingsURL(in root: URL) -> URL {
+ root.appendingPathComponent(MacAppSettings.fileName)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/ConversationStoreImport.swift b/Sources/TurboFieldfareApp/Core/Configuration/ConversationStoreImport.swift
new file mode 100644
index 00000000..1657ce46
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Configuration/ConversationStoreImport.swift
@@ -0,0 +1,207 @@
+import Darwin
+import Foundation
+import TurboFieldfare
+import TurboFieldfareRepackCore
+
+/// Publishes whole conversation directories while retaining the store lock's inode.
+/// The journal makes an interrupted multi-directory import rollback on the next attempt.
+enum ConversationStoreImport {
+ struct Journal: Codable {
+ var source: String
+ var fingerprints: [String: [String: String]]
+ }
+
+ static func run(from source: URL, to destination: URL,
+ destinationAlreadyLocked: Bool = false,
+ afterPublish: (() throws -> Void)? = nil) throws {
+ let sourceKind = try Posix.entryKind(source.standardizedFileURL.path)
+ guard sourceKind != .absent else { return }
+ let destinationKind = try Posix.entryKind(destination.standardizedFileURL.path)
+ guard sourceKind == .directory, destinationKind == .directory || destinationKind == .absent else {
+ throw ImportError("History source and destination must be regular directories, without symlink roots.")
+ }
+ let source = source.standardizedFileURL.resolvingSymlinksInPath()
+ let destination = destination.standardizedFileURL.resolvingSymlinksInPath()
+ guard source != destination else { return }
+ guard FileManager.default.fileExists(atPath: source.path) else { return }
+ guard !destination.path.hasPrefix(source.path + "/"), !source.path.hasPrefix(destination.path + "/") else {
+ throw ImportError("History source and destination must be separate directories.")
+ }
+ guard let sourceLock = try ConversationStoreLock.acquire(storeRoot: source) else {
+ throw ImportError("Close the app using the legacy history before importing it.")
+ }
+ let destinationLock: ConversationStoreLock?
+ if destinationAlreadyLocked { destinationLock = nil } else {
+ guard let lock = try ConversationStoreLock.acquire(storeRoot: destination) else {
+ throw ImportError("Close the other app using the destination history before importing it.")
+ }
+ destinationLock = lock
+ }
+ defer { withExtendedLifetime((sourceLock, destinationLock)) {} }
+ let manager = FileManager.default
+ let staging = destination.appendingPathComponent(".history-import", isDirectory: true)
+ let journalURL = destination.appendingPathComponent(".history-import.json")
+ try recover(at: destination, destinationAlreadyLocked: true)
+ if manager.fileExists(atPath: staging.path) { try manager.removeItem(at: staging) }
+ try manager.createDirectory(at: staging, withIntermediateDirectories: false)
+ var journal = Journal(source: source.path, fingerprints: [:])
+ do {
+ var required: Int64 = 0
+ let conversations = try manager.contentsOfDirectory(at: source, includingPropertiesForKeys: nil)
+ .filter { UUID(uuidString: $0.lastPathComponent) != nil }
+ // Verify every collision before publishing any conversation.
+ for conversation in conversations {
+ let name = conversation.lastPathComponent
+ let files = try fingerprint(conversation)
+ let existing = destination.appendingPathComponent(name)
+ if manager.fileExists(atPath: existing.path) {
+ guard try fingerprint(existing) == files else {
+ throw ImportError("History contains a conflicting conversation ID \(name). Import into a separate app-data root or resolve the conflict first.")
+ }
+ continue
+ }
+ for path in files.keys {
+ let values = try conversation.appendingPathComponent(path).resourceValues(forKeys: [.fileSizeKey])
+ required += Int64(values.fileSize ?? 0)
+ }
+ journal.fingerprints[name] = files
+ }
+ let available = try destination.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
+ .volumeAvailableCapacityForImportantUsage
+ guard let available, available >= required else { throw ImportError("Insufficient free space to import history on the app-data volume.") }
+ for (name, expected) in journal.fingerprints {
+ let copied = staging.appendingPathComponent(name)
+ try manager.copyItem(at: source.appendingPathComponent(name), to: copied)
+ guard try fingerprint(copied) == expected else { throw ImportError("History copy verification failed for \(name).") }
+ try makeDurable(copied, files: expected.keys)
+ }
+ try Posix.fsyncDirectory(staging.path)
+ try Posix.atomicWrite(JSONEncoder().encode(journal), to: journalURL.path, durableIn: destination.path)
+ for name in journal.fingerprints.keys.sorted() {
+ try manager.moveItem(at: staging.appendingPathComponent(name), to: destination.appendingPathComponent(name))
+ try afterPublish?()
+ }
+ try Posix.fsyncDirectory(staging.path)
+ try Posix.fsyncDirectory(destination.path)
+ // Completion is durable before abandoning the journal. Exact duplicates
+ // are verified again if settings persistence fails after this point.
+ let receipt = destination.appendingPathComponent(".history-import-completed.json")
+ try Posix.atomicWrite(JSONEncoder().encode(journal), to: receipt.path, durableIn: destination.path)
+ try manager.removeItem(at: journalURL)
+ try manager.removeItem(at: staging)
+ try Posix.fsyncDirectory(destination.path)
+ } catch {
+ if manager.fileExists(atPath: journalURL.path) {
+ do {
+ for (name, expected) in journal.fingerprints {
+ let published = destination.appendingPathComponent(name)
+ if manager.fileExists(atPath: published.path) {
+ guard try fingerprint(published) == expected else {
+ throw ImportError("Published conversation changed during rollback: \(name)")
+ }
+ try manager.removeItem(at: published)
+ }
+ }
+ try manager.removeItem(at: journalURL)
+ try manager.removeItem(at: staging)
+ } catch let rollbackError {
+ throw ImportError("History import failed: \(error); rollback also failed: \(rollbackError). Originals and the recovery journal were preserved.")
+ }
+ }
+ throw ImportError("History import failed; originals were preserved: \(error)")
+ }
+ }
+
+ /// Recovery needs only the destination lock: the source drive may have
+ /// disconnected since publication, while originals remain on that drive.
+ static func recover(at destination: URL, destinationAlreadyLocked: Bool = false) throws {
+ let journalURL = destination.appendingPathComponent(".history-import.json")
+ guard try Posix.entryKind(journalURL.path) != .absent else { return }
+ guard try Posix.entryKind(destination.path) == .directory else {
+ throw ImportError("History recovery refuses a symlink or special-file store root.")
+ }
+ let lock: ConversationStoreLock?
+ if destinationAlreadyLocked { lock = nil } else {
+ guard let acquired = try ConversationStoreLock.acquire(storeRoot: destination) else {
+ throw ImportError("Close the other app using history before recovering an interrupted import.")
+ }
+ lock = acquired
+ }
+ defer { withExtendedLifetime(lock) {} }
+ let manager = FileManager.default
+ let journal = try JSONDecoder().decode(Journal.self, from: Data(contentsOf: journalURL))
+ // Verify the entire rollback before removing anything, retaining changed
+ // records and the journal when manual recovery is required.
+ for (name, expected) in journal.fingerprints {
+ guard UUID(uuidString: name) != nil else { throw ImportError("Invalid history import journal.") }
+ let published = destination.appendingPathComponent(name)
+ if manager.fileExists(atPath: published.path), try fingerprint(published) != expected {
+ throw ImportError("Interrupted import contains changed conversation \(name); preserve it and recover manually.")
+ }
+ }
+ for name in journal.fingerprints.keys {
+ let published = destination.appendingPathComponent(name)
+ if manager.fileExists(atPath: published.path) { try manager.removeItem(at: published) }
+ }
+ let staging = destination.appendingPathComponent(".history-import")
+ if manager.fileExists(atPath: staging.path) { try manager.removeItem(at: staging) }
+ try manager.removeItem(at: journalURL)
+ try Posix.fsyncDirectory(destination.path)
+ }
+
+ private static func makeDurable(_ root: URL, files: Dictionary<String, String>.Keys) throws {
+ var directories: Set<URL> = [root]
+ for relative in files {
+ let file = root.appendingPathComponent(relative)
+ let descriptor = try Posix.openReadNoFollow(file.path)
+ do { try Posix.fsync(descriptor, path: file.path) }
+ catch { Darwin.close(descriptor); throw error }
+ Darwin.close(descriptor)
+ var parent = file.deletingLastPathComponent()
+ while parent.pathComponents.count >= root.pathComponents.count {
+ directories.insert(parent)
+ if parent == root { break }
+ parent.deleteLastPathComponent()
+ }
+ }
+ for directory in directories.sorted(by: { $0.pathComponents.count > $1.pathComponents.count }) {
+ try Posix.fsyncDirectory(directory.path)
+ }
+ }
+
+ private static func fingerprint(_ root: URL) throws -> [String: String] {
+ guard try Posix.entryKind(root.standardizedFileURL.path) == .directory else {
+ throw ImportError("History conversation is not a regular directory: \(root.path).")
+ }
+ let root = root.standardizedFileURL.resolvingSymlinksInPath()
+ let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey]
+ var enumerationError: Error?
+ guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys,
+ errorHandler: { _, error in enumerationError = error; return false }) else {
+ throw ImportError("Cannot enumerate history at \(root.path).")
+ }
+ var result: [String: String] = [:]
+ for case let url as URL in enumerator {
+ let values = try url.resourceValues(forKeys: Set(keys))
+ guard values.isSymbolicLink != true else { throw ImportError("History import refuses symlinks: \(url.path).") }
+ if values.isDirectory == true { continue }
+ guard values.isRegularFile == true else { throw ImportError("History import refuses special files: \(url.path).") }
+ let components = url.standardizedFileURL.resolvingSymlinksInPath().pathComponents
+ guard components.starts(with: root.pathComponents), components.count > root.pathComponents.count else {
+ throw ImportError("History file escaped the source directory: \(url.path)")
+ }
+ let relative = components.dropFirst(root.pathComponents.count).joined(separator: "/")
+ result[relative] = try Sha256Verifier.hashFile(at: url, chunkBytes: 65_536)
+ }
+ if let enumerationError { throw enumerationError }
+ guard result["conversation.json"] != nil, result["transcript.jsonl"] != nil else {
+ throw ImportError("History conversation is incomplete: \(root.path); files=\(result.keys.sorted()).")
+ }
+ return result
+ }
+
+ struct ImportError: Error, CustomStringConvertible {
+ let description: String
+ init(_ description: String) { self.description = description }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
index 60bf6208..6db9c588 100644
--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
@@ -1,11 +1,14 @@
import Foundation
import TurboFieldfare
+import TurboFieldfareRepackCore
struct MacAppSettings: Codable, Equatable, Sendable {
static let fileName = "mac-app-settings.json"
- static let currentVersion = 3
+ static let currentVersion = 4
var version: Int = currentVersion
+ var selectedModelPath: String?
+ var migratedHistorySources: [String] = []
var contextTokens: Int = AppContextLengthOption.eightK.tokens
var expertCacheSlots: Int = 16
var temperature: Double = 0.2
@@ -30,6 +33,8 @@ struct MacAppSettings: Codable, Equatable, Sendable {
private enum CodingKeys: String, CodingKey {
case version
+ case selectedModelPath
+ case migratedHistorySources
case contextTokens
case expertCacheSlots
case temperature
@@ -49,6 +54,8 @@ struct MacAppSettings: Codable, Equatable, Sendable {
}
init(version: Int = currentVersion,
+ selectedModelPath: String? = nil,
+ migratedHistorySources: [String] = [],
contextTokens: Int = AppContextLengthOption.eightK.tokens,
expertCacheSlots: Int = 16,
temperature: Double = 0.2,
@@ -66,6 +73,8 @@ struct MacAppSettings: Codable, Equatable, Sendable {
rdadvisePolicy: AppRDAdvicePolicy = .off,
loadModelOnLaunch: Bool = false) {
self.version = version
+ self.selectedModelPath = selectedModelPath
+ self.migratedHistorySources = migratedHistorySources
self.contextTokens = contextTokens
self.expertCacheSlots = expertCacheSlots
self.temperature = temperature
@@ -87,6 +96,8 @@ struct MacAppSettings: Codable, Equatable, Sendable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
version = try container.decode(Int.self, forKey: .version)
+ selectedModelPath = try container.decodeIfPresent(String.self, forKey: .selectedModelPath)
+ migratedHistorySources = try container.decodeIfPresent([String].self, forKey: .migratedHistorySources) ?? []
contextTokens = try container.decode(Int.self, forKey: .contextTokens)
expertCacheSlots = try container.decode(Int.self, forKey: .expertCacheSlots)
temperature = try container.decode(Double.self, forKey: .temperature)
@@ -102,7 +113,7 @@ struct MacAppSettings: Codable, Equatable, Sendable {
Bool.self,
forKey: .showPromptExamples) ?? true
// A damaged appearance preference must not reach settings-wide recovery,
- // which discards the file and would reset unrelated runtime choices.
+ // which disables settings writes and requires explicit recovery.
// Foundation can throw a non-DecodingError for a fractional integer.
if container.contains(.textSize) {
do {
@@ -133,8 +144,10 @@ struct MacAppSettings: Codable, Equatable, Sendable {
forKey: .loadModelOnLaunch) ?? false
}
+ /// Schema routing happens before decoding; value validation never replaces a damaged file.
func isValid() -> Bool {
- AppContextLengthOption.allCases.contains { $0.tokens == contextTokens }
+ (selectedModelPath.map { $0.hasPrefix("/") && !$0.contains("\0") } ?? true)
+ && AppContextLengthOption.allCases.contains { $0.tokens == contextTokens }
&& AppRuntimeOptions.allowedSlotCounts.contains(expertCacheSlots)
&& temperature.isFinite && (0...2).contains(temperature)
&& (1...256).contains(topK)
@@ -155,54 +168,62 @@ enum MacAppSettingsFileStore {
.appendingPathComponent(MacAppSettings.fileName, isDirectory: false)
}
+ static func load(at fileURL: URL) throws -> MacAppSettings? {
+ guard FileManager.default.fileExists(atPath: fileURL.path) else { return nil }
+ let data = try Data(contentsOf: fileURL)
+ let stamp = try JSONDecoder().decode(VersionStamp.self, from: data)
+ guard stamp.version <= MacAppSettings.currentVersion else {
+ throw SettingsError.unsupportedVersion(stamp.version)
+ }
+ var settings = try JSONDecoder().decode(MacAppSettings.self, from: data)
+ guard settings.isValid() else { throw SettingsError.invalidValues }
+ settings.version = MacAppSettings.currentVersion
+ if let path = settings.selectedModelPath {
+ settings.selectedModelPath = URL(fileURLWithPath: path).standardizedFileURL.path
+ }
+ return settings
+ }
+
static func loadOrCreate(forModelDirectory modelDirectory: URL,
fileManager: FileManager = .default) -> MacAppSettings {
- let fileURL = fileURL(forModelDirectory: modelDirectory)
- if fileManager.fileExists(atPath: fileURL.path) {
- do {
- let data = try Data(contentsOf: fileURL)
- // The version is read on its own, before the full decode, because
- // nine keys decode with a hard `decode` and a newer build is
- // entitled to have moved any of them. Decoding first threw on
- // exactly the files this branch exists to protect, and the throw
- // reached the `catch` below, which deletes the file - so an older
- // build silently replaced a newer one's settings with its own
- // defaults. A version gate that cannot survive a schema change
- // gates nothing.
- let stamp = try JSONDecoder().decode(VersionStamp.self, from: data)
- // This build does not know what a later version means, so it runs
- // on defaults and leaves the file exactly as its owner wrote it.
- guard stamp.version <= MacAppSettings.currentVersion else {
- return MacAppSettings()
- }
- var settings = try JSONDecoder().decode(MacAppSettings.self, from: data)
- let needsMigration = settings.version < MacAppSettings.currentVersion
- if needsMigration {
- // Version only: every existing value is still a deliberate
- // choice, and rewriting one here would silently discard it.
- settings.version = MacAppSettings.currentVersion
- }
- guard settings.isValid() else { throw InvalidSettings() }
- if needsMigration {
- try? save(settings, forModelDirectory: modelDirectory,
- fileManager: fileManager)
+ do {
+ if let settings = try load(at: fileURL(forModelDirectory: modelDirectory)) {
+ let original = try JSONDecoder().decode(VersionStamp.self, from: Data(contentsOf: fileURL(forModelDirectory: modelDirectory)))
+ if original.version < MacAppSettings.currentVersion {
+ try save(settings, forModelDirectory: modelDirectory, fileManager: fileManager)
}
return settings
- } catch {
- try? fileManager.removeItem(at: fileURL)
}
+ let settings = MacAppSettings()
+ try save(settings, forModelDirectory: modelDirectory, fileManager: fileManager)
+ return settings
+ } catch {
+ FileHandle.standardError.write(Data("Reading Mac app settings failed: \(error)\n".utf8))
+ return MacAppSettings()
}
+ }
- let settings = MacAppSettings()
- try? save(settings, forModelDirectory: modelDirectory, fileManager: fileManager)
- return settings
+ enum SettingsError: Error, CustomStringConvertible {
+ case unsupportedVersion(Int)
+ case invalidValues
+ var description: String {
+ switch self {
+ case .unsupportedVersion(let version): "Settings version \(version) requires a newer app. The original file was preserved."
+ case .invalidValues: "Settings contain invalid values. The original file was preserved."
+ }
+ }
}
static func save(_ settings: MacAppSettings,
forModelDirectory modelDirectory: URL,
fileManager: FileManager = .default) throws {
- guard settings.isValid() else { throw InvalidSettings() }
- let fileURL = fileURL(forModelDirectory: modelDirectory)
+ guard settings.isValid() else { throw SettingsError.invalidValues }
+ try save(settings, at: fileURL(forModelDirectory: modelDirectory), fileManager: fileManager)
+ }
+
+ static func save(_ settings: MacAppSettings, at fileURL: URL,
+ fileManager: FileManager = .default) throws {
+ guard settings.isValid() else { throw SettingsError.invalidValues }
try fileManager.createDirectory(
at: fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true)
@@ -210,8 +231,9 @@ enum MacAppSettingsFileStore {
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
var data = try encoder.encode(settings)
data.append(0x0A)
- try data.write(to: fileURL, options: .atomic)
+ try Posix.atomicWrite(data, to: fileURL.path,
+ durableIn: fileURL.deletingLastPathComponent().path,
+ uniqueTemporary: true)
}
- private struct InvalidSettings: Error {}
}
diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift
index 140d7b5a..a96940df 100644
--- a/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift
+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift
@@ -93,8 +93,7 @@ struct ConversationStoreListOperations: Sendable {
let beforeList: @Sendable () async -> Void
}
-/// The conversation store: a directory of plain-text conversations beside the
-/// settings and the model.
+/// The conversation store: plain-text conversations under the stable app-data root.
///
/// One directory per conversation, because that makes delete an `rm -rf`, makes
/// a corrupt conversation one skippable directory rather than a broken store,
@@ -219,6 +218,11 @@ public actor ConversationStore {
return nil
}
+ func importLegacyHistory(from source: URL) throws {
+ try requireWritable()
+ try ConversationStoreImport.run(from: source, to: rootURL, destinationAlreadyLocked: true)
+ }
+
public var isReadOnly: Bool { lock == nil }
public func directoryURL(for id: UUID) -> URL {
diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift
index 62ab3430..2d4891b0 100644
--- a/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift
+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift
@@ -1,7 +1,7 @@
import Foundation
import TurboFieldfare
-/// The conversation store and model identity belonging to one model path.
+/// One app-data store with the identity of the currently selected model.
///
/// Async store work captures the generation and must prove it is still current
/// before changing UI state. A path switch can otherwise let a slow list or
@@ -13,15 +13,16 @@ struct ConversationStoreBinding: Sendable {
var identity: ConversationIdentity?
let generation: UInt64
- init(modelDirectory: URL, identity: ConversationIdentity?, generation: UInt64,
+ init(modelDirectory: URL, appDataDirectory: URL? = nil, store: ConversationStore? = nil, identity: ConversationIdentity?, generation: UInt64,
storeProvider: @Sendable (URL) -> ConversationStore = {
ConversationStore(rootURL: $0)
}) {
let modelDirectory = modelDirectory.standardizedFileURL
self.modelDirectory = modelDirectory
- self.rootURL = ConversationStoreLocation.url(forModelDirectory: modelDirectory)
+ self.rootURL = appDataDirectory.map { ConversationStoreLocation.url(forAppDataDirectory: $0) }
+ ?? ConversationStoreLocation.url(forModelDirectory: modelDirectory)
.standardizedFileURL
- self.store = storeProvider(rootURL)
+ self.store = store ?? storeProvider(rootURL)
self.identity = identity
self.generation = generation
}
diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift
index 3d087029..301a943a 100644
--- a/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift
+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift
@@ -1,12 +1,5 @@
import Foundation
-/// Where conversations live: beside the settings file and the model, one
-/// directory per conversation.
-///
-/// The same derivation as `mac-app-settings.json`, deliberately. One location
-/// rule is the whole point: an installed app puts both under Application
-/// Support, a dev checkout puts both under `scratch/`, and moving the model with
-/// `TURBO_FIELDFARE_MODEL_PATH` moves both together.
public enum ConversationStoreLocation {
public static let directoryName = "conversations"
@@ -16,6 +9,14 @@ public enum ConversationStoreLocation {
.appendingPathComponent(directoryName, isDirectory: true)
}
+ public static func url(forAppDataDirectory root: URL) -> URL {
+ root.standardizedFileURL.appendingPathComponent(directoryName, isDirectory: true)
+ }
+
+ public static func contains(_ fileURL: URL, forAppDataDirectory appDataDirectory: URL) -> Bool {
+ contains(fileURL, root: url(forAppDataDirectory: appDataDirectory))
+ }
+
/// Whether `fileURL` names something inside the store for this model.
///
/// The decode service is handed image paths over a socket and opens
@@ -25,10 +26,13 @@ public enum ConversationStoreLocation {
/// a strict path-component prefix, so `.../conversations-elsewhere` cannot
/// pass as `.../conversations`.
public static func contains(_ fileURL: URL, forModelDirectory modelDirectory: URL) -> Bool {
+ contains(fileURL, root: url(forModelDirectory: modelDirectory))
+ }
+
+ private static func contains(_ fileURL: URL, root: URL) -> Bool {
guard fileURL.isFileURL else { return false }
let resolved = fileURL.standardizedFileURL.resolvingSymlinksInPath()
- let root = url(forModelDirectory: modelDirectory)
- .standardizedFileURL.resolvingSymlinksInPath()
+ let root = root.standardizedFileURL.resolvingSymlinksInPath()
let fileComponents = resolved.pathComponents
let rootComponents = root.pathComponents
guard fileComponents.count > rootComponents.count else { return false }
diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
index 3925d2da..ae349fc1 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
@@ -30,6 +30,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
public static let conversationRestoreTimeout: Duration = .seconds(1_800)
private let connection = Mutex(Connection())
+ private let appDataDirectory: URL
private let serviceURL: URL
private let testConnection: (@Sendable () throws -> (input: FileHandle, output: FileHandle))?
private let inferenceMemory = Mutex<UInt64?>(nil)
@@ -44,13 +45,15 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
inferenceTowerMemory.withLock { $0 }
}
- public init(serviceURL: URL? = nil) {
+ public init(serviceURL: URL? = nil, appDataDirectory: URL = AppDataLocation.resolve()) {
+ self.appDataDirectory = appDataDirectory.standardizedFileURL
self.serviceURL = serviceURL ?? Self.defaultServiceURL()
self.testConnection = nil
DecodeUnixSocket.ignoreSIGPIPEProcessWide()
}
init(testInput: FileHandle, responseOutput: FileHandle) {
+ self.appDataDirectory = AppDataLocation.resolve()
self.serviceURL = Self.defaultServiceURL()
self.testConnection = nil
DecodeUnixSocket.ignoreSIGPIPEProcessWide()
@@ -66,6 +69,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
}
init(testConnection: @escaping @Sendable () throws -> (input: FileHandle, output: FileHandle)) {
+ self.appDataDirectory = AppDataLocation.resolve()
self.serviceURL = Self.defaultServiceURL()
self.testConnection = testConnection
DecodeUnixSocket.ignoreSIGPIPEProcessWide()
@@ -449,6 +453,10 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
return try launchIndependentService()
}
+ static func appDataArguments(_ root: URL) -> [String] {
+ ["--app-data-directory", root.standardizedFileURL.path]
+ }
+
private func launchIndependentService() throws
-> (input: FileHandle, responses: DecodeServiceResponseRouter) {
guard FileManager.default.isExecutableFile(atPath: serviceURL.path) else {
@@ -467,7 +475,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
serviceURL.path,
"--socket", socketPath,
"--launch-label", label,
- ],
+ ] + Self.appDataArguments(appDataDirectory),
"RunAtLoad": true,
"KeepAlive": false,
"ProcessType": "Interactive",
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
index 26e00f41..7973d5c0 100644
--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
@@ -73,6 +73,7 @@ public struct AppModelInstallRequirement: Equatable, Sendable {
}
public enum AppModelInstallReadiness: Equatable, Sendable {
+ case installed
case checking
case ready(AppModelInstallRequirement)
case insufficientSpace(AppModelInstallRequirement)
@@ -82,7 +83,7 @@ public enum AppModelInstallReadiness: Equatable, Sendable {
switch self {
case .ready(let requirement), .insufficientSpace(let requirement):
return requirement
- case .checking, .failed:
+ case .installed, .checking, .failed:
return nil
}
}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift
index 7f8f44a3..9bf5340a 100644
--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift
@@ -1,7 +1,9 @@
import Foundation
+import TurboFieldfareRepackCore
enum AppModelLocation {
- static func defaultURL() -> URL {
+ static func defaultURL(environment: [String: String] = ProcessInfo.processInfo.environment,
+ persistedPath: String? = nil) -> URL {
let fileManager = FileManager.default
let applicationSupport = (try? fileManager.url(
for: .applicationSupportDirectory,
@@ -10,6 +12,8 @@ enum AppModelLocation {
create: false)) ?? fileManager.homeDirectoryForCurrentUser
return resolve(
explicitURL: nil,
+ environment: environment,
+ persistedPath: persistedPath,
executableURL: Bundle.main.executableURL,
currentDirectoryURL: URL(fileURLWithPath: fileManager.currentDirectoryPath,
isDirectory: true),
@@ -18,6 +22,8 @@ enum AppModelLocation {
}
static func resolve(explicitURL: URL?,
+ environment: [String: String] = [:],
+ persistedPath: String? = nil,
executableURL: URL?,
currentDirectoryURL: URL,
applicationSupportURL: URL,
@@ -25,6 +31,16 @@ enum AppModelLocation {
if let explicitURL {
return absoluteURL(explicitURL, relativeTo: currentDirectoryURL)
}
+ if let path = environment["TURBO_FIELDFARE_MODEL_PATH"], !path.isEmpty {
+ if path.hasPrefix("/") {
+ return URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL
+ }
+ return currentDirectoryURL.appendingPathComponent(path, isDirectory: true)
+ .standardizedFileURL
+ }
+ if let persistedPath {
+ return URL(fileURLWithPath: persistedPath, isDirectory: true).standardizedFileURL
+ }
if let executableURL,
let root = packageRoot(startingAt: executableURL.deletingLastPathComponent(),
fileExists: fileExists) {
@@ -41,6 +57,67 @@ enum AppModelLocation {
.standardizedFileURL
}
+ static func canonicalURL(_ url: URL) -> URL {
+ let url = url.standardizedFileURL
+ // The final .gturbo child may not exist yet. Resolve its existing parent
+ // first, since Foundation otherwise leaves parent aliases unresolved.
+ return url.deletingLastPathComponent().resolvingSymlinksInPath()
+ .appendingPathComponent(url.lastPathComponent, isDirectory: true)
+ .resolvingSymlinksInPath()
+ }
+
+ static func validate(_ candidate: URL, intent: AppModel.ModelLocationIntent) throws {
+ let candidate = canonicalURL(candidate)
+ guard isVolumeAvailable(for: candidate) else {
+ throw LocationError("The selected volume is unavailable. Reconnect it and retry, or choose another location.")
+ }
+ switch intent {
+ case .existing:
+ guard candidate.pathExtension == "gturbo" else {
+ let child = candidate.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ if AppModelInstallationProbe.status(at: child) == .complete {
+ throw LocationError("Choose the gemma4.gturbo folder inside this folder. The vision pack is found beside it automatically.")
+ }
+ throw LocationError("Choose a completed text model folder ending in .gturbo (for example, gemma4.gturbo). Select the model folder itself, not its parent or the vision pack.")
+ }
+ switch AppModelInstallationProbe.status(at: candidate) {
+ case .complete: break
+ case .missing: throw LocationError("The selected directory has no completed manifest.json.")
+ case .partial(let reason): throw LocationError("The selected installation is incompatible or incomplete: \(reason)")
+ }
+ case .download:
+ let parent = candidate.deletingLastPathComponent()
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: parent.path, isDirectory: &isDirectory), isDirectory.boolValue,
+ FileManager.default.isWritableFile(atPath: parent.path) else {
+ throw LocationError("The download parent directory must exist and be writable.")
+ }
+ if FileManager.default.fileExists(atPath: candidate.path) {
+ guard AppModelInstallationProbe.status(at: candidate) == .complete else {
+ throw LocationError("The destination already exists and is not a supported completed model. Choose another parent directory.")
+ }
+ }
+ _ = try RemoteStreamingRepacker.inspectPersistentInstall(
+ outputDirectory: candidate.path, repoID: AppModelInstallDescriptor.default.repoID,
+ requestedRevision: AppModelInstallDescriptor.default.revision)
+ }
+ }
+
+ static func isVolumeAvailable(for url: URL) -> Bool {
+ let components = url.standardizedFileURL.pathComponents
+ if components.count > 2, components[1] == "Volumes" {
+ var isDirectory: ObjCBool = false
+ let volume = "/Volumes/" + components[2]
+ return FileManager.default.fileExists(atPath: volume, isDirectory: &isDirectory) && isDirectory.boolValue
+ }
+ return true
+ }
+
+ struct LocationError: Error, CustomStringConvertible {
+ let description: String
+ init(_ description: String) { self.description = description }
+ }
+
private static func absoluteURL(_ url: URL, relativeTo base: URL) -> URL {
if url.path.hasPrefix("/") {
return url.standardizedFileURL
diff --git a/Sources/TurboFieldfareApp/Core/Installation/ExistingModelSelection.swift b/Sources/TurboFieldfareApp/Core/Installation/ExistingModelSelection.swift
new file mode 100644
index 00000000..77357c79
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Installation/ExistingModelSelection.swift
@@ -0,0 +1,77 @@
+import Foundation
+import TurboFieldfare
+
+public struct ExistingModelCandidate: Identifiable, Equatable, Sendable {
+ public var id: String { textURL.path }
+ public let textURL: URL
+ public let textStatus: AppModelInstallationStatus
+ public let visionURL: URL
+ public let visionStatus: AppVisionPackInstallationStatus
+ public var canSelect: Bool { textStatus == .complete }
+
+ public var textSummary: String {
+ switch textStatus {
+ case .complete: "Text model ready"
+ case .missing: "Incomplete text model: manifest.json is missing."
+ case .partial(let reason): "Text model unavailable: \(reason)"
+ }
+ }
+
+ public var visionSummary: String {
+ switch visionStatus {
+ case .complete: "Image support ready"
+ case .missing: "Text only — no matching vision pack found"
+ case .partial(let reason): "Text only — vision pack is invalid or incompatible: \(reason)"
+ case .unsupportedLayout: "Text only — this folder name cannot locate a vision pack"
+ }
+ }
+}
+
+public struct ExistingModelReview: Identifiable, Sendable {
+ public let id = UUID()
+ public let folder: URL
+ public let candidates: [ExistingModelCandidate]
+ public var initialSelection: String? {
+ candidates.count == 1 && candidates[0].canSelect ? candidates[0].id : nil
+ }
+}
+
+public enum ExistingModelSelection {
+ public static func inspect(_ folder: URL) throws -> ExistingModelReview {
+ let folder = AppModelLocation.canonicalURL(folder)
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: folder.path, isDirectory: &isDirectory), isDirectory.boolValue else {
+ throw AppModelLocation.LocationError("The selected folder is unavailable: \(folder.path)")
+ }
+ if folder.lastPathComponent.hasSuffix(".vision.gturbo") {
+ throw AppModelLocation.LocationError("This is a vision pack. Choose its parent folder or the text model folder beside it.")
+ }
+ let urls: [URL]
+ if folder.pathExtension == "gturbo" {
+ urls = [folder]
+ } else {
+ urls = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey])
+ .filter { url in
+ guard url.pathExtension == "gturbo", !url.lastPathComponent.hasSuffix(".vision.gturbo") else { return false }
+ let target = AppModelLocation.canonicalURL(url)
+ guard target.pathExtension == "gturbo",
+ !target.lastPathComponent.hasSuffix(".vision.gturbo") else { return false }
+ return try target.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true
+ }
+ }
+ // Aliases to the same pack must not manufacture an ambiguous choice.
+ let unique = Set(urls.map(AppModelLocation.canonicalURL)).sorted { $0.path < $1.path }
+ guard !unique.isEmpty else {
+ throw AppModelLocation.LocationError("No text model folders found directly inside \(folder.path). Choose a folder containing a completed .gturbo text model; a vision pack alone is not enough.")
+ }
+ return ExistingModelReview(folder: folder, candidates: try unique.map(candidate))
+ }
+
+ public static func candidate(at textURL: URL) throws -> ExistingModelCandidate {
+ let textURL = AppModelLocation.canonicalURL(textURL)
+ return ExistingModelCandidate(textURL: textURL,
+ textStatus: AppModelInstallationProbe.status(at: textURL),
+ visionURL: try VisionPackLocation.companionURL(forTextModel: textURL),
+ visionStatus: AppVisionPackInstallationProbe.status(at: textURL))
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
index af302286..a436376f 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
@@ -24,6 +24,26 @@ public final class AppModel {
case rewound
}
+ public let appDataDirectory: URL
+ public let isModelLocationOverridden: Bool
+ public private(set) var isModelChoiceRequired: Bool
+ public private(set) var settingsDiagnostic: String?
+ public let canResetSettings: Bool
+ public private(set) var isChangingModelLocation = false
+ public var existingModelReview: ExistingModelReview?
+ public private(set) var isInspectingModelLocation = false
+ public private(set) var modelLocationDiagnostic: String? {
+ didSet {
+ if let message = modelLocationDiagnostic {
+ error = .invalidRequest(message)
+ } else if let oldValue, error == .invalidRequest(oldValue) {
+ error = nil
+ }
+ }
+ }
+ private var settingsWritesAllowed: Bool
+ private var savedModelPath: String?
+ private var migratedHistorySources: [String]
public var modelPathText: String
public var promptText: String = ""
public private(set) var imageAttachments: [StagedImage] = []
@@ -221,6 +241,8 @@ public final class AppModel {
}
public init(modelDirectory: URL? = nil,
+ appDataDirectory: URL? = nil,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
client: any AppInferenceClient = RealInferenceClient(),
installer: any AppModelInstallerClient = RepackModelInstallerClient(),
visionInstaller: any AppVisionPackInstallerClient = RepackVisionPackInstallerClient(),
@@ -235,11 +257,30 @@ public final class AppModel {
ConversationStore(rootURL: $0)
},
hostMemoryBytes: UInt64 = ContextAdmission.hostMemoryBytes) {
- let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURL
+ let dataRoot = AppDataLocation.resolve(explicitURL: appDataDirectory, environment: environment)
+ let defaultModel = environment["TURBO_FIELDFARE_APP_DATA_PATH"] != nil
+ ? dataRoot.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ : AppModelLocation.defaultURL(environment: environment)
+ let legacy = (modelDirectory ?? defaultModel).standardizedFileURL
+ let bootstrap = AppDataBootstrap(root: dataRoot, legacyModel: legacy,
+ environment: environment, modelOverride: modelDirectory != nil, enabled: settingsPersistenceEnabled)
+ let settings = bootstrap.settings
+ let directory: URL
+ if let modelDirectory { directory = modelDirectory.standardizedFileURL }
+ else if let override = environment["TURBO_FIELDFARE_MODEL_PATH"], !override.isEmpty {
+ directory = URL(fileURLWithPath: override, isDirectory: true).standardizedFileURL
+ } else if let saved = settings.selectedModelPath {
+ directory = URL(fileURLWithPath: saved, isDirectory: true).standardizedFileURL
+ } else { directory = defaultModel.standardizedFileURL }
+ self.appDataDirectory = dataRoot
+ self.isModelLocationOverridden = modelDirectory != nil || !(environment["TURBO_FIELDFARE_MODEL_PATH"] ?? "").isEmpty
+ self.isModelChoiceRequired = bootstrap.modelChoiceRequired
+ self.settingsDiagnostic = bootstrap.failure
+ self.canResetSettings = settingsPersistenceEnabled && bootstrap.canResetSettings
+ self.settingsWritesAllowed = bootstrap.failure == nil
+ self.savedModelPath = settings.selectedModelPath
+ self.migratedHistorySources = settings.migratedHistorySources
let installETAClock = SuspendingClock()
- let settings = settingsPersistenceEnabled
- ? MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)
- : MacAppSettings()
self.modelPathText = directory.path
// The app always releases the image tower after each image. Keeping it
// resident saves a few hundred milliseconds on a run of images and
@@ -299,6 +340,7 @@ public final class AppModel {
}
conversationBinding = ConversationStoreBinding(
modelDirectory: directory,
+ appDataDirectory: dataRoot,
identity: identity,
generation: conversationBindingGeneration,
storeProvider: conversationStoreProvider)
@@ -376,7 +418,8 @@ public final class AppModel {
// message it was carrying, and queued behind the prefill on the service
// until the load timeout killed the connection.
public var canLoadModel: Bool {
- isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
+ if isChangingModelLocation || isModelChoiceRequired { return false }
+ return isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
&& (loadState == .notLoaded || loadState.isFailed)
}
@@ -386,12 +429,12 @@ public final class AppModel {
}
public var canReloadModel: Bool {
- isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
+ !isChangingModelLocation && isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
&& loadState.isReady && hasStaleLoadedRuntime
}
public var canUnloadModel: Bool {
- isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
+ !isChangingModelLocation && isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress
&& loadState.isReady
}
@@ -408,6 +451,7 @@ public final class AppModel {
public var isInstallingModel: Bool { installState.isInstalling }
public var canInstallModel: Bool {
+ if isChangingModelLocation || isModelChoiceRequired || !isModelLocationAvailable { return false }
guard case .ready = installReadiness else { return false }
return !isRunning && !loadState.isLoading && !isInstallingModel
&& !isVisionCompanionOperationInProgress
@@ -439,7 +483,7 @@ public final class AppModel {
/// Pack activation, repair and removal mutate the runtime's files and need
/// an unloaded model. Payload download does not use this gate.
public var canBeginVisionCompanionOperation: Bool {
- !isRunning && !loadState.isLoading && !loadState.isReady
+ !isChangingModelLocation && !isRunning && !loadState.isLoading && !loadState.isReady
&& !isInstallingModel && !isVisionCompanionOperationInProgress
}
@@ -449,6 +493,7 @@ public final class AppModel {
}
public var canInstallVisionPack: Bool {
+ if isChangingModelLocation { return false }
guard isVisionRuntimeSupported else { return false }
// A layout with nowhere to put a companion cannot be repaired by
// downloading one, so do not offer to.
@@ -567,6 +612,7 @@ public final class AppModel {
}
public var canRun: Bool {
+ if isChangingModelLocation { return false }
// Staging copies the files a request will carry. Starting a run while
// it is in flight sent a request without those images and then landed
// them on the next message instead.
@@ -576,7 +622,7 @@ public final class AppModel {
// second replay, and whichever finished last defined the epoch, so the
// first one's request came back rejected as belonging to a conversation
// that was no longer open.
- !isTurnInFlight && conversationDeletionTask == nil
+ return !isTurnInFlight && conversationDeletionTask == nil
&& !isAddingImages && isModelAvailable && !loadState.isLoading
&& !isVisionFilesystemMutationInProgress
&& !hasStaleLoadedRuntime
@@ -613,14 +659,11 @@ public final class AppModel {
}
public var hasOutputTranscript: Bool {
- // Same split as `transcriptHistory`: while a stored copy is on screen,
- // the live conversation belongs to another chat and is not what decides
- // whether this one has anything to show. A stored chat with no readable
- // turns has to fall through to the empty state rather than borrow the
- // held conversation's.
+ // Keep the transcript layout during a disk read; a missing document
+ // is still loading, not an empty chat. Never borrow the held chat's turns.
switch screen {
- case .reading, .replaying:
- return !transcriptHistory.isEmpty
+ case .reading(_, let document, _, _), .replaying(_, let document, _, _):
+ return document == nil || !transcriptHistory.isEmpty
case .live, .unreadable:
return !conversation.outOfContextPairs.isEmpty
|| !conversation.isEmpty
@@ -816,58 +859,169 @@ public final class AppModel {
temperature != 0
}
- public func setModelURL(_ url: URL) {
- // Rebinding replaces the screen machine outright, so a replay in
- // flight would lose the message it is carrying.
- guard !isTurnInFlight else { return }
- let path = url.standardizedFileURL.path
- guard path != modelPathText else { return }
+ public var isModelLocationAvailable: Bool {
+ AppModelLocation.isVolumeAvailable(for: URL(fileURLWithPath: modelPathText))
+ }
+
+ public var canChangeModelLocation: Bool {
+ !isModelLocationOverridden && settingsWritesAllowed && !isChangingModelLocation && !isInspectingModelLocation
+ && !isTurnInFlight && !isInstallingModel && !isVisionCompanionOperationInProgress
+ && loadTask == nil && unloadTask == nil && !loadState.isLoading && !isAddingImages
+ && conversationDeletionTask == nil
+ }
+
+ public enum ModelLocationIntent: Sendable { case download, existing }
+
+ public func reviewExistingModelLocation(_ folder: URL) async {
+ guard canChangeModelLocation, existingModelReview == nil else { return }
+ isInspectingModelLocation = true
+ do {
+ let review = try await Task.detached { try ExistingModelSelection.inspect(folder) }.value
+ isInspectingModelLocation = false
+ guard canChangeModelLocation else {
+ modelLocationDiagnostic = "The model became busy. Try choosing the folder again when it finishes."
+ return
+ }
+ let valid = review.candidates.filter(\.canSelect)
+ guard !valid.isEmpty else {
+ let reasons = review.candidates.map { "\($0.textURL.lastPathComponent): \($0.textSummary)" }
+ modelLocationDiagnostic = "No usable text model found. " + reasons.joined(separator: "\n")
+ return
+ }
+ modelLocationDiagnostic = nil
+ if valid.count == 1 {
+ await selectModelLocation(valid[0].textURL, intent: .existing)
+ } else {
+ existingModelReview = review
+ }
+ } catch {
+ isInspectingModelLocation = false
+ modelLocationDiagnostic = "Could not inspect model folder: \(error)"
+ }
+ }
- modelPathText = path
+ public func confirmExistingModelSelection(_ candidate: ExistingModelCandidate) async -> Bool {
+ guard canChangeModelLocation, let review = existingModelReview,
+ review.candidates.contains(candidate), candidate.canSelect else { return false }
+ do {
+ let current = try ExistingModelSelection.candidate(at: candidate.textURL)
+ guard current == candidate else {
+ existingModelReview = try ExistingModelSelection.inspect(review.folder)
+ modelLocationDiagnostic = "The model files changed while you were choosing. Review their status again."
+ return false
+ }
+ await selectModelLocation(candidate.textURL, intent: .existing)
+ guard modelLocationDiagnostic == nil,
+ AppModelLocation.canonicalURL(URL(fileURLWithPath: modelPathText)) == candidate.textURL else { return false }
+ existingModelReview = nil
+ return true
+ } catch {
+ modelLocationDiagnostic = "Could not select model: \(error)"
+ return false
+ }
+ }
+
+ public func selectModelLocation(_ url: URL, intent: ModelLocationIntent) async {
+ guard canChangeModelLocation else { return }
+ let candidate = intent == .download
+ ? url.appendingPathComponent("gemma4.gturbo", isDirectory: true) : url
+ do {
+ try AppModelLocation.validate(candidate, intent: intent)
+ modelLocationDiagnostic = nil
+ await changeModelURL(candidate, persistSelection: true)
+ } catch {
+ modelLocationDiagnostic = "Could not select model location: \(error)"
+ }
+ }
+
+ /// Internal callers already validated their candidate; UI uses selectModelLocation.
+ public func setModelURL(_ url: URL) async {
+ guard !isTurnInFlight && !isInstallingModel && !isVisionCompanionOperationInProgress
+ && loadTask == nil && unloadTask == nil && !loadState.isLoading
+ && conversationDeletionTask == nil && !isChangingModelLocation else { return }
+ await changeModelURL(url, persistSelection: !isModelLocationOverridden)
+ }
+
+ private func changeModelURL(_ url: URL, persistSelection: Bool) async {
+ let directory = AppModelLocation.canonicalURL(url)
+ let sameDirectory = directory.path == AppModelLocation.canonicalURL(URL(fileURLWithPath: modelPathText)).path
+ let needsSelectionCommit = persistSelection && settingsPersistenceEnabled && savedModelPath == nil
+ guard !sameDirectory || needsSelectionCommit || isModelChoiceRequired else {
+ recheckModelAtCurrentLocation()
+ return
+ }
+ isChangingModelLocation = true
+ defer { isChangingModelLocation = false }
+ guard await awaitPendingPersistence(timeout: .seconds(30)) else {
+ modelLocationDiagnostic = "Pending chat writes did not settle. Retry when saving finishes."
+ return
+ }
+ if persistSelection, settingsPersistenceEnabled {
+ do {
+ var settings = currentSettings()
+ settings.selectedModelPath = directory.path
+ try MacAppSettingsFileStore.save(settings, at: AppDataLocation.settingsURL(in: appDataDirectory))
+ savedModelPath = directory.path
+ settingsDiagnostic = nil
+ } catch {
+ modelLocationDiagnostic = "Could not save model location; previous selection retained: \(error)"
+ return
+ }
+ }
+ // A rejected settings write must leave the active runtime and chat intact.
+ if let lifecycle = client as? AppModelLifecycleClient { await lifecycle.unload() }
+ loadedRuntimeKey = nil
+ loadState = .notLoaded
+ endConversationForReleasedKV()
+ modelPathText = directory.path
+ runIdentity &+= 1
+ isModelChoiceRequired = false
clearImages()
- applyPersistedSettings(
- forModelDirectory: URL(fileURLWithPath: path, isDirectory: true))
loadGeneration &+= 1
- loadTask?.cancel()
- loadTask = nil
installGeneration &+= 1
- installTask?.cancel()
- installer.cancel()
- installTask = nil
visionInstallGeneration &+= 1
- visionInstallCancellationRequested = false
- visionInstallTask?.cancel()
- visionInstaller.cancel()
- visionInstallTask = nil
- resetInstallETA()
installState = .idle
visionInstallState = .idle
- pendingExplicitLoadRuntimeKey = nil
- activeRunRuntimeKey = nil
- loadedRuntimeKey = nil
- loadState = .notLoaded
- endConversationForReleasedKV()
+ resetInstallETA()
diagnostics = nil
error = nil
phase = .idle
- installationStatus = AppModelInstallationProbe.status(at: URL(fileURLWithPath: path))
- visionInstallationStatus = AppVisionPackInstallationProbe.status(
- at: URL(fileURLWithPath: path))
+ modelLocationDiagnostic = nil
+ installationStatus = AppModelInstallationProbe.status(at: directory)
+ visionInstallationStatus = AppVisionPackInstallationProbe.status(at: directory)
refreshInstallReadiness()
refreshVisionInstallReadiness()
- replaceConversationBinding(
- for: URL(fileURLWithPath: path, isDirectory: true),
- reason: "the model location changed")
-
- if let lifecycle = client as? AppModelLifecycleClient {
- unloadGeneration &+= 1
- let generation = unloadGeneration
- let task = Task { [weak self, lifecycle] in
- await lifecycle.unload()
- self?.clearUnloadTask(generation: generation)
- }
- unloadTask = task
+ replaceConversationBinding(for: directory, reason: "the model location changed")
+ }
+
+ public func importLegacyHistory(from modelDirectory: URL) async {
+ guard canChangeModelLocation, let store = conversationStore else { return }
+ isChangingModelLocation = true
+ defer { isChangingModelLocation = false }
+ guard await awaitPendingPersistence(timeout: .seconds(30)) else {
+ modelLocationDiagnostic = "Pending chat writes did not settle. Retry when saving finishes."
+ return
}
+ let source = ConversationStoreLocation.url(forModelDirectory: modelDirectory)
+ do {
+ try await store.importLegacyHistory(from: source)
+ if !migratedHistorySources.contains(source.path) { migratedHistorySources.append(source.path) }
+ persistSettings()
+ await refreshHistory()
+ } catch { modelLocationDiagnostic = "Could not import history: \(error)" }
+ }
+
+ public func resetSettingsAfterBackingUp() {
+ guard canResetSettings else { return }
+ do {
+ let url = AppDataLocation.settingsURL(in: appDataDirectory)
+ if FileManager.default.fileExists(atPath: url.path) {
+ try FileManager.default.copyItem(at: url, to: url.appendingPathExtension("backup-" + UUID().uuidString))
+ }
+ try MacAppSettingsFileStore.save(currentSettings(), at: url)
+ settingsWritesAllowed = true
+ settingsDiagnostic = nil
+ } catch { settingsDiagnostic = "Could not recover settings: \(error)" }
}
public func loadModel() {
@@ -991,7 +1145,7 @@ public final class AppModel {
/// the menu item can be disabled rather than silently doing nothing, plus
/// the installer: there is no chat to start before a model exists.
public var canStartNewChat: Bool {
- !isTurnInFlight && !requiresModelInstallation
+ !isChangingModelLocation && !isTurnInFlight && !requiresModelInstallation
}
@@ -1070,7 +1224,6 @@ public final class AppModel {
/// takes its own copy — so it must not outlive the staging that consumed
/// it, which is exactly how it leaked.
public func addImages(_ urls: [URL], discardingSourceDirectory: URL? = nil) {
- recheckVisionPackAtCurrentLocation()
// Every early return has to discard the promise directory itself. The
// staging task's `defer` below owns it only once that task exists, so a
// return above it strands the full-size copies with nothing left to
@@ -1080,6 +1233,12 @@ public final class AppModel {
try? FileManager.default.removeItem(at: discardingSourceDirectory)
}
}
+ guard !isChangingModelLocation else {
+ imageAttachmentError = "Wait for the model location change to finish before attaching images."
+ discardSource()
+ return
+ }
+ recheckVisionPackAtCurrentLocation()
guard isImageInputAvailable, !urls.isEmpty else {
if !isImageInputAvailable {
recordVisionAvailabilityError(
@@ -1142,6 +1301,10 @@ public final class AppModel {
/// of another app arrives on the pasteboard as data, and a drag from an app
/// that has not written the file yet arrives as a promise.
public func addImageData(_ data: Data, displayName: String) {
+ guard !isChangingModelLocation else {
+ imageAttachmentError = "Wait for the model location change to finish before attaching images."
+ return
+ }
recheckVisionPackAtCurrentLocation()
guard isImageInputAvailable else {
recordVisionAvailabilityError(
@@ -1653,7 +1816,14 @@ public final class AppModel {
modelStorageMetrics = nil
modelStorageMetricsError = "installed storage could not be measured: \(error)"
}
- guard !isModelInstalled else { return }
+ guard !isModelInstalled else {
+ installReadiness = .installed
+ return
+ }
+ guard AppModelLocation.isVolumeAvailable(for: outputDirectory) else {
+ installReadiness = .failed("The selected volume is unavailable. Reconnect it and check again, or choose another location.")
+ return
+ }
installReadiness = .checking
do {
let requirement = try installer.checkInstallRequirement(
@@ -1694,7 +1864,10 @@ public final class AppModel {
visionInstallReadiness = .failed("Install the text model first")
return
}
- guard !isVisionPackInstalled else { return }
+ guard !isVisionPackInstalled else {
+ visionInstallReadiness = .installed
+ return
+ }
if visionInstaller.preparedInstallIsValid(
textModelDirectory: textModelDirectory) {
let output = try? VisionPackLocation.companionURL(
@@ -2031,44 +2204,10 @@ public final class AppModel {
installETAText = DownloadETAFormatter.string(for: presentation)
}
- private func applyPersistedSettings(forModelDirectory modelDirectory: URL) {
- guard settingsPersistenceEnabled else { return }
- let settings = MacAppSettingsFileStore.loadOrCreate(
- forModelDirectory: modelDirectory)
- runtimeOptions = AppRuntimeOptions(
- expertCacheSlots: settings.expertCacheSlots,
- prefillEnabled: settings.prefillEnabled,
- rdadvisePolicy: settings.rdadvisePolicy,
- // Pinned for the same reason as `init`: the app always releases the
- // image tower. Reading the persisted value here would let a
- // `keepReady` written by an older build resurrect ~1 GB of resident
- // tower on a machine with no control that shows or clears it.
- visionResidencyPolicy: .onDemand)
- // Clamped for the same reason as `init`: another model directory can
- // carry a context this Mac cannot back, and adopting it would leave
- // the app on a setting the loader refuses. Assigned before the notice
- // because the assignment clears it.
- let admitted = Self.admittedContext(settings.contextTokens,
- hostMemoryBytes: hostMemoryBytes,
- expertCacheSlots: settings.expertCacheSlots)
- maxContextTokens = admitted.tokens
- contextClampNotice = admitted.notice
- temperature = settings.temperature
- topKEnabled = settings.topKEnabled
- topK = settings.topK
- topPEnabled = settings.topPEnabled
- topP = settings.topP
- newlineShortcut = settings.newlineShortcut
- showPromptExamples = settings.showPromptExamples
- textSize = settings.textSize
- isSidebarVisible = settings.sidebarVisible
- isInspectorVisible = settings.inspectorVisible
- loadModelOnLaunch = settings.loadModelOnLaunch
- }
-
- func persistSettings() {
- guard settingsPersistenceEnabled else { return }
- let settings = MacAppSettings(
+ private func currentSettings() -> MacAppSettings {
+ MacAppSettings(
+ selectedModelPath: savedModelPath,
+ migratedHistorySources: migratedHistorySources,
contextTokens: maxContextTokens,
expertCacheSlots: runtimeOptions.expertCacheSlots,
temperature: temperature,
@@ -2085,12 +2224,17 @@ public final class AppModel {
visionResidencyPolicy: runtimeOptions.visionResidencyPolicy,
rdadvisePolicy: runtimeOptions.rdadvisePolicy,
loadModelOnLaunch: loadModelOnLaunch)
- let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)
+ }
+
+ func persistSettings() {
+ guard settingsPersistenceEnabled, settingsWritesAllowed else { return }
do {
- try MacAppSettingsFileStore.save(settings, forModelDirectory: modelDirectory)
+ try MacAppSettingsFileStore.save(currentSettings(), at: AppDataLocation.settingsURL(in: appDataDirectory))
+ settingsDiagnostic = nil
} catch {
- FileHandle.standardError.write(Data(
- "Saving Mac app settings failed: \(error)\n".utf8))
+ let message = "Saving Mac app settings failed: \(error)"
+ settingsDiagnostic = message
+ self.error = .unknown(message)
}
}
@@ -2260,7 +2404,7 @@ public final class AppModel {
// sent; starting an empty chat under it left the window on the new chat
// and the model on the old one, and whichever landed last defined what
// the next turn was numbered against.
- guard !isTurnInFlight else { return }
+ guard !isChangingModelLocation, !isTurnInFlight else { return }
quarantinedPersistenceLineages.removeAll()
pendingServiceRecoveryConversationID = nil
// The empty chat is not written until its first send, so it takes no
diff --git a/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift
index 41c4434e..a723d854 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift
@@ -59,10 +59,6 @@ extension AppModel {
historyDiagnostic = nil
}
- pendingTurnImageWrite?.cancel()
- pendingTurnImageWrite = nil
- persistenceTail?.cancel()
- persistenceTail = nil
quarantinedPersistenceLineages.removeAll()
storedConversationID = nil
serviceEpoch = nil
@@ -75,6 +71,8 @@ extension AppModel {
history.setReadOnlyStore(false)
conversationBinding = ConversationStoreBinding(
modelDirectory: modelDirectory,
+ appDataDirectory: appDataDirectory,
+ store: conversationStore,
identity: identity,
generation: conversationBindingGeneration,
storeProvider: conversationStoreProvider)
@@ -539,7 +537,7 @@ extension AppModel {
/// A conversation that could not continue anyway is never replayed at all;
/// the row says why instead.
public func openConversation(id: UUID) {
- guard !isTurnInFlight, conversationStore != nil else { return }
+ guard !isChangingModelLocation, !isTurnInFlight, conversationStore != nil else { return }
guard let meta = history.entry(id) else { return }
if id == storedConversationID,
serviceEpoch == conversation.epoch,
@@ -1066,7 +1064,7 @@ extension AppModel {
}
public func canMutateConversation(id: UUID) -> Bool {
- conversationStore != nil && history.entry(id) != nil
+ !isChangingModelLocation && conversationStore != nil && history.entry(id) != nil
&& !history.isReadOnlyStore && !isTurnInFlight
&& conversationDeletionTask == nil
}
diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
index 8f945f03..aa761a5e 100644
--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
@@ -88,8 +88,26 @@ struct TurboFieldfareMacApp: App {
@StoredState private var model: AppModel
init() {
+ if CommandLine.arguments.contains("--check-resources") {
+ do {
+ try AppBundledResources.verify()
+ guard MacAppIcon.load() != nil else {
+ throw AppInferenceError.invalidRequest("Bundled app icon could not be read.")
+ }
+ guard SwiftMathTypesetter().render(latex: "x^2 + 1", fontSize: 18, tint: .textColor, mode: .inline) != nil else {
+ throw AppInferenceError.invalidRequest("Bundled math fonts could not render a formula.")
+ }
+ print("PASS app resources: prompts, Metal shaders, icon and math fonts")
+ Foundation.exit(0)
+ } catch {
+ FileHandle.standardError.write(Data("App resource check failed: \(error)\n".utf8))
+ Foundation.exit(1)
+ }
+ }
+ let dataRoot = AppDataLocation.resolve()
let model = AppModel(
- client: DecodeServiceInferenceClient(),
+ appDataDirectory: dataRoot,
+ client: DecodeServiceInferenceClient(appDataDirectory: dataRoot),
visionRuntimeSupported: AppModel.currentDeviceSupportsVisionRuntime,
settingsPersistenceEnabled: true)
_model = StoredState(initialValue: model)
@@ -105,6 +123,10 @@ struct TurboFieldfareMacApp: App {
// from disk in init, and loadModelAtLaunchIfEnabled ignores a
// model that is missing or already busy.
.task { model.loadModelAtLaunchIfEnabled() }
+ .sheet(item: Bindable(model).existingModelReview) { review in
+ ExistingModelSelectionView(model: model, review: review)
+ .id(review.id)
+ }
// On the window, not in the Inspector: the menu item works
// whether or not the Inspector is open.
.confirmationDialog(
@@ -187,6 +209,15 @@ struct TurboFieldfareMacApp: App {
.disabled(!model.canRemoveVisionPack)
}
CommandMenu("Settings") {
+ Button("Change Model Location…") {
+ ModelLocationPanels.choose(model: model, intent: .existing, title: "Change Model Location")
+ }
+ .disabled(!model.canChangeModelLocation)
+ .accessibilityIdentifier(.modelChangeLocation)
+ Button("Import Legacy Chats…") { ModelLocationPanels.importHistory(model: model) }
+ .disabled(!model.canChangeModelLocation)
+ .accessibilityIdentifier(.historyImportLegacy)
+ Divider()
Picker("Text Size", selection: textSizeBinding) {
ForEach(AppTextSize.allCases) { size in
Text(size.label).tag(size)
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
index de010899..f65344bf 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
@@ -94,8 +94,8 @@ struct InspectorView: View {
.font(.caption)
.foregroundStyle(.orange)
} else if case .unsupportedLayout = model.visionInstallationStatus {
- Text("Image support needs a model directory named "
- + "“<name>.gturbo”, which is where the companion pack lives.")
+ Text("Image support needs a text model named “<name>.gturbo” "
+ + "with “<name>.vision.gturbo” beside it.")
.font(.caption)
.foregroundStyle(.secondary)
} else if case .failed(let message) = model.visionInstallReadiness,
@@ -227,8 +227,10 @@ struct InspectorView: View {
.buttonStyle(.borderless)
.help("Copy model path")
.accessibilityIdentifier(.inspectorCopyPath)
+ ModelLocationMenu(model: model)
}
}
+ ModelLocationNotices(model: model)
if model.canUnloadModel {
Button("Unload Model", action: model.unloadModel)
.accessibilityIdentifier(.inspectorUnload)
@@ -280,8 +282,6 @@ struct InspectorView: View {
}
}
}
- .disabled(model.isRunning || model.isInstallingModel
- || model.isVisionFilesystemMutationInProgress)
}
/// The context is settable only through the model, because changing it has
@@ -389,15 +389,15 @@ struct InspectorView: View {
Section("Runtime") {
Toggle("Prefill", isOn: $model.runtimeOptions.prefillEnabled)
.accessibilityIdentifier(.inspectorPrefill)
- VStack(alignment: .leading, spacing: 8) {
- Text("RDADVISE")
+ LabeledContent("RDADVISE") {
Picker("RDADVISE", selection: $model.runtimeOptions.rdadvisePolicy) {
ForEach(AppRDAdvicePolicy.allCases) { policy in
Text(policy.label).tag(policy)
}
}
- .pickerStyle(.segmented)
+ .pickerStyle(.menu)
.labelsHidden()
+ .fixedSize()
.accessibilityIdentifier(.inspectorRDAdvise)
}
Text("RDADVISE is experimental. It may speed up short decodes but slow down long decodes.")
diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
index 6253aaa9..6d8c93f2 100644
--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
@@ -51,6 +51,7 @@ struct PromptComposerView: View {
newlineShortcut: model.newlineShortcut,
canRun: model.canRun,
canAcceptImages: model.isImageInputAvailable
+ && !model.isChangingModelLocation
&& !model.isTurnInFlight
&& !model.isAddingImages,
onSubmit: model.send,
@@ -106,7 +107,7 @@ struct PromptComposerView: View {
.frame(width: 28, height: 28)
}
.buttonStyle(.borderless)
- .disabled(model.isTurnInFlight || model.isAddingImages
+ .disabled(model.isChangingModelLocation || model.isTurnInFlight || model.isAddingImages
|| model.imageAttachments.count
>= model.maximumImageAttachments)
.help(model.maximumImageAttachments == 0
diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ExistingModelSelectionView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ExistingModelSelectionView.swift
new file mode 100644
index 00000000..e7dffb4b
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Mac/Installation/ExistingModelSelectionView.swift
@@ -0,0 +1,96 @@
+import SwiftUI
+import TurboFieldfareAppCore
+import TurboFieldfareMacPresentation
+
+struct ExistingModelSelectionView: View {
+ let model: AppModel
+ let review: ExistingModelReview
+ @StoredState private var selectedID: String?
+
+ init(model: AppModel, review: ExistingModelReview) {
+ self.model = model
+ self.review = review
+ _selectedID = StoredState(wrappedValue: review.initialSelection)
+ }
+
+ private var selected: ExistingModelCandidate? {
+ review.candidates.first { $0.id == selectedID }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ Text("Choose a model").font(.title2.bold())
+ Text(review.folder.path)
+ .font(.caption).foregroundStyle(.secondary)
+ .lineLimit(2).truncationMode(.middle).help(review.folder.path)
+ ScrollView {
+ Picker("Text model", selection: $selectedID) {
+ ForEach(Array(review.candidates.enumerated()), id: \.element.id) { index, candidate in
+ VStack(alignment: .leading, spacing: 4) {
+ Text(candidate.textURL.lastPathComponent).font(.headline)
+ Text(candidate.textURL.deletingLastPathComponent().path)
+ .font(.caption).foregroundStyle(.secondary)
+ .lineLimit(1).truncationMode(.middle).help(candidate.textURL.path)
+ Text(candidate.canSelect ? candidate.visionSummary : candidate.textSummary)
+ .font(.caption)
+ .foregroundStyle(candidate.canSelect ? Color.secondary : Color.red)
+ }
+ .tag(Optional(candidate.id))
+ .disabled(!candidate.canSelect)
+ .accessibilityIdentifier(AccessibilityID.Prefix.modelCandidate.rawValue + String(index))
+ }
+ }
+ .pickerStyle(.radioGroup)
+ .accessibilityIdentifier(.modelReviewPicker)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: min(CGFloat(review.candidates.count) * 94, 200))
+ ScrollView {
+ VStack(alignment: .leading, spacing: 12) {
+ if let selected {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Text model").font(.headline)
+ Text(selected.textURL.path).textSelection(.enabled)
+ Text("Vision pack").font(.headline)
+ Text(selected.visionURL.path).textSelection(.enabled)
+ Text(selected.visionSummary)
+ .foregroundStyle(selected.visionStatus == .complete ? Color.secondary : Color.orange)
+ }
+ .font(.caption)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ Text("Select a text model above. No model will be chosen automatically.")
+ .font(.callout).foregroundStyle(.secondary)
+ }
+ if let message = model.modelLocationDiagnostic {
+ Text(message).font(.caption).foregroundStyle(.red)
+ }
+ if !model.canChangeModelLocation {
+ Text("Wait for the current model operation to finish before confirming.")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 180)
+ HStack {
+ Spacer()
+ Button("Cancel") { model.existingModelReview = nil }
+ .keyboardShortcut(.cancelAction)
+ .disabled(model.isChangingModelLocation)
+ .accessibilityIdentifier(.modelReviewCancel)
+ Button("Use Model") {
+ guard let selected else { return }
+ Task { await model.confirmExistingModelSelection(selected) }
+ }
+ .keyboardShortcut(.defaultAction)
+ .disabled(selected?.canSelect != true || !model.canChangeModelLocation)
+ .accessibilityIdentifier(.modelReviewConfirm)
+ }
+ }
+ .padding(24)
+ .frame(width: 520)
+ .tint(TurboFieldfareMacTheme.accentColor)
+ .interactiveDismissDisabled(model.isChangingModelLocation)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift
index 9bf3cb90..f04f1daa 100644
--- a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift
@@ -10,15 +10,21 @@ struct ModelInstallView: View {
ScrollView {
VStack(spacing: 22) {
identity
- storageCard
- progressArea
+ ModelLocationView(model: model)
actions
+ VStack(alignment: .leading, spacing: 8) {
+ ModelLocationNotices(model: model, showsVolumeWarning: false)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ progressArea
+ storageCard
}
.frame(maxWidth: 560)
.padding(.horizontal, 28)
.padding(.vertical, 48)
.frame(maxWidth: .infinity)
}
+ .defaultScrollAnchor(.top, for: .sizeChanges)
.confirmationDialog(
"Discard the saved model download?",
isPresented: $showingDiscardConfirmation,
@@ -54,7 +60,7 @@ struct ModelInstallView: View {
if let requirement = model.installRequirement {
StorageRow(label: "Space required",
value: MetricFormat.storage(requirement.requiredBytes))
- StorageRow(label: "Available on this Mac",
+ StorageRow(label: "Available on selected volume",
value: MetricFormat.storage(requirement.availableBytes))
capacityStatus(requirement)
} else if case .failed(let message) = model.installReadiness {
@@ -72,12 +78,22 @@ struct ModelInstallView: View {
Spacer()
}
}
- Text(model.modelPathText)
- .font(.caption.monospaced())
- .foregroundStyle(.tertiary)
- .lineLimit(2)
- .truncationMode(.middle)
- .frame(maxWidth: .infinity, alignment: .leading)
+ HStack {
+ Button("Check Again", action: model.recheckModelAtCurrentLocation)
+ .buttonStyle(.borderless)
+ .disabled(model.isInstallingModel)
+ .accessibilityIdentifier(.installCheckAgain)
+ Spacer()
+ if model.hasPartialModelDownload && !model.isInstallingModel {
+ Button("Discard Download", role: .destructive) {
+ showingDiscardConfirmation = true
+ }
+ .buttonStyle(.borderless)
+ .disabled(!model.canDiscardModelDownload)
+ .accessibilityIdentifier(.installDiscard)
+ }
+ }
+ .controlSize(.small)
}
.padding(18)
.background {
@@ -166,32 +182,27 @@ struct ModelInstallView: View {
.disabled(!model.canCancelInstall)
.accessibilityIdentifier(.installCancel)
} else {
- if model.hasPartialModelDownload {
- Button("Discard Download", role: .destructive) {
- showingDiscardConfirmation = true
- }
- .buttonStyle(.bordered)
- .disabled(!model.canDiscardModelDownload)
- .accessibilityIdentifier(.installDiscard)
- }
-
- Button("Check Again", action: model.recheckModelAtCurrentLocation)
- .buttonStyle(.bordered)
- .disabled(model.isInstallingModel)
- .accessibilityIdentifier(.installCheckAgain)
-
- Button(model.hasPartialModelDownload ? "Resume" : "Download",
+ Button(model.hasPartialModelDownload ? "Resume Download" : "Download Model",
action: model.installModel)
.buttonStyle(.borderedProminent)
.disabled(!model.canInstallModel)
.accessibilityIdentifier(.installDownload)
}
+ Button("Use Existing Model…") {
+ ModelLocationPanels.choose(model: model, intent: .existing)
+ }
+ .buttonStyle(.bordered)
+ .tint(.primary)
+ .disabled(!model.canChangeModelLocation)
+ .accessibilityIdentifier(.modelUseExisting)
}
.controlSize(.large)
}
private var readinessLabel: String {
switch model.installReadiness {
+ case .installed:
+ return "Installed"
case .checking:
return "Checking available space"
case .failed(let message):
diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelLocationView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelLocationView.swift
new file mode 100644
index 00000000..08799d41
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelLocationView.swift
@@ -0,0 +1,160 @@
+import AppKit
+import SwiftUI
+import TurboFieldfareAppCore
+import TurboFieldfareMacPresentation
+
+struct ModelLocationView: View {
+ let model: AppModel
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text("Download location")
+ .font(.callout.weight(.medium))
+ Spacer()
+ Button("Change…") {
+ ModelLocationPanels.choose(model: model, intent: .download)
+ }
+ .buttonStyle(.borderless)
+ .help("Choose download location")
+ .disabled(!model.canChangeModelLocation)
+ .accessibilityIdentifier(.modelChooseDownload)
+ }
+ Text(model.modelPathText)
+ .font(.caption.monospaced())
+ .foregroundStyle(.secondary)
+ .lineLimit(2, reservesSpace: true)
+ .truncationMode(.middle)
+ .help(model.modelPathText)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+struct ModelLocationMenu: View {
+ let model: AppModel
+
+ var body: some View {
+ Menu("Location") {
+ Button("Change Model Location…") {
+ ModelLocationPanels.choose(model: model, intent: .existing, title: "Change Model Location")
+ }
+ .disabled(!model.canChangeModelLocation)
+ .accessibilityIdentifier(.modelChangeLocation)
+ Divider()
+ Button("Reveal in Finder") { ModelLocationPanels.reveal(model) }
+ .disabled(ModelLocationPanels.revealTarget(model) == .unavailable)
+ .accessibilityIdentifier(.modelReveal)
+ }
+ .menuStyle(.borderlessButton)
+ .fixedSize()
+ .help("Model location actions")
+ .accessibilityIdentifier(.modelLocationMenu)
+ }
+}
+
+struct ModelLocationNotices: View {
+ let model: AppModel
+ var showsVolumeWarning = true
+
+ var body: some View {
+ Group {
+ if model.isInspectingModelLocation {
+ Text("Checking models in the selected folder…")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ if model.isModelChoiceRequired {
+ Text("Multiple existing installations were found. Choose which model to use.")
+ .font(.caption).foregroundStyle(.orange)
+ }
+ if model.isModelLocationOverridden {
+ Text("Model location is overridden for this launch. Relaunch without the override to save a different location.")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ if showsVolumeWarning && !model.isModelLocationAvailable {
+ Text("The selected volume is unavailable. Reconnect it and choose Check Again, or choose another location.")
+ .font(.caption).foregroundStyle(.orange)
+ }
+ if let message = model.modelLocationDiagnostic {
+ Text(message).font(.caption).foregroundStyle(.red)
+ }
+ if let message = model.settingsDiagnostic {
+ Text(message).font(.caption).foregroundStyle(.red)
+ Button("Reveal Settings") { ModelLocationPanels.revealSettings(model) }
+ .accessibilityIdentifier(.settingsReveal)
+ if model.canResetSettings {
+ Button("Back Up and Reset Settings", action: model.resetSettingsAfterBackingUp)
+ .accessibilityIdentifier(.settingsRecover)
+ }
+ }
+ }
+ }
+}
+
+@MainActor
+enum ModelLocationPanels {
+ private static var activePanel: NSOpenPanel?
+ static func choose(model: AppModel, intent: AppModel.ModelLocationIntent, title: String? = nil) {
+ guard model.canChangeModelLocation, model.existingModelReview == nil, activePanel == nil else { return }
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.canCreateDirectories = intent == .download
+ panel.treatsFilePackagesAsDirectories = true
+ panel.title = title ?? (intent == .download ? "Choose Download Location" : "Use Existing Model")
+ panel.message = intent == .download
+ ? "Choose a parent folder. The model will be installed in gemma4.gturbo inside it."
+ : "Choose a folder containing your text and vision model packs, or a text .gturbo folder directly. If multiple usable text models are found, you can choose which to use."
+ panel.prompt = intent == .download ? "Choose Destination" : "Select Folder"
+ present(panel) { response in
+ guard response == .OK, let url = panel.url else { return }
+ Task { @MainActor in
+ if intent == .existing { await model.reviewExistingModelLocation(url) }
+ else { await model.selectModelLocation(url, intent: intent) }
+ }
+ }
+ }
+
+ static func importHistory(model: AppModel) {
+ guard model.canChangeModelLocation, activePanel == nil else { return }
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.treatsFilePackagesAsDirectories = true
+ panel.title = "Import Legacy Chats"
+ panel.message = "Choose the old .gturbo model directory. Chats beside it will be copied and verified; originals stay in place."
+ present(panel) { response in
+ guard response == .OK, let url = panel.url else { return }
+ Task { @MainActor in await model.importLegacyHistory(from: url) }
+ }
+ }
+
+ private static func present(_ panel: NSOpenPanel, completion: @escaping @MainActor (NSApplication.ModalResponse) -> Void) {
+ guard let window = NSApp.keyWindow else { return }
+ activePanel = panel
+ panel.beginSheetModal(for: window) { response in
+ activePanel = nil
+ completion(response)
+ }
+ }
+
+ static func reveal(_ model: AppModel) {
+ switch revealTarget(model) {
+ case .selectItem(let url): NSWorkspace.shared.activateFileViewerSelecting([url])
+ case .openContainer(let url): NSWorkspace.shared.open(url)
+ case .unavailable: break
+ }
+ }
+
+ static func revealTarget(_ model: AppModel) -> ModelRevealTarget {
+ ModelRevealPolicy.target(forModelPath: model.modelPathText,
+ fileExists: FileManager.default.fileExists(atPath:))
+ }
+
+ static func revealSettings(_ model: AppModel) {
+ NSWorkspace.shared.activateFileViewerSelecting([
+ model.appDataDirectory.appendingPathComponent("mac-app-settings.json")])
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index 342ebdce..aaf73bb5 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.1"
+ public static let fallbackShortVersion = "0.9.2"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
index 8fc7419b..2d6b5287 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
@@ -10,6 +10,17 @@ import TurboFieldfareAppCore
/// `Scripts/check_app_case_coverage.rb` fails when one has no case in the
/// `mac-app-acceptance` skill, so a new control cannot land without its case.
public enum AccessibilityID: String, CaseIterable, Sendable {
+ case modelChooseDownload = "model.chooseDownload"
+ case modelLocationMenu = "model.locationMenu"
+ case modelUseExisting = "model.useExisting"
+ case modelChangeLocation = "model.changeLocation"
+ case modelReviewPicker = "model.reviewPicker"
+ case modelReviewConfirm = "model.reviewConfirm"
+ case modelReviewCancel = "model.reviewCancel"
+ case modelReveal = "model.reveal"
+ case historyImportLegacy = "history.importLegacy"
+ case settingsReveal = "settings.reveal"
+ case settingsRecover = "settings.recover"
case settingsTextSize = "settings.textSize"
case settingsTextSizeStandard = "settings.textSize.standard"
case settingsTextSizeLarge = "settings.textSize.large"
@@ -93,6 +104,7 @@ public enum AccessibilityID: String, CaseIterable, Sendable {
case historyRowMenu = "history.row.menu."
case composerRemove = "composer.remove."
case example = "examples."
+ case modelCandidate = "model.candidate."
}
public static func row(_ id: UUID) -> String { Prefix.historyRow.rawValue + id.uuidString }
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift b/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift
index 31293319..1cc00434 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift
@@ -13,9 +13,10 @@ public enum ModelRevealPolicy {
// the menu item exists to answer.
public static func target(forModelPath path: String,
fileExists: (String) -> Bool) -> ModelRevealTarget {
- let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return .unavailable }
- let url = URL(fileURLWithPath: trimmed, isDirectory: true).standardizedFileURL
+ guard !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ return .unavailable
+ }
+ let url = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL
if fileExists(url.path) { return .selectItem(url) }
let container = url.deletingLastPathComponent().standardizedFileURL
if container.path != url.path, fileExists(container.path) {
diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swift
index aa27a6ec..25f4925f 100644
--- a/Sources/TurboFieldfareDecodeService/Entry.swift
+++ b/Sources/TurboFieldfareDecodeService/Entry.swift
@@ -14,13 +14,25 @@ enum DecodeServiceError: Error, CustomStringConvertible {
case .attachmentOutsideStore(let path):
"image attachment is not a staged attachment: \(path)"
case .replayImageOutsideStore(let path):
- "replay image is not inside this model's conversation store: \(path)"
+ "replay image is not inside the app's conversation store: \(path)"
}
}
}
@main enum TurboFieldfareDecodeServiceMain {
static func main() async {
+ if CommandLine.arguments.contains("--check-resources") {
+ do {
+ try AppBundledResources.verify()
+ print("PASS decode helper resources: prompts and Metal shaders")
+ Foundation.exit(0)
+ } catch {
+ FileHandle.standardError.write(Data("Decode helper resource check failed: \(error)\n".utf8))
+ Foundation.exit(1)
+ }
+ }
+ let appDataDirectory = argument(after: "--app-data-directory")
+ .map { URL(fileURLWithPath: $0, isDirectory: true) } ?? AppDataLocation.resolve(environment: [:])
let socketPath = argument(after: "--socket")
let launchLabel = argument(after: "--launch-label")
let handles: (input: FileHandle, output: FileHandle)
@@ -153,7 +165,7 @@ enum DecodeServiceError: Error, CustomStringConvertible {
return
}
case .restoreConversation(let request):
- guard let modelDirectory else {
+ guard modelDirectory != nil else {
// Not `try?`: the app waits out the whole restore deadline
// for a terminal event that never lands. A lost write is an
// EOF the client rebuilds from, the same as below.
@@ -176,7 +188,7 @@ enum DecodeServiceError: Error, CustomStringConvertible {
// free to send turns onto a lineage that does not exist.
do {
let lineage = try restoreLineage(
- request, modelDirectory: modelDirectory)
+ request, appDataDirectory: appDataDirectory)
let options = try appRuntimeOptions(request.runtimeOptions)
// Progress goes straight out: the writer thread belongs to a
// generation, and a restore has none. The loop is awaiting
@@ -377,17 +389,17 @@ enum DecodeServiceError: Error, CustomStringConvertible {
///
/// Same trust boundary as an image attachment: these paths arrive over a
/// socket and this process opens and hashes whatever they name. Without the
- /// check a peer could use the service to read any file the user can, and a
- /// store rooted on the loaded model is the only place a stored conversation
- /// can legitimately live.
- private static func restoreLineage(
+ /// check a peer could use the service to read any file the user can, and
+ /// the app-data root supplied at launch is the only place a stored
+ /// conversation can legitimately live, even when model weights move.
+ static func restoreLineage(
_ request: DecodeRestoreConversationRequest,
- modelDirectory: URL
+ appDataDirectory: URL
) throws -> AppConversationLineage {
let images = try request.images.map { image -> AppConversationReplayImage in
let url = URL(fileURLWithPath: image.path)
guard ConversationStoreLocation.contains(
- url, forModelDirectory: modelDirectory) else {
+ url, forAppDataDirectory: appDataDirectory) else {
throw DecodeServiceError.replayImageOutsideStore(path: image.path)
}
return AppConversationReplayImage(
diff --git a/Sources/TurboFieldfareRepack/Core/System/Posix.swift b/Sources/TurboFieldfareRepack/Core/System/Posix.swift
index a88896f0..ff0b2166 100644
--- a/Sources/TurboFieldfareRepack/Core/System/Posix.swift
+++ b/Sources/TurboFieldfareRepack/Core/System/Posix.swift
@@ -181,20 +181,25 @@ public enum Posix {
public static func atomicWrite(_ data: Data,
to path: String,
durableIn directory: String,
+ uniqueTemporary: Bool = false,
afterRename: (() throws -> Void)? = nil) throws {
- let temporary = path + ".tmp"
- switch try entryKind(temporary) {
- case .absent:
- break
- case .regular:
- if unlink(temporary) != 0 {
- throw RepackError.fileOpenFailed(path: temporary, errno: errno)
+ // Installers own their staging paths under a lock; independent writers
+ // need separate staging files and must never clean up another writer's.
+ let temporary = path + (uniqueTemporary ? ".\(UUID().uuidString).tmp" : ".tmp")
+ if !uniqueTemporary {
+ switch try entryKind(temporary) {
+ case .absent:
+ break
+ case .regular:
+ if unlink(temporary) != 0 {
+ throw RepackError.fileOpenFailed(path: temporary, errno: errno)
+ }
+ try fsyncDirectory(directory)
+ default:
+ throw RepackError.installPathUnsafe(
+ path: temporary,
+ detail: "atomic-write temporary has the wrong type")
}
- try fsyncDirectory(directory)
- default:
- throw RepackError.installPathUnsafe(
- path: temporary,
- detail: "atomic-write temporary has the wrong type")
}
let fd = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
if fd < 0 { throw RepackError.fileOpenFailed(path: temporary, errno: errno) }
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppDataBootstrapTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppDataBootstrapTests.swift
new file mode 100644
index 00000000..c0a5d89f
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppDataBootstrapTests.swift
@@ -0,0 +1,180 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+@Suite struct AppDataBootstrapTests {
+ @Test(arguments: [false, true])
+ func completedOverrideImportIsNotRepeatedAfterCentralChatChanges(explicitOverride: Bool) throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let legacy = root.appendingPathComponent("legacy/gemma4.gturbo")
+ let central = root.appendingPathComponent("app-data")
+ let source = ConversationStoreLocation.url(forModelDirectory: legacy)
+ let id = UUID().uuidString
+ let conversation = source.appendingPathComponent(id)
+ try FileManager.default.createDirectory(at: conversation, withIntermediateDirectories: true)
+ let original = Data("legacy chat".utf8)
+ for name in ["conversation.json", "transcript.jsonl"] {
+ try original.write(to: conversation.appendingPathComponent(name))
+ }
+ let first = AppDataBootstrap(root: central, legacyModel: legacy,
+ environment: explicitOverride ? [:] : ["TURBO_FIELDFARE_MODEL_PATH": legacy.path],
+ modelOverride: explicitOverride, enabled: true)
+ #expect(first.failure == nil)
+ #expect(first.settings.selectedModelPath == nil)
+ #expect(first.settings.migratedHistorySources == [source.path])
+ let imported = ConversationStoreLocation.url(forAppDataDirectory: central).appendingPathComponent(id)
+ let changed = Data("continued and renamed centrally".utf8)
+ for name in ["conversation.json", "transcript.jsonl"] {
+ try changed.write(to: imported.appendingPathComponent(name))
+ }
+ // Reimporting this completed source used to report an ID conflict and
+ // disable all settings writes and model selection on normal relaunch.
+ let next = AppDataBootstrap(root: central, legacyModel: legacy, environment: [:], enabled: true)
+ #expect(next.failure == nil)
+ #expect(next.settings.selectedModelPath == legacy.path)
+ #expect(next.settings.migratedHistorySources == [source.path])
+ #expect(try MacAppSettingsFileStore.load(at: AppDataLocation.settingsURL(in: central))?.selectedModelPath == legacy.path)
+ for name in ["conversation.json", "transcript.jsonl"] {
+ #expect(try Data(contentsOf: imported.appendingPathComponent(name)) == changed)
+ #expect(try Data(contentsOf: conversation.appendingPathComponent(name)) == original)
+ }
+ }
+
+ private func root() throws -> URL {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("bootstrap-\(UUID())")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ @Test func firstLaunchImportsLegacyPreferencesAndHistoryWithoutMovingOriginals() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let legacy = root.appendingPathComponent("legacy/gemma4.gturbo")
+ let central = root.appendingPathComponent("app-data")
+ try MacAppSettingsFileStore.save(.init(temperature: 0.73, textSize: .largest),
+ at: AppDataLocation.settingsURL(in: legacy.deletingLastPathComponent()))
+ let name = UUID().uuidString
+ let conversation = ConversationStoreLocation.url(forModelDirectory: legacy).appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: conversation, withIntermediateDirectories: true)
+ for file in ["conversation.json", "transcript.jsonl"] {
+ try Data("fixture".utf8).write(to: conversation.appendingPathComponent(file))
+ }
+ let bootstrap = AppDataBootstrap(root: central, legacyModel: legacy, environment: [:], enabled: true)
+ #expect(bootstrap.failure == nil)
+ #expect(bootstrap.settings.temperature == 0.73)
+ #expect(bootstrap.settings.textSize == .largest)
+ #expect(bootstrap.settings.selectedModelPath == legacy.path)
+ let copied = ConversationStoreLocation.url(forAppDataDirectory: central).appendingPathComponent(name)
+ #expect(try Data(contentsOf: copied.appendingPathComponent("transcript.jsonl")) == Data("fixture".utf8))
+ #expect(FileManager.default.fileExists(atPath: conversation.path))
+ let relaunched = AppDataBootstrap(root: central, legacyModel: legacy, environment: [:], enabled: true)
+ #expect(relaunched.failure == nil)
+ #expect(relaunched.settings.migratedHistorySources.count == 1)
+ }
+
+ @Test func centralSettingsWinWithoutReadingMalformedLegacySettings() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let central = root.appendingPathComponent("app-data")
+ let legacy = root.appendingPathComponent("legacy/gemma4.gturbo")
+ let legacySettings = AppDataLocation.settingsURL(in: legacy.deletingLastPathComponent())
+ try FileManager.default.createDirectory(at: legacySettings.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("broken".utf8).write(to: legacySettings)
+ let saved = "/Volumes/unavailable/gemma4.gturbo"
+ try MacAppSettingsFileStore.save(.init(selectedModelPath: saved, temperature: 0.81),
+ at: AppDataLocation.settingsURL(in: central))
+ let bootstrap = AppDataBootstrap(root: central, legacyModel: legacy, environment: [:], enabled: true)
+ #expect(bootstrap.failure == nil)
+ #expect(bootstrap.settings.selectedModelPath == saved)
+ #expect(bootstrap.settings.temperature == 0.81)
+ #expect(try Data(contentsOf: legacySettings) == Data("broken".utf8))
+ }
+
+ @Test func isolatedRootDoesNotReadLegacyPreferencesOrHistory() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let central = root.appendingPathComponent("app-data")
+ let legacy = root.appendingPathComponent("legacy/gemma4.gturbo")
+ let legacySettings = AppDataLocation.settingsURL(in: legacy.deletingLastPathComponent())
+ try FileManager.default.createDirectory(at: legacySettings.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("broken".utf8).write(to: legacySettings)
+ let bootstrap = AppDataBootstrap(root: central, legacyModel: legacy,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": central.path], enabled: true)
+ #expect(bootstrap.failure == nil)
+ #expect(bootstrap.settings.temperature == MacAppSettings().temperature)
+ #expect(bootstrap.settings.migratedHistorySources.isEmpty)
+ }
+
+ @Test func multipleKnownInstallsRequireChoiceAndKeepCentralPreferencesOnRelaunch() throws {
+ let root = try root()
+ let legacy = try makeCompleteModelInstall("bootstrap-ambiguity")
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: legacy)
+ }
+ let second = root.appendingPathComponent("gemma4.gturbo")
+ try FileManager.default.copyItem(at: legacy, to: second)
+ let receipt = second.appendingPathComponent("verified-install.json")
+ var metadata = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: receipt)) as? [String: Any])
+ metadata["modelDirectoryPath"] = second.standardizedFileURL.path
+ try JSONSerialization.data(withJSONObject: metadata).write(to: receipt)
+ #expect(AppModelInstallationProbe.status(at: second) == .complete)
+ try MacAppSettingsFileStore.save(.init(temperature: 0.91), at: AppDataLocation.settingsURL(in: root))
+ for _ in 0..<2 {
+ let bootstrap = AppDataBootstrap(root: root, legacyModel: legacy, environment: [:], enabled: true)
+ #expect(bootstrap.failure == nil)
+ #expect(bootstrap.modelChoiceRequired)
+ #expect(bootstrap.settings.selectedModelPath == nil)
+ #expect(bootstrap.settings.temperature == 0.91)
+ #expect(bootstrap.settings.migratedHistorySources.isEmpty)
+ }
+ }
+
+ @Test func failedHistoryRecoveryPreservesReadableSettingsAndExplainsTheCorrectRepair() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let saved = root.appendingPathComponent("selected.gturbo").path
+ let file = AppDataLocation.settingsURL(in: root)
+ try MacAppSettingsFileStore.save(.init(selectedModelPath: saved, temperature: 0.67), at: file)
+ let bytes = try Data(contentsOf: file)
+ let store = ConversationStoreLocation.url(forAppDataDirectory: root)
+ try FileManager.default.createDirectory(at: store, withIntermediateDirectories: true)
+ try Data("broken journal".utf8).write(to: store.appendingPathComponent(".history-import.json"))
+ let bootstrap = AppDataBootstrap(root: root, legacyModel: root.appendingPathComponent("default.gturbo"),
+ environment: [:], enabled: true)
+ #expect(bootstrap.settings.selectedModelPath == saved)
+ #expect(bootstrap.settings.temperature == 0.67)
+ #expect(bootstrap.failure?.contains("Recovering an interrupted history import") == true)
+ #expect(bootstrap.failure?.contains("reset settings") == false)
+ #expect(!bootstrap.canResetSettings)
+ #expect(try Data(contentsOf: file) == bytes)
+ }
+
+ @Test func interruptedImportRecoversOnStartupEvenWhenSavedSourceDriveIsUnavailable() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let saved = "/Volumes/Unavailable-\(UUID())/gemma4.gturbo"
+ try MacAppSettingsFileStore.save(.init(selectedModelPath: saved, temperature: 0.67),
+ at: AppDataLocation.settingsURL(in: root))
+ let store = ConversationStoreLocation.url(forAppDataDirectory: root)
+ let name = UUID().uuidString
+ let published = store.appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: published, withIntermediateDirectories: true)
+ let data = Data("bounded fixture".utf8)
+ var fingerprints: [String: String] = [:]
+ for file in ["conversation.json", "transcript.jsonl"] {
+ try data.write(to: published.appendingPathComponent(file))
+ fingerprints[file] = Sha256Verifier.hashData(data)
+ }
+ let journal = store.appendingPathComponent(".history-import.json")
+ try JSONEncoder().encode(ConversationStoreImport.Journal(source: saved, fingerprints: [name: fingerprints])).write(to: journal)
+ let bootstrap = AppDataBootstrap(root: root, legacyModel: URL(fileURLWithPath: saved), environment: [:], enabled: true)
+ #expect(bootstrap.failure == nil)
+ #expect(bootstrap.settings.selectedModelPath == saved)
+ #expect(bootstrap.settings.temperature == 0.67)
+ #expect(!FileManager.default.fileExists(atPath: journal.path))
+ #expect(!FileManager.default.fileExists(atPath: published.path))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppDataPersistenceTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppDataPersistenceTests.swift
new file mode 100644
index 00000000..498475a2
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppDataPersistenceTests.swift
@@ -0,0 +1,198 @@
+import Foundation
+import Synchronization
+import Testing
+@testable import TurboFieldfareAppCore
+
+@Suite struct AppDataPersistenceTests {
+ @Test func settingsSaveDoesNotRemoveAnotherWritersStagingFile() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let file = AppDataLocation.settingsURL(in: root)
+ let otherWriter = file.appendingPathExtension("tmp")
+ let bytes = Data("another writer owns this file".utf8)
+ try bytes.write(to: otherWriter)
+ // The shared .tmp path used to be unlinked by an unrelated save.
+ try MacAppSettingsFileStore.save(.init(temperature: 0.71), at: file)
+ #expect(try Data(contentsOf: otherWriter) == bytes)
+ #expect(try MacAppSettingsFileStore.load(at: file)?.temperature == 0.71)
+ }
+
+ @Test func concurrentSettingsSavesPublishWholeSnapshotsWithoutInterfering() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let file = AppDataLocation.settingsURL(in: root)
+ let failures = Mutex<[String]>([])
+ // Writers must not share or remove each other's staging paths, even
+ // when they enter the file operation concurrently without a store lock.
+ DispatchQueue.concurrentPerform(iterations: 32) { index in
+ do {
+ let settings = MacAppSettings(selectedModelPath: "/models/\(index).gturbo", topK: index + 1)
+ try MacAppSettingsFileStore.save(settings, at: file)
+ guard let loaded = try MacAppSettingsFileStore.load(at: file),
+ loaded.selectedModelPath == "/models/\(loaded.topK - 1).gturbo" else {
+ throw CocoaError(.fileReadCorruptFile)
+ }
+ } catch { failures.withLock { $0.append(String(describing: error)) } }
+ }
+ #expect(failures.withLock { $0 }.isEmpty)
+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == [MacAppSettings.fileName])
+ }
+
+ private func root() throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("app data тест \(UUID())")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ @MainActor @Test func savedUnavailableLocationWinsAndSurvivesPreferenceWrites() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let unavailable = "/Volumes/Unavailable-\(UUID())/gemma4.gturbo"
+ try MacAppSettingsFileStore.save(.init(selectedModelPath: unavailable, temperature: 0.7),
+ at: AppDataLocation.settingsURL(in: root))
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ #expect(model.modelPathText == unavailable)
+ #expect(!model.isModelLocationAvailable)
+ #expect(!model.canInstallModel)
+ if case .failed(let message) = model.installReadiness {
+ #expect(message.contains("selected volume is unavailable"))
+ } else { Issue.record("Missing drive must report unavailable instead of local-volume capacity") }
+ model.setTextSize(.largest)
+ let saved = try #require(try MacAppSettingsFileStore.load(at: AppDataLocation.settingsURL(in: root)))
+ #expect(saved.selectedModelPath == unavailable)
+ #expect(saved.temperature == 0.7)
+ #expect(model.conversationBinding?.rootURL.path == root.appendingPathComponent("conversations").path)
+ #expect(!FileManager.default.fileExists(atPath: "/Volumes/" + URL(fileURLWithPath: unavailable).pathComponents[2]))
+ }
+
+ @MainActor @Test func launchOverrideNeverRewritesSavedSelectionOrHistoryRoot() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let saved = root.appendingPathComponent("selected.gturbo").path
+ try MacAppSettingsFileStore.save(.init(selectedModelPath: saved), at: AppDataLocation.settingsURL(in: root))
+ let model = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_MODEL_PATH": root.appendingPathComponent("override.gturbo").path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ #expect(model.isModelLocationOverridden)
+ #expect(!model.canChangeModelLocation)
+ model.setTextSize(.largest)
+ #expect(try MacAppSettingsFileStore.load(at: AppDataLocation.settingsURL(in: root))?.selectedModelPath == saved)
+ #expect(model.conversationBinding?.rootURL.path == root.appendingPathComponent("conversations").path)
+ }
+
+ @MainActor @Test(arguments: [Data("broken json".utf8), Data("{\"version\":999,\"future\":true}".utf8)])
+ func damagedOrNewerSettingsDisableWritesUntilExplicitBackupRecovery(_ data: Data) async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let file = AppDataLocation.settingsURL(in: root)
+ try data.write(to: file)
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ #expect(model.settingsDiagnostic != nil)
+ #expect(!model.canChangeModelLocation)
+ model.setTextSize(.largest)
+ model.shutdownForTermination()
+ #expect(try Data(contentsOf: file) == data)
+ model.resetSettingsAfterBackingUp()
+ #expect(model.settingsDiagnostic == nil)
+ let backup = try #require(FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
+ .first { $0.lastPathComponent.contains(".backup-") })
+ #expect(try Data(contentsOf: backup) == data)
+ #expect(try MacAppSettingsFileStore.load(at: file)?.textSize == .largest)
+ // Recovery has no saved model selection yet. Explicitly choosing the
+ // displayed default must commit it even though the runtime path is equal.
+ await model.selectModelLocation(root, intent: .download)
+ #expect(try MacAppSettingsFileStore.load(at: file)?.selectedModelPath == model.modelPathText)
+ }
+
+ @MainActor @Test func durableSelectionPreservesPreferencesAndStoreAcrossRepeatedSwitches() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ let store = try #require(model.conversationStore)
+ try await store.activate()
+ model.setTextSize(.largest)
+ for name in ["one тест", "two with spaces", "one тест"] {
+ let parent = root.appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
+ await model.selectModelLocation(parent, intent: .download)
+ #expect(model.modelPathText == parent.appendingPathComponent("gemma4.gturbo").path)
+ #expect(model.conversationStore === store)
+ #expect(await !store.isReadOnly)
+ #expect(model.textSize == .largest)
+ #expect(try MacAppSettingsFileStore.load(at: AppDataLocation.settingsURL(in: root))?.selectedModelPath == model.modelPathText)
+ }
+ let current = URL(fileURLWithPath: model.modelPathText)
+ let alias = root.appendingPathComponent("same-parent-alias")
+ try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: current.deletingLastPathComponent())
+ model.loadState = .ready(modelDirectory: current, loadSeconds: 0)
+ await model.selectModelLocation(alias, intent: .download)
+ #expect(model.loadState.isReady)
+ #expect(model.conversationStore === store)
+ let restored = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ #expect(restored.modelPathText == model.modelPathText)
+ #expect(restored.textSize == .largest)
+ }
+
+ @MainActor @Test func failedSelectionWritePreservesOldPathAndLoadedRuntime() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ let previous = model.modelPathText
+ model.loadState = .ready(modelDirectory: URL(fileURLWithPath: previous), loadSeconds: 0)
+ let epoch = model.conversation.epoch
+ let settings = AppDataLocation.settingsURL(in: root)
+ try FileManager.default.removeItem(at: settings)
+ try FileManager.default.createDirectory(at: settings, withIntermediateDirectories: false)
+ let other = root.appendingPathComponent("another download")
+ try FileManager.default.createDirectory(at: other, withIntermediateDirectories: false)
+ await model.selectModelLocation(other, intent: .download)
+ #expect(model.modelPathText == previous)
+ #expect(model.loadState.isReady)
+ #expect(model.conversation.epoch == epoch)
+ #expect(model.modelLocationDiagnostic?.contains("previous selection retained") == true)
+ }
+
+ @MainActor @Test func switchingIsRefusedWhileLoadOrInstallOwnsTheRuntime() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient(),
+ settingsPersistenceEnabled: true)
+ model.installState = .copyingPayload(reusedBytes: 0, downloadedThisRunBytes: 1, totalBytes: 2)
+ let previous = model.modelPathText
+ #expect(!model.canChangeModelLocation)
+ await model.selectModelLocation(root, intent: .download)
+ #expect(model.modelPathText == previous)
+ }
+
+ @Test func appDataOverrideIsIndependentOfModelOverride() {
+ let environment = ["TURBO_FIELDFARE_APP_DATA_PATH": "/tmp/app-data", "TURBO_FIELDFARE_MODEL_PATH": "/tmp/model"]
+ #expect(AppDataLocation.resolve(environment: environment).path == URL(fileURLWithPath: "/tmp/app-data").resolvingSymlinksInPath().path)
+ #expect(AppDataLocation.resolve(environment: [:], applicationSupportURL: URL(fileURLWithPath: "/tmp/support")).path == "/tmp/support/TurboFieldfare")
+ }
+
+ @MainActor @Test(arguments: [AppModelLoadState.loading(.tokenizer), .cancelling, .unloading])
+ func locationActionRefusesBusyTransitionAndWorksAfterItSettles(_ state: AppModelLoadState) async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ let destination = root.appendingPathComponent("another destination")
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)
+ let original = model.modelPathText
+ model.loadState = state
+ #expect(!model.canChangeModelLocation)
+ await model.selectModelLocation(destination, intent: .download)
+ #expect(model.modelPathText == original)
+ model.loadState = .notLoaded
+ #expect(model.canChangeModelLocation)
+ await model.selectModelLocation(destination, intent: .download)
+ #expect(model.modelPathText == destination.appendingPathComponent("gemma4.gturbo").path)
+ model.shutdownForTermination()
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift
index 1c460af8..10b545fa 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift
@@ -51,23 +51,23 @@ import Testing
#expect(decoded.version == MacAppSettings.currentVersion)
}
- @MainActor @Test func selectionPersistsBeforeSendAndFollowsModelLocation() throws {
+ @MainActor @Test func selectionPersistsBeforeSendAndFollowsModelLocation() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let first = root.appendingPathComponent("first/model.gturbo")
let second = root.appendingPathComponent("second/model.gturbo")
try MacAppSettingsFileStore.save(.init(textSize: .large), forModelDirectory: second)
- let model = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),
+ let model = AppModel(modelDirectory: first, appDataDirectory: first.deletingLastPathComponent(), client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true)
model.setTextSize(.largest)
model.setTextSize(.largest)
#expect(MacAppSettingsFileStore.loadOrCreate(forModelDirectory: first).textSize == .largest)
- let reopened = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),
+ let reopened = AppModel(modelDirectory: first, appDataDirectory: first.deletingLastPathComponent(), client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true)
#expect(reopened.textSize == .largest)
- model.setModelURL(second)
- #expect(model.textSize == .large)
- model.setModelURL(first)
+ await model.setModelURL(second)
+ #expect(model.textSize == .largest)
+ await model.setModelURL(first)
#expect(model.textSize == .largest)
}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/ConversationStoreImportTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/ConversationStoreImportTests.swift
new file mode 100644
index 00000000..353abfe3
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Configuration/ConversationStoreImportTests.swift
@@ -0,0 +1,121 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+@Suite struct ConversationStoreImportTests {
+ private func roots() throws -> (URL, URL, URL) {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("history-import-\(UUID())")
+ let source = root.appendingPathComponent("legacy/conversations")
+ let destination = root.appendingPathComponent("central/conversations")
+ try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
+ return (root, source, destination)
+ }
+
+ private func conversation(in root: URL, id: UUID = UUID(), content: String = "record") throws -> UUID {
+ let directory = root.appendingPathComponent(id.uuidString)
+ try FileManager.default.createDirectory(at: directory.appendingPathComponent("images"), withIntermediateDirectories: true)
+ try Data("{\"id\":\"\(id)\"}".utf8).write(to: directory.appendingPathComponent("conversation.json"))
+ try Data(content.utf8).write(to: directory.appendingPathComponent("transcript.jsonl"))
+ try Data(repeating: 42, count: 131_072).write(to: directory.appendingPathComponent("images/picture.png"))
+ return id
+ }
+
+ @Test func importPreservesOriginalsAttachmentsIDsAndLockInodeAndIsIdempotent() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ let lockURL = destination.appendingPathComponent(ConversationStoreLock.fileName)
+ do { let lock = try ConversationStoreLock.acquire(storeRoot: destination); withExtendedLifetime(lock) {} }
+ let inode = try FileManager.default.attributesOfItem(atPath: lockURL.path)[.systemFileNumber] as? NSNumber
+ try ConversationStoreImport.run(from: source, to: destination)
+ try ConversationStoreImport.run(from: source, to: destination)
+ #expect(FileManager.default.fileExists(atPath: source.appendingPathComponent(id.uuidString).path))
+ #expect(try Data(contentsOf: source.appendingPathComponent("\(id)/images/picture.png")) == Data(contentsOf: destination.appendingPathComponent("\(id)/images/picture.png")))
+ #expect(try FileManager.default.attributesOfItem(atPath: lockURL.path)[.systemFileNumber] as? NSNumber == inode)
+ #expect(try FileManager.default.contentsOfDirectory(atPath: destination.path).filter { UUID(uuidString: $0) != nil }.count == 1)
+ }
+
+ @Test func conflictingIDRejectsWholeImportBeforePublishing() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let conflict = try conversation(in: source)
+ _ = try conversation(in: destination, id: conflict, content: "different")
+ let other = try conversation(in: source)
+ #expect(throws: (any Error).self) { try ConversationStoreImport.run(from: source, to: destination) }
+ #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent(other.uuidString).path))
+ #expect(try String(contentsOf: destination.appendingPathComponent("\(conflict)/transcript.jsonl"), encoding: .utf8) == "different")
+ }
+
+ @Test func sourceWriterLockRejectsImport() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ _ = try conversation(in: source)
+ let lock = try #require(try ConversationStoreLock.acquire(storeRoot: source))
+ #expect(throws: (any Error).self) { try ConversationStoreImport.run(from: source, to: destination) }
+ withExtendedLifetime(lock) {}
+ }
+
+ @Test func publishFailureRollsBackAndRetryDoesNotDuplicate() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ struct Interrupted: Error {}
+ #expect(throws: (any Error).self) {
+ try ConversationStoreImport.run(from: source, to: destination, afterPublish: { throw Interrupted() })
+ }
+ #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent(id.uuidString).path))
+ try ConversationStoreImport.run(from: source, to: destination)
+ #expect(FileManager.default.fileExists(atPath: destination.appendingPathComponent(id.uuidString).path))
+ }
+
+ @Test func interruptedPublishJournalRecoversBeforeRetrying() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ let name = id.uuidString
+ let original = source.appendingPathComponent(name)
+ let published = destination.appendingPathComponent(name)
+ try FileManager.default.copyItem(at: original, to: published)
+ var files: [String: String] = [:]
+ for path in ["conversation.json", "transcript.jsonl", "images/picture.png"] {
+ files[path] = try Sha256Verifier.hashFile(at: original.appendingPathComponent(path), chunkBytes: 65_536)
+ }
+ let journal = ConversationStoreImport.Journal(source: source.path, fingerprints: [name: files])
+ try JSONEncoder().encode(journal).write(to: destination.appendingPathComponent(".history-import.json"))
+ try ConversationStoreImport.run(from: source, to: destination)
+ #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent(".history-import.json").path))
+ #expect(try FileManager.default.contentsOfDirectory(atPath: destination.path).filter { UUID(uuidString: $0) != nil }.count == 1)
+ #expect(FileManager.default.fileExists(atPath: original.path))
+ }
+
+ @Test func symlinkAttachmentRefusesImport() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ try FileManager.default.createSymbolicLink(at: source.appendingPathComponent("\(id)/images/escape"), withDestinationURL: root)
+ #expect(throws: (any Error).self) { try ConversationStoreImport.run(from: source, to: destination) }
+ #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent(id.uuidString).path))
+ }
+
+ @Test func symlinkConversationCannotQualifyAsAnExactDuplicate() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ let existing = destination.appendingPathComponent(id.uuidString)
+ try FileManager.default.createSymbolicLink(at: existing, withDestinationURL: source.appendingPathComponent(id.uuidString))
+ #expect(throws: (any Error).self) { try ConversationStoreImport.run(from: source, to: destination) }
+ #expect(try existing.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true)
+ }
+
+ @Test func symlinkHistoryRootIsRefusedBeforeAnyPublication() throws {
+ let (root, source, destination) = try roots()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let id = try conversation(in: source)
+ let alias = root.appendingPathComponent("alias")
+ try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: source)
+ #expect(throws: (any Error).self) { try ConversationStoreImport.run(from: alias, to: destination) }
+ #expect(!FileManager.default.fileExists(atPath: destination.appendingPathComponent(id.uuidString).path))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
index f939d244..42abb48e 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
@@ -26,7 +26,7 @@ import Testing
#expect(decoded == MacAppSettings())
}
- @Test func malformedFileIsReplacedWithDefaults() throws {
+ @Test func malformedFileIsPreserved() throws {
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
@@ -36,13 +36,10 @@ import Testing
let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)
#expect(settings == MacAppSettings())
- let decoded = try JSONDecoder().decode(
- MacAppSettings.self,
- from: Data(contentsOf: fileURL))
- #expect(decoded == MacAppSettings())
+ #expect(try Data(contentsOf: fileURL) == Data("not json".utf8))
}
- @Test func invalidValuesAreReplacedWithDefaults() throws {
+ @Test func invalidValuesArePreserved() throws {
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
@@ -129,7 +126,7 @@ import Testing
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)
- let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), settingsPersistenceEnabled: true)
model.setMaxContextTokens(4_096)
@@ -250,7 +247,7 @@ import Testing
let persisted = try JSONDecoder().decode(
MacAppSettings.self, from: Data(contentsOf: fileURL))
- #expect(settings.version == 3)
+ #expect(settings.version == MacAppSettings.currentVersion)
#expect(settings.contextTokens == 4_096,
"the version bump rewrote a deliberately chosen context")
#expect(settings.expertCacheSlots == 24)
@@ -296,7 +293,7 @@ import Testing
defer { try? FileManager.default.removeItem(at: root) }
let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
let stored = MacAppSettings(contextTokens: 262_144)
- #expect(stored.version == 3)
+ #expect(stored.version == MacAppSettings.currentVersion)
try MacAppSettingsFileStore.save(stored, forModelDirectory: model)
let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)
@@ -397,6 +394,7 @@ import Testing
let model = AppModel(
modelDirectory: modelDirectory,
+ appDataDirectory: modelDirectory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
#expect(model.maxContextTokens == 8_192)
#expect(model.runtimeOptions.expertCacheSlots == 24)
@@ -437,6 +435,7 @@ import Testing
let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
let model = AppModel(
modelDirectory: modelDirectory,
+ appDataDirectory: modelDirectory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
model.setNewlineShortcut(.shiftReturn)
@@ -453,6 +452,7 @@ import Testing
let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
let model = AppModel(
modelDirectory: modelDirectory,
+ appDataDirectory: modelDirectory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
model.setShowPromptExamples(false)
@@ -463,7 +463,7 @@ import Testing
}
@MainActor
- @Test func changingModelDirectoryLoadsItsNewlineShortcut() throws {
+ @Test func changingModelDirectoryPreservesItsNewlineShortcut() async throws {
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)
@@ -474,14 +474,14 @@ import Testing
try MacAppSettingsFileStore.save(
MacAppSettings(newlineShortcut: .shiftReturn, showPromptExamples: false),
forModelDirectory: second)
- let model = AppModel(modelDirectory: first, settingsPersistenceEnabled: true)
+ let model = AppModel(modelDirectory: first, appDataDirectory: first.deletingLastPathComponent(), settingsPersistenceEnabled: true)
#expect(model.newlineShortcut == .return)
#expect(model.showPromptExamples)
- model.setModelURL(second)
+ await model.setModelURL(second)
- #expect(model.newlineShortcut == .shiftReturn)
- #expect(!model.showPromptExamples)
+ #expect(model.newlineShortcut == .return)
+ #expect(model.showPromptExamples)
}
/// Phase D item 15. The newer-version branch says "Every key decodes with
@@ -559,7 +559,7 @@ import Testing
}
@MainActor
- @Test func changingModelDirectoryStillReleasesTheImageTower() throws {
+ @Test func changingModelDirectoryStillReleasesTheImageTower() async throws {
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)
@@ -570,10 +570,12 @@ import Testing
try MacAppSettingsFileStore.save(
MacAppSettings(visionResidencyPolicy: .keepReady),
forModelDirectory: second)
- let model = AppModel(modelDirectory: first, settingsPersistenceEnabled: true)
+ let model = AppModel(modelDirectory: first,
+ appDataDirectory: root.appendingPathComponent("app-data"),
+ settingsPersistenceEnabled: true)
#expect(model.runtimeOptions.visionResidencyPolicy == .onDemand)
- model.setModelURL(second)
+ await model.setModelURL(second)
#expect(model.runtimeOptions.visionResidencyPolicy == .onDemand,
"a persisted keep-ready came back through the model path change")
diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift
index 243961c0..3572f339 100644
--- a/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift
+++ b/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift
@@ -55,7 +55,7 @@ import TurboFieldfare
try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])
.write(to: receiptURL)
try installVisionCompanion(forTextModel: directory)
- let model = AppModel(modelDirectory: directory, client: client,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: client,
attachmentStore: attachments,
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLaunchPolicyTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLaunchPolicyTests.swift
index 53fee86d..be8a9539 100644
--- a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLaunchPolicyTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLaunchPolicyTests.swift
@@ -1,7 +1,13 @@
+import Foundation
import Testing
@testable import TurboFieldfareAppCore
@Suite struct DecodeServiceLaunchPolicyTests {
+ @Test func appDataRootIsATrustedLaunchArgumentIndependentOfTheModel() {
+ let root = URL(fileURLWithPath: "/tmp/app data тест")
+ #expect(DecodeServiceInferenceClient.appDataArguments(root) == ["--app-data-directory", root.path])
+ }
+
@Test func kickstartTargetsGUIJobWithoutRestartingIt() {
let arguments = DecodeServiceInferenceClient.kickstartArguments(
uid: 501, label: "com.turbofieldfare.decode.test")
diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift
index 1b39e187..ac626f15 100644
--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift
@@ -58,6 +58,7 @@ import TurboFieldfareRepackCore
let client = FakeInferenceClient(eventDelay: .milliseconds(1))
let model = AppModel(
modelDirectory: missing,
+ appDataDirectory: missing.deletingLastPathComponent(),
client: client,
installer: MockModelInstallerClient(events: [.installed(installed)]),
settingsPersistenceEnabled: true)
diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift
index a74103d6..fbde871e 100644
--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift
@@ -45,3 +45,71 @@ import Testing
#expect(result.path == "/support/TurboFieldfare/gemma4.gturbo")
}
}
+
+@Suite struct SelectedModelLocationValidationTests {
+ @MainActor @Test func parentSelectionPointsToCompletedTextModelChild() throws {
+ let fixture = try makeCompleteModelInstall("parent-selection-guidance")
+ defer { try? FileManager.default.removeItem(at: fixture) }
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("parent-selection-\(UUID())")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let directory = root.appendingPathComponent("gemma4.gturbo")
+ try FileManager.default.moveItem(at: fixture, to: directory)
+ // The fixture receipt binds its original location; rebind only this synthetic pack.
+ let receiptURL = directory.appendingPathComponent("verified-install.json")
+ var receipt = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any])
+ receipt["modelDirectoryPath"] = directory.standardizedFileURL.path
+ try JSONSerialization.data(withJSONObject: receipt).write(to: receiptURL)
+ #expect(AppModelInstallationProbe.status(at: directory) == .complete)
+ // A parent folder is not necessarily source checkpoint files.
+ do {
+ try AppModelLocation.validate(directory.deletingLastPathComponent(), intent: .existing)
+ Issue.record("Parent selection must require choosing the text model itself")
+ } catch {
+ #expect(String(describing: error).contains("Choose the gemma4.gturbo folder inside this folder"))
+ }
+ }
+
+ @Test(arguments: [false, true]) func unrelatedFolderGuidanceDoesNotClaimItContainsAModel(hasIncompleteChild: Bool) throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("empty-selection-\(UUID())")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ if hasIncompleteChild {
+ try FileManager.default.createDirectory(at: directory.appendingPathComponent("gemma4.gturbo"), withIntermediateDirectories: true)
+ }
+ do {
+ try AppModelLocation.validate(directory, intent: .existing)
+ Issue.record("Unrelated folder must be rejected")
+ } catch {
+ #expect(String(describing: error).contains("Choose a completed text model folder ending in .gturbo"))
+ }
+ }
+
+ @MainActor @Test func existingSelectionAcceptsReadOnlyInstallAndRejectsSourceOrPartialDirectories() throws {
+ let directory = try makeCompleteModelInstall("existing-selection")
+ defer {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
+ try? FileManager.default.removeItem(at: directory)
+ }
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: directory.path)
+ try AppModelLocation.validate(directory, intent: .existing)
+ #expect(throws: (any Error).self) { try AppModelLocation.validate(directory.deletingLastPathComponent(), intent: .existing) }
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
+ try FileManager.default.removeItem(at: directory.appendingPathComponent("manifest.json"))
+ #expect(throws: (any Error).self) { try AppModelLocation.validate(directory, intent: .existing) }
+ }
+
+ @MainActor @Test func downloadSelectionRejectsUnrelatedDirectoryAndMissingVolume() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("destination-validation-\(UUID())")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let candidate = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ try FileManager.default.createDirectory(at: candidate, withIntermediateDirectories: true)
+ #expect(throws: (any Error).self) { try AppModelLocation.validate(candidate, intent: .download) }
+ #expect(throws: (any Error).self) { try AppModelLocation.validate(URL(fileURLWithPath: "/Volumes/missing-\(UUID())/gemma4.gturbo"), intent: .download) }
+ try FileManager.default.removeItem(at: candidate)
+ try AppModelLocation.validate(candidate, intent: .download)
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: root.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path) }
+ #expect(throws: (any Error).self) { try AppModelLocation.validate(candidate, intent: .download) }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Installation/ExistingModelSelectionTests.swift b/Tests/TurboFieldfareApp/Core/Installation/ExistingModelSelectionTests.swift
new file mode 100644
index 00000000..15f37efc
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Installation/ExistingModelSelectionTests.swift
@@ -0,0 +1,205 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+@Suite struct ExistingModelSelectionTests {
+ @MainActor @Test(arguments: ["not-a-pack", "other.vision.gturbo"])
+ func invalidAliasTargetDoesNotHideAValidSiblingModel(targetName: String) throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = try fixture(in: root, name: "ready")
+ let target = root.appendingPathComponent(targetName)
+ try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("invalid.gturbo"),
+ withDestinationURL: target)
+ // Validate the resolved target, not just the alias's .gturbo suffix.
+ let review = try ExistingModelSelection.inspect(root)
+ #expect(review.candidates.map(\.textURL.path) == [text.path])
+ #expect(review.initialSelection == text.path)
+ }
+
+ private func root() throws -> URL {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("model-review-\(UUID())")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ @MainActor private func fixture(in root: URL, name: String, vision: Bool = false) throws -> URL {
+ let original = try makeCompleteModelInstall("folder-review")
+ defer { try? FileManager.default.removeItem(at: original) }
+ let text = root.appendingPathComponent(name + ".gturbo")
+ try FileManager.default.moveItem(at: original, to: text)
+ let receiptURL = text.appendingPathComponent("verified-install.json")
+ var receipt = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any])
+ receipt["modelDirectoryPath"] = text.standardizedFileURL.path
+ try JSONSerialization.data(withJSONObject: receipt).write(to: receiptURL)
+ if vision { try installVisionCompanion(forTextModel: text) }
+ return text
+ }
+
+ @MainActor @Test func parentAndDirectSelectionFindSamePairWithoutIncludingVisionAsText() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = try fixture(in: root, name: "custom тест", vision: true)
+ let parent = try ExistingModelSelection.inspect(root)
+ let direct = try ExistingModelSelection.inspect(text)
+ #expect(parent.candidates == direct.candidates)
+ #expect(parent.candidates.count == 1)
+ #expect(parent.initialSelection == text.path)
+ #expect(parent.candidates[0].visionStatus == .complete)
+ #expect(parent.candidates[0].visionURL.lastPathComponent == "custom тест.vision.gturbo")
+ #expect(throws: (any Error).self) { try ExistingModelSelection.inspect(parent.candidates[0].visionURL) }
+ }
+
+ @MainActor @Test func multipleCandidatesRequireChoiceAndNeverBorrowAnotherModelsVisionPack() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let first = try fixture(in: root, name: "a", vision: true)
+ let second = try fixture(in: root, name: "b")
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("incomplete.gturbo"), withIntermediateDirectories: true)
+ let review = try ExistingModelSelection.inspect(root)
+ #expect(review.initialSelection == nil)
+ #expect(review.candidates.count == 3)
+ #expect(review.candidates.first { $0.textURL.path == first.path }?.visionStatus == .complete)
+ #expect(review.candidates.first { $0.textURL.path == second.path }?.visionStatus == .missing)
+ #expect(review.candidates.last?.canSelect == false)
+ }
+
+ @MainActor @Test func brokenAliasDoesNotHideAValidSiblingModel() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = try fixture(in: root, name: "ready")
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("disconnected.gturbo"),
+ withDestinationURL: root.appendingPathComponent("missing/model.gturbo"))
+ let review = try ExistingModelSelection.inspect(root)
+ #expect(review.candidates.filter(\.canSelect).map(\.textURL.path) == [text.path])
+ }
+
+ @Test func emptyMissingAndNestedOnlyFoldersAreRejected() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ #expect(throws: (any Error).self) { try ExistingModelSelection.inspect(root) }
+ #expect(throws: (any Error).self) { try ExistingModelSelection.inspect(root.appendingPathComponent("missing")) }
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("nested/model.gturbo"), withIntermediateDirectories: true)
+ #expect(throws: (any Error).self) { try ExistingModelSelection.inspect(root) }
+ }
+
+ @MainActor @Test func incompatibleCompanionIsReportedWithoutRejectingValidText() throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = try fixture(in: root, name: "a", vision: true)
+ let vision = try VisionPackLocation.companionURL(forTextModel: text)
+ let manifest = vision.appendingPathComponent("manifest.json")
+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: manifest)) as? [String: Any])
+ json["compatibleTextManifestSha256"] = String(repeating: "0", count: 64)
+ try JSONSerialization.data(withJSONObject: json).write(to: manifest)
+ let candidate = try #require(ExistingModelSelection.inspect(root).candidates.first)
+ #expect(candidate.canSelect)
+ if case .partial = candidate.visionStatus {} else { Issue.record("Incompatible vision must explain the failure") }
+ #expect(candidate.visionSummary.contains("invalid or incompatible"))
+ }
+
+ @MainActor @Test(arguments: [false, true], [false, true])
+ func singleValidModelIsSelectedWithoutReview(vision: Bool, direct: Bool) async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let packs = root.appendingPathComponent("packs")
+ try FileManager.default.createDirectory(at: packs, withIntermediateDirectories: true)
+ let text = try fixture(in: packs, name: "chosen", vision: vision)
+ try FileManager.default.createDirectory(at: packs.appendingPathComponent("partial.gturbo"), withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: packs.appendingPathComponent("alias.gturbo"), withDestinationURL: text)
+ let data = root.appendingPathComponent("app-data")
+ let model = AppModel(appDataDirectory: data,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": data.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { model.shutdownForTermination() }
+ // Partial packs and aliases must not force confirmation of the only usable model.
+ await model.reviewExistingModelLocation(direct ? text : packs)
+ #expect(model.existingModelReview == nil)
+ #expect(model.modelPathText == text.path)
+ #expect(model.modelLocationDiagnostic == nil)
+ #expect(model.isVisionPackInstalled == vision)
+ #expect(try MacAppSettingsFileStore.load(at: data.appendingPathComponent("mac-app-settings.json"))?.selectedModelPath == text.path)
+ }
+
+ @MainActor @Test func reviewCancelAndChangedFilesDoNotCommitSelection() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let packs = root.appendingPathComponent("packs")
+ try FileManager.default.createDirectory(at: packs, withIntermediateDirectories: true)
+ let text = try fixture(in: packs, name: "chosen", vision: true)
+ _ = try fixture(in: packs, name: "other")
+ let data = root.appendingPathComponent("app-data")
+ let model = AppModel(appDataDirectory: data,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": data.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { model.shutdownForTermination() }
+ let previous = model.modelPathText
+ let settings = data.appendingPathComponent("mac-app-settings.json")
+ let saved = try Data(contentsOf: settings)
+ await model.reviewExistingModelLocation(packs)
+ #expect(model.modelPathText == previous)
+ #expect(try Data(contentsOf: settings) == saved)
+ model.existingModelReview = nil
+ #expect(try Data(contentsOf: settings) == saved)
+ await model.reviewExistingModelLocation(packs)
+ let candidate = try #require(model.existingModelReview?.candidates.first)
+ try FileManager.default.removeItem(at: candidate.visionURL)
+ #expect(await !model.confirmExistingModelSelection(candidate))
+ #expect(model.modelPathText == previous)
+ #expect(try Data(contentsOf: settings) == saved)
+ let refreshed = try #require(model.existingModelReview?.candidates.first)
+ #expect(refreshed.visionStatus == .missing)
+ #expect(await model.confirmExistingModelSelection(refreshed))
+ #expect(model.modelPathText == text.path)
+ #expect(try MacAppSettingsFileStore.load(at: settings)?.selectedModelPath == text.path)
+ #expect(model.existingModelReview == nil)
+ #expect(!model.isVisionPackInstalled)
+ model.shutdownForTermination()
+ let reopened = AppModel(appDataDirectory: data,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": data.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { reopened.shutdownForTermination() }
+ #expect(reopened.modelPathText == text.path)
+ }
+
+ @MainActor @Test func aliasesAreDeduplicatedAndBusyConfirmationDoesNotChangeSelection() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = try fixture(in: root, name: "original")
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("alias.gturbo"), withDestinationURL: text)
+ #expect(try ExistingModelSelection.inspect(root).candidates.count == 1)
+ let aliases = root.appendingPathComponent("aliases")
+ try FileManager.default.createDirectory(at: aliases, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: aliases.appendingPathComponent("external.gturbo"), withDestinationURL: text)
+ #expect(try ExistingModelSelection.inspect(aliases).candidates.first?.id == text.path)
+ let data = root.appendingPathComponent("settings")
+ let model = AppModel(appDataDirectory: data, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": data.path], client: MockLifecycleInferenceClient())
+ defer { model.shutdownForTermination() }
+ let previous = model.modelPathText
+ _ = try fixture(in: root, name: "second")
+ await model.reviewExistingModelLocation(root)
+ let candidate = try #require(model.existingModelReview?.candidates.first)
+ model.loadState = .loading(.tokenizer)
+ #expect(await !model.confirmExistingModelSelection(candidate))
+ #expect(model.modelPathText == previous)
+ }
+
+ @MainActor @Test func invalidTextCandidateCannotBeConfirmed() async throws {
+ let root = try root()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("partial.gturbo"), withIntermediateDirectories: true)
+ let review = try ExistingModelSelection.inspect(root)
+ #expect(review.initialSelection == nil)
+ #expect(review.candidates[0].canSelect == false)
+ let model = AppModel(appDataDirectory: root, environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path], client: MockLifecycleInferenceClient())
+ defer { model.shutdownForTermination() }
+ let previous = model.modelPathText
+ await model.reviewExistingModelLocation(root)
+ #expect(model.existingModelReview == nil)
+ #expect(model.modelLocationDiagnostic?.contains("manifest.json is missing") == true)
+ #expect(await !model.confirmExistingModelSelection(review.candidates[0]))
+ #expect(model.modelPathText == previous)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift
index a4390dc1..6793a273 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift
@@ -159,7 +159,7 @@ import Testing
#expect(model.conversation.committedTurns == 2)
let before = model.conversation.epoch
- model.setModelURL(FileManager.default.temporaryDirectory
+ await model.setModelURL(FileManager.default.temporaryDirectory
.appendingPathComponent("another-model", isDirectory: true))
#expect(model.conversation.committedTurns == 0)
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift
index df387131..2123dec5 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift
@@ -494,7 +494,7 @@ import TurboFieldfare
let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
try FileManager.default.createDirectory(
at: directory, withIntermediateDirectories: true)
- let model = AppModel(modelDirectory: directory, client: client,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: client,
attachmentStore: attachmentStore,
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
@@ -610,7 +610,7 @@ import TurboFieldfare
}
@MainActor
- @Test func deletionWaitingOnAnOldBindingDoesNotMutateEitherStore() async throws {
+ @Test func modelSwitchIsRefusedWhileDeletionOwnsTheStore() async throws {
let client = FakeInferenceClient(eventDelay: .milliseconds(1))
let (model, root) = try await readyModel(client)
defer { try? FileManager.default.removeItem(at: root) }
@@ -626,12 +626,12 @@ import TurboFieldfare
let deletion = try #require(model.conversationDeletionTask)
await Task.yield()
let newDirectory = root.appendingPathComponent("other/gemma4.gturbo")
- model.setModelURL(newDirectory)
+ await model.setModelURL(newDirectory)
await gate.open()
await deletion.value
try await model.waitForHistory(count: 0)
- #expect(FileManager.default.fileExists(atPath: folder.path))
- #expect(model.modelPathText == newDirectory.path)
+ #expect(!FileManager.default.fileExists(atPath: folder.path))
+ #expect(model.modelPathText != newDirectory.path)
#expect(model.storedConversationID == nil)
#expect(model.conversationDeletionTask == nil)
#expect(model.historyDiagnostic == nil)
@@ -755,7 +755,7 @@ import TurboFieldfare
}
@MainActor
- @Test func rootSwitchCancelsAQueuedTurnBeforeItCanAppendOrReport() async throws {
+ @Test func modelSwitchWaitsForQueuedTurnAndKeepsTheStore() async throws {
let client = FakeInferenceClient(eventDelay: .milliseconds(20))
let (model, root) = try await readyModel(client)
defer { try? FileManager.default.removeItem(at: root) }
@@ -777,21 +777,24 @@ import TurboFieldfare
let newDirectory = root.appendingPathComponent("other/model.gturbo", isDirectory: true)
try FileManager.default.createDirectory(
at: newDirectory, withIntermediateDirectories: true)
- model.setModelURL(newDirectory)
+ let switching = Task { await model.setModelURL(newDirectory) }
+ await Task.yield()
+ #expect(model.conversationStore === oldStore)
await gate.open()
await oldTail.value
+ await switching.value
let oldTurns = try await oldStore.open(id: oldID).records.filter {
if case .turn = $0 { return true }
return false
}
- #expect(oldTurns.isEmpty)
+ #expect(!oldTurns.isEmpty)
#expect(model.conversationBinding?.modelDirectory == newDirectory.standardizedFileURL)
#expect(model.historyDiagnostic == nil)
}
@MainActor
- @Test func rootSwitchCancelsAnOlderWriteAtTheBatchBoundary() async throws {
+ @Test func modelSwitchWaitsAtBatchBoundaryAndKeepsTheStore() async throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("history-batch-cancel-\(UUID())", isDirectory: true)
defer { try? FileManager.default.removeItem(at: root) }
@@ -801,6 +804,7 @@ import TurboFieldfare
let client = FakeInferenceClient(eventDelay: .milliseconds(1))
let model = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: client,
settingsPersistenceEnabled: true,
conversationStoreProvider: { root in
@@ -829,16 +833,18 @@ import TurboFieldfare
let newDirectory = root.appendingPathComponent("other/model.gturbo", isDirectory: true)
try FileManager.default.createDirectory(
at: newDirectory, withIntermediateDirectories: true)
- model.setModelURL(newDirectory)
+ let switching = Task { await model.setModelURL(newDirectory) }
+ await Task.yield()
+ #expect(model.conversationStore === oldStore)
await gate.open()
await oldTail.value
+ await switching.value
let oldTurns = try await oldStore.open(id: oldID).records.filter {
if case .turn = $0 { return true }
return false
}
- #expect(oldTurns.isEmpty,
- "cancellation after entering append must stop the old-root batch")
+ #expect(!oldTurns.isEmpty, "model switching must let the committed batch finish")
#expect(model.conversationBinding?.modelDirectory == newDirectory.standardizedFileURL)
#expect(model.historyDiagnostic == nil)
}
@@ -854,6 +860,7 @@ import TurboFieldfare
let client = FakeInferenceClient(eventDelay: .milliseconds(1))
let model = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: client,
settingsPersistenceEnabled: true,
conversationStoreProvider: { root in
@@ -950,6 +957,7 @@ import TurboFieldfare
let model = AppModel(
modelDirectory: directoryA,
+ appDataDirectory: directoryA.deletingLastPathComponent(),
client: FakeInferenceClient(),
settingsPersistenceEnabled: true,
conversationIdentityProvider: { directory in
@@ -961,15 +969,16 @@ import TurboFieldfare
? storeA : storeB
})
await gate.waitUntilEntered()
- model.setModelURL(directoryB)
- try await model.waitForHistory(count: 1)
+ await model.setModelURL(directoryB)
await gate.open()
+ try await model.waitForHistory(count: 1)
try await Task.sleep(for: .milliseconds(30))
#expect(model.conversationBinding?.modelDirectory == directoryB.standardizedFileURL)
#expect(model.conversationIdentity == identityB)
- #expect(model.history.entries.map(\.id) == [metaB.id])
- #expect(model.history.entry(metaA.id) == nil)
+ #expect(model.history.entries.map(\.id) == [metaA.id])
+ #expect(model.history.entry(metaB.id) == nil)
+ #expect(model.conversationStore === storeA)
}
@MainActor
@@ -989,6 +998,7 @@ import TurboFieldfare
let model = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: FakeInferenceClient(),
settingsPersistenceEnabled: true)
try await waitUntil { await model.history.discardedLegacyTrashCount == 2 }
@@ -1038,6 +1048,7 @@ import TurboFieldfare
let model = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: FakeInferenceClient(),
settingsPersistenceEnabled: true,
conversationIdentityProvider: { _ in
@@ -1199,6 +1210,7 @@ import TurboFieldfare
let firstClient = FakeInferenceClient(eventDelay: .milliseconds(1))
var first: AppModel? = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: firstClient,
settingsPersistenceEnabled: true)
first?.conversationIdentity = Self.identity
@@ -1226,6 +1238,7 @@ import TurboFieldfare
let second = AppModel(
modelDirectory: directory,
+ appDataDirectory: directory.deletingLastPathComponent(),
client: FakeInferenceClient(eventDelay: .milliseconds(1)),
settingsPersistenceEnabled: true)
second.conversationIdentity = Self.identity
@@ -2268,7 +2281,7 @@ import TurboFieldfare
try FileManager.default.createDirectory(
at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
- let model = AppModel(modelDirectory: directory, client: client,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: client,
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
model.conversationIdentity = Self.identity
@@ -3083,7 +3096,7 @@ extension AppModelHistoryTests {
rootURL: ConversationStoreLocation.url(forModelDirectory: directory))
try await holder.activate()
- let model = AppModel(modelDirectory: directory, client: client,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: client,
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
model.conversationIdentity = Self.identity
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift
index 9ee2ff18..ad62d773 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift
@@ -210,24 +210,26 @@ import Testing
let model = AppModel(modelDirectory: oldURL, client: client)
model.loadState = .ready(modelDirectory: oldURL, loadSeconds: 1)
- model.setModelURL(newURL)
+ let switchTask = Task { await model.setModelURL(newURL) }
await client.waitForUnloadStart()
model.loadModel()
#expect(client.ensureLoadedCallCount() == 0)
client.releaseUnloads()
+ await switchTask.value
+ model.loadModel()
await client.waitForEnsureLoadedCallCount(1)
#expect(client.ensureLoadedCallCount() == 1)
}
@MainActor
- @Test func staleReadyStateForOldModelPathIsIgnored() {
+ @Test func staleReadyStateForOldModelPathIsIgnored() async {
let model = AppModel(client: MockInferenceClient())
let oldURL = URL(fileURLWithPath: "/tmp/old.gturbo")
let newURL = URL(fileURLWithPath: "/tmp/new.gturbo")
model.modelPathText = oldURL.path
- model.setModelURL(newURL)
+ await model.setModelURL(newURL)
model.applyLoadState(.ready(modelDirectory: oldURL, loadSeconds: 0))
#expect(model.loadState == .notLoaded)
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift
index 204fe733..beec58d7 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift
@@ -78,7 +78,7 @@ import TurboFieldfare
try installVisionCompanion(forTextModel: directory)
let attachments = AppImageAttachmentStore(
directoryURL: root.appendingPathComponent("staged", isDirectory: true))
- let model = AppModel(modelDirectory: directory, client: client,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: client,
attachmentStore: attachments,
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift
index 1d2bcacd..923da411 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift
@@ -13,14 +13,14 @@ import Testing
let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
- let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), settingsPersistenceEnabled: true)
model.modelPathText = directory.path
// Slider bindings update the model without invoking a persistence action.
model.temperature = 0.35
model.topK = 17
model.topP = 0.8
model.shutdownForTermination()
- let reopened = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)
+ let reopened = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), settingsPersistenceEnabled: true)
#expect(reopened.temperature == 0.35)
#expect(reopened.topK == 17)
#expect(reopened.topP == 0.8)
@@ -35,7 +35,7 @@ import Testing
at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
- let model = AppModel(modelDirectory: directory,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
#expect(model.isSidebarVisible, "the list is shown by default")
@@ -45,12 +45,12 @@ import Testing
// A new model over the same directory has to come back hidden: the
// window remembering its shape is the whole reason this is persisted.
- let reopened = AppModel(modelDirectory: directory,
+ let reopened = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
#expect(!reopened.isSidebarVisible)
model.setSidebarVisible(true)
- let again = AppModel(modelDirectory: directory,
+ let again = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
#expect(again.isSidebarVisible)
}
@@ -67,7 +67,7 @@ import Testing
at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
- let model = AppModel(modelDirectory: directory,
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
model.modelPathText = directory.path
#expect(model.isInspectorVisible, "the Inspector is shown by default")
@@ -76,7 +76,7 @@ import Testing
#expect(!model.isInspectorVisible)
#expect(model.isSidebarVisible, "hiding one panel moved the other")
- let reopened = AppModel(modelDirectory: directory,
+ let reopened = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(),
settingsPersistenceEnabled: true)
#expect(!reopened.isInspectorVisible)
#expect(reopened.isSidebarVisible)
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
index 172f4027..122ea419 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
@@ -37,7 +37,7 @@ import Testing
let root = try makeSettingsRoot()
defer { try? FileManager.default.removeItem(at: root) }
let directory = root.appendingPathComponent("model.gturbo")
- let model = AppModel(modelDirectory: directory, client: MockLifecycleInferenceClient(),
+ let model = AppModel(modelDirectory: directory, appDataDirectory: directory.deletingLastPathComponent(), client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true, hostMemoryBytes: 8 << 30)
model.setMaxContextTokens(131_072)
model.setExpertCacheSlots(24)
@@ -52,7 +52,7 @@ import Testing
#expect(model.maxContextTokens == 65_536)
}
- @MainActor @Test func storedCacheGrowthClampsOnLaunchAndModelChange() throws {
+ @MainActor @Test func storedCacheGrowthClampsOnLaunchAndModelChange() async throws {
let root = try makeSettingsRoot()
defer { try? FileManager.default.removeItem(at: root) }
let first = root.appendingPathComponent("first/model.gturbo")
@@ -62,11 +62,11 @@ import Testing
expertCacheSlots: 24),
forModelDirectory: directory)
}
- let model = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),
+ let model = AppModel(modelDirectory: first, appDataDirectory: first.deletingLastPathComponent(), client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true, hostMemoryBytes: 8 << 30)
#expect(model.maxContextTokens == 65_536)
#expect(model.contextClampNotice != nil)
- model.setModelURL(second)
+ await model.setModelURL(second)
#expect(model.maxContextTokens == 65_536)
#expect(model.contextClampNotice != nil)
}
@@ -438,7 +438,7 @@ import Testing
}
@MainActor
- @Test func changingModelPathInvalidatesLoadedStateAndDiagnostics() {
+ @Test func changingModelPathInvalidatesLoadedStateAndDiagnostics() async {
let model = AppModel(client: MockInferenceClient(),
installer: MockModelInstallerClient())
let testDirectory = FileManager.default.temporaryDirectory
@@ -457,7 +457,7 @@ import Testing
runtimeOptions: AppRuntimeOptions())
model.error = .unknown("old error")
- model.setModelURL(newURL)
+ await model.setModelURL(newURL)
#expect(model.modelPathText == newURL.standardizedFileURL.path)
#expect(model.loadState == .notLoaded)
@@ -480,7 +480,7 @@ import Testing
try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),
forModelDirectory: modelDirectory)
- let model = AppModel(modelDirectory: modelDirectory,
+ let model = AppModel(modelDirectory: modelDirectory, appDataDirectory: modelDirectory.deletingLastPathComponent(),
client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true,
hostMemoryBytes: 8_589_934_592)
@@ -509,7 +509,7 @@ import Testing
/// to survive being set — assigning the context clears it, so an
/// assignment made after the notice would wipe it.
@MainActor
- @Test func achangedModelDirectoryClampsItsStoredContextToo() throws {
+ @Test func changingModelDirectoryPreservesCentralContext() async throws {
let root = try makeSettingsRoot()
defer { try? FileManager.default.removeItem(at: root) }
let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)
@@ -518,17 +518,16 @@ import Testing
forModelDirectory: first)
try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),
forModelDirectory: second)
- let model = AppModel(modelDirectory: first,
+ let model = AppModel(modelDirectory: first, appDataDirectory: first.deletingLastPathComponent(),
client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true,
hostMemoryBytes: 8_589_934_592)
try #require(model.contextClampNotice == nil)
- model.setModelURL(second)
+ await model.setModelURL(second)
- #expect(model.maxContextTokens == 131_072)
- #expect(model.contextClampNotice?.contains("262,144") == true,
- "the clamp on the settings-apply path said nothing")
+ #expect(model.maxContextTokens == 8_192)
+ #expect(model.contextClampNotice == nil)
}
@MainActor
@@ -539,7 +538,7 @@ import Testing
try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),
forModelDirectory: modelDirectory)
- let model = AppModel(modelDirectory: modelDirectory,
+ let model = AppModel(modelDirectory: modelDirectory, appDataDirectory: modelDirectory.deletingLastPathComponent(),
client: MockLifecycleInferenceClient(),
settingsPersistenceEnabled: true,
hostMemoryBytes: 25_769_803_776)
diff --git a/Tests/TurboFieldfareApp/Core/State/AppVisionSelectionReadinessTests.swift b/Tests/TurboFieldfareApp/Core/State/AppVisionSelectionReadinessTests.swift
new file mode 100644
index 00000000..45e5b9c6
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppVisionSelectionReadinessTests.swift
@@ -0,0 +1,144 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+@Suite struct AppVisionSelectionReadinessTests {
+ @MainActor @Test func selectingInstalledPairClearsMissingTextFailureAndSurvivesRelaunch() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("vision-selection-\(UUID())")
+ let text = try makeVisionReadyModelInstall("selection-readiness")
+ let vision = try VisionPackLocation.companionURL(forTextModel: text)
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: text)
+ try? FileManager.default.removeItem(at: vision)
+ }
+ let model = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { model.shutdownForTermination() }
+ #expect(model.visionInstallReadiness == .failed("Install the text model first"))
+ await model.selectModelLocation(text, intent: .existing)
+ #expect(model.isModelInstalled)
+ #expect(model.installReadiness == .installed)
+ #expect(!model.canInstallModel)
+ #expect(model.isVisionPackInstalled)
+ #expect(model.isImageInputAvailable)
+ // Previously the completed-pack early return retained the first-run failure.
+ #expect(model.visionInstallReadiness == .installed)
+ #expect(!model.canInstallVisionPack)
+ model.refreshVisionInstallReadiness()
+ #expect(model.visionInstallReadiness == .installed)
+ model.shutdownForTermination()
+ let reopened = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { reopened.shutdownForTermination() }
+ #expect(reopened.isVisionPackInstalled)
+ #expect(reopened.visionInstallReadiness == .installed)
+ }
+
+ @MainActor @Test func selectingSameModelRefreshesVisionAndClearsOnlyItsSelectionError() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("same-model-\(UUID())")
+ let text = try makeCompleteModelInstall("same-model-refresh")
+ let vision = try VisionPackLocation.companionURL(forTextModel: text)
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: text)
+ try? FileManager.default.removeItem(at: vision)
+ }
+ let model = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { model.shutdownForTermination() }
+ await model.selectModelLocation(text, intent: .existing)
+ #expect(!model.isVisionPackInstalled)
+ model.loadState = .ready(modelDirectory: text, loadSeconds: 0)
+ await model.reviewExistingModelLocation(root.appendingPathComponent("absent"))
+ #expect(model.modelLocationDiagnostic != nil)
+ #expect(model.error != nil)
+ try installVisionCompanion(forTextModel: text)
+ // Reselecting the active path previously returned before refreshing its companion.
+ await model.reviewExistingModelLocation(text)
+ #expect(model.isVisionPackInstalled)
+ #expect(model.visionInstallReadiness == .installed)
+ #expect(model.loadState.isReady)
+ #expect(model.modelLocationDiagnostic == nil)
+ #expect(model.error == nil)
+ model.error = .connectionLost("independent failure")
+ await model.reviewExistingModelLocation(text)
+ #expect(model.error == .connectionLost("independent failure"))
+ }
+
+ @MainActor @Test func modelSwitchBlocksImagesWhileWaitingForChatPersistence() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("switch-images-\(UUID())")
+ let text = try makeVisionReadyModelInstall("switch-images")
+ let vision = try VisionPackLocation.companionURL(forTextModel: text)
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: text)
+ try? FileManager.default.removeItem(at: vision)
+ }
+ let model = AppModel(appDataDirectory: root,
+ environment: ["TURBO_FIELDFARE_APP_DATA_PATH": root.path],
+ client: MockLifecycleInferenceClient(), settingsPersistenceEnabled: true)
+ defer { model.shutdownForTermination() }
+ await model.selectModelLocation(text, intent: .existing)
+ let gate = AsyncStream<Void>.makeStream()
+ model.persistenceTail = Task { for await _ in gate.stream {} }
+ let destination = root.appendingPathComponent("new-destination")
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
+ let change = Task { await model.selectModelLocation(destination, intent: .download) }
+ while !model.isChangingModelLocation { await Task.yield() }
+ // Promised drops can arrive after the panel has begun switching models.
+ let promised = root.appendingPathComponent("promised")
+ try FileManager.default.createDirectory(at: promised, withIntermediateDirectories: true)
+ let file = promised.appendingPathComponent("image.png")
+ try Data([0]).write(to: file)
+ model.addImages([file], discardingSourceDirectory: promised)
+ #expect(!model.isAddingImages)
+ #expect(!FileManager.default.fileExists(atPath: promised.path))
+ model.addImageData(Data([0]), displayName: "pasted.png")
+ #expect(!model.isAddingImages)
+ #expect(model.imageAttachmentError?.contains("model location change") == true)
+ gate.continuation.finish()
+ await change.value
+ }
+
+ @MainActor @Test func installedPairClearsStorageWarningButMissingOrDamagedFilesRemainVisible() throws {
+ let text = try makeCompleteModelInstall("vision-readiness-transitions")
+ let vision = try VisionPackLocation.companionURL(forTextModel: text)
+ defer {
+ try? FileManager.default.removeItem(at: text)
+ try? FileManager.default.removeItem(at: vision)
+ }
+ let installer = MockVisionPackInstallerClient(requirement: .init(probePath: text.path, requiredBytes: 10, availableBytes: 0))
+ let model = AppModel(modelDirectory: text, client: MockLifecycleInferenceClient(), visionInstaller: installer)
+ defer { model.shutdownForTermination() }
+ #expect(model.visionInstallReadiness.requirement?.shortfallBytes == 10)
+ try installVisionCompanion(forTextModel: text)
+ model.recheckModelAtCurrentLocation()
+ #expect(model.visionInstallReadiness == .installed)
+ #expect(model.isImageInputAvailable)
+
+ let manifest = text.appendingPathComponent("manifest.json")
+ let saved = try Data(contentsOf: manifest)
+ try FileManager.default.removeItem(at: manifest)
+ model.recheckModelAtCurrentLocation()
+ #expect(model.visionInstallReadiness == .failed("Install the text model first"))
+ #expect(!model.isImageInputAvailable)
+ try saved.write(to: manifest)
+ model.recheckModelAtCurrentLocation()
+ #expect(model.visionInstallReadiness == .installed)
+
+ try Data("broken".utf8).write(to: vision.appendingPathComponent("manifest.json"))
+ model.recheckModelAtCurrentLocation()
+ if case .partial = model.visionInstallationStatus {} else { Issue.record("Corrupt companion must remain a visible repair failure") }
+ #expect(!model.isImageInputAvailable)
+ #expect(model.visionInstallReadiness != .installed)
+ try FileManager.default.removeItem(at: vision)
+ model.recheckModelAtCurrentLocation()
+ #expect(model.visionInstallationStatus == .missing)
+ #expect(model.visionInstallReadiness.requirement?.shortfallBytes == 10)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift b/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift
index 6570f026..07e23789 100644
--- a/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift
@@ -12,6 +12,48 @@ import TurboFieldfare
/// and a new screen case or a new event fails to compile until every cell it
/// creates is written down.
@Suite struct ConversationScreenMachineTests {
+ @MainActor
+ @Test(arguments: [false, true])
+ func loadingSavedChatNeverShowsNewChatScreen(emptyDocument: Bool) {
+ let model = AppModel(client: FakeInferenceClient())
+ model.setShowPromptExamples(true)
+ #expect(!model.hasOutputTranscript)
+ #expect(model.shouldShowPromptExamples)
+
+ _ = model.machine.apply(Self.clicked(Self.row))
+ // A pending disk read used to show the startup screen and examples.
+ #expect(model.screen.document == nil)
+ #expect(model.hasOutputTranscript)
+ #expect(!model.shouldShowPromptExamples)
+ #expect(!model.showsLiveTurn)
+
+ let document = emptyDocument ? ConversationDocument.load(
+ ConversationOpenResult(meta: Self.stored.meta, records: [],
+ isReadOnly: false, droppedTornFinalLine: false),
+ directory: URL(fileURLWithPath: "/tmp/unused-chat-fixture")) : Self.stored
+ _ = model.machine.apply(.documentLoaded(
+ id: Self.row, renderID: Self.renderB, document: document, state: .continuable))
+ #expect(model.hasOutputTranscript == !emptyDocument)
+
+ _ = model.machine.apply(Self.clicked(Self.other))
+ #expect(model.hasOutputTranscript)
+ #expect(!model.shouldShowPromptExamples)
+ // A stale read cannot bring the previous chat or its empty state back.
+ _ = model.machine.apply(.documentLoaded(
+ id: Self.row, renderID: Self.renderB, document: document, state: .continuable))
+ #expect(model.screen.conversationID == Self.other)
+ #expect(model.hasOutputTranscript)
+
+ _ = model.machine.apply(.documentFailed(
+ id: Self.other, renderID: Self.renderB, Self.unreadableError))
+ #expect(model.screen.shape == .unreadable)
+ #expect(!model.hasOutputTranscript)
+
+ _ = model.machine.apply(.newChat)
+ #expect(!model.hasOutputTranscript)
+ #expect(model.shouldShowPromptExamples)
+ }
+
@Test(arguments: [false, true])
func adversarialOldReadCannotReplaceReopenedSameChat(failure: Bool) {
var machine = ConversationScreenMachine()
diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift
index ba3db1d7..1a3eb31e 100644
--- a/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift
+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift
@@ -117,7 +117,7 @@ final class HistoryHarness {
attachmentStore = AppImageAttachmentStore(
directoryURL: root.appendingPathComponent(
"staged-\(UUID().uuidString)", isDirectory: true))
- let model = AppModel(modelDirectory: modelDirectory, client: client,
+ let model = AppModel(modelDirectory: modelDirectory, appDataDirectory: modelDirectory.deletingLastPathComponent(), client: client,
attachmentStore: attachmentStore,
settingsPersistenceEnabled: true)
model.modelPathText = modelDirectory.path
diff --git a/Tests/TurboFieldfareApp/MacPresentation/InspectorLayoutTests.swift b/Tests/TurboFieldfareApp/MacPresentation/InspectorLayoutTests.swift
new file mode 100644
index 00000000..029a1f10
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/InspectorLayoutTests.swift
@@ -0,0 +1,53 @@
+import AppKit
+import SwiftUI
+import Testing
+@testable import TurboFieldfareAppCore
+@testable import TurboFieldfareMac
+
+@Suite(.serialized) @MainActor struct InspectorLayoutTests {
+ @Test func runtimeControlsStayInsideTheInspector() async throws {
+ _ = NSApplication.shared
+ let modelURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("inspector-layout-\(UUID()).gturbo")
+ let model = AppModel(modelDirectory: modelURL, environment: [:])
+ model.installationStatus = .complete
+ model.applyLoadState(.ready(modelDirectory: modelURL, loadSeconds: 0))
+ let host = NSHostingView(rootView: InspectorView(model: model)
+ .frame(width: RootView.inspectorWidth))
+ let window = NSWindow(
+ contentRect: NSRect(x: 0, y: 0, width: RootView.inspectorWidth, height: 780),
+ styleMask: .borderless, backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = host
+ window.orderFront(nil)
+ defer {
+ window.orderOut(nil)
+ window.contentView = nil
+ window.close()
+ }
+ let deadline = ContinuousClock.now + .seconds(3)
+ while scrollViews(in: host).isEmpty, ContinuousClock.now < deadline {
+ await Task.yield()
+ host.layoutSubtreeIfNeeded()
+ }
+ let scroll = try #require(scrollViews(in: host).first)
+ for policy in AppRDAdvicePolicy.allCases {
+ model.runtimeOptions.rdadvisePolicy = policy
+ for topK in [false, true] {
+ model.topKEnabled = topK
+ await Task.yield()
+ host.layoutSubtreeIfNeeded()
+ // The segmented picker forced this scroll view wider than its
+ // fixed panel; clicking it widened it again and clipped every row.
+ let frame = scroll.convert(scroll.bounds, to: host)
+ #expect(frame.width <= RootView.inspectorWidth + 0.5)
+ #expect(frame.minX >= -0.5)
+ #expect(frame.maxX <= host.bounds.width + 0.5)
+ }
+ }
+ }
+
+ private func scrollViews(in view: NSView) -> [NSScrollView] {
+ (view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap(scrollViews)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift
index e30a4198..9f5f3289 100644
--- a/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift
+++ b/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift
@@ -46,4 +46,19 @@ import Testing
#expect(ModelRevealPolicy.target(forModelPath: "/",
fileExists: { _ in false }) == .unavailable)
}
+
+ @Test func existingDirectoryWithTrailingSpaceKeepsItsExactName() {
+ // A folder picked from Finder can end with a space. Trimming it would
+ // reveal a different model or its parent instead of the selected item.
+ let path = "/Volumes/Models/модель.gturbo "
+ #expect(ModelRevealPolicy.target(forModelPath: path,
+ fileExists: { $0 == path }) == .selectItem(
+ URL(fileURLWithPath: path, isDirectory: true)))
+ }
+
+ @Test func disconnectedVolumeDoesNotRevealUnrelatedVolumesDirectory() {
+ #expect(ModelRevealPolicy.target(
+ forModelPath: "/Volumes/Disconnected/gemma4.gturbo",
+ fileExists: { $0 == "/Volumes" || $0 == "/" }) == .unavailable)
+ }
}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift b/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift
index 230c6fc7..7cd33171 100644
--- a/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift
+++ b/Tests/TurboFieldfareApp/MacPresentation/StoredStateTests.swift
@@ -128,6 +128,7 @@ import TurboFieldfareAppCore
}
let delegateModel = AppModel(
modelDirectory: directory.appendingPathComponent("missing.gturbo"),
+ appDataDirectory: directory.appendingPathComponent("app-data"),
client: NoGenerationClient(), visionRuntimeSupported: false,
settingsPersistenceEnabled: true)
defer { delegateModel.shutdownForTermination() }
diff --git a/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift b/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift
index 12a9ab52..be4224d7 100644
--- a/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift
+++ b/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift
@@ -236,3 +236,23 @@ import TurboFieldfareDecodeProtocol
#expect(!ConversationStoreLocation.contains(store, forModelDirectory: model))
}
}
+
+@Suite struct DecodeReplayImageAppDataTrustTests {
+ @Test func appDataContainmentExcludesModelVolumeAndSimilarPrefixes() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("trusted-replay-\(UUID())")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let images = root.appendingPathComponent("conversations/\(UUID())/images", isDirectory: true)
+ try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true)
+ let inside = images.appendingPathComponent("image.png")
+ try Data([0]).write(to: inside)
+ #expect(ConversationStoreLocation.contains(inside, forAppDataDirectory: root))
+ #expect(!ConversationStoreLocation.contains(root.appendingPathComponent("conversations-elsewhere/image.png"), forAppDataDirectory: root))
+ #expect(!ConversationStoreLocation.contains(root.appendingPathComponent("gemma4.gturbo/image.png"), forAppDataDirectory: root))
+ let outside = root.appendingPathComponent("outside.png")
+ try Data([1]).write(to: outside)
+ let escaped = images.appendingPathComponent("escaped.png")
+ try FileManager.default.createSymbolicLink(at: escaped, withDestinationURL: outside)
+ #expect(!ConversationStoreLocation.contains(escaped, forAppDataDirectory: root))
+ #expect(!ConversationStoreLocation.contains(images.appendingPathComponent("../../../outside.png"), forAppDataDirectory: root))
+ }
+}