Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import AudioToolbox
import AVFoundation
import BackgroundTasks
import CoreMotion
#if canImport(FoundationModels)
import FoundationModels
#endif

@main
@objc class AppDelegate: FlutterAppDelegate {
Expand Down Expand Up @@ -88,6 +91,10 @@ import CoreMotion
}
// Home-screen icon switching (setAlternateIconName). iOS only — see the
// bridge below for the system-alert cost it carries.
// Apple's on-device model (Foundation Models) for the AI features.
if let registrar = registry.registrar(forPlugin: "AppleIntelligenceBridge") {
AppleIntelligenceBridge.register(messenger: registrar.messenger())
}
if let registrar = registry.registrar(forPlugin: "AppIconBridge") {
AppIconBridge.register(messenger: registrar.messenger())
}
Expand Down Expand Up @@ -378,3 +385,129 @@ enum AppIconBridge {
}
}
}


/// Apple's on-device language model (Foundation Models, iOS 26+), for the
/// coach, briefings and journal when "Apple on-device" is chosen. No key, no
/// network: the prompt and the answer never leave the phone.
///
/// `status` → "available" | "notEnabled" | "notReady" | "deviceNotEligible" |
/// "unsupportedOS". `respond` takes {instructions, prompt, temperature} and
/// returns the text, or a FlutterError whose CODE names the failure
/// ("notEnabled", "notReady", "deviceNotEligible", "unsupported", "tooLong",
/// "declined", "timeout", "failed"); the Dart side turns the code into
/// translated text, and the message is only a detail for logs.
enum AppleIntelligenceBridge {
private static let channelName = "openstrap/apple_ai"

/// A stalled generation must not leave the Dart call waiting forever.
private static let respondTimeoutSeconds: Double = 60

static func register(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
switch call.method {
case "status":
result(status())
case "respond":
let args = call.arguments as? [String: Any] ?? [:]
let instructions = args["instructions"] as? String ?? ""
let prompt = args["prompt"] as? String ?? ""
let temperature = args["temperature"] as? Double
let reply = ReplyOnce(result)
let work = Task {
let out = await respond(instructions: instructions, prompt: prompt,
temperature: temperature)
DispatchQueue.main.async { _ = reply.send(out) }
}
DispatchQueue.main.asyncAfter(deadline: .now() + respondTimeoutSeconds) {
if reply.send(.failure(code: "timeout", detail: "no answer in \(Int(respondTimeoutSeconds)) s")) {
work.cancel()
}
}
default:
result(FlutterMethodNotImplemented)
}
}
}

enum Outcome { case success(String), failure(code: String, detail: String) }

/// Delivers the first outcome only: the answer or the timeout, whichever
/// comes first. Used on the main queue only, so it needs no lock.
final class ReplyOnce {
private var result: FlutterResult?
init(_ result: @escaping FlutterResult) { self.result = result }

/// False when an outcome was already delivered.
func send(_ outcome: Outcome) -> Bool {
guard let r = result else { return false }
result = nil
switch outcome {
case .success(let text): r(text)
case .failure(let code, let detail):
r(FlutterError(code: code, message: detail, details: nil))
}
return true
}
}

static func status() -> String {
#if canImport(FoundationModels)
if #available(iOS 26.0, *) {
switch SystemLanguageModel.default.availability {
case .available:
return "available"
case .unavailable(.appleIntelligenceNotEnabled):
return "notEnabled"
case .unavailable(.modelNotReady):
return "notReady"
case .unavailable(.deviceNotEligible):
return "deviceNotEligible"
default:
return "unavailable"
}
}
#endif
return "unsupportedOS"
}

