Skip to content
10 changes: 6 additions & 4 deletions Localization/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,13 @@
"Activate" = "Activate";
"Activate Profile" = "Activate Profile";
"Adaptive thinking budgets tuned for multi-step math and logic." = "Adaptive thinking budgets tuned for multi-step math and logic.";
"All 91" = "All 91";
"All %lld" = "All %lld";
"Belnap" = "Belnap";
"Bundled Profile" = "Bundled Profile";
"CLI Command" = "CLI Command";
"Chat" = "Chat";
"Choose any hardware-tuned multi-model profile on the left." = "Choose any hardware-tuned multi-model profile on the left.";
"Cloud Cap" = "Cloud Cap";
"Code" = "Code";
"Coding Agent & MCP" = "Coding Agent & MCP";
"Compose Profiles" = "Compose Profiles";
"Compose Specification (YAML)" = "Compose Specification (YAML)";
Expand Down Expand Up @@ -229,7 +228,6 @@
"Speech" = "Speech";
"Targets %@ Macs; may exceed this Mac's memory" = "Targets %@ Macs; may exceed this Mac's memory";
"TeaCache" = "TeaCache";
"Thinking" = "Thinking";
"TTS 44.1 kHz" = "TTS 44.1 kHz";
"Upsample" = "Upsample";
"Vision" = "Vision";
Expand Down Expand Up @@ -270,7 +268,6 @@
"Estimating output footprint…" = "Estimating output footprint…";
"PV-Tuning (Teacher KL Code & Scale Refinement)" = "PV-Tuning (Teacher KL Code & Scale Refinement)";
"Preset" = "Preset";
"Fast" = "Fast";
"Balanced" = "Balanced";
"Thorough" = "Thorough";
"Teacher Model" = "Teacher Model";
Expand Down Expand Up @@ -352,3 +349,8 @@
"Merge LoRA Adapter (Optional)" = "Merge LoRA Adapter (Optional)";
"org/adapter-repo" = "org/adapter-repo";
"Fuses a PEFT or mlx-lm LoRA repository into the converted weights." = "Fuses a PEFT or mlx-lm LoRA repository into the converted weights.";
"Target Budget: %@ bpw" = "Target Budget: %@ bpw";
"%lld-bit" = "%lld-bit";
"Estimated Size: %@ → %@" = "Estimated Size: %@ → %@";
"Peak Conversion RAM: %@" = "Peak Conversion RAM: %@";
"%@ of %@" = "%@ of %@";
12 changes: 7 additions & 5 deletions Localization/ru.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,13 @@
"Activate" = "Включить";
"Activate Profile" = "Активировать профиль";
"Adaptive thinking budgets tuned for multi-step math and logic." = "Адаптивный бюджет размышлений для многошаговой логики и математики.";
"All 91" = "Все 91";
"All %lld" = "Все %lld";
"Belnap" = "Белнап";
"Bundled Profile" = "Встроенный профиль";
"CLI Command" = "Команда CLI";
"Chat" = "Чат";
"Choose any hardware-tuned multi-model profile on the left." = "Выберите любой аппаратный профиль многомодельной системы слева.";
"Cloud Cap" = "Лимит облака";
"Code" = "Код";
"Coding Agent & MCP" = "Кодинг-агент и MCP";
"Compose Profiles" = "Профили Compose";
"Compose Specification (YAML)" = "Спецификация Compose (YAML)";
Expand All @@ -186,7 +185,7 @@
"Epistemic" = "Эпистемика";
"Epistemic Grounded Research" = "Верифицированный поиск и факты";
"Estimated Resident RAM" = "Оценка резидентной памяти";
"Fast" = "Быстро";
"Fast" = "Быстрый";
"Fast everyday chat, Apple Vision attachments, and local speech input." = "Быстрый чат на каждый день, вложения через Apple Vision и голосовой ввод.";
"Filter profiles or models" = "Поиск профилей или моделей";
"Frontier MoE Engine" = "Флагманский MoE-движок";
Expand Down Expand Up @@ -229,7 +228,6 @@
"Speech" = "Речь";
"Targets %@ Macs; may exceed this Mac's memory" = "Рассчитан на Mac с %@; может превысить память этого Mac";
"TeaCache" = "TeaCache";
"Thinking" = "Мышление";
"TTS 44.1 kHz" = "TTS 44,1 кГц";
"Upsample" = "Апсемпл";
"Vision" = "Зрение";
Expand Down Expand Up @@ -270,7 +268,6 @@
"Estimating output footprint…" = "Оценка размера выходной модели…";
"PV-Tuning (Teacher KL Code & Scale Refinement)" = "PV-тюнинг (доводка кодов и шкал по KL учителя)";
"Preset" = "Профиль";
"Fast" = "Быстрый";
"Balanced" = "Сбалансированный";
"Thorough" = "Тщательный";
"Teacher Model" = "Модель-учитель";
Expand Down Expand Up @@ -352,3 +349,8 @@
"Merge LoRA Adapter (Optional)" = "Влить LoRA-адаптер (необязательно)";
"org/adapter-repo" = "org/adapter-repo";
"Fuses a PEFT or mlx-lm LoRA repository into the converted weights." = "Вливает PEFT или mlx-lm LoRA-репозиторий в конвертируемые веса.";
"Target Budget: %@ bpw" = "Целевой бюджет: %@ бит/вес";
"%lld-bit" = "%lld бит";
"Estimated Size: %@ → %@" = "Оценка размера: %@ → %@";
"Peak Conversion RAM: %@" = "Пиковое ОЗУ конвертации: %@";
"%@ of %@" = "%@ из %@";
15 changes: 9 additions & 6 deletions Sources/BasaltApp/App/AppModel+ComposeProfiles.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import Foundation
extension AppModel {
static func makeComposeProfilesStore(
initialCompose: String,
supervisor: EngineSupervisor
supervisor: EngineSupervisor,
cloudEnvironment: @escaping @Sendable () -> [String: String] = { CloudKeys.environment(defaults: .standard, keychain: .live()) }
) -> ComposeProfilesStore {
Store(
ComposeProfilesState(activeCompose: initialCompose),
Expand All @@ -18,7 +19,9 @@ extension AppModel {
await send(.failed("Unknown compose profile: \(id)"))
return
}
if let endpoint = await supervisor.endpoint {
let current = await supervisor.launch
let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment())
if freshEnv == current.environment, let endpoint = await supervisor.endpoint {
do {
let diff = try await EngineClient.http(endpoint).applyCompose(ComposeApplyCall(yaml: yaml))
if let refusal = diff.refusal {
Expand All @@ -37,13 +40,13 @@ extension AppModel {
} catch {}
}
guard !Task.isCancelled else { return }
let current = await supervisor.launch
let freshEnv = CloudKeys.environment(defaults: .standard, keychain: .live())
let latest = await supervisor.launch
let relaunchEnv = Self.refreshedEnvironment(preserving: latest.environment, cloud: cloudEnvironment())
await supervisor.relaunch(
HelperLaunch(
executable: current.executable,
executable: latest.executable,
arguments: ["serve", "--compose", id],
environment: freshEnv
environment: relaunchEnv
)
)
guard !Task.isCancelled else { return }
Expand Down
84 changes: 62 additions & 22 deletions Sources/BasaltApp/App/AppModel+Features.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,36 +23,76 @@ extension AppModel {
matchedConversationIDs = Set(ids)
}

public func switchEngine(_ arguments: [String]) async {
nonisolated static func refreshedEnvironment(
preserving current: [String: String],
cloud: [String: String]
) -> [String: String] {
var merged = cloud
for (key, value) in current where key.hasPrefix("BASALT_") && !value.isEmpty && merged[key] == nil {
merged[key] = value
}
return merged
}

public func switchEngine(_ arguments: [String], forceRestart: Bool = false) async {
if let index = arguments.firstIndex(of: "--model"), arguments.indices.contains(index + 1) {
configuredModel = arguments[index + 1]
}
let current = await supervisor.launch
let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment())
let fallback = HelperLaunch(executable: current.executable, arguments: arguments, environment: freshEnv)
if forceRestart || freshEnv != current.environment {
await supervisor.relaunch(fallback)
syncComposeProfileIfNeeded(arguments)
return
}
let isReady = if case .ready = engine.phase { true } else { false }
switch HotSwitchPlan.plan(from: current.arguments, to: arguments, isReady: isReady) {
case .noop:
await supervisor.start()
case .hotLoadModel(let id):
if (try? await hotSwitchModel(id)) != nil { return }
await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment))
await supervisor.relaunch(fallback)
case .hotApplyCompose(let path):
do {
if let bundled = ComposeProfileCatalog.bundledYAML[path] {
_ = try await applyComposeYAML(bundled, filePath: path)
} else {
_ = try await applyComposeFile(URL(fileURLWithPath: path))
}
composeProfiles.send(.syncActive(path))
return
} catch EngineError.refused {
return
} catch {
composeProfiles.send(.syncActive(path))
await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment))
}
await hotApplyCompose(path, fallback: fallback)
case .relaunch:
await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment))
await supervisor.relaunch(fallback)
}
}

