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
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
15 changes: 14 additions & 1 deletion Sources/NotebookApp/Appearance.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
26 changes: 20 additions & 6 deletions Sources/NotebookApp/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
34 changes: 28 additions & 6 deletions Sources/NotebookApp/Credentials.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import NotebookKit
import Security

/// The gateway key, in the Keychain.
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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
}
}
Expand Down
3 changes: 1 addition & 2 deletions Sources/NotebookApp/NotebookModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading