Skip to content
Open
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
6 changes: 4 additions & 2 deletions Sources/Howler/AppSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ final class AppSettings: ObservableObject {
private let store: ServiceStore
/// The key read this session, so the keychain is queried once until the setup changes.
private var keyCache: (revision: String, service: ModelService, key: String)?
private var observedKeyRevision: String?
private var checkingRevision: String?
private var observer: NSObjectProtocol?

Expand Down Expand Up @@ -140,10 +141,11 @@ final class AppSettings: ObservableObject {
if demoMode { return }
#endif
let stored = store.service
var connectionChanged = stored != service
let keyRevision = store.keyRevision
let connectionChanged = stored != service || observedKeyRevision != keyRevision
observedKeyRevision = keyRevision
if let cached = keyCache, cached.revision != store.keyRevision || cached.service != stored {
// Reloading preferences must not cause a blocking Keychain prompt.
connectionChanged = true
keyCache = nil
}
if stored != service { service = stored }
Expand Down
144 changes: 107 additions & 37 deletions Sources/Howler/CLI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,59 @@ enum CLI {

/// Runs a command-line invocation and returns its exit status, or nil when the
/// arguments are not a command and the app should launch as usual.
static func run(_ arguments: [String], store suppliedStore: ServiceStore? = nil) -> Int32? {
static func run(_ arguments: [String], store makeStore: @autoclosure () -> ServiceStore = ServiceStore()) -> Int32? {
let args = Array(arguments.dropFirst())
guard let command = args.first, commands.contains(command) else { return nil }
// Keep stdout and stderr in order when piped (an assistant reads both).
setvbuf(stdout, nil, _IOLBF, 0)
let store = suppliedStore ?? ServiceStore()
store.migrateLegacySetup()
do {
switch command {
case "config": try config(Array(args.dropFirst()), store: store)
case "check": return check(verbose: args.contains("--verbose") || args.contains("-v"), store: store)
case "version", "--version": print("\(AppInfo.name) \(AppInfo.version)")
default: print(usage)
let operation = try parse(args)
switch operation {
case .help:
print(usage)
return 0
case .version:
print("\(AppInfo.name) \(AppInfo.version)")
return 0
case .schema:
print(SetupGuide.schema(appName: name))
return 0
default:
break
}
let store = makeStore()
switch operation {
case .reset:
try store.reset()
print("Removed the model service and its API key.")
case .stage(let fields):
let service = try ServiceConfig.apply(fields, to: store.pendingDirectService ?? store.directService)
try store.stageDirectService(service)
print("Prepared: \(service.summary)")
print("Subscription stays active. Open Settings > General > API Key > Edit, then Save & Check.")
case .set(let fields):
// Validate against the direct configuration before migration can touch storage.
_ = try ServiceConfig.apply(fields, to: store.directServiceForEditing)
store.migrateLegacySetup()
let service = try ServiceConfig.apply(fields, to: store.directService)
try store.save(service)
print("Saved: \(service.summary)")
print(store.hasKey ? "Next: \(name) check" : "Next: open Settings > General, edit the model configuration, then Save & Check.")
case .setKey(let key):
guard store.service?.usesMagpie != true else { throw ConfigurationFailure.magpieKey }
guard store.directServiceForEditing != nil else { throw ServiceConfigError.missing(["format", "base-url", "model"]) }
store.migrateLegacySetup()
try store.setAPIKey(key)
print("API key saved in Keychain.")
print("Next: \(name) check")
case .show:
store.migrateLegacySetup()
show(store)
case .check(let verbose):
store.migrateLegacySetup()
return check(verbose: verbose, store: store)
case .help, .version, .schema:
break
}
return 0
} catch {
Expand Down Expand Up @@ -55,38 +95,69 @@ enum CLI {

// MARK: config

private static func config(_ args: [String], store: ServiceStore) throws {
private enum Operation {
case help, version, schema, show, reset
case set([String]), stage([String])
case setKey(String)
case check(Bool)
}

private static func parse(_ args: [String]) throws -> Operation {
let tail = Array(args.dropFirst())
switch args.first {
case "schema":
print(SetupGuide.schema(appName: name))
case "show", nil:
show(store)
case "stage":
let fields = Array(args.dropFirst())
guard !fields.isEmpty else { throw UsageError("Nothing to stage. See: \(name) config schema") }
let service = try ServiceConfig.apply(fields, to: store.pendingDirectService ?? store.directService)
try store.stageDirectService(service)
print("Prepared: \(service.summary)")
print("Subscription stays active. Open Settings > General > API Key > Edit, then Save & Check.")
case "set":
let fields = Array(args.dropFirst())
if fields.first == "api-key" {
try setKey(Array(fields.dropFirst()), store: store)
} else {
guard !fields.isEmpty else { throw UsageError("Nothing to set. See: \(name) config schema") }
let service = try ServiceConfig.apply(fields, to: store.directService)
try store.save(service)
print("Saved: \(service.summary)")
print(store.hasKey ? "Next: \(name) check" : "Next: open Settings > General, edit the model configuration, then Save & Check.")
case "help", "--help", "-h":
guard tail.isEmpty else { throw UsageError(usage) }
return .help
case "version", "--version":
guard tail.isEmpty else { throw UsageError(usage) }
return .version
case "check":
guard tail.allSatisfy({ ["--verbose", "-v", "--help", "-h"].contains($0) }) else {
throw UsageError(usage)
}
return tail.contains(where: isHelp) ? .help : .check(!tail.isEmpty)
case "config":
guard let action = tail.first else { return .show }
let fields = Array(tail.dropFirst())
if isHelp(action) {
guard fields.isEmpty else { throw UsageError(usage) }
return .help
}
switch action {
case "schema", "show", "reset":
guard fields.isEmpty || (fields.count == 1 && isHelp(fields[0])) else {
throw UsageError(usage)
}
if !fields.isEmpty { return .help }
switch action {
case "schema": return .schema
case "show": return .show
default: return .reset
}
case "set", "stage":
guard !fields.isEmpty else { throw UsageError("Nothing to \(action). See: \(name) config schema") }
if fields.count == 1 && isHelp(fields[0]) { return .help }
if action == "set", fields.first == "api-key" {
if fields.count == 2 && isHelp(fields[1]) { return .help }
return .setKey(try ServiceStore.validatedAPIKey(readKey(Array(fields.dropFirst()))))
}
do {
_ = try ServiceConfig.apply(fields, to: nil)
} catch ServiceConfigError.missing {
}
return action == "set" ? .set(fields) : .stage(fields)
default:
throw UsageError(usage)
}
case "reset":
store.reset()
print("Removed the model service and its API key.")
default:
throw UsageError(usage)
}
}

private static func isHelp(_ argument: String) -> Bool {
argument == "--help" || argument == "-h"
}

private static func show(_ store: ServiceStore) {
guard let service = store.service else {
print("No model service yet. See the fields with: \(name) config schema")
Expand Down Expand Up @@ -125,10 +196,11 @@ enum CLI {

/// The key comes from a pipe, an environment variable or a file — never an argument,
/// where it would end up in shell history and process listings.
private static func setKey(_ args: [String], store: ServiceStore) throws {
private static func readKey(_ args: [String]) throws -> String {
let raw: String
switch args.first {
case "--stdin":
guard args.count == 1 else { throw UsageError("Usage: \(name) config set api-key --stdin") }
guard isatty(FileHandle.standardInput.fileDescriptor) == 0 else {
throw UsageError("--stdin reads a pipe. Copy the key, then run: pbpaste | \(name) config set api-key --stdin")
}
Expand All @@ -149,9 +221,7 @@ enum CLI {
default:
throw ServiceConfigError.apiKeyOnCommandLine
}
try store.setAPIKey(raw)
print("API key saved in Keychain.")
if store.service != nil { print("Next: \(name) check") }
return raw
}

// MARK: check
Expand Down
2 changes: 2 additions & 0 deletions Sources/Howler/ChatViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,11 @@ final class ChatViewModel: ObservableObject {

func withdraw(_ id: UUID) {
guard input.isEmpty, attachment == nil, let task = queue.withdraw(id) else { return }
isAbsorbingPaste = true
input = task.question
attachment = task.attachment
draftImageID = task.imageID
isAbsorbingPaste = false
focusTick += 1
}

Expand Down
7 changes: 5 additions & 2 deletions Sources/Howler/Keychain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ enum Keychain {
return SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess
}

static func delete(account: String) {
SecItemDelete(baseQuery(account: account) as CFDictionary)
static func delete(account: String, operations: Operations = Operations()) throws {
let status = operations.delete(baseQuery(account: account) as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError(status: status, operation: "delete")
}
}
}
Loading
Loading