diff --git a/README.md b/README.md index 55d3f35..e788a04 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,13 @@ part is entirely local. It is generation that needs the fleet. It is an ordinary OpenAI client: `POST /v1/chat/completions` with a bearer token, reading `choices[0].message.content`. So any OpenAI-compatible endpoint -works - set the Gateway field in Settings and put the key in the same place. +works - a dAI fleet, a private vLLM or LM Studio, OpenAI itself. + +**Destinations are saved by name.** Settings holds a list: add one, name it, +give it a URL, a model and a key, and switch between them from the picker. Each +keeps its own key in the Keychain, so moving between a fleet and a cloud +endpoint is a menu choice rather than retyping three fields and losing whichever +one you were not using. Deleting a destination forgets its key with it. Two things to know before you do. diff --git a/Sources/NotebookApp/Appearance.swift b/Sources/NotebookApp/Appearance.swift index c7059fa..8b6f594 100644 --- a/Sources/NotebookApp/Appearance.swift +++ b/Sources/NotebookApp/Appearance.swift @@ -46,14 +46,27 @@ enum Appearance: String, CaseIterable, Identifiable { } } + /// `NSApplication.shared`, not `NSApp`. + /// + /// `NSApp` is nil until the application instance has been created, and the + /// one caller that matters runs in `App.init()` - before the first window, + /// deliberately, so it does not flash the system appearance first. There + /// `NSApp` is nil, the optional chain evaluates to nothing, and the + /// assignment is discarded in silence: the setting saved, the toolbar + /// agreed with itself, and every launch came up light. + /// + /// `NSApplication.shared` creates the instance if it does not exist, so the + /// same call at the same moment now lands. + @MainActor func apply() { - NSApp?.appearance = nsAppearance + NSApplication.shared.appearance = nsAppearance } // ---------------------------------------------------------- persistence private static let key = "appearance" + @MainActor static var current: Appearance { get { Appearance(rawValue: UserDefaults.standard.string(forKey: key) ?? "") ?? .system } diff --git a/Sources/NotebookApp/ContentView.swift b/Sources/NotebookApp/ContentView.swift index ba588ae..6a1c5bb 100644 --- a/Sources/NotebookApp/ContentView.swift +++ b/Sources/NotebookApp/ContentView.swift @@ -1273,12 +1273,26 @@ struct AskBar: View { /// what this app did before generation existed. A turn without an answer /// says so rather than pretending. static func gateway() -> Gateway? { - guard let url = URL(string: GatewaySettings.baseURL), - Credentials.read()?.isEmpty == false else { return nil } - let ca = GatewaySettings.caPath - return Gateway(configuration: .init(baseURL: url, - caCertificatePath: ca.isEmpty ? nil : ca), - credential: { Credentials.read() }) + let store = EndpointStore() + store.migrateIfNeeded() + guard let endpoint = store.selected, + let configuration = endpoint.configuration, + Credentials.read(endpoint.id)?.isEmpty == false else { return nil } + // The key is fetched per request rather than captured, so switching + // endpoint or editing a key takes effect on the next question. + let id = endpoint.id + return Gateway(configuration: configuration, + credential: { Credentials.read(id) }) + } + + /// The model the selected endpoint should be asked for, if it names one. + /// + /// Empty means "let the endpoint choose", which only a dAI fleet can do - + /// Gateway refuses the request off-fleet rather than letting it come back + /// as a 400 that reads like a bad key. + static func selectedModel() -> String? { + let model = EndpointStore().selected?.model ?? "" + return model.isEmpty ? nil : model } var body: some View { diff --git a/Sources/NotebookApp/Credentials.swift b/Sources/NotebookApp/Credentials.swift index d166f17..d4275b8 100644 --- a/Sources/NotebookApp/Credentials.swift +++ b/Sources/NotebookApp/Credentials.swift @@ -1,4 +1,5 @@ import Foundation +import NotebookKit import Security /// The gateway key, in the Keychain. @@ -11,11 +12,29 @@ import Security /// `kSecAttrAccessibleWhenUnlocked` rather than the default: the app has no /// reason to read the key while the machine is locked, and a key that cannot be /// read then cannot be taken from a sleeping laptop. +/// One item per endpoint, since each destination has its own key. +/// +/// The account is the endpoint's id. That is why `EndpointStore.migratedID` is +/// a fixed value rather than a fresh UUID: the key saved before endpoints +/// existed lives under the old account name, and the migration has to be able +/// to find it again from nothing but the id it invented. enum Credentials { private static let service = "com.dai.notebookmlx.gateway" - private static let account = "api-key" + /// What the single-destination version used. Read for migration, then left + /// alone - deleting it would make the migration unrepeatable if it is wrong. + private static let legacyAccount = "api-key" + + private static func account(_ id: UUID) -> String { id.uuidString } - static func read() -> String? { + static func read(_ id: UUID) -> String? { + if let found = read(account: account(id)) { return found } + // The migrated endpoint inherits the key that predates endpoints. Only + // that id, so a second endpoint does not silently borrow it. + if id == EndpointStore.migratedID { return read(account: legacyAccount) } + return nil + } + + private static func read(account: String) -> String? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, @@ -30,9 +49,10 @@ enum Credentials { } @discardableResult - static func write(_ key: String) -> Bool { + static func write(_ key: String, for id: UUID) -> Bool { + let account = account(id) let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { return delete() } + if trimmed.isEmpty { return delete(id) } let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, @@ -51,12 +71,14 @@ enum Credentials { nil) == errSecSuccess } + /// Forgets an endpoint's key. Called when the endpoint is deleted, so a + /// credential does not outlive the thing it was for. @discardableResult - static func delete() -> Bool { + static func delete(_ id: UUID) -> Bool { SecItemDelete([ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, - kSecAttrAccount as String: account, + kSecAttrAccount as String: account(id), ] as CFDictionary) == errSecSuccess } } diff --git a/Sources/NotebookApp/NotebookModel.swift b/Sources/NotebookApp/NotebookModel.swift index dcc84f8..2624732 100644 --- a/Sources/NotebookApp/NotebookModel.swift +++ b/Sources/NotebookApp/NotebookModel.swift @@ -400,8 +400,7 @@ final class NotebookModel { question: question, passages: hits.map { ($0.chunk.citation, $0.chunk.text) }, history: Array(history), - model: GatewaySettings.model.isEmpty - ? nil : GatewaySettings.model, + model: AskBar.selectedModel(), maxTokens: GatewaySettings.maxTokens) answer = reply.text node = reply.node diff --git a/Sources/NotebookApp/SettingsView.swift b/Sources/NotebookApp/SettingsView.swift index 025a6c2..294f5fe 100644 --- a/Sources/NotebookApp/SettingsView.swift +++ b/Sources/NotebookApp/SettingsView.swift @@ -7,25 +7,93 @@ import SwiftUI /// one of these can be individually correct and collectively wrong, and finding /// that out on the first question rather than here means blaming the notebook. struct SettingsView: View { - @State private var baseURL = GatewaySettings.baseURL - @State private var caPath = GatewaySettings.caPath - @State private var model = GatewaySettings.model + @State private var endpoints: [Endpoint] + @State private var selectedID: UUID + @State private var name: String + @State private var baseURL: String + @State private var caPath: String + @State private var model: String + /// nil is "work it out from the address"; a value is the operator saying. + @State private var isDaiFleet: Bool? @State private var maxTokens = GatewaySettings.maxTokens @State private var appearance = Appearance.current @State private var available: [Gateway.Model] = [] @State private var loadingModels = false @State private var modelsProblem: String? - @State private var key = Credentials.read() ?? "" + @State private var key: String @State private var result: String? @State private var testing = false + /// Bumped on every model fetch, so a late reply for a destination that is + /// no longer selected is dropped rather than displayed. + @State private var generation = 0 + + private let store = EndpointStore() + + init() { + let store = EndpointStore() + // Bring a single-destination installation forward the first time this + // window opens, and give a fresh one something to edit rather than an + // empty list and no obvious next move. + store.migrateIfNeeded() + var list = store.all + if list.isEmpty { + let fresh = Endpoint(name: "Fleet", baseURL: "https://localhost:8452") + store.save(fresh) + store.selectedID = fresh.id + list = [fresh] + } + let current = store.selected ?? list[0] + _endpoints = State(initialValue: list) + _selectedID = State(initialValue: current.id) + _name = State(initialValue: current.name) + _baseURL = State(initialValue: current.baseURL) + _caPath = State(initialValue: current.caPath) + _model = State(initialValue: current.model) + _isDaiFleet = State(initialValue: current.isDaiFleet) + _key = State(initialValue: Credentials.read(current.id) ?? "") + } var body: some View { Form { - Section("Fleet") { + Section("Destination") { + // Saved by name, because switching between a fleet, a private + // server and somebody's cloud endpoint used to mean retyping + // three fields and losing whichever one you were not using - + // along with its key, which is the part that stings. + Picker("In use", selection: inUse) { + ForEach(endpoints) { e in + Text(e.problem == nil ? e.name : "\(e.name) · \(e.problem!)") + .tag(e.id) + } + } + HStack(spacing: 8) { + Button("Add") { add() } + Button("Duplicate") { duplicate() } + Button("Delete") { remove() } + .disabled(endpoints.count < 2) + Spacer() + } + .buttonStyle(.bordered) + .controlSize(.small) + } + Section("Where it points") { + TextField("Name", text: $name, prompt: Text("Fleet, OpenAI, work vLLM")) + // Declared, not guessed. The address heuristic said 127.0.0.1 + // was a fleet, which is true of the network and false of LM + // Studio - and the consequence was waiving the model + // requirement for a server that enforces it. + Picker("Server", selection: $isDaiFleet) { + Text("Work it out").tag(Bool?.none) + Text("dAI fleet").tag(Bool?.some(true)) + Text("OpenAI-compatible").tag(Bool?.some(false)) + } + .pickerStyle(.segmented) TextField("Gateway", text: $baseURL, prompt: Text("https://host:8452")) HStack { TextField("CA certificate", text: $caPath, - prompt: Text("the installer prints this path")) + prompt: Text(destination.looksLikeFleet + ? "the installer prints this path" + : "leave empty - a public server uses the system roots")) Button("Choose…") { choose() } } // A picker fed from the fleet, not a field to type an id into. @@ -35,7 +103,8 @@ struct SettingsView: View { // refusal that reads as the fleet being broken rather than as a // setting being wrong. Picker("Model", selection: $model) { - Text("Whatever the fleet is serving").tag("") + Text(destination.looksLikeFleet ? "Whatever the fleet is serving" + : "Choose a model").tag("") // Loaded first, then the rest. Both can be served; the // ones already in memory answer immediately, and the others // pay a cold load on the first question. @@ -52,7 +121,7 @@ struct SettingsView: View { } .disabled(available.isEmpty && model.isEmpty) HStack(spacing: 8) { - Button(loadingModels ? "Loading…" : "Refresh from fleet") { + Button(refreshLabel) { loadModels() } .disabled(loadingModels) @@ -126,9 +195,22 @@ struct SettingsView: View { // key in a plist is readable by anything running as this user // and turns up in backups and screen shares. SecureField("API key", text: $key) - Text("Kept in the Keychain. An operator mints one with " - + "POST /admin/v1/auth/keys.") - .font(.caption).foregroundStyle(.secondary) + // The advice depends on where this points. "An operator mints + // one" is true of a fleet and nonsense for OpenAI, and a local + // server usually wants no key at all while the app still + // insists on something non-empty - which reads as a bug unless + // it is said out loud. + if destination.looksLikeFleet { + Text("Kept in the Keychain. An operator mints one with " + + "POST /admin/v1/auth/keys.") + .font(.caption).foregroundStyle(.secondary) + } else { + Text("Kept in the Keychain. Use the key this provider " + + "issued you. A local server that ignores " + + "credentials still needs something here - any " + + "text will do.") + .font(.caption).foregroundStyle(.secondary) + } } Section { HStack { @@ -156,6 +238,19 @@ struct SettingsView: View { /// when it is worth reading, rather than after they have closed the window. /// An unparseable URL falls back to the local default and warns about /// nothing: an empty field is somebody who has not decided yet. + /// Broken out because the ternary inline in the label defeated the type + /// checker: "unable to type-check this expression in reasonable time". + private var refreshLabel: String { + if loadingModels { return "Loading…" } + return destination.looksLikeFleet ? "Refresh from fleet" : "Refresh from server" + } + + /// The fields on screen as an endpoint record, before they are saved. + private var edited: Endpoint { + Endpoint(id: selectedID, name: name, baseURL: baseURL, + caPath: caPath, model: model, isDaiFleet: isDaiFleet) + } + private var destination: Gateway.Configuration { let trimmed = baseURL.trimmingCharacters(in: .whitespacesAndNewlines) return Gateway.Configuration( @@ -180,34 +275,151 @@ struct SettingsView: View { /// Failure is reported beside the control rather than thrown away: a picker /// that is simply empty cannot be told apart from a fleet with nothing to /// offer, and the two need different actions. + /// Ask the destination on screen what it serves. + /// + /// Built from the fields, not from `AskBar.gateway()`. That reads the + /// *saved* selection out of the store, and the store does not know about + /// the switch until the next persist - so Refresh listed the destination + /// you had just left. It showed the fleet's nine models beside a LM Studio + /// URL, with the chosen model marked "not offered now" because the fleet + /// has never heard of it. The same bug meant typing a new URL and pressing + /// Refresh queried the old one. + /// + /// `generation` discards a reply that arrives after another switch. Without + /// it a slow fleet answering late overwrites a fast local server's list, + /// which looks identical to the bug above and is not the same cause. private func loadModels() { + guard let configuration = edited.configuration else { + available = [] + modelsProblem = "That is not a URL." + return + } + let trimmedKey = key.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedKey.isEmpty else { + available = [] + modelsProblem = "Set a key first." + return + } + generation &+= 1 + let mine = generation loadingModels = true modelsProblem = nil + let gateway = Gateway(configuration: configuration, credential: { trimmedKey }) Task { - defer { loadingModels = false } - guard let gateway = AskBar.gateway() else { - modelsProblem = "Set the gateway and a key first." - return - } + defer { if mine == generation { loadingModels = false } } do { // Loaded models first: the ones that answer without a wait. - available = try await gateway.models() + let found = try await gateway.models() .sorted { a, b in a.loaded == b.loaded ? a.shortName < b.shortName : a.loaded } - if available.isEmpty { modelsProblem = "The fleet offers no models." } + guard mine == generation else { return } + available = found + if available.isEmpty { modelsProblem = "It offers no models." } } catch { + guard mine == generation else { return } + available = [] modelsProblem = "\(error)" } } } + /// Switching destination, as one indivisible step. + /// + /// This was `.onChange(of: selectedID)`, and it destroyed a saved endpoint. + /// SwiftUI runs onChange *after* the view update, so `add()` - which sets + /// selectedID and then loads the new endpoint's values into the fields - + /// had already replaced them by the time the handler ran. The handler then + /// did what it was told: saved the fields on screen into the endpoint that + /// had just been switched away from. The result was a Fleet record + /// containing "New destination" and "https://", and nothing anywhere said + /// so - the only reason it was recoverable is that the migration leaves the + /// original defaults keys in place. + /// + /// A binding keeps save-switch-load in one synchronous sequence with no + /// second writer, so ordering cannot be the question. + private var inUse: Binding { + Binding(get: { selectedID }, + set: { new in + guard new != selectedID else { return } + persist(into: selectedID) + selectedID = new + load(new) + }) + } + + /// Write the fields on screen into one endpoint, and its key beside it. + private func persist(into id: UUID) { + var endpoint = endpoints.first(where: { $0.id == id }) + ?? Endpoint(id: id, name: name, baseURL: baseURL) + endpoint.name = name.trimmingCharacters(in: .whitespacesAndNewlines) + if endpoint.name.isEmpty { endpoint.name = "Untitled" } + endpoint.baseURL = baseURL + endpoint.caPath = caPath + endpoint.model = model + endpoint.isDaiFleet = isDaiFleet + store.save(endpoint) + store.selectedID = selectedID + Credentials.write(key, for: id) + endpoints = store.all + } + + /// Show a different endpoint, key included. + private func load(_ id: UUID) { + guard let e = endpoints.first(where: { $0.id == id }) else { return } + name = e.name + baseURL = e.baseURL + caPath = e.caPath + model = e.model + isDaiFleet = e.isDaiFleet + key = Credentials.read(id) ?? "" + // The model list belongs to the endpoint that offered it. + available = [] + modelsProblem = nil + result = nil + loadModels() + } + + private func add() { + persist(into: selectedID) + let fresh = Endpoint(name: "New destination", baseURL: "https://") + store.save(fresh) + endpoints = store.all + selectedID = fresh.id + load(fresh.id) + } + + private func duplicate() { + persist(into: selectedID) + // A new id, so it gets its own Keychain item rather than sharing one. + // The key is not copied: the common reason to duplicate is the same + // server with different credentials, and silently carrying one over + // would be the wrong guess in the case that matters. + let copy = Endpoint(name: "\(name) copy", baseURL: baseURL, + caPath: caPath, model: model, isDaiFleet: isDaiFleet) + store.save(copy) + endpoints = store.all + selectedID = copy.id + load(copy.id) + } + + private func remove() { + guard endpoints.count > 1 else { return } + let doomed = selectedID + // The key goes with it. A credential outliving the destination it was + // for is a secret nobody is looking after any more. + Credentials.delete(doomed) + store.remove(doomed) + endpoints = store.all + if let next = store.selected?.id { + selectedID = next + load(next) + } + } + private func save() { - GatewaySettings.baseURL = baseURL - GatewaySettings.caPath = caPath - GatewaySettings.model = model GatewaySettings.maxTokens = maxTokens - Credentials.write(key) + persist(into: selectedID) } private func choose() { @@ -226,10 +438,11 @@ struct SettingsView: View { guard let url = URL(string: baseURL) else { result = "That is not a URL."; testing = false; return } + let id = selectedID let gateway = Gateway( configuration: .init(baseURL: url, caCertificatePath: caPath.isEmpty ? nil : caPath), - credential: { Credentials.read() }) + credential: { Credentials.read(id) }) do { // A real request rather than a ping, because reachability and // a working credential are different questions and only the diff --git a/Sources/NotebookKit/Endpoints.swift b/Sources/NotebookKit/Endpoints.swift new file mode 100644 index 0000000..0b74d0a --- /dev/null +++ b/Sources/NotebookKit/Endpoints.swift @@ -0,0 +1,183 @@ +import Foundation + +/// A place this notebook can send a question, saved by name. +/// +/// There was one, and it was three loose defaults keys. That is right while the +/// answer is always "the fleet downstairs", and wrong the moment it is not: a +/// private vLLM at work, somebody's OpenAI key for a comparison, a fleet at +/// another site. Retyping a URL, a certificate path and a model to switch +/// between them loses whichever one you were not using, and the key with it. +/// +/// So each destination is a record and the app holds a list. Everything that +/// differs between destinations lives here; `maxTokens` and the like stay +/// global, because they are preferences about answers rather than about where +/// answers come from. +/// +/// The API key does **not** live here. It goes in the Keychain, one item per +/// endpoint id, for the reasons `Credentials` gives - and because a list of +/// endpoints is the sort of thing somebody exports to move to a new machine. +public struct Endpoint: Identifiable, Codable, Equatable, Sendable { + public var id: UUID + /// What the operator calls it. Never sent anywhere. + public var name: String + public var baseURL: String + /// A private authority to trust instead of the system store. Empty means + /// the system roots, which is what any public endpoint needs. + public var caPath: String + /// Empty asks the endpoint to choose, which only a dAI fleet can do. + public var model: String + /// Whether this is a dAI fleet. nil means infer from the address. + /// + /// The inference is only ever a guess and it was wrong where it counted: + /// LM Studio on 127.0.0.1 is a private address and not a fleet, so the + /// model requirement got waived for a server that enforces it. Optional, + /// not a plain Bool, so records written before this decode as "infer" and + /// keep behaving as they did. + public var isDaiFleet: Bool? + + public init(id: UUID = UUID(), name: String, baseURL: String, + caPath: String = "", model: String = "", + isDaiFleet: Bool? = nil) { + self.id = id + self.name = name + self.baseURL = baseURL + self.caPath = caPath + self.model = model + self.isDaiFleet = isDaiFleet + } + + /// The gateway configuration this describes, or nil if the URL is unusable. + public var configuration: Gateway.Configuration? { + let trimmed = baseURL.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, let url = URL(string: trimmed), url.host != nil else { + return nil + } + return Gateway.Configuration(baseURL: url, + caCertificatePath: caPath.isEmpty ? nil : caPath, + isDaiFleet: isDaiFleet) + } + + /// Whether this destination can be asked at all as it stands. + /// + /// Separate from whether it will answer. A model is required off-fleet, and + /// saying so in the list is better than letting somebody select a broken + /// destination and find out at the next question. + public var problem: String? { + guard let configuration else { return "needs a valid URL" } + if !configuration.looksLikeFleet && model.isEmpty { + return "needs a model" + } + return nil + } +} + +/// The saved destinations and which one is in use. +/// +/// Backed by `UserDefaults`, injectable so the migration can be tested against +/// a scratch domain rather than the developer's own settings - which is how a +/// previous test in this project came to be reading the machine it ran on. +/// Not `Sendable`, because `UserDefaults` is not. It is thread safe in +/// practice - the compiler objects to the shared mutable reference rather than +/// to the access - and this is only ever touched from the main actor, so +/// claiming otherwise would be a promise nothing checks. +public struct EndpointStore { + public static let listKey = "gateway.endpoints" + public static let selectedKey = "gateway.selectedEndpoint" + + /// The single-destination keys this replaces. Read once, at migration. + static let legacyURL = "gateway.baseURL" + static let legacyCA = "gateway.ca" + static let legacyModel = "gateway.model" + + private let defaults: UserDefaults + public init(defaults: UserDefaults = .standard) { self.defaults = defaults } + + public var all: [Endpoint] { + get { + guard let data = defaults.data(forKey: Self.listKey), + let list = try? JSONDecoder().decode([Endpoint].self, from: data) + else { return [] } + return list + } + nonmutating set { + defaults.set(try? JSONEncoder().encode(newValue), forKey: Self.listKey) + } + } + + public var selectedID: UUID? { + get { + guard let raw = defaults.string(forKey: Self.selectedKey) else { return nil } + return UUID(uuidString: raw) + } + nonmutating set { + defaults.set(newValue?.uuidString, forKey: Self.selectedKey) + } + } + + /// The destination in use, falling back to the first saved one. + /// + /// A dangling selection - the selected endpoint deleted on another machine, + /// or the list edited by hand - resolves to the first rather than to + /// nothing, because a notebook that silently stops answering is worse than + /// one that answers from the wrong place and says which. + public var selected: Endpoint? { + let list = all + if let id = selectedID, let match = list.first(where: { $0.id == id }) { + return match + } + return list.first + } + + public func save(_ endpoint: Endpoint) { + var list = all + if let i = list.firstIndex(where: { $0.id == endpoint.id }) { + list[i] = endpoint + } else { + list.append(endpoint) + } + all = list + } + + /// Removes one, and hands back its id so the caller can forget its key. + /// + /// The Keychain is not touched here: this type is in NotebookKit and has no + /// business holding credentials. Leaving the item behind on delete would be + /// a secret outliving the thing it was for, so the caller must do it, and + /// the return value is the reminder. + @discardableResult + public func remove(_ id: UUID) -> UUID { + all = all.filter { $0.id != id } + if selectedID == id { selectedID = all.first?.id } + return id + } + + /// Bring a single-destination installation forward, once. + /// + /// Runs when the list is empty and the old keys are present. The endpoint + /// keeps a **stable, derived id** rather than a fresh one, so the Keychain + /// item saved against it can be found again by a caller that computes the + /// same id - the alternative is a migration that silently loses the key and + /// presents an endpoint that cannot authenticate. + /// + /// The legacy keys are left in place. They cost nothing, and a migration + /// that deletes its own source cannot be run again after a bug is found. + @discardableResult + public func migrateIfNeeded() -> Endpoint? { + guard all.isEmpty else { return nil } + let url = defaults.string(forKey: Self.legacyURL) ?? "" + let ca = defaults.string(forKey: Self.legacyCA) ?? "" + let model = defaults.string(forKey: Self.legacyModel) ?? "" + guard !url.isEmpty || !ca.isEmpty || !model.isEmpty else { return nil } + + let migrated = Endpoint(id: Self.migratedID, name: "Fleet", + baseURL: url.isEmpty ? "https://localhost:8452" : url, + caPath: ca, model: model) + all = [migrated] + selectedID = migrated.id + return migrated + } + + /// Fixed so the migrated endpoint's Keychain item can be located without + /// having to have been recorded anywhere. + public static let migratedID = UUID(uuidString: "00000000-0000-0000-0000-00000da10001")! +} diff --git a/Sources/NotebookKit/Gateway.swift b/Sources/NotebookKit/Gateway.swift index 2fa9faf..38ad976 100644 --- a/Sources/NotebookKit/Gateway.swift +++ b/Sources/NotebookKit/Gateway.swift @@ -13,10 +13,21 @@ public actor Gateway { /// The control plane's own CA, so its certificate can be trusted /// without trusting everything else signed by nobody. public var caCertificatePath: String? - - public init(baseURL: URL, caCertificatePath: String? = nil) { + /// Whether this is a dAI fleet, when the caller knows. + /// + /// nil means "work it out from the address", which is what everything + /// did before and is still right for a bare `Configuration`. It is only + /// ever a guess though, and the guess was wrong in the case that + /// matters: LM Studio on 127.0.0.1 is a private address and not a + /// fleet, so the model requirement was waived for a server that + /// enforces it. An endpoint the operator configured can simply say. + public var isDaiFleet: Bool? + + public init(baseURL: URL, caCertificatePath: String? = nil, + isDaiFleet: Bool? = nil) { self.baseURL = baseURL self.caCertificatePath = caCertificatePath + self.isDaiFleet = isDaiFleet } public static let localhost = Configuration( @@ -36,6 +47,8 @@ public actor Gateway { /// whether to insist on a model and whether to warn, not whether to /// connect. public var looksLikeFleet: Bool { + // A declaration beats an inference. + if let declared = isDaiFleet { return declared } if let ca = caCertificatePath, !ca.isEmpty { return true } guard let host = baseURL.host?.lowercased() else { return false } if host == "localhost" || host == "::1" || host.hasSuffix(".local") { diff --git a/Tests/NotebookKitTests/EndpointStoreTests.swift b/Tests/NotebookKitTests/EndpointStoreTests.swift new file mode 100644 index 0000000..f99e02a --- /dev/null +++ b/Tests/NotebookKitTests/EndpointStoreTests.swift @@ -0,0 +1,153 @@ +import Foundation +import Testing +@testable import NotebookKit + +/// Saved destinations, and bringing a single-destination installation forward. +/// +/// Against a scratch `UserDefaults` suite, never `.standard`. A test that wrote +/// to the real domain would rewrite the developer's own settings while it ran, +/// which is the mistake this project has already made once today in the backup +/// suite - and there it was writing to a live certificate authority. +struct EndpointStoreTests { + /// A fresh domain per test, removed afterwards. + private func scratch(_ body: (EndpointStore) throws -> Void) rethrows { + let name = "notebookmlx.tests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + defer { defaults.removePersistentDomain(forName: name) } + try body(EndpointStore(defaults: defaults)) + } + + @Test("saves, lists and selects") + func basics() { + scratch { store in + let a = Endpoint(name: "Fleet", baseURL: "https://localhost:8452") + let b = Endpoint(name: "OpenAI", baseURL: "https://api.openai.com", + model: "gpt-4o-mini") + store.save(a) + store.save(b) + #expect(store.all.count == 2) + // Nothing selected yet resolves to the first, rather than to + // nothing: a notebook that silently stops answering is worse than + // one that answers and says from where. + #expect(store.selected?.id == a.id) + store.selectedID = b.id + #expect(store.selected?.name == "OpenAI") + } + } + + @Test("editing replaces rather than appends") + func editInPlace() { + scratch { store in + var e = Endpoint(name: "Fleet", baseURL: "https://localhost:8452") + store.save(e) + e.name = "Home fleet" + store.save(e) + #expect(store.all.count == 1) + #expect(store.all.first?.name == "Home fleet") + } + } + + @Test("saving one destination never disturbs another") + func saveIsolation() { + // The invariant the Settings window broke: two writers, one of them + // deferred, wrote the fields on screen into the endpoint that had just + // been switched away from. The store itself was never at fault, so + // this would not have caught that bug - it pins the guarantee the view + // is entitled to rely on, which is the half that can be tested here. + scratch { store in + let a = Endpoint(name: "Fleet", baseURL: "https://localhost:8452", + caPath: "/etc/dai/srv-ca.crt") + let b = Endpoint(name: "OpenAI", baseURL: "https://api.openai.com", + model: "gpt-4o-mini") + store.save(a) + store.save(b) + var edited = b + edited.name = "OpenAI (work)" + edited.baseURL = "https://api.openai.com/v1" + store.save(edited) + + let fleet = store.all.first { $0.id == a.id } + #expect(fleet?.name == "Fleet") + #expect(fleet?.baseURL == "https://localhost:8452") + #expect(fleet?.caPath == "/etc/dai/srv-ca.crt") + #expect(store.all.count == 2) + } + } + + @Test("a dangling selection falls back rather than answering nothing") + func danglingSelection() { + scratch { store in + let a = Endpoint(name: "Fleet", baseURL: "https://localhost:8452") + store.save(a) + store.selectedID = UUID() // deleted elsewhere, or hand-edited + #expect(store.selected?.id == a.id) + } + } + + @Test("removing clears the selection with it") + func removal() { + scratch { store in + let a = Endpoint(name: "A", baseURL: "https://localhost:8452") + let b = Endpoint(name: "B", baseURL: "https://10.0.0.5:8452") + store.save(a); store.save(b) + store.selectedID = b.id + store.remove(b.id) + #expect(store.all.count == 1) + #expect(store.selectedID == a.id) + } + } + + @Test("brings a single-destination installation forward once") + func migrates() { + let name = "notebookmlx.tests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + defer { defaults.removePersistentDomain(forName: name) } + defaults.set("https://rotorua.local:8452", forKey: EndpointStore.legacyURL) + defaults.set("/etc/dai/srv-ca.crt", forKey: EndpointStore.legacyCA) + defaults.set("mlx-community/Qwen2.5-14B-Instruct-4bit", forKey: EndpointStore.legacyModel) + + let store = EndpointStore(defaults: defaults) + let migrated = store.migrateIfNeeded() + #expect(migrated?.baseURL == "https://rotorua.local:8452") + #expect(migrated?.caPath == "/etc/dai/srv-ca.crt") + #expect(migrated?.model == "mlx-community/Qwen2.5-14B-Instruct-4bit") + #expect(store.selected?.id == EndpointStore.migratedID) + + // The id is fixed, not fresh. The Keychain item predating endpoints is + // filed under the old account name, and only a known id lets the app + // find it again - a fresh UUID would lose the key and present an + // endpoint that cannot authenticate. + #expect(migrated?.id == EndpointStore.migratedID) + + // Idempotent: running again must not add a second copy. + #expect(store.migrateIfNeeded() == nil) + #expect(store.all.count == 1) + + // And the source keys survive, so a migration found to be wrong can be + // corrected and re-run. + #expect(defaults.string(forKey: EndpointStore.legacyURL) != nil) + } + + @Test("a fresh installation has nothing to migrate") + func nothingToMigrate() { + scratch { store in + #expect(store.migrateIfNeeded() == nil) + #expect(store.all.isEmpty) + } + } + + @Test("says what is wrong with a destination before it is selected") + func problems() { + // Off-fleet without a model is the mistake worth catching in the list, + // because the alternative is a 400 at the next question that reads as + // a bad key. + #expect(Endpoint(name: "OpenAI", baseURL: "https://api.openai.com").problem + == "needs a model") + #expect(Endpoint(name: "OpenAI", baseURL: "https://api.openai.com", + model: "gpt-4o-mini").problem == nil) + // A fleet may be asked without one. + #expect(Endpoint(name: "Fleet", baseURL: "https://localhost:8452").problem == nil) + #expect(Endpoint(name: "Broken", baseURL: "not a url").problem == "needs a valid URL") + #expect(Endpoint(name: "Empty", baseURL: "").problem == "needs a valid URL") + } +} diff --git a/Tests/NotebookKitTests/GatewayDestinationTests.swift b/Tests/NotebookKitTests/GatewayDestinationTests.swift index e9a16e6..1067cac 100644 --- a/Tests/NotebookKitTests/GatewayDestinationTests.swift +++ b/Tests/NotebookKitTests/GatewayDestinationTests.swift @@ -82,6 +82,39 @@ struct GatewayDestinationTests { } } + @Test("a declaration beats the address") + func declarationWins() { + // The case the heuristic got wrong. LM Studio on 127.0.0.1 is a private + // address and not a fleet, so "private means fleet" waived the model + // requirement for a server that enforces it. + let local = Gateway.Configuration( + baseURL: URL(string: "http://127.0.0.1:1234")!, isDaiFleet: false) + #expect(!local.looksLikeFleet) + #expect(Endpoint(name: "LM Studio", baseURL: "http://127.0.0.1:1234", + isDaiFleet: false).problem == "needs a model") + + // And the other way: a fleet on a routable name, reached over https + // with no CA path, is still a fleet if it says so. + let remote = Gateway.Configuration( + baseURL: URL(string: "https://dai.example.com:8452")!, isDaiFleet: true) + #expect(remote.looksLikeFleet) + + // Unset still infers, so records written before this behave as before. + #expect(Gateway.Configuration( + baseURL: URL(string: "http://127.0.0.1:1234")!).looksLikeFleet) + } + + @Test("a declared third-party endpoint is refused without a model") + func declaredLocalNeedsModel() async { + let gateway = Gateway( + configuration: .init(baseURL: URL(string: "http://127.0.0.1:1234")!, + isDaiFleet: false), + credential: { "sk-test" }) + await #expect(throws: Gateway.Failure.modelRequired) { + _ = try await gateway.answer(question: "why", passages: [], history: []) + } + } + @Test("a fleet may still be asked without one") func fleetNeedsNoModel() async { // The behaviour the optional field exists for: the group decides. diff --git a/Tests/NotebookKitTests/OpenAIWireTests.swift b/Tests/NotebookKitTests/OpenAIWireTests.swift new file mode 100644 index 0000000..51928d9 --- /dev/null +++ b/Tests/NotebookKitTests/OpenAIWireTests.swift @@ -0,0 +1,205 @@ +import Foundation +import Network +import Testing +@testable import NotebookKit + +/// What this client actually puts on the wire, checked against a server that is +/// not dAI. +/// +/// Every other test here asserts what the client does with a reply. None +/// asserted what it *sends*, which is the half that decides whether pointing +/// this at OpenAI, vLLM, LM Studio or anything else compatible works at all. +/// "It is an ordinary OpenAI client" was true by inspection and by nothing else. +/// +/// A local listener rather than a real provider: no key, no spend, nothing +/// leaves the machine, and it runs in CI. It speaks the minimum of the protocol +/// and records the request so the shape can be asserted rather than assumed. +struct OpenAIWireTests { + + @Test("sends a request an OpenAI-compatible server accepts, and reads the reply") + func roundTrip() async throws { + let server = try StubServer() + defer { server.stop() } + let port = try await server.start() + + let gateway = Gateway( + configuration: .init(baseURL: URL(string: "http://127.0.0.1:\(port)")!), + credential: { "sk-test-key" }) + + let answer = try await gateway.answer( + question: "what is the retention period?", + passages: [(citation: "Retention Policy", text: "Records are kept seven years.")], + history: [(question: "hello", answer: "hi")], + model: "gpt-4o-mini", + maxTokens: 64) + + // The reply, parsed the way any OpenAI response would be. + #expect(answer.text == "Seven years (Retention Policy).") + #expect(answer.model == "gpt-4o-mini") + #expect(answer.finishReason == "stop") + // No `dai` object from a third party, and that must be absent rather + // than a failure: it is the fleet's own annotation. + #expect(answer.node == nil) + #expect(answer.cappedByPolicy == false) + + // And the request, which is the part nothing checked before. + let request = try #require(server.received) + #expect(request.path == "/v1/chat/completions") + #expect(request.method == "POST") + #expect(request.headers["authorization"] == "Bearer sk-test-key") + + let body = try #require(request.json) + #expect(body["model"] as? String == "gpt-4o-mini") + #expect(body["max_tokens"] as? Int == 64) + + let messages = try #require(body["messages"] as? [[String: String]]) + // system, then the prior turn as user/assistant, then this question. + #expect(messages.count == 4) + #expect(messages[0]["role"] == "system") + #expect(messages[1]["role"] == "user") + #expect(messages[2]["role"] == "assistant") + #expect(messages[3]["role"] == "user") + // The passages ride in the final user turn, not the system prompt - + // the prompt cache keys on longest common prefix, so anything that + // changes every turn has to come last. + #expect(messages[3]["content"]?.contains("Records are kept seven years.") == true) + #expect(messages[0]["content"]?.contains("Records are kept seven years.") == false) + } +} + +/// The smallest thing that answers like OpenAI. +/// +/// NWListener rather than a package: this needs one endpoint and one canned +/// reply, and a dependency for that would be more code to own than the fifty +/// lines below. +private final class StubServer: @unchecked Sendable { + struct Request { + var method = "" + var path = "" + var headers: [String: String] = [:] + var bodyData = Data() + var json: [String: Any]? { + try? JSONSerialization.jsonObject(with: bodyData) as? [String: Any] + } + } + + private let listener: NWListener + private let lock = NSLock() + private var _received: Request? + private var _resumed = false + var received: Request? { lock.lock(); defer { lock.unlock() }; return _received } + + init() throws { + let parameters = NWParameters.tcp + parameters.allowLocalEndpointReuse = true + listener = try NWListener(using: parameters, on: .any) + } + + func start() async throws -> UInt16 { + listener.newConnectionHandler = { [weak self] connection in + connection.start(queue: .global()) + self?.read(connection, into: Request(), accumulated: Data()) + } + return try await withCheckedThrowingContinuation { continuation in + // The flag lives behind the lock rather than being captured: a + // state handler can fire more than once and resuming a + // continuation twice is a crash, not a warning. + listener.stateUpdateHandler = { [weak self] state in + guard let self, self.claimStart() else { return } + switch state { + case .ready: + continuation.resume(returning: self.listener.port?.rawValue ?? 0) + case let .failed(error): + continuation.resume(throwing: error) + default: + self.releaseStart() + } + } + listener.start(queue: .global()) + } + } + + func stop() { listener.cancel() } + + /// True exactly once, for whichever state update resolves the start. + private func claimStart() -> Bool { + lock.lock(); defer { lock.unlock() } + if _resumed { return false } + _resumed = true + return true + } + + /// Hands the claim back for states that are neither ready nor failed. + private func releaseStart() { + lock.lock(); defer { lock.unlock() } + _resumed = false + } + + /// Reads until the declared Content-Length has arrived, then answers. + /// + /// A single recv is not enough: the body follows the headers in a separate + /// segment often enough that assuming otherwise makes the test flaky rather + /// than wrong, which is worse. + private func read(_ connection: NWConnection, into request: Request, accumulated: Data) { + connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { + [weak self] chunk, _, isComplete, _ in + guard let self else { return } + var buffer = accumulated + if let chunk { buffer.append(chunk) } + + guard let headerEnd = buffer.range(of: Data("\r\n\r\n".utf8)) else { + if isComplete { connection.cancel() } else { + self.read(connection, into: request, accumulated: buffer) + } + return + } + + var parsed = Request() + let head = String(decoding: buffer[..= 2 { + parsed.method = String(start[0]) + parsed.path = String(start[1]) + } + for line in lines.dropFirst() { + guard let colon = line.firstIndex(of: ":") else { continue } + parsed.headers[line[..= expected else { + self.read(connection, into: parsed, accumulated: buffer) + return + } + parsed.bodyData = Data(body.prefix(expected)) + + self.lock.lock(); self._received = parsed; self.lock.unlock() + self.respond(on: connection) + } + } + + private func respond(on connection: NWConnection) { + let payload: [String: Any] = [ + "id": "chatcmpl-stub", + "object": "chat.completion", + "model": "gpt-4o-mini", + "choices": [[ + "index": 0, + "finish_reason": "stop", + "message": ["role": "assistant", + "content": "Seven years (Retention Policy)."], + ]], + ] + let json = (try? JSONSerialization.data(withJSONObject: payload)) ?? Data() + var response = Data("HTTP/1.1 200 OK\r\n".utf8) + response.append(Data("Content-Type: application/json\r\n".utf8)) + response.append(Data("Content-Length: \(json.count)\r\n".utf8)) + response.append(Data("Connection: close\r\n\r\n".utf8)) + response.append(json) + connection.send(content: response, completion: .contentProcessed { _ in + connection.cancel() + }) + } +} diff --git a/packaging/make-app.sh b/packaging/make-app.sh index 5f2c43c..9a85661 100755 --- a/packaging/make-app.sh +++ b/packaging/make-app.sh @@ -29,7 +29,25 @@ cp "$BIN" "$APP/Contents/MacOS/NotebookMLX" # bundle is borrowed: it is the same vendored mlx-swift, by path, so it is the # same shaders. If the agent has not been built, embedding will abort with # "Failed to load the default metallib" and this says so now instead. -CMLX="$ROOT/../agent/.xcbuild/Build/Products/Release/mlx-swift_Cmlx.bundle" +# Where to look for it. This was a single relative path into `../agent`, which +# was correct while this app lived inside dAI's tree and broke silently the day +# it moved out: the warning below is easy to miss and the app it produces aborts +# at the first embedding with "Failed to load the default metallib". +# +# So: an explicit override first, then a sibling dAI checkout, then the old +# in-tree layout for anyone who still has one. +CMLX_REL="Build/Products/Release/mlx-swift_Cmlx.bundle" +CMLX="" +for candidate in \ + "${DAI_CMLX_BUNDLE:-}" \ + "$ROOT/../dAI/agent/.xcbuild/$CMLX_REL" \ + "$ROOT/../agent/.xcbuild/$CMLX_REL" +do + [[ -n "$candidate" && -d "$candidate" ]] || continue + CMLX="$candidate" + break +done +[[ -n "$CMLX" ]] || CMLX="$ROOT/../dAI/agent/.xcbuild/$CMLX_REL" if [[ -d "$CMLX" ]]; then # Both locations, because the lookup differs by how the binary is launched. # A bare SwiftPM executable finds its package bundles beside itself; inside a @@ -39,8 +57,11 @@ if [[ -d "$CMLX" ]]; then cp -R "$CMLX" "$APP/Contents/MacOS/" cp -R "$CMLX" "$APP/Contents/Resources/" else - echo "warning: no Metal shader bundle found at $CMLX" >&2 - echo " build the agent first, or embedding will abort at runtime" >&2 + echo "warning: no Metal shader bundle found" >&2 + echo " looked for: $CMLX" >&2 + echo " build dAI's agent with xcodebuild, or set DAI_CMLX_BUNDLE." >&2 + echo " Without it embedding aborts at runtime with" >&2 + echo " 'Failed to load the default metallib'." >&2 fi # The icon, if it has been built. Checked in rather than generated here so a @@ -69,6 +90,19 @@ cat > "$APP/Contents/Info.plist" <<'PLIST' LSUIElement NSHighResolutionCapable + + NSAppTransportSecurity + + NSAllowsLocalNetworking + UTExportedTypeDeclarations