static func respond(instructions: String, prompt: String,
temperature: Double?) async -> Outcome {
#if canImport(FoundationModels)
if #available(iOS 26.0, *) {
let state = status()
guard state == "available" else {
return .failure(code: unavailableCode(state), detail: state)
}
do {
let session = LanguageModelSession(instructions: instructions)
let options = GenerationOptions(temperature: temperature)
let response = try await session.respond(to: prompt, options: options)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
return .success(response.content)
} catch let error as LanguageModelSession.GenerationError {
switch error {
case .exceededContextWindowSize:
return .failure(code: "tooLong", detail: error.localizedDescription)
case .guardrailViolation:
return .failure(code: "declined", detail: error.localizedDescription)
default:
return .failure(code: "failed", detail: error.localizedDescription)
}
} catch {
return .failure(code: "failed", detail: error.localizedDescription)
}
}
#endif
return .failure(code: "unsupported", detail: "unsupportedOS")
}

static func unavailableCode(_ state: String) -> String {
switch state {
case "notEnabled", "notReady", "deviceNotEligible":
return state
default:
return "unsupported"
}
}
}
13 changes: 13 additions & 0 deletions lib/ai/briefing.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,22 @@ class Briefing {
/// were actually present — absent metrics are never fabricated).
final Map<String, dynamic> inputs;

/// Where the request went and which model answered, recorded when it was
/// written: the "what was sent" screen describes THIS briefing, not
/// whatever the settings say now. Null on a note saved before these were
/// recorded, and on one that called no model.
final String? endpoint;
final String? model;

const Briefing({
required this.day,
required this.period,
required this.oneLiner,
required this.breakdownMd,
required this.generatedAtMs,
required this.inputs,
this.endpoint,
this.model,
});

/// Whether producing this note involved a model at all.
Expand All @@ -90,6 +99,8 @@ class Briefing {
'breakdown_md': breakdownMd,
'generated_at_ms': generatedAtMs,
'inputs': inputs,
'endpoint': ?endpoint,
'model': ?model,
};

static Briefing? fromJson(dynamic j) {
Expand All @@ -108,6 +119,8 @@ class Briefing {
inputs: j['inputs'] is Map
? (j['inputs'] as Map).cast<String, dynamic>()
: const {},
endpoint: j['endpoint'] is String ? j['endpoint'] as String : null,
model: j['model'] is String ? j['model'] as String : null,
);
}
}
Expand Down
21 changes: 21 additions & 0 deletions lib/ai/briefing_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ import '../ui2/screens/home_screen.dart' as ring show readinessBand;
import 'briefing.dart';
import 'nightly_sweep.dart';

/// Where a briefing's request went, as stored on the [Briefing]: Apple's
/// on-device pseudo-base, or the endpoint's scheme, host and port ONLY. A
/// custom base URL can carry an access key in its path or query, and saved
/// briefings travel in backups, so nothing past the host is kept. Null when
/// the endpoint has no host, which the screen then reports as unknown.
String? briefingEndpointOf(CoachConfig config) {
if (config.usesApple) return kAppleOnDeviceBase;
final u = Uri.tryParse(config.apiBase.trim());
if (u == null || u.host.isEmpty) return null;
// Built with Uri so an IPv6 host keeps its brackets (http://[::1]:11434).
return Uri(scheme: u.scheme, host: u.host, port: u.hasPort ? u.port : null)
.toString();
}

/// Injectable one-shot completion (tests pass a fake; production defaults to
/// [CoachEngine.completeText] — the shared BYOK plumbing).
typedef BriefingComplete = Future<String> Function({
Expand Down Expand Up @@ -556,6 +570,11 @@ class BriefingEngine {
BriefingStore.write(b);
return b;
}
// Where the request goes, read in the same synchronous run as the request
// itself (postChat reads the config before its first await): a provider
// switched while the model is answering must not relabel this briefing.
final sentTo = briefingEndpointOf(config);
final sentModel = config.model;
final raw = await (complete ??
(({required String system, required String user}) =>
CoachEngine.completeText(
Expand All @@ -574,6 +593,8 @@ class BriefingEngine {
breakdownMd: parsed.breakdownMd,
generatedAtMs: (wallNow ?? effectiveNow).millisecondsSinceEpoch,
inputs: inputs,
endpoint: sentTo,
model: sentModel,
);
// An older request must not overwrite a complete briefing a newer one
// already stored while this one waited on the model.
Expand Down
Loading