private func hotApplyCompose(_ path: String, fallback: HelperLaunch) async {
do {
if let bundled = ComposeProfileCatalog.bundledYAML[path] {
_ = try await applyComposeYAML(bundled, filePath: path)
} else {
_ = try await applyComposeFile(URL(fileURLWithPath: path))
}
composeProfiles.send(.syncActive(path))
} catch EngineError.refused {
return
} catch {
composeProfiles.send(.syncActive(path))
await supervisor.relaunch(fallback)
}
}

private func syncComposeProfileIfNeeded(_ arguments: [String]) {
if let index = arguments.firstIndex(of: "--compose"), arguments.indices.contains(index + 1) {
composeProfiles.send(.syncActive(arguments[index + 1]))
}
}

public func recordLoadedModel(_ id: String) async {
configuredModel = id
await supervisor.updateLaunchArguments(["serve", "--model", id])
UserDefaults.standard.set(id, forKey: EngineChoice.modelKey)
if !library.state.models.isEmpty {
let updated = library.state.models.map {
LibraryModel(id: $0.id, sizeBytes: $0.sizeBytes, isLoaded: $0.id == id)
}
library.send(.listed(updated))
}
library.send(.appeared)
}

@discardableResult
Expand All @@ -67,13 +107,12 @@ extension AppModel {
}
guard let client = resolved else { throw EngineError.notRunning }
let loaded = try await client.loadModel(id)
configuredModel = loaded
await supervisor.updateLaunchArguments(["serve", "--model", loaded])
UserDefaults.standard.set(loaded, forKey: EngineChoice.modelKey)
library.send(.appeared)
await recordLoadedModel(loaded)
return loaded
}
}

extension AppModel {
@discardableResult
public func applyComposeFile(_ url: URL, client override: EngineClient? = nil) async throws -> Bool {
let accessed = url.startAccessingSecurityScopedResource()
Expand Down Expand Up @@ -112,8 +151,9 @@ extension AppModel {
}
guard let filePath else { return false }
let current = await supervisor.launch
let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment())
UserDefaults.standard.set(filePath, forKey: EngineChoice.composeKey)
await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: ["serve", "--compose", filePath], environment: current.environment))
await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: ["serve", "--compose", filePath], environment: freshEnv))
return false
}

Expand Down
33 changes: 28 additions & 5 deletions Sources/BasaltApp/App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ public typealias ChatStore = Store<ChatState, ChatAction, ChatEffect>
public typealias MonitorStore = Store<MonitorState, MonitorAction, MonitorEffect>
public typealias LibraryStore = Store<LibraryState, LibraryAction, LibraryEffect>

@MainActor
private final class MainActorCallback<Value: Sendable> {
var invoke: (@MainActor (Value) -> Void)?
}

@Observable @MainActor
public final class AppModel {
public static let defaultModel = "mlx-community/gemma-4-12B-it-qat-4bit"
Expand All @@ -29,16 +34,24 @@ public final class AppModel {
public let drafts: DraftStore
@ObservationIgnored let supervisor: EngineSupervisor
@ObservationIgnored let repository: ConversationRepository
@ObservationIgnored let cloudEnvironment: @Sendable () -> [String: String]
public internal(set) var configuredModel: String
public var model: String { library.state.models.first(where: \.isLoaded)?.id ?? configuredModel }
@ObservationIgnored private var listening = false
@ObservationIgnored var composeEventsTask: Task<Void, Never>?

@ObservationIgnored public var answered: @MainActor (ConversationSnapshot) -> Void = { _ in }

public init(launch: HelperLaunch, model: String, storeURL: URL?, environment: EngineEnvironment = .live, drafts: DraftStore = .defaults()) throws {
public init(
launch: HelperLaunch,
model: String,
storeURL: URL?,
environment: EngineEnvironment = .live,
drafts: DraftStore = .defaults(),
cloudEnvironment: @escaping @Sendable () -> [String: String] = { CloudKeys.environment(defaults: .standard, keychain: .live()) }
) throws {
let supervisor = EngineSupervisor(launch: launch, environment: environment)
(self.supervisor, self.configuredModel, self.drafts) = (supervisor, model, drafts)
(self.supervisor, self.configuredModel, self.drafts, self.cloudEnvironment) = (supervisor, model, drafts, cloudEnvironment)
repository = ConversationRepository(modelContainer: try ConversationRepository.container(at: storeURL))
monitor = Store(MonitorState(), reduce: MonitorReducer.reduce, handle: MonitorReducer.handler(
stats: {
Expand All @@ -49,14 +62,24 @@ public final class AppModel {
guard let endpoint = await supervisor.endpoint else { return nil }
return try await EngineClient.http(endpoint).compose()
}))
let onChosen = MainActorCallback<String>()
library = Store(LibraryState(pending: UserDefaults.standard.stringArray(forKey: Self.pendingKey) ?? []), reduce: LibraryReducer.reduce, handle: LibraryEffects.handler(
LibraryEnvironment(
client: { await supervisor.endpoint.map { LibraryClient.live($0) } },
savePending: { UserDefaults.standard.set($0, forKey: AppModel.pendingKey) },
chose: { id in UserDefaults.standard.set(id, forKey: "model") })))
chose: { id in
UserDefaults.standard.set(id, forKey: EngineChoice.modelKey)
await supervisor.updateLaunchArguments(["serve", "--model", id])
await MainActor.run { onChosen.invoke?(id) }
})))
let initialCompose = UserDefaults.standard.string(forKey: EngineChoice.composeKey) ?? ""
composeProfiles = Self.makeComposeProfilesStore(initialCompose: initialCompose, supervisor: supervisor)
composeProfiles = Self.makeComposeProfilesStore(
initialCompose: initialCompose,
supervisor: supervisor,
cloudEnvironment: cloudEnvironment
)
voice = AudioSessionController(engine: { await supervisor.endpoint.map { EngineClient.http($0) } })
onChosen.invoke = { [weak self] id in self?.configuredModel = id }
voice.onSubmitTranscript = { [weak self] text in self?.submitVoiceTranscript(text) }
}

Expand Down Expand Up @@ -111,7 +134,7 @@ public final class AppModel {

public func restart() async {
let current = await supervisor.launch
let freshEnv = CloudKeys.environment(defaults: .standard, keychain: .live())
let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment())
await supervisor.relaunch(
HelperLaunch(executable: current.executable, arguments: current.arguments, environment: freshEnv)
)
Expand Down
2 changes: 2 additions & 0 deletions Sources/BasaltApp/Audio/AudioSessionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public actor AudioCaptureActor {
audioEngine.stop()
(self.engine, self.captured) = (nil, nil)
let recorded = sink.state.withLock { $0 }
guard !recorded.samples.isEmpty else { return Data() }
return Self.encodeMono16kWAV(samples: recorded.samples, sourceRate: recorded.rate)
}

Expand Down Expand Up @@ -139,6 +140,7 @@ public actor AudioCaptureActor {
}

public nonisolated static func encodeMono16kWAV(samples: [Float], sourceRate: Double) -> Data {
guard !samples.isEmpty else { return Data() }
let resampled = resample(samples: samples, from: sourceRate, to: Double(targetSampleRate))
return WAVEncoder.encode(samples: resampled, sampleRate: targetSampleRate)
}
Expand Down
10 changes: 5 additions & 5 deletions Sources/BasaltApp/Chat/ComposerGlassBar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,11 @@ struct ComposerGlassBar: View {
}

static func attach(_ url: URL, to store: ChatStore) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
if let data = try? Data(contentsOf: url),
let attachment = ChatAttachment(name: url.lastPathComponent, data: data, sourcePath: url.path) {
store.send(.attach(attachment))
guard url.isFileURL, ChatAttachment.accepts(url.lastPathComponent) else { return }
Task {
if let attachment = await ChatAttachment.loadAsync(from: url) {
store.send(.attach(attachment))
}
}
}
}
Expand Down
23 changes: 20 additions & 3 deletions Sources/BasaltApp/Chat/InlineVideoPlayerCard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -396,14 +396,31 @@ enum InlineVideoIO {
}

static func exportMP4WithPanel(part: GeneratedVideoPart) {
guard let path = part.filePath,
let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return }
guard let path = part.filePath, FileManager.default.fileExists(atPath: path) else { return }
let sourceURL = URL(fileURLWithPath: path)
let panel = NSSavePanel()
panel.allowedContentTypes = [.mpeg4Movie, .quickTimeMovie]
panel.canCreateDirectories = true
panel.nameFieldStringValue = part.assetID.isEmpty ? "basalt-video.mp4" : part.assetID
if panel.runModal() == .OK, let outURL = panel.url {
try? data.write(to: outURL, options: .atomic)
Task { try? await copyFile(from: sourceURL, to: outURL) }
}
}

@concurrent
static func copyFile(from source: URL, to destination: URL) async throws {
let resolvedSource = source.resolvingSymlinksInPath()
let resolvedDestination = destination.resolvingSymlinksInPath()
guard resolvedSource != resolvedDestination else { return }
let fm = FileManager.default
let tempURL = destination.deletingLastPathComponent()
.appending(path: ".\(destination.lastPathComponent).\(UUID().uuidString).tmp")
defer { try? fm.removeItem(at: tempURL) }
try fm.copyItem(at: resolvedSource, to: tempURL)
if fm.fileExists(atPath: destination.path) {
_ = try fm.replaceItemAt(destination, withItemAt: tempURL)
} else {
try fm.moveItem(at: tempURL, to: destination)
}
}
}
Loading