bots-garden/razorbillpublic Fork
⑂ 0c75ccb
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#57 #58: TUI Models screen (cache, download, remove) and Settings screen (tui.yaml, $EDITOR, reload)

Models: the Hugging Face cache read directly (ModelStore), loaded and
declared marks, p downloads through the build's engine with a progress
gauge, d removes after y (a loaded model is unloaded first; refused on
409), size against the server's free memory.

Settings: TUI preferences in ~/.config/razorbill/tui.yaml
(TUIPreferencesLoader in Core: unknown keys and wrong values reported
with their line; RZB_TUI_PREFERENCES overrides the path), edited in a
form and applied live where possible. The server's file opens in
$EDITOR (terminal suspended, comments kept), is checked on return, then
reloaded; Ctrl-R reloads it as it is. /rzb/status gains config_file.

rzb tui: options > tui.yaml > --config > defaults. Tests: Linux 323,
Mac 349.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-27T06:10:10+01:00 Browse files
0c75ccb parent: 2a96bad
modified Sources/RazorbillCLI/CLIEnvironment.swift +10 -2
@@ -51,8 +51,16 @@ public struct CLIEnvironment: Sendable {
5151 settings, engines: engines, store: modelStore, onRunning: onRunning)
5252 }
5353 self.hasTerminal = hasTerminal
54- let colors = variables["NO_COLOR"] == nil
55- self.tui = tui ?? { launch in await launch.run(colors: colors) }
54+ self.tui =
55+ tui ?? { launch in
56+ let environment = TUIEnvironment(
57+ store: modelStore,
58+ download: { model, progress in
59+ try await engines.make().download(model, progress: progress)
60+ },
61+ preferencesFile: launch.preferencesFile, configFile: launch.configFile)
62+ await launch.run(environment: environment)
63+ }
5664 }
5765
5866 /// The real terminal, model cache, environment variables and server, with the given engines.
@@ -51,8 +51,16 @@ public struct CLIEnvironment: Sendable {
51 settings, engines: engines, store: modelStore, onRunning: onRunning)51 settings, engines: engines, store: modelStore, onRunning: onRunning)
52 }52 }
53 self.hasTerminal = hasTerminal53 self.hasTerminal = hasTerminal
54- let colors = variables["NO_COLOR"] == nil54+ self.tui =
55- self.tui = tui ?? { launch in await launch.run(colors: colors) }55+ tui ?? { launch in
56+ let environment = TUIEnvironment(
57+ store: modelStore,
58+ download: { model, progress in
59+ try await engines.make().download(model, progress: progress)
60+ },
61+ preferencesFile: launch.preferencesFile, configFile: launch.configFile)
62+ await launch.run(environment: environment)
63+ }
56 }64 }
57 65
58 /// The real terminal, model cache, environment variables and server, with the given engines.66 /// The real terminal, model cache, environment variables and server, with the given engines.
modified Sources/RazorbillCLI/Commands/TUICommand.swift +26 -7
@@ -50,8 +50,12 @@ struct TUICommand: AsyncParsableCommand {
5050 let environment = CLIEnvironment.current
5151 try await reportingErrors(environment.console) {
5252 let section = try config.map { try ServerConfigLoader().load(file: $0).server }
53- let launch = launch(
54- section: section ?? ServerSection(), variables: environment.variables)
53+ let file = Self.preferencesFile(environment.variables)
54+ let preferences = try TUIPreferencesLoader().load(file: file)
55+ var launch = launch(
56+ section: section ?? ServerSection(), preferences: preferences,
57+ variables: environment.variables)
58+ launch.preferencesFile = file
5559 guard environment.hasTerminal else {
5660 environment.console.writeErrorLine(
5761 "error: rzb tui needs a terminal (standard input and output); "
@@ -62,14 +66,29 @@ struct TUICommand: AsyncParsableCommand {
6266 }
6367 }
6468
65- /// The options first, then the file's `server:` section, then the defaults.
66- func launch(section: ServerSection, variables: [String: String]) -> TUILaunch {
67- let address = url.flatMap(Self.baseURL) ?? Self.address(of: section)
69+ /// The options first, then `tui.yaml`, then the file's `server:` section, then the defaults.
70+ func launch(
71+ section: ServerSection, preferences: TUIPreferences = TUIPreferences(),
72+ variables: [String: String]
73+ ) -> TUILaunch {
74+ let address =
75+ url.flatMap(Self.baseURL) ?? preferences.serverURL.flatMap(Self.baseURL)
76+ ?? Self.address(of: section)
6877 let variable =
69- apiKeyVariable ?? section.apiKeyVariable ?? ServeCommand.defaultAPIKeyVariable
78+ apiKeyVariable ?? preferences.apiKeyVariable ?? section.apiKeyVariable
79+ ?? ServeCommand.defaultAPIKeyVariable
7080 let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 }
7181 let start = config.map { "rzb serve --config \($0)" } ?? "rzb serve"
72- return TUILaunch(url: address, apiKey: key, startCommand: start)
82+ let colors = variables["NO_COLOR"] == nil && preferences.colors != false
83+ return TUILaunch(
84+ url: address, apiKey: key, startCommand: start, preferences: preferences,
85+ configFile: config, colors: colors)
86+ }
87+
88+ /// `$RZB_TUI_PREFERENCES` when set (tests, several profiles), else `~/.config/razorbill/tui.yaml`.
89+ static func preferencesFile(_ variables: [String: String]) -> String {
90+ variables["RZB_TUI_PREFERENCES"].flatMap { $0.isEmpty ? nil : $0 }
91+ ?? TUIPreferences.defaultFile()
7392 }
7493
7594 /// Where a server started with `section` answers on this machine. A wildcard address
@@ -50,8 +50,12 @@ struct TUICommand: AsyncParsableCommand {
50 let environment = CLIEnvironment.current50 let environment = CLIEnvironment.current
51 try await reportingErrors(environment.console) {51 try await reportingErrors(environment.console) {
52 let section = try config.map { try ServerConfigLoader().load(file: $0).server }52 let section = try config.map { try ServerConfigLoader().load(file: $0).server }
53- let launch = launch(53+ let file = Self.preferencesFile(environment.variables)
54- section: section ?? ServerSection(), variables: environment.variables)54+ let preferences = try TUIPreferencesLoader().load(file: file)
55+ var launch = launch(
56+ section: section ?? ServerSection(), preferences: preferences,
57+ variables: environment.variables)
58+ launch.preferencesFile = file
55 guard environment.hasTerminal else {59 guard environment.hasTerminal else {
56 environment.console.writeErrorLine(60 environment.console.writeErrorLine(
57 "error: rzb tui needs a terminal (standard input and output); "61 "error: rzb tui needs a terminal (standard input and output); "
@@ -62,14 +66,29 @@ struct TUICommand: AsyncParsableCommand {
62 }66 }
63 }67 }
64 68
65- /// The options first, then the file's `server:` section, then the defaults.69+ /// The options first, then `tui.yaml`, then the file's `server:` section, then the defaults.
66- func launch(section: ServerSection, variables: [String: String]) -> TUILaunch {70+ func launch(
67- let address = url.flatMap(Self.baseURL) ?? Self.address(of: section)71+ section: ServerSection, preferences: TUIPreferences = TUIPreferences(),
72+ variables: [String: String]
73+ ) -> TUILaunch {
74+ let address =
75+ url.flatMap(Self.baseURL) ?? preferences.serverURL.flatMap(Self.baseURL)
76+ ?? Self.address(of: section)
68 let variable =77 let variable =
69- apiKeyVariable ?? section.apiKeyVariable ?? ServeCommand.defaultAPIKeyVariable78+ apiKeyVariable ?? preferences.apiKeyVariable ?? section.apiKeyVariable
79+ ?? ServeCommand.defaultAPIKeyVariable
70 let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 }80 let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 }
71 let start = config.map { "rzb serve --config \($0)" } ?? "rzb serve"81 let start = config.map { "rzb serve --config \($0)" } ?? "rzb serve"
72- return TUILaunch(url: address, apiKey: key, startCommand: start)82+ let colors = variables["NO_COLOR"] == nil && preferences.colors != false
83+ return TUILaunch(
84+ url: address, apiKey: key, startCommand: start, preferences: preferences,
85+ configFile: config, colors: colors)
86+ }
87+
88+ /// `$RZB_TUI_PREFERENCES` when set (tests, several profiles), else `~/.config/razorbill/tui.yaml`.
89+ static func preferencesFile(_ variables: [String: String]) -> String {
90+ variables["RZB_TUI_PREFERENCES"].flatMap { $0.isEmpty ? nil : $0 }
91+ ?? TUIPreferences.defaultFile()
73 }92 }
74 93
75 /// Where a server started with `section` answers on this machine. A wildcard address94 /// Where a server started with `section` answers on this machine. A wildcard address
added Sources/RazorbillCore/Config/TUIPreferences.swift +196 -0
new file mode 100644
@@ -0,0 +1,196 @@
1+import Foundation
2+import Yams
3+
4+/// The preferences of `rzb tui`, kept in `~/.config/razorbill/tui.yaml`. Every key is optional;
5+/// `rzb tui`'s options win over them.
6+///
7+/// ```yaml
8+/// server_url: http://127.0.0.1:7920
9+/// api_key_env: RZB_API_KEY
10+/// reasoning: folded # shown, folded or hidden
11+/// colors: true
12+/// poll_interval: 1s
13+/// chat:
14+/// temperature: 0.7
15+/// max_tokens: 1024
16+/// thinking: false
17+/// ```
18+public struct TUIPreferences: Sendable, Equatable {
19+ public var serverURL: String?
20+ public var apiKeyVariable: String?
21+ /// `shown`, `folded` or `hidden`.
22+ public var reasoning: String?
23+ public var colors: Bool?
24+ public var pollInterval: Duration?
25+ public var chat = ChatDefaults()
26+
27+ /// The sampling the Chat screen starts with; `nil` leaves the server's value.
28+ public struct ChatDefaults: Sendable, Equatable {
29+ public var temperature: Double?
30+ public var topP: Double?
31+ public var topK: Int?
32+ public var minP: Double?
33+ public var maxTokens: Int?
34+ public var thinking: Bool?
35+
36+ public init() {}
37+ }
38+
39+ public init() {}
40+
41+ public static let reasoningDisplays = ["shown", "folded", "hidden"]
42+
43+ /// `~/.config/razorbill/tui.yaml`.
44+ public static func defaultFile(home: String = NSHomeDirectory()) -> String {
45+ URL(fileURLWithPath: home).appendingPathComponent(".config/razorbill/tui.yaml").path
46+ }
47+
48+ /// The file's text: only the keys that are set.
49+ public var yaml: String {
50+ var lines = ["# rzb tui preferences (rzb tui's options win over them)"]
51+ if let serverURL { lines.append("server_url: \(Self.quoted(serverURL))") }
52+ if let apiKeyVariable { lines.append("api_key_env: \(Self.quoted(apiKeyVariable))") }
53+ if let reasoning { lines.append("reasoning: \(reasoning)") }
54+ if let colors { lines.append("colors: \(colors)") }
55+ if let pollInterval {
56+ lines.append("poll_interval: \(Int(pollInterval / .milliseconds(1)))ms")
57+ }
58+ var chatLines: [String] = []
59+ if let value = chat.temperature { chatLines.append(" temperature: \(value)") }
60+ if let value = chat.topP { chatLines.append(" top_p: \(value)") }
61+ if let value = chat.topK { chatLines.append(" top_k: \(value)") }
62+ if let value = chat.minP { chatLines.append(" min_p: \(value)") }
63+ if let value = chat.maxTokens { chatLines.append(" max_tokens: \(value)") }
64+ if let value = chat.thinking { chatLines.append(" thinking: \(value)") }
65+ if !chatLines.isEmpty { lines += ["chat:"] + chatLines }
66+ return lines.joined(separator: "\n") + "\n"
67+ }
68+
69+ /// Writes ``yaml`` to `file`, creating its folder.
70+ public func save(to file: String) throws {
71+ let url = URL(fileURLWithPath: file)
72+ try FileManager.default.createDirectory(
73+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
74+ try yaml.write(to: url, atomically: true, encoding: .utf8)
75+ }
76+
77+ /// A YAML string in double quotes, so `:` or `#` in a URL stay text.
78+ private static func quoted(_ text: String) -> String {
79+ let escaped = text.replacingOccurrences(of: "\\", with: "\\\\")
80+ .replacingOccurrences(of: "\"", with: "\\\"")
81+ return "\"" + escaped + "\""
82+ }
83+}
84+
85+/// Reads `tui.yaml`, reporting every problem with its line, like ``ServerConfigLoader``.
86+///
87+/// ```swift
88+/// let preferences = try TUIPreferencesLoader().load(file: TUIPreferences.defaultFile())
89+/// ```
90+public struct TUIPreferencesLoader: Sendable {
91+ public init() {}
92+
93+ static let topLevelKeys = [
94+ "server_url", "api_key_env", "reasoning", "colors", "poll_interval", "chat",
95+ ]
96+ static let chatKeys = ["temperature", "top_p", "top_k", "min_p", "max_tokens", "thinking"]
97+
98+ /// The preferences in `file`; the defaults when it does not exist.
99+ public func load(file: String) throws -> TUIPreferences {
100+ guard FileManager.default.fileExists(atPath: file) else { return TUIPreferences() }
101+ guard let text = try? String(contentsOfFile: file, encoding: .utf8) else {
102+ throw ConfigError(
103+ file: file,
104+ issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")])
105+ }
106+ return try parse(text, file: file)
107+ }
108+
109+ public func parse(_ text: String, file: String? = nil) throws -> TUIPreferences {
110+ let root: Node?
111+ do {
112+ root = try Yams.compose(yaml: text)
113+ } catch {
114+ let issue = ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)")
115+ throw ConfigError(file: file, issues: [issue])
116+ }
117+ guard let root else { return TUIPreferences() }
118+ let reader = ConfigReader()
119+ let preferences = read(root, reader)
120+ guard reader.issues.isEmpty, let preferences else {
121+ throw ConfigError(file: file, issues: reader.issues)
122+ }
123+ return preferences
124+ }
125+
126+ private func read(_ root: Node, _ reader: ConfigReader) -> TUIPreferences? {
127+ guard let document = reader.mapping(root, path: "") else { return nil }
128+ reader.rejectUnknownKeys(document, allowed: Self.topLevelKeys, path: "")
129+ var preferences = TUIPreferences()
130+ preferences.serverURL = reader.string(document, "server_url", path: "")
131+ preferences.apiKeyVariable = reader.string(document, "api_key_env", path: "")
132+ preferences.colors = reader.bool(document, "colors", path: "")
133+ if let display = reader.string(document, "reasoning", path: "") {
134+ if TUIPreferences.reasoningDisplays.contains(display) {
135+ preferences.reasoning = display
136+ } else {
137+ reader.report(
138+ "reasoning", document["reasoning"], "must be one of: shown, folded, hidden")
139+ }
140+ }
141+ if let text = reader.string(document, "poll_interval", path: "") {
142+ if let interval = Quantities.duration(text) {
143+ preferences.pollInterval = interval
144+ } else {
145+ reader.report(
146+ "poll_interval", document["poll_interval"],
147+ "must be a duration such as 500ms or 2s")
148+ }
149+ }
150+ if let node = document["chat"], !reader.isNull(node) {
151+ if let chat = reader.mapping(node, path: "chat") {
152+ preferences.chat = readChat(chat, reader)
153+ }
154+ }
155+ return preferences
156+ }
157+
158+ private func readChat(
159+ _ chat: Node.Mapping, _ reader: ConfigReader
160+ ) -> TUIPreferences.ChatDefaults {
161+ reader.rejectUnknownKeys(chat, allowed: Self.chatKeys, path: "chat")
162+ var defaults = TUIPreferences.ChatDefaults()
163+ defaults.temperature = number(chat, "temperature", 0 ... 2, reader)
164+ defaults.topP = number(chat, "top_p", 0 ... 1, reader)
165+ defaults.minP = number(chat, "min_p", 0 ... 1, reader)
166+ defaults.topK = whole(chat, "top_k", atLeast: 0, reader)
167+ defaults.maxTokens = whole(chat, "max_tokens", atLeast: 1, reader)
168+ defaults.thinking = reader.bool(chat, "thinking", path: "chat")
169+ return defaults
170+ }
171+
172+ private func number(
173+ _ mapping: Node.Mapping, _ key: String, _ range: ClosedRange<Double>,
174+ _ reader: ConfigReader
175+ ) -> Double? {
176+ guard let value = reader.double(mapping, key, path: "chat") else { return nil }
177+ guard range.contains(value) else {
178+ reader.report(
179+ "chat.\(key)", mapping[key],
180+ "must be between \(range.lowerBound) and \(range.upperBound)")
181+ return nil
182+ }
183+ return value
184+ }
185+
186+ private func whole(
187+ _ mapping: Node.Mapping, _ key: String, atLeast minimum: Int, _ reader: ConfigReader
188+ ) -> Int? {
189+ guard let value = reader.int(mapping, key, path: "chat") else { return nil }
190+ guard value >= minimum else {
191+ reader.report("chat.\(key)", mapping[key], "must be \(minimum) or more")
192+ return nil
193+ }
194+ return value
195+ }
196+}
new file mode 100644
@@ -0,0 +1,196 @@
1+import Foundation
2+import Yams
3+
4+/// The preferences of `rzb tui`, kept in `~/.config/razorbill/tui.yaml`. Every key is optional;
5+/// `rzb tui`'s options win over them.
6+///
7+/// ```yaml
8+/// server_url: http://127.0.0.1:7920
9+/// api_key_env: RZB_API_KEY
10+/// reasoning: folded # shown, folded or hidden
11+/// colors: true
12+/// poll_interval: 1s
13+/// chat:
14+/// temperature: 0.7
15+/// max_tokens: 1024
16+/// thinking: false
17+/// ```
18+public struct TUIPreferences: Sendable, Equatable {
19+ public var serverURL: String?
20+ public var apiKeyVariable: String?
21+ /// `shown`, `folded` or `hidden`.
22+ public var reasoning: String?
23+ public var colors: Bool?
24+ public var pollInterval: Duration?
25+ public var chat = ChatDefaults()
26+
27+ /// The sampling the Chat screen starts with; `nil` leaves the server's value.
28+ public struct ChatDefaults: Sendable, Equatable {
29+ public var temperature: Double?
30+ public var topP: Double?
31+ public var topK: Int?
32+ public var minP: Double?
33+ public var maxTokens: Int?
34+ public var thinking: Bool?
35+
36+ public init() {}
37+ }
38+
39+ public init() {}
40+
41+ public static let reasoningDisplays = ["shown", "folded", "hidden"]
42+
43+ /// `~/.config/razorbill/tui.yaml`.
44+ public static func defaultFile(home: String = NSHomeDirectory()) -> String {
45+ URL(fileURLWithPath: home).appendingPathComponent(".config/razorbill/tui.yaml").path
46+ }
47+
48+ /// The file's text: only the keys that are set.
49+ public var yaml: String {
50+ var lines = ["# rzb tui preferences (rzb tui's options win over them)"]
51+ if let serverURL { lines.append("server_url: \(Self.quoted(serverURL))") }
52+ if let apiKeyVariable { lines.append("api_key_env: \(Self.quoted(apiKeyVariable))") }
53+ if let reasoning { lines.append("reasoning: \(reasoning)") }
54+ if let colors { lines.append("colors: \(colors)") }
55+ if let pollInterval {
56+ lines.append("poll_interval: \(Int(pollInterval / .milliseconds(1)))ms")
57+ }
58+ var chatLines: [String] = []
59+ if let value = chat.temperature { chatLines.append(" temperature: \(value)") }
60+ if let value = chat.topP { chatLines.append(" top_p: \(value)") }
61+ if let value = chat.topK { chatLines.append(" top_k: \(value)") }
62+ if let value = chat.minP { chatLines.append(" min_p: \(value)") }
63+ if let value = chat.maxTokens { chatLines.append(" max_tokens: \(value)") }
64+ if let value = chat.thinking { chatLines.append(" thinking: \(value)") }
65+ if !chatLines.isEmpty { lines += ["chat:"] + chatLines }
66+ return lines.joined(separator: "\n") + "\n"
67+ }
68+
69+ /// Writes ``yaml`` to `file`, creating its folder.
70+ public func save(to file: String) throws {
71+ let url = URL(fileURLWithPath: file)
72+ try FileManager.default.createDirectory(
73+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
74+ try yaml.write(to: url, atomically: true, encoding: .utf8)
75+ }
76+
77+ /// A YAML string in double quotes, so `:` or `#` in a URL stay text.
78+ private static func quoted(_ text: String) -> String {
79+ let escaped = text.replacingOccurrences(of: "\\", with: "\\\\")
80+ .replacingOccurrences(of: "\"", with: "\\\"")
81+ return "\"" + escaped + "\""
82+ }
83+}
84+
85+/// Reads `tui.yaml`, reporting every problem with its line, like ``ServerConfigLoader``.
86+///
87+/// ```swift
88+/// let preferences = try TUIPreferencesLoader().load(file: TUIPreferences.defaultFile())
89+/// ```
90+public struct TUIPreferencesLoader: Sendable {
91+ public init() {}
92+
93+ static let topLevelKeys = [
94+ "server_url", "api_key_env", "reasoning", "colors", "poll_interval", "chat",
95+ ]
96+ static let chatKeys = ["temperature", "top_p", "top_k", "min_p", "max_tokens", "thinking"]
97+
98+ /// The preferences in `file`; the defaults when it does not exist.
99+ public func load(file: String) throws -> TUIPreferences {
100+ guard FileManager.default.fileExists(atPath: file) else { return TUIPreferences() }
101+ guard let text = try? String(contentsOfFile: file, encoding: .utf8) else {
102+ throw ConfigError(
103+ file: file,
104+ issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")])
105+ }
106+ return try parse(text, file: file)
107+ }
108+
109+ public func parse(_ text: String, file: String? = nil) throws -> TUIPreferences {
110+ let root: Node?
111+ do {
112+ root = try Yams.compose(yaml: text)
113+ } catch {
114+ let issue = ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)")
115+ throw ConfigError(file: file, issues: [issue])
116+ }
117+ guard let root else { return TUIPreferences() }
118+ let reader = ConfigReader()
119+ let preferences = read(root, reader)
120+ guard reader.issues.isEmpty, let preferences else {
121+ throw ConfigError(file: file, issues: reader.issues)
122+ }
123+ return preferences
124+ }
125+
126+ private func read(_ root: Node, _ reader: ConfigReader) -> TUIPreferences? {
127+ guard let document = reader.mapping(root, path: "") else { return nil }
128+ reader.rejectUnknownKeys(document, allowed: Self.topLevelKeys, path: "")
129+ var preferences = TUIPreferences()
130+ preferences.serverURL = reader.string(document, "server_url", path: "")
131+ preferences.apiKeyVariable = reader.string(document, "api_key_env", path: "")
132+ preferences.colors = reader.bool(document, "colors", path: "")
133+ if let display = reader.string(document, "reasoning", path: "") {
134+ if TUIPreferences.reasoningDisplays.contains(display) {
135+ preferences.reasoning = display
136+ } else {
137+ reader.report(
138+ "reasoning", document["reasoning"], "must be one of: shown, folded, hidden")
139+ }
140+ }
141+ if let text = reader.string(document, "poll_interval", path: "") {
142+ if let interval = Quantities.duration(text) {
143+ preferences.pollInterval = interval
144+ } else {
145+ reader.report(
146+ "poll_interval", document["poll_interval"],
147+ "must be a duration such as 500ms or 2s")
148+ }
149+ }
150+ if let node = document["chat"], !reader.isNull(node) {
151+ if let chat = reader.mapping(node, path: "chat") {
152+ preferences.chat = readChat(chat, reader)
153+ }
154+ }
155+ return preferences
156+ }
157+
158+ private func readChat(
159+ _ chat: Node.Mapping, _ reader: ConfigReader
160+ ) -> TUIPreferences.ChatDefaults {
161+ reader.rejectUnknownKeys(chat, allowed: Self.chatKeys, path: "chat")
162+ var defaults = TUIPreferences.ChatDefaults()
163+ defaults.temperature = number(chat, "temperature", 0 ... 2, reader)
164+ defaults.topP = number(chat, "top_p", 0 ... 1, reader)
165+ defaults.minP = number(chat, "min_p", 0 ... 1, reader)
166+ defaults.topK = whole(chat, "top_k", atLeast: 0, reader)
167+ defaults.maxTokens = whole(chat, "max_tokens", atLeast: 1, reader)
168+ defaults.thinking = reader.bool(chat, "thinking", path: "chat")
169+ return defaults
170+ }
171+
172+ private func number(
173+ _ mapping: Node.Mapping, _ key: String, _ range: ClosedRange<Double>,
174+ _ reader: ConfigReader
175+ ) -> Double? {
176+ guard let value = reader.double(mapping, key, path: "chat") else { return nil }
177+ guard range.contains(value) else {
178+ reader.report(
179+ "chat.\(key)", mapping[key],
180+ "must be between \(range.lowerBound) and \(range.upperBound)")
181+ return nil
182+ }
183+ return value
184+ }
185+
186+ private func whole(
187+ _ mapping: Node.Mapping, _ key: String, atLeast minimum: Int, _ reader: ConfigReader
188+ ) -> Int? {
189+ guard let value = reader.int(mapping, key, path: "chat") else { return nil }
190+ guard value >= minimum else {
191+ reader.report("chat.\(key)", mapping[key], "must be \(minimum) or more")
192+ return nil
193+ }
194+ return value
195+ }
196+}
modified Sources/RazorbillCore/Models/ModelStore.swift +10 -0
@@ -13,6 +13,16 @@ public struct StoredModel: Sendable, Equatable {
1313 /// At least one revision is complete in MLX format (`config.json` + `*.safetensors`), so
1414 /// razorbill can load it. GGUF repositories and unfinished downloads are not.
1515 public var isLoadable: Bool
16+
17+ public init(
18+ id: String, sizeInBytes: Int64, revisions: [String], directory: URL, isLoadable: Bool
19+ ) {
20+ self.id = id
21+ self.sizeInBytes = sizeInBytes
22+ self.revisions = revisions
23+ self.directory = directory
24+ self.isLoadable = isLoadable
25+ }
1626 }
1727
1828 /// Reads the Hugging Face cache, the place where models are downloaded and shared with the
@@ -13,6 +13,16 @@ public struct StoredModel: Sendable, Equatable {
13 /// At least one revision is complete in MLX format (`config.json` + `*.safetensors`), so13 /// At least one revision is complete in MLX format (`config.json` + `*.safetensors`), so
14 /// razorbill can load it. GGUF repositories and unfinished downloads are not.14 /// razorbill can load it. GGUF repositories and unfinished downloads are not.
15 public var isLoadable: Bool15 public var isLoadable: Bool
16+
17+ public init(
18+ id: String, sizeInBytes: Int64, revisions: [String], directory: URL, isLoadable: Bool
19+ ) {
20+ self.id = id
21+ self.sizeInBytes = sizeInBytes
22+ self.revisions = revisions
23+ self.directory = directory
24+ self.isLoadable = isLoadable
25+ }
16 }26 }
17 27
18 /// Reads the Hugging Face cache, the place where models are downloaded and shared with the28 /// Reads the Hugging Face cache, the place where models are downloaded and shared with the
modified Sources/RazorbillServer/AdminRoutes.swift +11 -0
@@ -1,3 +1,4 @@
1+import Foundation
12 import Hummingbird
23 import RazorbillCore
34
@@ -60,12 +61,18 @@ struct AdminRoutes {
6061 }
6162 }
6263
64+ /// `server.yaml` → `/the/working/directory/server.yaml`.
65+ static func absolutePath(_ path: String) -> String {
66+ URL(fileURLWithPath: path).standardizedFileURL.path
67+ }
68+
6369 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {
6470 ServerStatus(
6571 version: Razorbill.version,
6672 uptimeSeconds: Int((now - startedAt) / .seconds(1)),
6773 host: settings.host,
6874 port: settings.port,
75+ configFile: settings.configFile.map(Self.absolutePath),
6976 models: await models.status(now: now).map(StatusModel.init),
7077 recentRequests: history.recent,
7178 memory: memory?().map(StatusMemory.init))
@@ -116,6 +123,8 @@ struct ServerStatus: Encodable {
116123 let host: String
117124 /// The configured port (`0` when the server picked a free one).
118125 let port: Int
126+ /// The `--config` file, as an absolute path; `null` when the server runs without one.
127+ let configFile: String?
119128 let models: [StatusModel]
120129 /// Newest first; the `/rzb/` routes are not in it.
121130 let recentRequests: [RequestRecord]
@@ -126,6 +135,7 @@ struct ServerStatus: Encodable {
126135 case version, host, port, models, memory
127136 case uptimeSeconds = "uptime_seconds"
128137 case recentRequests = "recent_requests"
138+ case configFile = "config_file"
129139 }
130140
131141 /// Written by hand so a missing `memory` is an explicit `null`, not an absent key.
@@ -135,6 +145,7 @@ struct ServerStatus: Encodable {
135145 try container.encode(uptimeSeconds, forKey: .uptimeSeconds)
136146 try container.encode(host, forKey: .host)
137147 try container.encode(port, forKey: .port)
148+ try container.encode(configFile, forKey: .configFile)
138149 try container.encode(models, forKey: .models)
139150 try container.encode(recentRequests, forKey: .recentRequests)
140151 try container.encode(memory, forKey: .memory)
@@ -1,3 +1,4 @@
1+import Foundation
1 import Hummingbird2 import Hummingbird
2 import RazorbillCore3 import RazorbillCore
3 4
@@ -60,12 +61,18 @@ struct AdminRoutes {
60 }61 }
61 }62 }
62 63
64+ /// `server.yaml` → `/the/working/directory/server.yaml`.
65+ static func absolutePath(_ path: String) -> String {
66+ URL(fileURLWithPath: path).standardizedFileURL.path
67+ }
68+
63 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {69 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {
64 ServerStatus(70 ServerStatus(
65 version: Razorbill.version,71 version: Razorbill.version,
66 uptimeSeconds: Int((now - startedAt) / .seconds(1)),72 uptimeSeconds: Int((now - startedAt) / .seconds(1)),
67 host: settings.host,73 host: settings.host,
68 port: settings.port,74 port: settings.port,
75+ configFile: settings.configFile.map(Self.absolutePath),
69 models: await models.status(now: now).map(StatusModel.init),76 models: await models.status(now: now).map(StatusModel.init),
70 recentRequests: history.recent,77 recentRequests: history.recent,
71 memory: memory?().map(StatusMemory.init))78 memory: memory?().map(StatusMemory.init))
@@ -116,6 +123,8 @@ struct ServerStatus: Encodable {
116 let host: String123 let host: String
117 /// The configured port (`0` when the server picked a free one).124 /// The configured port (`0` when the server picked a free one).
118 let port: Int125 let port: Int
126+ /// The `--config` file, as an absolute path; `null` when the server runs without one.
127+ let configFile: String?
119 let models: [StatusModel]128 let models: [StatusModel]
120 /// Newest first; the `/rzb/` routes are not in it.129 /// Newest first; the `/rzb/` routes are not in it.
121 let recentRequests: [RequestRecord]130 let recentRequests: [RequestRecord]
@@ -126,6 +135,7 @@ struct ServerStatus: Encodable {
126 case version, host, port, models, memory135 case version, host, port, models, memory
127 case uptimeSeconds = "uptime_seconds"136 case uptimeSeconds = "uptime_seconds"
128 case recentRequests = "recent_requests"137 case recentRequests = "recent_requests"
138+ case configFile = "config_file"
129 }139 }
130 140
131 /// Written by hand so a missing `memory` is an explicit `null`, not an absent key.141 /// Written by hand so a missing `memory` is an explicit `null`, not an absent key.
@@ -135,6 +145,7 @@ struct ServerStatus: Encodable {
135 try container.encode(uptimeSeconds, forKey: .uptimeSeconds)145 try container.encode(uptimeSeconds, forKey: .uptimeSeconds)
136 try container.encode(host, forKey: .host)146 try container.encode(host, forKey: .host)
137 try container.encode(port, forKey: .port)147 try container.encode(port, forKey: .port)
148+ try container.encode(configFile, forKey: .configFile)
138 try container.encode(models, forKey: .models)149 try container.encode(models, forKey: .models)
139 try container.encode(recentRequests, forKey: .recentRequests)150 try container.encode(recentRequests, forKey: .recentRequests)
140 try container.encode(memory, forKey: .memory)151 try container.encode(memory, forKey: .memory)
modified Sources/RazorbillTUI/AppRenderer.swift +0 -12
@@ -82,16 +82,4 @@ public struct AppRenderer: Sendable {
8282 static func gigabytes(_ bytes: Int64) -> String {
8383 String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
8484 }
85-
86- /// The body of a screen whose content is not built yet, naming the ticket that brings it.
87- public static func placeholder(for screen: AppScreen) -> [String] {
88- let ticket: String =
89- switch screen {
90- case .chat: "#55"
91- case .dashboard: "#56"
92- case .models: "#57"
93- case .settings: "#58"
94- }
95- return ["", " \(screen.title): coming with \(ticket)."]
96- }
9785 }
@@ -82,16 +82,4 @@ public struct AppRenderer: Sendable {
82 static func gigabytes(_ bytes: Int64) -> String {82 static func gigabytes(_ bytes: Int64) -> String {
83 String(format: "%.1f GB", Double(bytes) / 1_073_741_824)83 String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
84 }84 }
85-
86- /// The body of a screen whose content is not built yet, naming the ticket that brings it.
87- public static func placeholder(for screen: AppScreen) -> [String] {
88- let ticket: String =
89- switch screen {
90- case .chat: "#55"
91- case .dashboard: "#56"
92- case .models: "#57"
93- case .settings: "#58"
94- }
95- return ["", " \(screen.title): coming with \(ticket)."]
96- }
97 }85 }
modified Sources/RazorbillTUI/ChatScreen.swift +9 -0
@@ -1,4 +1,5 @@
11 import Foundation
2+import RazorbillCore
23
34 /// One line of the conversation as the Chat screen keeps it.
45 public struct ChatEntry: Sendable, Equatable {
@@ -108,6 +109,14 @@ public struct ChatScreen: Sendable, Equatable {
108109 setModels(ids.map { ServedModel(id: $0, loaded: nil, kind: nil) })
109110 }
110111
112+ /// Starts with the preferences' reasoning display and sampling (Settings, `tui.yaml`).
113+ public mutating func apply(_ preferences: TUIPreferences) {
114+ if let display = preferences.reasoning.flatMap(ReasoningDisplay.init(rawValue:)) {
115+ reasoning = display
116+ }
117+ options = ChatOptions(preferences.chat)
118+ }
119+
111120 // MARK: Keys
112121
113122 public mutating func handle(_ key: Key) -> Action {
@@ -1,4 +1,5 @@
1 import Foundation1 import Foundation
2+import RazorbillCore
2 3
3 /// One line of the conversation as the Chat screen keeps it.4 /// One line of the conversation as the Chat screen keeps it.
4 public struct ChatEntry: Sendable, Equatable {5 public struct ChatEntry: Sendable, Equatable {
@@ -108,6 +109,14 @@ public struct ChatScreen: Sendable, Equatable {
108 setModels(ids.map { ServedModel(id: $0, loaded: nil, kind: nil) })109 setModels(ids.map { ServedModel(id: $0, loaded: nil, kind: nil) })
109 }110 }
110 111
112+ /// Starts with the preferences' reasoning display and sampling (Settings, `tui.yaml`).
113+ public mutating func apply(_ preferences: TUIPreferences) {
114+ if let display = preferences.reasoning.flatMap(ReasoningDisplay.init(rawValue:)) {
115+ reasoning = display
116+ }
117+ options = ChatOptions(preferences.chat)
118+ }
119+
111 // MARK: Keys120 // MARK: Keys
112 121
113 public mutating func handle(_ key: Key) -> Action {122 public mutating func handle(_ key: Key) -> Action {
added Sources/RazorbillTUI/ModelsRenderer.swift +93 -0
new file mode 100644
@@ -0,0 +1,93 @@
1+/// Draws the Models screen: the cache's models in columns, downloads with their progress, a hint
2+/// about the selected model's size against the server's memory, and the bottom line (a notice,
3+/// the id being typed, or the removal question).
4+///
5+/// ```swift
6+/// let (lines, cursor) = ModelsRenderer(style: style).render(screen, memory: status?.memory, width: 100, height: 20)
7+/// ```
8+public struct ModelsRenderer: Sendable {
9+ public var style: Style
10+
11+ public init(style: Style) {
12+ self.style = style
13+ }
14+
15+ static let widths = [44, 11, 10, 8, 0]
16+ static let header = DashboardScreen.columns(
17+ ["ID", "KIND", "SIZE", "LOADED", "DECLARED AS"], widths: widths)
18+
19+ public func render(
20+ _ screen: ModelsScreen, memory: EngineMemory?, width: Int, height: Int
21+ ) -> (lines: [String], cursor: FormView.Cursor?) {
22+ var lines = [
23+ "",
24+ style.bold(" Models in the Hugging Face cache")
25+ + style.dim(" ↑↓ select · p download · d remove · r refresh"),
26+ style.dim(" " + Self.header),
27+ ]
28+ let footer = footerLines(screen, memory: memory)
29+ let room = max(1, height - lines.count - footer.count - 1)
30+ if screen.rows.isEmpty {
31+ lines.append(" no MLX model in the cache yet: p to download one")
32+ } else {
33+ var list = screen.list
34+ lines += list.render(
35+ screen.rows.map(Self.row), width: width, height: min(room, screen.rows.count),
36+ style: style)
37+ }
38+ lines.append("")
39+ let top = Array(lines.prefix(max(0, height - footer.count)))
40+ let padding = Array(repeating: "", count: max(0, height - top.count - footer.count))
41+ let all = (top + padding + footer).map { TextLayout.truncate($0, width: width) }
42+ return (all, cursor(screen, row: all.count - 1))
43+ }
44+
45+ static func row(_ model: ModelRow) -> String {
46+ " "
47+ + DashboardScreen.columns(
48+ [
49+ model.id, model.kind ?? "-", AppRenderer.gigabytes(model.sizeBytes),
50+ model.loaded ? "yes" : "", model.declaredAs.joined(separator: ", "),
51+ ], widths: widths)
52+ }
53+
54+ func footerLines(_ screen: ModelsScreen, memory: EngineMemory?) -> [String] {
55+ var lines: [String] = []
56+ for (id, progress) in screen.downloads.sorted(by: { $0.key < $1.key }) {
57+ let percent = Int((progress * 100).rounded())
58+ lines.append(
59+ " ↓ \(id) " + DashboardScreen.gauge(Int64(percent), of: 100) + " \(percent)%")
60+ }
61+ if let selected = screen.selected { lines.append(style.dim(hint(selected, memory))) }
62+ lines.append(bottomLine(screen))
63+ return lines
64+ }
65+
66+ /// `org/a: 4.2 GB on disk · the server's memory: 0.4 GB in use of 30.4 GB`
67+ func hint(_ model: ModelRow, _ memory: EngineMemory?) -> String {
68+ var hint = " \(model.id): \(AppRenderer.gigabytes(model.sizeBytes)) on disk"
69+ guard let memory else { return hint }
70+ let free = memory.limitBytes - memory.activeBytes
71+ let used = AppRenderer.gigabytes(memory.activeBytes)
72+ let limit = AppRenderer.gigabytes(memory.limitBytes)
73+ hint += " · the server's memory: \(used) in use of \(limit)"
74+ if !model.loaded && model.sizeBytes > free { hint += " · more than is free now" }
75+ return hint
76+ }
77+
78+ func bottomLine(_ screen: ModelsScreen) -> String {
79+ switch screen.mode {
80+ case .enteringID(let field):
81+ return " Download (Enter, Esc): " + field.text
82+ case .confirmingRemoval(let id):
83+ return style.yellow(" Remove \(id) from the disk? y / n")
84+ case .browsing:
85+ return screen.notice.map { " " + $0 } ?? ""
86+ }
87+ }
88+
89+ func cursor(_ screen: ModelsScreen, row: Int) -> FormView.Cursor? {
90+ guard case .enteringID(let field) = screen.mode else { return nil }
91+ return (row, " Download (Enter, Esc): ".count + field.cursor)
92+ }
93+}
new file mode 100644
@@ -0,0 +1,93 @@
1+/// Draws the Models screen: the cache's models in columns, downloads with their progress, a hint
2+/// about the selected model's size against the server's memory, and the bottom line (a notice,
3+/// the id being typed, or the removal question).
4+///
5+/// ```swift
6+/// let (lines, cursor) = ModelsRenderer(style: style).render(screen, memory: status?.memory, width: 100, height: 20)
7+/// ```
8+public struct ModelsRenderer: Sendable {
9+ public var style: Style
10+
11+ public init(style: Style) {
12+ self.style = style
13+ }
14+
15+ static let widths = [44, 11, 10, 8, 0]
16+ static let header = DashboardScreen.columns(
17+ ["ID", "KIND", "SIZE", "LOADED", "DECLARED AS"], widths: widths)
18+
19+ public func render(
20+ _ screen: ModelsScreen, memory: EngineMemory?, width: Int, height: Int
21+ ) -> (lines: [String], cursor: FormView.Cursor?) {
22+ var lines = [
23+ "",
24+ style.bold(" Models in the Hugging Face cache")
25+ + style.dim(" ↑↓ select · p download · d remove · r refresh"),
26+ style.dim(" " + Self.header),
27+ ]
28+ let footer = footerLines(screen, memory: memory)
29+ let room = max(1, height - lines.count - footer.count - 1)
30+ if screen.rows.isEmpty {
31+ lines.append(" no MLX model in the cache yet: p to download one")
32+ } else {
33+ var list = screen.list
34+ lines += list.render(
35+ screen.rows.map(Self.row), width: width, height: min(room, screen.rows.count),
36+ style: style)
37+ }
38+ lines.append("")
39+ let top = Array(lines.prefix(max(0, height - footer.count)))
40+ let padding = Array(repeating: "", count: max(0, height - top.count - footer.count))
41+ let all = (top + padding + footer).map { TextLayout.truncate($0, width: width) }
42+ return (all, cursor(screen, row: all.count - 1))
43+ }
44+
45+ static func row(_ model: ModelRow) -> String {
46+ " "
47+ + DashboardScreen.columns(
48+ [
49+ model.id, model.kind ?? "-", AppRenderer.gigabytes(model.sizeBytes),
50+ model.loaded ? "yes" : "", model.declaredAs.joined(separator: ", "),
51+ ], widths: widths)
52+ }
53+
54+ func footerLines(_ screen: ModelsScreen, memory: EngineMemory?) -> [String] {
55+ var lines: [String] = []
56+ for (id, progress) in screen.downloads.sorted(by: { $0.key < $1.key }) {
57+ let percent = Int((progress * 100).rounded())
58+ lines.append(
59+ " ↓ \(id) " + DashboardScreen.gauge(Int64(percent), of: 100) + " \(percent)%")
60+ }
61+ if let selected = screen.selected { lines.append(style.dim(hint(selected, memory))) }
62+ lines.append(bottomLine(screen))
63+ return lines
64+ }
65+
66+ /// `org/a: 4.2 GB on disk · the server's memory: 0.4 GB in use of 30.4 GB`
67+ func hint(_ model: ModelRow, _ memory: EngineMemory?) -> String {
68+ var hint = " \(model.id): \(AppRenderer.gigabytes(model.sizeBytes)) on disk"
69+ guard let memory else { return hint }
70+ let free = memory.limitBytes - memory.activeBytes
71+ let used = AppRenderer.gigabytes(memory.activeBytes)
72+ let limit = AppRenderer.gigabytes(memory.limitBytes)
73+ hint += " · the server's memory: \(used) in use of \(limit)"
74+ if !model.loaded && model.sizeBytes > free { hint += " · more than is free now" }
75+ return hint
76+ }
77+
78+ func bottomLine(_ screen: ModelsScreen) -> String {
79+ switch screen.mode {
80+ case .enteringID(let field):
81+ return " Download (Enter, Esc): " + field.text
82+ case .confirmingRemoval(let id):
83+ return style.yellow(" Remove \(id) from the disk? y / n")
84+ case .browsing:
85+ return screen.notice.map { " " + $0 } ?? ""
86+ }
87+ }
88+
89+ func cursor(_ screen: ModelsScreen, row: Int) -> FormView.Cursor? {
90+ guard case .enteringID(let field) = screen.mode else { return nil }
91+ return (row, " Download (Enter, Esc): ".count + field.cursor)
92+ }
93+}
added Sources/RazorbillTUI/ModelsScreen.swift +134 -0
new file mode 100644
@@ -0,0 +1,134 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// One model of the Hugging Face cache, as the Models screen lists it.
5+public struct ModelRow: Sendable, Equatable {
6+ public var id: String
7+ public var sizeBytes: Int64
8+ /// `chat` or `embedding` when the configuration or the server tells; `nil` otherwise (the
9+ /// cache does not record it).
10+ public var kind: String?
11+ /// The server has it in memory.
12+ public var loaded: Bool
13+ /// The configuration's ids that point to it.
14+ public var declaredAs: [String]
15+
16+ /// The rows for the cache's loadable models, marked from the server's status and the
17+ /// server's configuration (either may be missing).
18+ public static func rows(
19+ _ stored: [StoredModel], status: StatusSnapshot?, config: ServerConfig?
20+ ) -> [ModelRow] {
21+ let loadedKeys = Set(status?.models.map(\.key) ?? [])
22+ return stored.filter(\.isLoadable).map { model in
23+ let entries = (config?.models ?? []).filter { entry in
24+ if case .huggingFace(let id, _) = entry.source { return id == model.id }
25+ return false
26+ }
27+ let loadedAsEmbedding = loadedKeys.contains("\(model.id)#embedding")
28+ let kind =
29+ entries.first?.kind.rawValue
30+ ?? (loadedAsEmbedding ? "embedding" : loadedKeys.contains(model.id) ? "chat" : nil)
31+ return ModelRow(
32+ id: model.id, sizeBytes: model.sizeInBytes, kind: kind,
33+ loaded: loadedKeys.contains(model.id) || loadedAsEmbedding,
34+ declaredAs: entries.map(\.id))
35+ }
36+ }
37+}
38+
39+/// The Models screen (#57): the cache's models, downloads in progress, and the keys to download
40+/// (`p`), remove (`d`, with confirmation) and refresh (`r`).
41+///
42+/// ```swift
43+/// var screen = ModelsScreen()
44+/// screen.setRows(rows)
45+/// screen.handle(.character("d")) // asks "Remove org/a from the disk? y / n"
46+/// screen.handle(.character("y")) // .remove("org/a")
47+/// ```
48+public struct ModelsScreen: Sendable, Equatable {
49+ /// What the bottom line is doing.
50+ public enum Mode: Sendable, Equatable {
51+ case browsing
52+ /// Typing the id to download.
53+ case enteringID(TextField)
54+ /// Waiting for `y` to remove this model.
55+ case confirmingRemoval(String)
56+ }
57+
58+ /// What a key asks the app to do.
59+ public enum Action: Sendable, Equatable {
60+ case none
61+ case redraw
62+ /// Read the cache again.
63+ case refresh
64+ case pull(String)
65+ case remove(String)
66+ }
67+
68+ public private(set) var rows: [ModelRow] = []
69+ public private(set) var list = ListView()
70+ public private(set) var mode = Mode.browsing
71+ /// Downloads in progress, from 0 to 1, by id.
72+ public var downloads: [String: Double] = [:]
73+ public var notice: String?
74+
75+ public init() {}
76+
77+ public mutating func setRows(_ rows: [ModelRow]) {
78+ self.rows = rows
79+ list.resize(to: rows.count)
80+ }
81+
82+ public var selected: ModelRow? { list.selected < rows.count ? rows[list.selected] : nil }
83+
84+ public mutating func handle(_ key: Key) -> Action {
85+ switch mode {
86+ case .enteringID(var field): return typeID(key, field: &field)
87+ case .confirmingRemoval(let id):
88+ mode = .browsing
89+ guard key == .character("y") || key == .character("Y") else {
90+ notice = "kept \(id)"
91+ return .redraw
92+ }
93+ return .remove(id)
94+ case .browsing: return browse(key)
95+ }
96+ }
97+
98+ private mutating func browse(_ key: Key) -> Action {
99+ if list.handle(key, pageSize: 10) { return .redraw }
100+ switch key {
101+ case .character("p"):
102+ mode = .enteringID(TextField())
103+ return .redraw
104+ case .character("d"), .delete:
105+ guard let selected else { return .none }
106+ mode = .confirmingRemoval(selected.id)
107+ return .redraw
108+ case .character("r"):
109+ return .refresh
110+ default:
111+ return .none
112+ }
113+ }
114+
115+ private mutating func typeID(_ key: Key, field: inout TextField) -> Action {
116+ switch key {
117+ case .escape:
118+ mode = .browsing
119+ return .redraw
120+ case .enter:
121+ let id = field.text.trimmingCharacters(in: .whitespaces)
122+ guard id.split(separator: "/").count == 2, !id.contains(" ") else {
123+ notice = "a Hugging Face id looks like org/name"
124+ return .redraw
125+ }
126+ mode = .browsing
127+ return .pull(id)
128+ default:
129+ field.handle(key)
130+ mode = .enteringID(field)
131+ return .redraw
132+ }
133+ }
134+}
new file mode 100644
@@ -0,0 +1,134 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// One model of the Hugging Face cache, as the Models screen lists it.
5+public struct ModelRow: Sendable, Equatable {
6+ public var id: String
7+ public var sizeBytes: Int64
8+ /// `chat` or `embedding` when the configuration or the server tells; `nil` otherwise (the
9+ /// cache does not record it).
10+ public var kind: String?
11+ /// The server has it in memory.
12+ public var loaded: Bool
13+ /// The configuration's ids that point to it.
14+ public var declaredAs: [String]
15+
16+ /// The rows for the cache's loadable models, marked from the server's status and the
17+ /// server's configuration (either may be missing).
18+ public static func rows(
19+ _ stored: [StoredModel], status: StatusSnapshot?, config: ServerConfig?
20+ ) -> [ModelRow] {
21+ let loadedKeys = Set(status?.models.map(\.key) ?? [])
22+ return stored.filter(\.isLoadable).map { model in
23+ let entries = (config?.models ?? []).filter { entry in
24+ if case .huggingFace(let id, _) = entry.source { return id == model.id }
25+ return false
26+ }
27+ let loadedAsEmbedding = loadedKeys.contains("\(model.id)#embedding")
28+ let kind =
29+ entries.first?.kind.rawValue
30+ ?? (loadedAsEmbedding ? "embedding" : loadedKeys.contains(model.id) ? "chat" : nil)
31+ return ModelRow(
32+ id: model.id, sizeBytes: model.sizeInBytes, kind: kind,
33+ loaded: loadedKeys.contains(model.id) || loadedAsEmbedding,
34+ declaredAs: entries.map(\.id))
35+ }
36+ }
37+}
38+
39+/// The Models screen (#57): the cache's models, downloads in progress, and the keys to download
40+/// (`p`), remove (`d`, with confirmation) and refresh (`r`).
41+///
42+/// ```swift
43+/// var screen = ModelsScreen()
44+/// screen.setRows(rows)
45+/// screen.handle(.character("d")) // asks "Remove org/a from the disk? y / n"
46+/// screen.handle(.character("y")) // .remove("org/a")
47+/// ```
48+public struct ModelsScreen: Sendable, Equatable {
49+ /// What the bottom line is doing.
50+ public enum Mode: Sendable, Equatable {
51+ case browsing
52+ /// Typing the id to download.
53+ case enteringID(TextField)
54+ /// Waiting for `y` to remove this model.
55+ case confirmingRemoval(String)
56+ }
57+
58+ /// What a key asks the app to do.
59+ public enum Action: Sendable, Equatable {
60+ case none
61+ case redraw
62+ /// Read the cache again.
63+ case refresh
64+ case pull(String)
65+ case remove(String)
66+ }
67+
68+ public private(set) var rows: [ModelRow] = []
69+ public private(set) var list = ListView()
70+ public private(set) var mode = Mode.browsing
71+ /// Downloads in progress, from 0 to 1, by id.
72+ public var downloads: [String: Double] = [:]
73+ public var notice: String?
74+
75+ public init() {}
76+
77+ public mutating func setRows(_ rows: [ModelRow]) {
78+ self.rows = rows
79+ list.resize(to: rows.count)
80+ }
81+
82+ public var selected: ModelRow? { list.selected < rows.count ? rows[list.selected] : nil }
83+
84+ public mutating func handle(_ key: Key) -> Action {
85+ switch mode {
86+ case .enteringID(var field): return typeID(key, field: &field)
87+ case .confirmingRemoval(let id):
88+ mode = .browsing
89+ guard key == .character("y") || key == .character("Y") else {
90+ notice = "kept \(id)"
91+ return .redraw
92+ }
93+ return .remove(id)
94+ case .browsing: return browse(key)
95+ }
96+ }
97+
98+ private mutating func browse(_ key: Key) -> Action {
99+ if list.handle(key, pageSize: 10) { return .redraw }
100+ switch key {
101+ case .character("p"):
102+ mode = .enteringID(TextField())
103+ return .redraw
104+ case .character("d"), .delete:
105+ guard let selected else { return .none }
106+ mode = .confirmingRemoval(selected.id)
107+ return .redraw
108+ case .character("r"):
109+ return .refresh
110+ default:
111+ return .none
112+ }
113+ }
114+
115+ private mutating func typeID(_ key: Key, field: inout TextField) -> Action {
116+ switch key {
117+ case .escape:
118+ mode = .browsing
119+ return .redraw
120+ case .enter:
121+ let id = field.text.trimmingCharacters(in: .whitespaces)
122+ guard id.split(separator: "/").count == 2, !id.contains(" ") else {
123+ notice = "a Hugging Face id looks like org/name"
124+ return .redraw
125+ }
126+ mode = .browsing
127+ return .pull(id)
128+ default:
129+ field.handle(key)
130+ mode = .enteringID(field)
131+ return .redraw
132+ }
133+ }
134+}
modified Sources/RazorbillTUI/ServerAPI.swift +2 -0
@@ -7,6 +7,8 @@ public struct StatusSnapshot: Sendable, Equatable, Decodable {
77 public var uptimeSeconds: Int
88 public var host: String
99 public var port: Int
10+ /// The server's `--config` file (absolute); `nil` without one, or before razorbill 0.3.
11+ public var configFile: String?
1012 public var models: [LoadedModel]
1113 public var recentRequests: [RecentRequest]
1214 /// `nil` when the server's engine cannot measure it (Linux).
@@ -7,6 +7,8 @@ public struct StatusSnapshot: Sendable, Equatable, Decodable {
7 public var uptimeSeconds: Int7 public var uptimeSeconds: Int
8 public var host: String8 public var host: String
9 public var port: Int9 public var port: Int
10+ /// The server's `--config` file (absolute); `nil` without one, or before razorbill 0.3.
11+ public var configFile: String?
10 public var models: [LoadedModel]12 public var models: [LoadedModel]
11 public var recentRequests: [RecentRequest]13 public var recentRequests: [RecentRequest]
12 /// `nil` when the server's engine cannot measure it (Linux).14 /// `nil` when the server's engine cannot measure it (Linux).
added Sources/RazorbillTUI/SettingsScreen.swift +196 -0
new file mode 100644
@@ -0,0 +1,196 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Settings screen (#58): the TUI's preferences in a form (saved to `tui.yaml`), and the
5+/// server's configuration file, opened in `$EDITOR` (Ctrl-O) — so its comments survive — then
6+/// checked and reloaded into the server; Ctrl-R reloads it as it is.
7+///
8+/// ```swift
9+/// var settings = SettingsScreen(preferences: TUIPreferences())
10+/// settings.handle(.enter) // .save(preferences) once every field is valid
11+/// ```
12+public struct SettingsScreen: Sendable, Equatable {
13+ /// What a key asks the app to do.
14+ public enum Action: Sendable, Equatable {
15+ case none
16+ case redraw
17+ case save(TUIPreferences)
18+ case editServerConfig
19+ case reloadServer
20+ }
21+
22+ /// The form's fields: label and `tui.yaml` key.
23+ static let fields: [(label: String, key: String)] = [
24+ ("Server URL", "server_url"), ("API key variable", "api_key_env"),
25+ ("Reasoning (shown, folded, hidden)", "reasoning"), ("Colours (on, off)", "colors"),
26+ ("Poll interval (500ms, 2s)", "poll_interval"), ("Chat temperature", "temperature"),
27+ ("Chat top_p", "top_p"), ("Chat top_k", "top_k"), ("Chat min_p", "min_p"),
28+ ("Chat max_tokens", "max_tokens"), ("Chat thinking (on, off)", "thinking"),
29+ ]
30+
31+ public private(set) var form: FormView
32+ /// The preferences as last saved (Esc goes back to them).
33+ public private(set) var saved: TUIPreferences
34+ public var notice: String?
35+
36+ public init(preferences: TUIPreferences) {
37+ saved = preferences
38+ form = Self.form(preferences)
39+ }
40+
41+ public mutating func handle(_ key: Key) -> Action {
42+ switch key {
43+ case .control("o"): return .editServerConfig
44+ case .control("r"): return .reloadServer
45+ default: break
46+ }
47+ switch form.handle(key) {
48+ case .submit:
49+ do {
50+ let preferences = try Self.preferences(from: form.values)
51+ saved = preferences
52+ return .save(preferences)
53+ } catch {
54+ notice = "\(error)"
55+ return .redraw
56+ }
57+ case .cancel:
58+ form = Self.form(saved)
59+ notice = "changes undone"
60+ return .redraw
61+ case .none:
62+ return .redraw
63+ case .ignored:
64+ return .none
65+ }
66+ }
67+
68+ static func form(_ preferences: TUIPreferences) -> FormView {
69+ let values = text(of: preferences)
70+ return FormView(
71+ fields: zip(fields, values).map { FormView.Field(label: $0.label, text: $1) })
72+ }
73+
74+ /// The fields' text for `preferences`, in ``fields`` order; empty when not set.
75+ static func text(of preferences: TUIPreferences) -> [String] {
76+ let chat = preferences.chat
77+ return [
78+ preferences.serverURL ?? "", preferences.apiKeyVariable ?? "",
79+ preferences.reasoning ?? "", preferences.colors.map { $0 ? "on" : "off" } ?? "",
80+ preferences.pollInterval.map(durationText) ?? "",
81+ chat.temperature.map { "\($0)" } ?? "", chat.topP.map { "\($0)" } ?? "",
82+ chat.topK.map { "\($0)" } ?? "", chat.minP.map { "\($0)" } ?? "",
83+ chat.maxTokens.map { "\($0)" } ?? "", chat.thinking.map { $0 ? "on" : "off" } ?? "",
84+ ]
85+ }
86+
87+ /// Reads the form back; the error names the first wrong field.
88+ static func preferences(from values: [String]) throws -> TUIPreferences {
89+ let trimmed = values.map { $0.trimmingCharacters(in: .whitespaces) }
90+ let field = Dictionary(uniqueKeysWithValues: zip(fields.map(\.key), trimmed))
91+ var preferences = TUIPreferences()
92+ let url = field["server_url"] ?? ""
93+ if !url.isEmpty {
94+ guard url.hasPrefix("http://") || url.hasPrefix("https://") else {
95+ throw ChatOptions.Invalid(description: "Server URL must start with http://")
96+ }
97+ preferences.serverURL = url
98+ }
99+ preferences.apiKeyVariable = nonEmpty(field["api_key_env"])
100+ if let display = nonEmpty(field["reasoning"]) {
101+ guard TUIPreferences.reasoningDisplays.contains(display) else {
102+ throw ChatOptions.Invalid(description: "Reasoning is shown, folded or hidden")
103+ }
104+ preferences.reasoning = display
105+ }
106+ if let colors = nonEmpty(field["colors"]) {
107+ guard ["on", "off"].contains(colors) else {
108+ throw ChatOptions.Invalid(description: "Colours is on or off")
109+ }
110+ preferences.colors = colors == "on"
111+ }
112+ if let interval = nonEmpty(field["poll_interval"]) {
113+ guard let duration = Quantities.duration(interval) else {
114+ throw ChatOptions.Invalid(description: "Poll interval is a duration: 500ms, 2s")
115+ }
116+ preferences.pollInterval = duration
117+ }
118+ var options = ChatOptions()
119+ for name in ChatOptions.names { try options.set(name, to: field[name] ?? "") }
120+ preferences.chat = options.defaults
121+ return preferences
122+ }
123+
124+ private static func nonEmpty(_ text: String?) -> String? {
125+ guard let text, !text.isEmpty else { return nil }
126+ return text
127+ }
128+
129+ /// `2s` for whole seconds, `500ms` otherwise.
130+ static func durationText(_ duration: Duration) -> String {
131+ let milliseconds = Int(duration / .milliseconds(1))
132+ return milliseconds % 1000 == 0 ? "\(milliseconds / 1000)s" : "\(milliseconds)ms"
133+ }
134+}
135+
136+extension ChatOptions {
137+ /// The same settings as `tui.yaml`'s `chat:` section.
138+ public var defaults: TUIPreferences.ChatDefaults {
139+ var defaults = TUIPreferences.ChatDefaults()
140+ defaults.temperature = temperature
141+ defaults.topP = topP
142+ defaults.topK = topK
143+ defaults.minP = minP
144+ defaults.maxTokens = maxTokens
145+ defaults.thinking = thinking
146+ return defaults
147+ }
148+
149+ /// The options `tui.yaml`'s `chat:` section starts a session with.
150+ public init(_ defaults: TUIPreferences.ChatDefaults) {
151+ self.init()
152+ temperature = defaults.temperature
153+ topP = defaults.topP
154+ topK = defaults.topK
155+ minP = defaults.minP
156+ maxTokens = defaults.maxTokens
157+ thinking = defaults.thinking
158+ }
159+}
160+
161+/// Draws the Settings screen.
162+public struct SettingsRenderer: Sendable {
163+ public var style: Style
164+
165+ public init(style: Style) {
166+ self.style = style
167+ }
168+
169+ public func render(
170+ _ settings: SettingsScreen, preferencesFile: String, serverConfigFile: String?,
171+ width: Int, height: Int
172+ ) -> (lines: [String], cursor: FormView.Cursor?) {
173+ var lines = [
174+ "",
175+ style.bold(" TUI preferences") + style.dim(" Tab ↑↓ field · Enter save · Esc undo"),
176+ style.dim(" file: \(preferencesFile)"),
177+ "",
178+ ]
179+ let (form, cursor) = settings.form.render(width: width - 4, style: style)
180+ let formTop = lines.count
181+ lines += form.map { " " + $0 }
182+ lines += [
183+ "",
184+ style.bold(" Server configuration")
185+ + style.dim(" Ctrl-O edit in $EDITOR (then checked and reloaded) · Ctrl-R reload"),
186+ style.dim(" file: \(serverConfigFile ?? "none — the server runs without --config")"),
187+ "",
188+ ]
189+ if let notice = settings.notice {
190+ lines += TextLayout.wrap(notice, width: width - 4).map { " " + $0 }
191+ }
192+ let shown = lines.prefix(height).map { TextLayout.truncate($0, width: width) }
193+ let row = formTop + cursor.row
194+ return (Array(shown), row < height ? (row, cursor.column + 4) : nil)
195+ }
196+}
new file mode 100644
@@ -0,0 +1,196 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Settings screen (#58): the TUI's preferences in a form (saved to `tui.yaml`), and the
5+/// server's configuration file, opened in `$EDITOR` (Ctrl-O) — so its comments survive — then
6+/// checked and reloaded into the server; Ctrl-R reloads it as it is.
7+///
8+/// ```swift
9+/// var settings = SettingsScreen(preferences: TUIPreferences())
10+/// settings.handle(.enter) // .save(preferences) once every field is valid
11+/// ```
12+public struct SettingsScreen: Sendable, Equatable {
13+ /// What a key asks the app to do.
14+ public enum Action: Sendable, Equatable {
15+ case none
16+ case redraw
17+ case save(TUIPreferences)
18+ case editServerConfig
19+ case reloadServer
20+ }
21+
22+ /// The form's fields: label and `tui.yaml` key.
23+ static let fields: [(label: String, key: String)] = [
24+ ("Server URL", "server_url"), ("API key variable", "api_key_env"),
25+ ("Reasoning (shown, folded, hidden)", "reasoning"), ("Colours (on, off)", "colors"),
26+ ("Poll interval (500ms, 2s)", "poll_interval"), ("Chat temperature", "temperature"),
27+ ("Chat top_p", "top_p"), ("Chat top_k", "top_k"), ("Chat min_p", "min_p"),
28+ ("Chat max_tokens", "max_tokens"), ("Chat thinking (on, off)", "thinking"),
29+ ]
30+
31+ public private(set) var form: FormView
32+ /// The preferences as last saved (Esc goes back to them).
33+ public private(set) var saved: TUIPreferences
34+ public var notice: String?
35+
36+ public init(preferences: TUIPreferences) {
37+ saved = preferences
38+ form = Self.form(preferences)
39+ }
40+
41+ public mutating func handle(_ key: Key) -> Action {
42+ switch key {
43+ case .control("o"): return .editServerConfig
44+ case .control("r"): return .reloadServer
45+ default: break
46+ }
47+ switch form.handle(key) {
48+ case .submit:
49+ do {
50+ let preferences = try Self.preferences(from: form.values)
51+ saved = preferences
52+ return .save(preferences)
53+ } catch {
54+ notice = "\(error)"
55+ return .redraw
56+ }
57+ case .cancel:
58+ form = Self.form(saved)
59+ notice = "changes undone"
60+ return .redraw
61+ case .none:
62+ return .redraw
63+ case .ignored:
64+ return .none
65+ }
66+ }
67+
68+ static func form(_ preferences: TUIPreferences) -> FormView {
69+ let values = text(of: preferences)
70+ return FormView(
71+ fields: zip(fields, values).map { FormView.Field(label: $0.label, text: $1) })
72+ }
73+
74+ /// The fields' text for `preferences`, in ``fields`` order; empty when not set.
75+ static func text(of preferences: TUIPreferences) -> [String] {
76+ let chat = preferences.chat
77+ return [
78+ preferences.serverURL ?? "", preferences.apiKeyVariable ?? "",
79+ preferences.reasoning ?? "", preferences.colors.map { $0 ? "on" : "off" } ?? "",
80+ preferences.pollInterval.map(durationText) ?? "",
81+ chat.temperature.map { "\($0)" } ?? "", chat.topP.map { "\($0)" } ?? "",
82+ chat.topK.map { "\($0)" } ?? "", chat.minP.map { "\($0)" } ?? "",
83+ chat.maxTokens.map { "\($0)" } ?? "", chat.thinking.map { $0 ? "on" : "off" } ?? "",
84+ ]
85+ }
86+
87+ /// Reads the form back; the error names the first wrong field.
88+ static func preferences(from values: [String]) throws -> TUIPreferences {
89+ let trimmed = values.map { $0.trimmingCharacters(in: .whitespaces) }
90+ let field = Dictionary(uniqueKeysWithValues: zip(fields.map(\.key), trimmed))
91+ var preferences = TUIPreferences()
92+ let url = field["server_url"] ?? ""
93+ if !url.isEmpty {
94+ guard url.hasPrefix("http://") || url.hasPrefix("https://") else {
95+ throw ChatOptions.Invalid(description: "Server URL must start with http://")
96+ }
97+ preferences.serverURL = url
98+ }
99+ preferences.apiKeyVariable = nonEmpty(field["api_key_env"])
100+ if let display = nonEmpty(field["reasoning"]) {
101+ guard TUIPreferences.reasoningDisplays.contains(display) else {
102+ throw ChatOptions.Invalid(description: "Reasoning is shown, folded or hidden")
103+ }
104+ preferences.reasoning = display
105+ }
106+ if let colors = nonEmpty(field["colors"]) {
107+ guard ["on", "off"].contains(colors) else {
108+ throw ChatOptions.Invalid(description: "Colours is on or off")
109+ }
110+ preferences.colors = colors == "on"
111+ }
112+ if let interval = nonEmpty(field["poll_interval"]) {
113+ guard let duration = Quantities.duration(interval) else {
114+ throw ChatOptions.Invalid(description: "Poll interval is a duration: 500ms, 2s")
115+ }
116+ preferences.pollInterval = duration
117+ }
118+ var options = ChatOptions()
119+ for name in ChatOptions.names { try options.set(name, to: field[name] ?? "") }
120+ preferences.chat = options.defaults
121+ return preferences
122+ }
123+
124+ private static func nonEmpty(_ text: String?) -> String? {
125+ guard let text, !text.isEmpty else { return nil }
126+ return text
127+ }
128+
129+ /// `2s` for whole seconds, `500ms` otherwise.
130+ static func durationText(_ duration: Duration) -> String {
131+ let milliseconds = Int(duration / .milliseconds(1))
132+ return milliseconds % 1000 == 0 ? "\(milliseconds / 1000)s" : "\(milliseconds)ms"
133+ }
134+}
135+
136+extension ChatOptions {
137+ /// The same settings as `tui.yaml`'s `chat:` section.
138+ public var defaults: TUIPreferences.ChatDefaults {
139+ var defaults = TUIPreferences.ChatDefaults()
140+ defaults.temperature = temperature
141+ defaults.topP = topP
142+ defaults.topK = topK
143+ defaults.minP = minP
144+ defaults.maxTokens = maxTokens
145+ defaults.thinking = thinking
146+ return defaults
147+ }
148+
149+ /// The options `tui.yaml`'s `chat:` section starts a session with.
150+ public init(_ defaults: TUIPreferences.ChatDefaults) {
151+ self.init()
152+ temperature = defaults.temperature
153+ topP = defaults.topP
154+ topK = defaults.topK
155+ minP = defaults.minP
156+ maxTokens = defaults.maxTokens
157+ thinking = defaults.thinking
158+ }
159+}
160+
161+/// Draws the Settings screen.
162+public struct SettingsRenderer: Sendable {
163+ public var style: Style
164+
165+ public init(style: Style) {
166+ self.style = style
167+ }
168+
169+ public func render(
170+ _ settings: SettingsScreen, preferencesFile: String, serverConfigFile: String?,
171+ width: Int, height: Int
172+ ) -> (lines: [String], cursor: FormView.Cursor?) {
173+ var lines = [
174+ "",
175+ style.bold(" TUI preferences") + style.dim(" Tab ↑↓ field · Enter save · Esc undo"),
176+ style.dim(" file: \(preferencesFile)"),
177+ "",
178+ ]
179+ let (form, cursor) = settings.form.render(width: width - 4, style: style)
180+ let formTop = lines.count
181+ lines += form.map { " " + $0 }
182+ lines += [
183+ "",
184+ style.bold(" Server configuration")
185+ + style.dim(" Ctrl-O edit in $EDITOR (then checked and reloaded) · Ctrl-R reload"),
186+ style.dim(" file: \(serverConfigFile ?? "none — the server runs without --config")"),
187+ "",
188+ ]
189+ if let notice = settings.notice {
190+ lines += TextLayout.wrap(notice, width: width - 4).map { " " + $0 }
191+ }
192+ let shown = lines.prefix(height).map { TextLayout.truncate($0, width: width) }
193+ let row = formTop + cursor.row
194+ return (Array(shown), row < height ? (row, cursor.column + 4) : nil)
195+ }
196+}
added Sources/RazorbillTUI/TUIApp+Models.swift +84 -0
new file mode 100644
@@ -0,0 +1,84 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Models screen's actions: read the cache, download, remove.
5+extension TUIApp {
6+ // MARK: Models screen
7+
8+ func perform(_ action: ModelsScreen.Action) {
9+ switch action {
10+ case .none, .redraw: break
11+ case .refresh: refreshModels()
12+ case .pull(let id): Task { await pull(id) }
13+ case .remove(let id): Task { await remove(id) }
14+ }
15+ }
16+
17+ /// Reads the cache again and marks what the server has loaded or declares.
18+ func refreshModels() {
19+ let stored = (try? environment.store.list()) ?? []
20+ models.setRows(ModelRow.rows(stored, status: snapshot, config: serverConfig()))
21+ }
22+
23+ /// The server's configuration, when its file is known and valid.
24+ func serverConfig() -> ServerConfig? {
25+ guard let file = serverConfigFile else { return nil }
26+ return try? ServerConfigLoader().load(file: file)
27+ }
28+
29+ var serverConfigFile: String? { environment.configFile ?? snapshot?.configFile }
30+
31+ func pull(_ id: String) async {
32+ guard let download = environment.download else {
33+ models.notice = "this build of rzb cannot download models"
34+ redraw()
35+ return
36+ }
37+ models.downloads[id] = 0
38+ redraw()
39+ do {
40+ let model = ModelReference.huggingFace(id: id, revision: ModelReference.defaultRevision)
41+ try await download(model) { progress in
42+ Task { await self.downloaded(id, progress) }
43+ }
44+ models.notice = "downloaded \(id)"
45+ } catch {
46+ models.notice = "cannot download \(id): \(error)"
47+ }
48+ models.downloads[id] = nil
49+ refreshModels()
50+ redraw()
51+ }
52+
53+ func downloaded(_ id: String, _ progress: Double) {
54+ guard models.downloads[id] != nil else { return }
55+ models.downloads[id] = progress
56+ redraw()
57+ }
58+
59+ /// Unloads the model first when the server has it; refused while the server is using it.
60+ func remove(_ id: String) async {
61+ if let row = models.rows.first(where: { $0.id == id }), row.loaded {
62+ do {
63+ _ = try await server.unload(id)
64+ } catch let ServerClientError.server(_, _, message) {
65+ models.notice = "not removed: \(message)"
66+ redraw()
67+ return
68+ } catch {
69+ models.notice = "not removed, cannot unload it first: \(error)"
70+ redraw()
71+ return
72+ }
73+ }
74+ do {
75+ try environment.store.remove(id: id)
76+ models.notice = "removed \(id)"
77+ } catch {
78+ models.notice = "cannot remove \(id): \(error)"
79+ }
80+ await refresh()
81+ refreshModels()
82+ redraw()
83+ }
84+}
new file mode 100644
@@ -0,0 +1,84 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Models screen's actions: read the cache, download, remove.
5+extension TUIApp {
6+ // MARK: Models screen
7+
8+ func perform(_ action: ModelsScreen.Action) {
9+ switch action {
10+ case .none, .redraw: break
11+ case .refresh: refreshModels()
12+ case .pull(let id): Task { await pull(id) }
13+ case .remove(let id): Task { await remove(id) }
14+ }
15+ }
16+
17+ /// Reads the cache again and marks what the server has loaded or declares.
18+ func refreshModels() {
19+ let stored = (try? environment.store.list()) ?? []
20+ models.setRows(ModelRow.rows(stored, status: snapshot, config: serverConfig()))
21+ }
22+
23+ /// The server's configuration, when its file is known and valid.
24+ func serverConfig() -> ServerConfig? {
25+ guard let file = serverConfigFile else { return nil }
26+ return try? ServerConfigLoader().load(file: file)
27+ }
28+
29+ var serverConfigFile: String? { environment.configFile ?? snapshot?.configFile }
30+
31+ func pull(_ id: String) async {
32+ guard let download = environment.download else {
33+ models.notice = "this build of rzb cannot download models"
34+ redraw()
35+ return
36+ }
37+ models.downloads[id] = 0
38+ redraw()
39+ do {
40+ let model = ModelReference.huggingFace(id: id, revision: ModelReference.defaultRevision)
41+ try await download(model) { progress in
42+ Task { await self.downloaded(id, progress) }
43+ }
44+ models.notice = "downloaded \(id)"
45+ } catch {
46+ models.notice = "cannot download \(id): \(error)"
47+ }
48+ models.downloads[id] = nil
49+ refreshModels()
50+ redraw()
51+ }
52+
53+ func downloaded(_ id: String, _ progress: Double) {
54+ guard models.downloads[id] != nil else { return }
55+ models.downloads[id] = progress
56+ redraw()
57+ }
58+
59+ /// Unloads the model first when the server has it; refused while the server is using it.
60+ func remove(_ id: String) async {
61+ if let row = models.rows.first(where: { $0.id == id }), row.loaded {
62+ do {
63+ _ = try await server.unload(id)
64+ } catch let ServerClientError.server(_, _, message) {
65+ models.notice = "not removed: \(message)"
66+ redraw()
67+ return
68+ } catch {
69+ models.notice = "not removed, cannot unload it first: \(error)"
70+ redraw()
71+ return
72+ }
73+ }
74+ do {
75+ try environment.store.remove(id: id)
76+ models.notice = "removed \(id)"
77+ } catch {
78+ models.notice = "cannot remove \(id): \(error)"
79+ }
80+ await refresh()
81+ refreshModels()
82+ redraw()
83+ }
84+}
added Sources/RazorbillTUI/TUIApp+Settings.swift +76 -0
new file mode 100644
@@ -0,0 +1,76 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Settings screen's actions: save the preferences, edit and reload the server's file.
5+extension TUIApp {
6+ // MARK: Settings screen
7+
8+ func perform(_ action: SettingsScreen.Action) {
9+ switch action {
10+ case .none, .redraw: break
11+ case .save(let preferences): save(preferences)
12+ case .editServerConfig: Task { await editServerConfig() }
13+ case .reloadServer: Task { await reloadServer() }
14+ }
15+ }
16+
17+ /// Saves to `tui.yaml` and applies what can change while running.
18+ func save(_ preferences: TUIPreferences) {
19+ do {
20+ try preferences.save(to: environment.preferencesFile)
21+ } catch {
22+ settings.notice = "cannot save \(environment.preferencesFile): \(error)"
23+ return
24+ }
25+ chat.apply(preferences)
26+ if let interval = preferences.pollInterval { pollInterval = interval }
27+ if let colors = preferences.colors { style = Style(colors: colors) }
28+ settings.notice =
29+ "saved to \(environment.preferencesFile). The server URL and the API key variable"
30+ + " apply the next time rzb tui starts."
31+ }
32+
33+ /// Opens the server's file in the editor, checks it on return, then reloads the server.
34+ func editServerConfig() async {
35+ guard let file = serverConfigFile else {
36+ settings.notice = "the server runs without --config: there is no file to edit"
37+ redraw()
38+ return
39+ }
40+ terminal.suspend()
41+ await environment.edit(file)
42+ terminal.resume()
43+ do {
44+ _ = try ServerConfigLoader().load(file: file)
45+ } catch {
46+ settings.notice =
47+ "\(error)\nThe server keeps its configuration: Ctrl-O to fix the file."
48+ redraw()
49+ return
50+ }
51+ await reloadServer()
52+ }
53+
54+ func reloadServer() async {
55+ do {
56+ let reply = try await server.reload()
57+ var notice = "reloaded \(reply.file): \(reply.declaredModels) declared models"
58+ if !reply.unloaded.isEmpty {
59+ notice += "; unloaded \(reply.unloaded.joined(separator: ", "))"
60+ }
61+ if !reply.unloadWhenIdle.isEmpty {
62+ notice += "; unloading when idle \(reply.unloadWhenIdle.joined(separator: ", "))"
63+ }
64+ if !reply.restartRequired.isEmpty {
65+ let keys = reply.restartRequired.joined(separator: ", ")
66+ notice += "; restart the server to apply \(keys)"
67+ }
68+ settings.notice = notice
69+ } catch let ServerClientError.server(_, _, message) {
70+ settings.notice = message
71+ } catch {
72+ settings.notice = "cannot reload: \(error)"
73+ }
74+ redraw()
75+ }
76+}
new file mode 100644
@@ -0,0 +1,76 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// The Settings screen's actions: save the preferences, edit and reload the server's file.
5+extension TUIApp {
6+ // MARK: Settings screen
7+
8+ func perform(_ action: SettingsScreen.Action) {
9+ switch action {
10+ case .none, .redraw: break
11+ case .save(let preferences): save(preferences)
12+ case .editServerConfig: Task { await editServerConfig() }
13+ case .reloadServer: Task { await reloadServer() }
14+ }
15+ }
16+
17+ /// Saves to `tui.yaml` and applies what can change while running.
18+ func save(_ preferences: TUIPreferences) {
19+ do {
20+ try preferences.save(to: environment.preferencesFile)
21+ } catch {
22+ settings.notice = "cannot save \(environment.preferencesFile): \(error)"
23+ return
24+ }
25+ chat.apply(preferences)
26+ if let interval = preferences.pollInterval { pollInterval = interval }
27+ if let colors = preferences.colors { style = Style(colors: colors) }
28+ settings.notice =
29+ "saved to \(environment.preferencesFile). The server URL and the API key variable"
30+ + " apply the next time rzb tui starts."
31+ }
32+
33+ /// Opens the server's file in the editor, checks it on return, then reloads the server.
34+ func editServerConfig() async {
35+ guard let file = serverConfigFile else {
36+ settings.notice = "the server runs without --config: there is no file to edit"
37+ redraw()
38+ return
39+ }
40+ terminal.suspend()
41+ await environment.edit(file)
42+ terminal.resume()
43+ do {
44+ _ = try ServerConfigLoader().load(file: file)
45+ } catch {
46+ settings.notice =
47+ "\(error)\nThe server keeps its configuration: Ctrl-O to fix the file."
48+ redraw()
49+ return
50+ }
51+ await reloadServer()
52+ }
53+
54+ func reloadServer() async {
55+ do {
56+ let reply = try await server.reload()
57+ var notice = "reloaded \(reply.file): \(reply.declaredModels) declared models"
58+ if !reply.unloaded.isEmpty {
59+ notice += "; unloaded \(reply.unloaded.joined(separator: ", "))"
60+ }
61+ if !reply.unloadWhenIdle.isEmpty {
62+ notice += "; unloading when idle \(reply.unloadWhenIdle.joined(separator: ", "))"
63+ }
64+ if !reply.restartRequired.isEmpty {
65+ let keys = reply.restartRequired.joined(separator: ", ")
66+ notice += "; restart the server to apply \(keys)"
67+ }
68+ settings.notice = notice
69+ } catch let ServerClientError.server(_, _, message) {
70+ settings.notice = message
71+ } catch {
72+ settings.notice = "cannot reload: \(error)"
73+ }
74+ redraw()
75+ }
76+}
modified Sources/RazorbillTUI/TUIApp.swift +43 -20
@@ -1,4 +1,5 @@
11 import Foundation
2+import RazorbillCore
23
34 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
45 public protocol StatusSource: Sendable {
@@ -10,6 +11,7 @@ public protocol TUIServer: StatusSource {
1011 func models() async throws -> [ServedModel]
1112 func unload(_ id: String) async throws -> UnloadReply
1213 func chat(model: String, messages: [ChatTurn], options: ChatOptions) -> ServerClient.ChatStream
14+ func reload() async throws -> ReloadReply
1315 }
1416
1517 extension ServerClient: TUIServer {}
@@ -22,42 +24,52 @@ extension ServerClient: TUIServer {}
2224 /// await TUIApp(terminal: PosixTerminal(), server: client, serverURL: client.baseURL).run()
2325 /// ```
2426 public actor TUIApp {
25- private let terminal: any Terminal
26- private let server: any TUIServer
27- private let renderer: AppRenderer
28- private let chatRenderer: ChatRenderer
29- private let pollInterval: Duration
27+ let terminal: any Terminal
28+ let server: any TUIServer
29+ let environment: TUIEnvironment
30+ var style: Style
31+ var pollInterval: Duration
3032 private let startCommand: String
3133 private let now: @Sendable () -> Date
3234 private var state: AppState
33- private var snapshot: StatusSnapshot?
35+ var snapshot: StatusSnapshot?
3436 private var dashboard = DashboardScreen()
35- private var chat = ChatScreen()
37+ var chat = ChatScreen()
38+ var models = ModelsScreen()
39+ var settings: SettingsScreen
3640 private var answer: Task<Void, Never>?
3741 private var modelsRequested = false
3842 /// False once `run` returns: work still in flight must not draw on the restored terminal.
3943 private var running = false
4044
4145 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
46+ /// - Parameter environment: the model cache, downloads, files and editor (tests replace them).
4247 public init(
4348 terminal: any Terminal, server: any TUIServer, serverURL: String,
4449 startCommand: String = "rzb serve", colors: Bool = true,
45- pollInterval: Duration = .seconds(1), now: @escaping @Sendable () -> Date = { Date() }
50+ pollInterval: Duration = .seconds(1), preferences: TUIPreferences = TUIPreferences(),
51+ environment: TUIEnvironment = TUIEnvironment(
52+ store: ModelStore(), preferencesFile: TUIPreferences.defaultFile()),
53+ now: @escaping @Sendable () -> Date = { Date() }
4654 ) {
4755 self.terminal = terminal
4856 self.server = server
49- self.renderer = AppRenderer(style: Style(colors: colors))
50- self.chatRenderer = ChatRenderer(style: Style(colors: colors))
57+ self.environment = environment
58+ self.style = Style(colors: colors)
5159 self.pollInterval = pollInterval
5260 self.startCommand = startCommand
5361 self.now = now
5462 self.state = AppState(serverURL: serverURL)
63+ self.settings = SettingsScreen(preferences: preferences)
64+ self.chat.apply(preferences)
5565 }
5666
5767 /// The current state (tests).
5868 public var currentState: AppState { state }
5969 public var chatScreen: ChatScreen { chat }
6070 public var dashboardScreen: DashboardScreen { dashboard }
71+ public var modelsScreen: ModelsScreen { models }
72+ public var settingsScreen: SettingsScreen { settings }
6173
6274 /// Runs until Ctrl-Q (or Ctrl-C outside a generation) or the end of input; the terminal is
6375 /// always restored.
@@ -104,18 +116,21 @@ public actor TUIApp {
104116 }
105117 case .chat:
106118 perform(chat.handle(key))
107- case .models, .settings:
108- break
119+ case .models:
120+ perform(models.handle(key))
121+ case .settings:
122+ perform(settings.handle(key))
109123 }
110124 }
111125
112126 private func screenShown() {
113127 if state.screen == .chat && !modelsRequested { loadModels() }
128+ if state.screen == .models { refreshModels() }
114129 }
115130
116131 // MARK: Actions
117132
118- private func perform(_ action: ChatScreen.Action) {
133+ func perform(_ action: ChatScreen.Action) {
119134 switch action {
120135 case .none, .redraw:
121136 break
@@ -128,6 +143,8 @@ public actor TUIApp {
128143 }
129144 }
130145
146+ // MARK: Chat screen
147+
131148 private func loadModels() {
132149 modelsRequested = true
133150 Task { await fetchModels() }
@@ -210,6 +227,7 @@ public actor TUIApp {
210227 state.model = status.models.first?.name
211228 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
212229 if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() }
230+ if state.screen == .models { refreshModels() }
213231 }
214232
215233 private func lose(_ connection: Connection) {
@@ -221,13 +239,13 @@ public actor TUIApp {
221239
222240 // MARK: Drawing
223241
224- private func redraw() {
242+ func redraw() {
225243 guard running else { return }
226244 let size = terminal.size
227245 let height = max(1, size.rows - 2)
228246 let (body, cursor) = body(width: size.columns, height: height)
229247 terminal.draw(
230- renderer.render(
248+ AppRenderer(style: style).render(
231249 state, body: body, cursor: cursor, rows: size.rows, columns: size.columns))
232250 }
233251
@@ -239,13 +257,18 @@ public actor TUIApp {
239257 case .dashboard:
240258 guard let snapshot else { return (["", " Waiting for the server's status…"], nil) }
241259 let lines = dashboard.render(
242- snapshot, width: width, height: height - 1, now: now(), style: renderer.style)
260+ snapshot, width: width, height: height - 1, now: now(), style: style)
243261 return ([""] + lines, nil)
244262 case .chat:
245- let (lines, cursor) = chatRenderer.render(chat, width: width, height: height)
246- return (lines, cursor)
247- case .models, .settings:
248- return (AppRenderer.placeholder(for: state.screen), nil)
263+ let drawn = ChatRenderer(style: style).render(chat, width: width, height: height)
264+ return (drawn.lines, drawn.cursor)
265+ case .models:
266+ return ModelsRenderer(style: style).render(
267+ models, memory: snapshot?.memory, width: width, height: height)
268+ case .settings:
269+ return SettingsRenderer(style: style).render(
270+ settings, preferencesFile: environment.preferencesFile,
271+ serverConfigFile: serverConfigFile, width: width, height: height)
249272 }
250273 }
251274 }
@@ -1,4 +1,5 @@
1 import Foundation1 import Foundation
2+import RazorbillCore
2 3
3 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.4 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
4 public protocol StatusSource: Sendable {5 public protocol StatusSource: Sendable {
@@ -10,6 +11,7 @@ public protocol TUIServer: StatusSource {
10 func models() async throws -> [ServedModel]11 func models() async throws -> [ServedModel]
11 func unload(_ id: String) async throws -> UnloadReply12 func unload(_ id: String) async throws -> UnloadReply
12 func chat(model: String, messages: [ChatTurn], options: ChatOptions) -> ServerClient.ChatStream13 func chat(model: String, messages: [ChatTurn], options: ChatOptions) -> ServerClient.ChatStream
14+ func reload() async throws -> ReloadReply
13 }15 }
14 16
15 extension ServerClient: TUIServer {}17 extension ServerClient: TUIServer {}
@@ -22,42 +24,52 @@ extension ServerClient: TUIServer {}
22 /// await TUIApp(terminal: PosixTerminal(), server: client, serverURL: client.baseURL).run()24 /// await TUIApp(terminal: PosixTerminal(), server: client, serverURL: client.baseURL).run()
23 /// ```25 /// ```
24 public actor TUIApp {26 public actor TUIApp {
25- private let terminal: any Terminal27+ let terminal: any Terminal
26- private let server: any TUIServer28+ let server: any TUIServer
27- private let renderer: AppRenderer29+ let environment: TUIEnvironment
28- private let chatRenderer: ChatRenderer30+ var style: Style
29- private let pollInterval: Duration31+ var pollInterval: Duration
30 private let startCommand: String32 private let startCommand: String
31 private let now: @Sendable () -> Date33 private let now: @Sendable () -> Date
32 private var state: AppState34 private var state: AppState
33- private var snapshot: StatusSnapshot?35+ var snapshot: StatusSnapshot?
34 private var dashboard = DashboardScreen()36 private var dashboard = DashboardScreen()
35- private var chat = ChatScreen()37+ var chat = ChatScreen()
38+ var models = ModelsScreen()
39+ var settings: SettingsScreen
36 private var answer: Task<Void, Never>?40 private var answer: Task<Void, Never>?
37 private var modelsRequested = false41 private var modelsRequested = false
38 /// False once `run` returns: work still in flight must not draw on the restored terminal.42 /// False once `run` returns: work still in flight must not draw on the restored terminal.
39 private var running = false43 private var running = false
40 44
41 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.45 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
46+ /// - Parameter environment: the model cache, downloads, files and editor (tests replace them).
42 public init(47 public init(
43 terminal: any Terminal, server: any TUIServer, serverURL: String,48 terminal: any Terminal, server: any TUIServer, serverURL: String,
44 startCommand: String = "rzb serve", colors: Bool = true,49 startCommand: String = "rzb serve", colors: Bool = true,
45- pollInterval: Duration = .seconds(1), now: @escaping @Sendable () -> Date = { Date() }50+ pollInterval: Duration = .seconds(1), preferences: TUIPreferences = TUIPreferences(),
51+ environment: TUIEnvironment = TUIEnvironment(
52+ store: ModelStore(), preferencesFile: TUIPreferences.defaultFile()),
53+ now: @escaping @Sendable () -> Date = { Date() }
46 ) {54 ) {
47 self.terminal = terminal55 self.terminal = terminal
48 self.server = server56 self.server = server
49- self.renderer = AppRenderer(style: Style(colors: colors))57+ self.environment = environment
50- self.chatRenderer = ChatRenderer(style: Style(colors: colors))58+ self.style = Style(colors: colors)
51 self.pollInterval = pollInterval59 self.pollInterval = pollInterval
52 self.startCommand = startCommand60 self.startCommand = startCommand
53 self.now = now61 self.now = now
54 self.state = AppState(serverURL: serverURL)62 self.state = AppState(serverURL: serverURL)
63+ self.settings = SettingsScreen(preferences: preferences)
64+ self.chat.apply(preferences)
55 }65 }
56 66
57 /// The current state (tests).67 /// The current state (tests).
58 public var currentState: AppState { state }68 public var currentState: AppState { state }
59 public var chatScreen: ChatScreen { chat }69 public var chatScreen: ChatScreen { chat }
60 public var dashboardScreen: DashboardScreen { dashboard }70 public var dashboardScreen: DashboardScreen { dashboard }
71+ public var modelsScreen: ModelsScreen { models }
72+ public var settingsScreen: SettingsScreen { settings }
61 73
62 /// Runs until Ctrl-Q (or Ctrl-C outside a generation) or the end of input; the terminal is74 /// Runs until Ctrl-Q (or Ctrl-C outside a generation) or the end of input; the terminal is
63 /// always restored.75 /// always restored.
@@ -104,18 +116,21 @@ public actor TUIApp {
104 }116 }
105 case .chat:117 case .chat:
106 perform(chat.handle(key))118 perform(chat.handle(key))
107- case .models, .settings:119+ case .models:
108- break120+ perform(models.handle(key))
121+ case .settings:
122+ perform(settings.handle(key))
109 }123 }
110 }124 }
111 125
112 private func screenShown() {126 private func screenShown() {
113 if state.screen == .chat && !modelsRequested { loadModels() }127 if state.screen == .chat && !modelsRequested { loadModels() }
128+ if state.screen == .models { refreshModels() }
114 }129 }
115 130
116 // MARK: Actions131 // MARK: Actions
117 132
118- private func perform(_ action: ChatScreen.Action) {133+ func perform(_ action: ChatScreen.Action) {
119 switch action {134 switch action {
120 case .none, .redraw:135 case .none, .redraw:
121 break136 break
@@ -128,6 +143,8 @@ public actor TUIApp {
128 }143 }
129 }144 }
130 145
146+ // MARK: Chat screen
147+
131 private func loadModels() {148 private func loadModels() {
132 modelsRequested = true149 modelsRequested = true
133 Task { await fetchModels() }150 Task { await fetchModels() }
@@ -210,6 +227,7 @@ public actor TUIApp {
210 state.model = status.models.first?.name227 state.model = status.models.first?.name
211 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }228 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
212 if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() }229 if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() }
230+ if state.screen == .models { refreshModels() }
213 }231 }
214 232
215 private func lose(_ connection: Connection) {233 private func lose(_ connection: Connection) {
@@ -221,13 +239,13 @@ public actor TUIApp {
221 239
222 // MARK: Drawing240 // MARK: Drawing
223 241
224- private func redraw() {242+ func redraw() {
225 guard running else { return }243 guard running else { return }
226 let size = terminal.size244 let size = terminal.size
227 let height = max(1, size.rows - 2)245 let height = max(1, size.rows - 2)
228 let (body, cursor) = body(width: size.columns, height: height)246 let (body, cursor) = body(width: size.columns, height: height)
229 terminal.draw(247 terminal.draw(
230- renderer.render(248+ AppRenderer(style: style).render(
231 state, body: body, cursor: cursor, rows: size.rows, columns: size.columns))249 state, body: body, cursor: cursor, rows: size.rows, columns: size.columns))
232 }250 }
233 251
@@ -239,13 +257,18 @@ public actor TUIApp {
239 case .dashboard:257 case .dashboard:
240 guard let snapshot else { return (["", " Waiting for the server's status…"], nil) }258 guard let snapshot else { return (["", " Waiting for the server's status…"], nil) }
241 let lines = dashboard.render(259 let lines = dashboard.render(
242- snapshot, width: width, height: height - 1, now: now(), style: renderer.style)260+ snapshot, width: width, height: height - 1, now: now(), style: style)
243 return ([""] + lines, nil)261 return ([""] + lines, nil)
244 case .chat:262 case .chat:
245- let (lines, cursor) = chatRenderer.render(chat, width: width, height: height)263+ let drawn = ChatRenderer(style: style).render(chat, width: width, height: height)
246- return (lines, cursor)264+ return (drawn.lines, drawn.cursor)
247- case .models, .settings:265+ case .models:
248- return (AppRenderer.placeholder(for: state.screen), nil)266+ return ModelsRenderer(style: style).render(
267+ models, memory: snapshot?.memory, width: width, height: height)
268+ case .settings:
269+ return SettingsRenderer(style: style).render(
270+ settings, preferencesFile: environment.preferencesFile,
271+ serverConfigFile: serverConfigFile, width: width, height: height)
249 }272 }
250 }273 }
251 }274 }
added Sources/RazorbillTUI/TUIEnvironment.swift +53 -0
new file mode 100644
@@ -0,0 +1,53 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// What `rzb tui` uses besides the server: the model cache on disk, a way to download, the
5+/// files it edits, and how to run an editor. The CLI fills it in; tests replace the parts.
6+///
7+/// ```swift
8+/// let environment = TUIEnvironment(store: ModelStore(), preferencesFile: TUIPreferences.defaultFile())
9+/// ```
10+public struct TUIEnvironment: Sendable {
11+ /// Downloads a model into the cache, reporting progress from 0 to 1.
12+ public typealias Downloader =
13+ @Sendable (ModelReference, _ progress: @escaping @Sendable (Double) -> Void) async throws
14+ -> Void
15+ /// Opens a file in an editor and returns when it closes.
16+ public typealias Editor = @Sendable (String) async -> Void
17+
18+ public var store: ModelStore
19+ /// `nil` when this build cannot download (no engine).
20+ public var download: Downloader?
21+ /// Where the Settings screen saves the preferences.
22+ public var preferencesFile: String
23+ /// The server's configuration file given to `rzb tui --config`; else the one `/rzb/status`
24+ /// reports is used.
25+ public var configFile: String?
26+ public var edit: Editor
27+
28+ public init(
29+ store: ModelStore, download: Downloader? = nil, preferencesFile: String,
30+ configFile: String? = nil, edit: @escaping Editor = TUIEnvironment.systemEditor
31+ ) {
32+ self.store = store
33+ self.download = download
34+ self.preferencesFile = preferencesFile
35+ self.configFile = configFile
36+ self.edit = edit
37+ }
38+
39+ /// `$VISUAL`, else `$EDITOR`, else `vi`, run through the shell on the terminal.
40+ public static let systemEditor: Editor = { file in
41+ let process = Process()
42+ process.executableURL = URL(fileURLWithPath: "/bin/sh")
43+ process.arguments = ["-c", "${VISUAL:-${EDITOR:-vi}} \"$1\"", "sh", file]
44+ await withCheckedContinuation { (finished: CheckedContinuation<Void, Never>) in
45+ process.terminationHandler = { _ in finished.resume() }
46+ do {
47+ try process.run()
48+ } catch {
49+ finished.resume()
50+ }
51+ }
52+ }
53+}
new file mode 100644
@@ -0,0 +1,53 @@
1+import Foundation
2+import RazorbillCore
3+
4+/// What `rzb tui` uses besides the server: the model cache on disk, a way to download, the
5+/// files it edits, and how to run an editor. The CLI fills it in; tests replace the parts.
6+///
7+/// ```swift
8+/// let environment = TUIEnvironment(store: ModelStore(), preferencesFile: TUIPreferences.defaultFile())
9+/// ```
10+public struct TUIEnvironment: Sendable {
11+ /// Downloads a model into the cache, reporting progress from 0 to 1.
12+ public typealias Downloader =
13+ @Sendable (ModelReference, _ progress: @escaping @Sendable (Double) -> Void) async throws
14+ -> Void
15+ /// Opens a file in an editor and returns when it closes.
16+ public typealias Editor = @Sendable (String) async -> Void
17+
18+ public var store: ModelStore
19+ /// `nil` when this build cannot download (no engine).
20+ public var download: Downloader?
21+ /// Where the Settings screen saves the preferences.
22+ public var preferencesFile: String
23+ /// The server's configuration file given to `rzb tui --config`; else the one `/rzb/status`
24+ /// reports is used.
25+ public var configFile: String?
26+ public var edit: Editor
27+
28+ public init(
29+ store: ModelStore, download: Downloader? = nil, preferencesFile: String,
30+ configFile: String? = nil, edit: @escaping Editor = TUIEnvironment.systemEditor
31+ ) {
32+ self.store = store
33+ self.download = download
34+ self.preferencesFile = preferencesFile
35+ self.configFile = configFile
36+ self.edit = edit
37+ }
38+
39+ /// `$VISUAL`, else `$EDITOR`, else `vi`, run through the shell on the terminal.
40+ public static let systemEditor: Editor = { file in
41+ let process = Process()
42+ process.executableURL = URL(fileURLWithPath: "/bin/sh")
43+ process.arguments = ["-c", "${VISUAL:-${EDITOR:-vi}} \"$1\"", "sh", file]
44+ await withCheckedContinuation { (finished: CheckedContinuation<Void, Never>) in
45+ process.terminationHandler = { _ in finished.resume() }
46+ do {
47+ try process.run()
48+ } catch {
49+ finished.resume()
50+ }
51+ }
52+ }
53+}
modified Sources/RazorbillTUI/TUILaunch.swift +25 -5
@@ -1,8 +1,11 @@
1-/// What `rzb tui` starts with: the server to watch, its API key, and how to start it.
1+import RazorbillCore
2+
3+/// What `rzb tui` starts with: the server to watch, its API key, how to start it, and the
4+/// preferences read from `tui.yaml`.
25 ///
36 /// ```swift
47 /// let launch = TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve")
5-/// await launch.run(colors: true) // full screen until Ctrl-Q
8+/// await launch.run(environment: TUIEnvironment(store: ModelStore(), preferencesFile: file))
69 /// ```
710 public struct TUILaunch: Sendable, Equatable {
811 /// `http://host:port`, without `/v1`.
@@ -10,19 +13,36 @@ public struct TUILaunch: Sendable, Equatable {
1013 public var apiKey: String?
1114 /// Shown when no server answers.
1215 public var startCommand: String
16+ public var preferences: TUIPreferences
17+ /// Where the preferences are saved.
18+ public var preferencesFile: String
19+ /// The server's configuration file, when `--config` gave it.
20+ public var configFile: String?
21+ public var colors: Bool
1322
14- public init(url: String, apiKey: String?, startCommand: String) {
23+ public init(
24+ url: String, apiKey: String?, startCommand: String,
25+ preferences: TUIPreferences = TUIPreferences(),
26+ preferencesFile: String = TUIPreferences.defaultFile(), configFile: String? = nil,
27+ colors: Bool = true
28+ ) {
1529 self.url = url
1630 self.apiKey = apiKey
1731 self.startCommand = startCommand
32+ self.preferences = preferences
33+ self.preferencesFile = preferencesFile
34+ self.configFile = configFile
35+ self.colors = colors
1836 }
1937
2038 /// Runs the TUI on the process's terminal until the user quits.
21- public func run(colors: Bool) async {
39+ public func run(environment: TUIEnvironment) async {
2240 let client = ServerClient(baseURL: url, apiKey: apiKey)
2341 let app = TUIApp(
2442 terminal: PosixTerminal(), server: client, serverURL: client.baseURL,
25- startCommand: startCommand, colors: colors)
43+ startCommand: startCommand, colors: colors,
44+ pollInterval: preferences.pollInterval ?? .seconds(1), preferences: preferences,
45+ environment: environment)
2646 await app.run()
2747 }
2848 }
@@ -1,8 +1,11 @@
1-/// What `rzb tui` starts with: the server to watch, its API key, and how to start it.1+import RazorbillCore
2+
3+/// What `rzb tui` starts with: the server to watch, its API key, how to start it, and the
4+/// preferences read from `tui.yaml`.
2 ///5 ///
3 /// ```swift6 /// ```swift
4 /// let launch = TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve")7 /// let launch = TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve")
5-/// await launch.run(colors: true) // full screen until Ctrl-Q8+/// await launch.run(environment: TUIEnvironment(store: ModelStore(), preferencesFile: file))
6 /// ```9 /// ```
7 public struct TUILaunch: Sendable, Equatable {10 public struct TUILaunch: Sendable, Equatable {
8 /// `http://host:port`, without `/v1`.11 /// `http://host:port`, without `/v1`.
@@ -10,19 +13,36 @@ public struct TUILaunch: Sendable, Equatable {
10 public var apiKey: String?13 public var apiKey: String?
11 /// Shown when no server answers.14 /// Shown when no server answers.
12 public var startCommand: String15 public var startCommand: String
16+ public var preferences: TUIPreferences
17+ /// Where the preferences are saved.
18+ public var preferencesFile: String
19+ /// The server's configuration file, when `--config` gave it.
20+ public var configFile: String?
21+ public var colors: Bool
13 22
14- public init(url: String, apiKey: String?, startCommand: String) {23+ public init(
24+ url: String, apiKey: String?, startCommand: String,
25+ preferences: TUIPreferences = TUIPreferences(),
26+ preferencesFile: String = TUIPreferences.defaultFile(), configFile: String? = nil,
27+ colors: Bool = true
28+ ) {
15 self.url = url29 self.url = url
16 self.apiKey = apiKey30 self.apiKey = apiKey
17 self.startCommand = startCommand31 self.startCommand = startCommand
32+ self.preferences = preferences
33+ self.preferencesFile = preferencesFile
34+ self.configFile = configFile
35+ self.colors = colors
18 }36 }
19 37
20 /// Runs the TUI on the process's terminal until the user quits.38 /// Runs the TUI on the process's terminal until the user quits.
21- public func run(colors: Bool) async {39+ public func run(environment: TUIEnvironment) async {
22 let client = ServerClient(baseURL: url, apiKey: apiKey)40 let client = ServerClient(baseURL: url, apiKey: apiKey)
23 let app = TUIApp(41 let app = TUIApp(
24 terminal: PosixTerminal(), server: client, serverURL: client.baseURL,42 terminal: PosixTerminal(), server: client, serverURL: client.baseURL,
25- startCommand: startCommand, colors: colors)43+ startCommand: startCommand, colors: colors,
44+ pollInterval: preferences.pollInterval ?? .seconds(1), preferences: preferences,
45+ environment: environment)
26 await app.run()46 await app.run()
27 }47 }
28 }48 }
modified Sources/RazorbillTUI/Terminal.swift +36 -2
@@ -18,12 +18,20 @@ public protocol Terminal: Sendable {
1818 func keys() -> AsyncStream<Key>
1919 /// Replaces the whole screen with `screen`.
2020 func draw(_ screen: Screen)
21+ /// Gives the terminal back for a while (to run `$EDITOR`): normal mode, normal screen, and
22+ /// no keys read until ``resume()``.
23+ func suspend()
24+ /// Takes the terminal again after ``suspend()``.
25+ func resume()
2126 }
2227
2328 /// The process's terminal (standard input and output), driven with termios and ANSI codes.
2429 public final class PosixTerminal: Terminal, @unchecked Sendable {
2530 /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable.
2631 private var resizeSource: (any DispatchSourceSignal)?
32+ private let lock = NSLock()
33+ /// While set, the key reader leaves standard input to another program.
34+ private var paused = false
2735
2836 public init() {}
2937
@@ -39,19 +47,35 @@ public final class PosixTerminal: Terminal, @unchecked Sendable {
3947 }
4048
4149 public func enter() {
50+ takeOver()
51+ TerminalRestorer.installSignalHandlers()
52+ }
53+
54+ /// Raw mode and the alternate screen, cleared.
55+ private func takeOver() {
4256 TerminalRestorer.save()
4357 var raw = TerminalRestorer.original ?? termios()
4458 cfmakeraw(&raw)
4559 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)
46- // Alternate screen, cleared.
4760 write("\u{1B}[?1049h\u{1B}[2J")
48- TerminalRestorer.installSignalHandlers()
4961 }
5062
5163 public func leave() {
5264 TerminalRestorer.restore()
5365 }
5466
67+ public func suspend() {
68+ lock.withLock { paused = true }
69+ // Let a read that saw input before the pause finish.
70+ usleep(60_000)
71+ TerminalRestorer.restore()
72+ }
73+
74+ public func resume() {
75+ takeOver()
76+ lock.withLock { paused = false }
77+ }
78+
5579 public func keys() -> AsyncStream<Key> {
5680 AsyncStream { continuation in
5781 let resize = DispatchSource.makeSignalSource(signal: SIGWINCH)
@@ -63,6 +87,16 @@ public final class PosixTerminal: Terminal, @unchecked Sendable {
6387 var decoder = KeyDecoder()
6488 var buffer = [UInt8](repeating: 0, count: 256)
6589 while true {
90+ // Wait for input in short slices, so a pause takes effect before the next read.
91+ if self.lock.withLock({ self.paused }) {
92+ usleep(20_000)
93+ continue
94+ }
95+ var watched = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0)
96+ let ready = poll(&watched, 1, 50)
97+ if ready == 0 || (ready < 0 && errno == EINTR) { continue }
98+ if ready < 0 { break }
99+ if self.lock.withLock({ self.paused }) { continue }
66100 let count = read(STDIN_FILENO, &buffer, buffer.count)
67101 if count < 0, errno == EINTR { continue }
68102 if count <= 0 { break }
@@ -18,12 +18,20 @@ public protocol Terminal: Sendable {
18 func keys() -> AsyncStream<Key>18 func keys() -> AsyncStream<Key>
19 /// Replaces the whole screen with `screen`.19 /// Replaces the whole screen with `screen`.
20 func draw(_ screen: Screen)20 func draw(_ screen: Screen)
21+ /// Gives the terminal back for a while (to run `$EDITOR`): normal mode, normal screen, and
22+ /// no keys read until ``resume()``.
23+ func suspend()
24+ /// Takes the terminal again after ``suspend()``.
25+ func resume()
21 }26 }
22 27
23 /// The process's terminal (standard input and output), driven with termios and ANSI codes.28 /// The process's terminal (standard input and output), driven with termios and ANSI codes.
24 public final class PosixTerminal: Terminal, @unchecked Sendable {29 public final class PosixTerminal: Terminal, @unchecked Sendable {
25 /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable.30 /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable.
26 private var resizeSource: (any DispatchSourceSignal)?31 private var resizeSource: (any DispatchSourceSignal)?
32+ private let lock = NSLock()
33+ /// While set, the key reader leaves standard input to another program.
34+ private var paused = false
27 35
28 public init() {}36 public init() {}
29 37
@@ -39,19 +47,35 @@ public final class PosixTerminal: Terminal, @unchecked Sendable {
39 }47 }
40 48
41 public func enter() {49 public func enter() {
50+ takeOver()
51+ TerminalRestorer.installSignalHandlers()
52+ }
53+
54+ /// Raw mode and the alternate screen, cleared.
55+ private func takeOver() {
42 TerminalRestorer.save()56 TerminalRestorer.save()
43 var raw = TerminalRestorer.original ?? termios()57 var raw = TerminalRestorer.original ?? termios()
44 cfmakeraw(&raw)58 cfmakeraw(&raw)
45 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)59 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)
46- // Alternate screen, cleared.
47 write("\u{1B}[?1049h\u{1B}[2J")60 write("\u{1B}[?1049h\u{1B}[2J")
48- TerminalRestorer.installSignalHandlers()
49 }61 }
50 62
51 public func leave() {63 public func leave() {
52 TerminalRestorer.restore()64 TerminalRestorer.restore()
53 }65 }
54 66
67+ public func suspend() {
68+ lock.withLock { paused = true }
69+ // Let a read that saw input before the pause finish.
70+ usleep(60_000)
71+ TerminalRestorer.restore()
72+ }
73+
74+ public func resume() {
75+ takeOver()
76+ lock.withLock { paused = false }
77+ }
78+
55 public func keys() -> AsyncStream<Key> {79 public func keys() -> AsyncStream<Key> {
56 AsyncStream { continuation in80 AsyncStream { continuation in
57 let resize = DispatchSource.makeSignalSource(signal: SIGWINCH)81 let resize = DispatchSource.makeSignalSource(signal: SIGWINCH)
@@ -63,6 +87,16 @@ public final class PosixTerminal: Terminal, @unchecked Sendable {
63 var decoder = KeyDecoder()87 var decoder = KeyDecoder()
64 var buffer = [UInt8](repeating: 0, count: 256)88 var buffer = [UInt8](repeating: 0, count: 256)
65 while true {89 while true {
90+ // Wait for input in short slices, so a pause takes effect before the next read.
91+ if self.lock.withLock({ self.paused }) {
92+ usleep(20_000)
93+ continue
94+ }
95+ var watched = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0)
96+ let ready = poll(&watched, 1, 50)
97+ if ready == 0 || (ready < 0 && errno == EINTR) { continue }
98+ if ready < 0 { break }
99+ if self.lock.withLock({ self.paused }) { continue }
66 let count = read(STDIN_FILENO, &buffer, buffer.count)100 let count = read(STDIN_FILENO, &buffer, buffer.count)
67 if count < 0, errno == EINTR { continue }101 if count < 0, errno == EINTR { continue }
68 if count <= 0 { break }102 if count <= 0 { break }
modified Tests/RazorbillCLITests/Harness.swift +9 -0
@@ -64,6 +64,10 @@ struct World {
6464 }
6565
6666 var cacheDirectory: URL { URL(fileURLWithPath: directory).appendingPathComponent("hub") }
67+ /// The `tui.yaml` rzb tui reads in this world (absent until a test writes it).
68+ var preferencesFile: String {
69+ URL(fileURLWithPath: directory).appendingPathComponent("tui.yaml").path
70+ }
6771
6872 var environment: CLIEnvironment {
6973 let engine = self.engine
@@ -71,6 +75,11 @@ struct World {
7175 engines.register("fake") { _ in engine }
7276 let servers = self.servers
7377 let tuis = self.tuis
78+ // rzb tui never reads the real ~/.config/razorbill/tui.yaml in tests.
79+ var variables = self.variables
80+ if variables["RZB_TUI_PREFERENCES"] == nil {
81+ variables["RZB_TUI_PREFERENCES"] = preferencesFile
82+ }
7483 return CLIEnvironment(
7584 engines: engines, console: console,
7685 modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables,
@@ -64,6 +64,10 @@ struct World {
64 }64 }
65 65
66 var cacheDirectory: URL { URL(fileURLWithPath: directory).appendingPathComponent("hub") }66 var cacheDirectory: URL { URL(fileURLWithPath: directory).appendingPathComponent("hub") }
67+ /// The `tui.yaml` rzb tui reads in this world (absent until a test writes it).
68+ var preferencesFile: String {
69+ URL(fileURLWithPath: directory).appendingPathComponent("tui.yaml").path
70+ }
67 71
68 var environment: CLIEnvironment {72 var environment: CLIEnvironment {
69 let engine = self.engine73 let engine = self.engine
@@ -71,6 +75,11 @@ struct World {
71 engines.register("fake") { _ in engine }75 engines.register("fake") { _ in engine }
72 let servers = self.servers76 let servers = self.servers
73 let tuis = self.tuis77 let tuis = self.tuis
78+ // rzb tui never reads the real ~/.config/razorbill/tui.yaml in tests.
79+ var variables = self.variables
80+ if variables["RZB_TUI_PREFERENCES"] == nil {
81+ variables["RZB_TUI_PREFERENCES"] = preferencesFile
82+ }
74 return CLIEnvironment(83 return CLIEnvironment(
75 engines: engines, console: console,84 engines: engines, console: console,
76 modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables,85 modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables,
modified Tests/RazorbillCLITests/TUICommandTests.swift +44 -9
@@ -10,10 +10,11 @@ import Testing
1010 let world = try World()
1111 let result = await world.rzb("tui")
1212 #expect(result.exitCode == 0)
13- #expect(
14- world.tuis.opened == [
15- TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve")
16- ])
13+ let launch = try #require(world.tuis.opened.first)
14+ #expect(launch.url == "http://127.0.0.1:7920" && launch.apiKey == nil)
15+ #expect(launch.startCommand == "rzb serve" && launch.configFile == nil)
16+ #expect(launch.preferencesFile == world.preferencesFile && launch.colors)
17+ #expect(launch.preferences == TUIPreferences())
1718 }
1819
1920 @Test func urlIsCleanedOfSlashAndV1() async throws {
@@ -37,11 +38,9 @@ import Testing
3738 try "server: { host: 0.0.0.0, port: 9100, api_key_env: TEAM_KEY }\n".write(
3839 toFile: path, atomically: true, encoding: .utf8)
3940 _ = await world.rzb("tui", "--config", path)
40- #expect(
41- world.tuis.opened.first
42- == TUILaunch(
43- url: "http://127.0.0.1:9100", apiKey: "k",
44- startCommand: "rzb serve --config \(path)"))
41+ let launch = try #require(world.tuis.opened.first)
42+ #expect(launch.url == "http://127.0.0.1:9100" && launch.apiKey == "k")
43+ #expect(launch.startCommand == "rzb serve --config \(path)" && launch.configFile == path)
4544
4645 _ = await world.rzb("tui", "--config", path, "--url", "http://[::1]:7000")
4746 #expect(world.tuis.opened.last?.url == "http://[::1]:7000")
@@ -56,6 +55,42 @@ import Testing
5655 #expect(world.tuis.opened.last?.apiKey == "m")
5756 }
5857
58+ @Test func preferencesComeAfterTheOptionsAndBeforeTheConfig() async throws {
59+ var world = try World()
60+ world.variables = ["PREF_KEY": "p", "OPT_KEY": "o"]
61+ let yaml = """
62+ server_url: http://localhost:8100/v1
63+ api_key_env: PREF_KEY
64+ colors: false
65+ chat: { temperature: 0.3 }
66+ """
67+ try yaml.write(toFile: world.preferencesFile, atomically: true, encoding: .utf8)
68+ _ = await world.rzb("tui")
69+ let launch = try #require(world.tuis.opened.first)
70+ #expect(launch.url == "http://localhost:8100" && launch.apiKey == "p" && !launch.colors)
71+ #expect(launch.preferences.chat.temperature == 0.3)
72+ _ = await world.rzb("tui", "--url", "http://localhost:9", "--api-key-env", "OPT_KEY")
73+ #expect(world.tuis.opened.last?.url == "http://localhost:9")
74+ #expect(world.tuis.opened.last?.apiKey == "o")
75+ }
76+
77+ @Test func invalidPreferencesAreReportedWithTheirLine() async throws {
78+ let world = try World()
79+ try "reasoning: loud\n".write(
80+ toFile: world.preferencesFile, atomically: true, encoding: .utf8)
81+ let result = await world.rzb("tui")
82+ #expect(result.exitCode == 2)
83+ #expect(result.stderr.contains("line 1: reasoning"))
84+ #expect(world.tuis.opened.isEmpty)
85+ }
86+
87+ @Test func noColorWins() async throws {
88+ var world = try World()
89+ world.variables = ["NO_COLOR": "1"]
90+ _ = await world.rzb("tui")
91+ #expect(world.tuis.opened.first?.colors == false)
92+ }
93+
5994 @Test func invalidConfigIsReported() async throws {
6095 let world = try World()
6196 let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path
@@ -10,10 +10,11 @@ import Testing
10 let world = try World()10 let world = try World()
11 let result = await world.rzb("tui")11 let result = await world.rzb("tui")
12 #expect(result.exitCode == 0)12 #expect(result.exitCode == 0)
13- #expect(13+ let launch = try #require(world.tuis.opened.first)
14- world.tuis.opened == [14+ #expect(launch.url == "http://127.0.0.1:7920" && launch.apiKey == nil)
15- TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve")15+ #expect(launch.startCommand == "rzb serve" && launch.configFile == nil)
16- ])16+ #expect(launch.preferencesFile == world.preferencesFile && launch.colors)
17+ #expect(launch.preferences == TUIPreferences())
17 }18 }
18 19
19 @Test func urlIsCleanedOfSlashAndV1() async throws {20 @Test func urlIsCleanedOfSlashAndV1() async throws {
@@ -37,11 +38,9 @@ import Testing
37 try "server: { host: 0.0.0.0, port: 9100, api_key_env: TEAM_KEY }\n".write(38 try "server: { host: 0.0.0.0, port: 9100, api_key_env: TEAM_KEY }\n".write(
38 toFile: path, atomically: true, encoding: .utf8)39 toFile: path, atomically: true, encoding: .utf8)
39 _ = await world.rzb("tui", "--config", path)40 _ = await world.rzb("tui", "--config", path)
40- #expect(41+ let launch = try #require(world.tuis.opened.first)
41- world.tuis.opened.first42+ #expect(launch.url == "http://127.0.0.1:9100" && launch.apiKey == "k")
42- == TUILaunch(43+ #expect(launch.startCommand == "rzb serve --config \(path)" && launch.configFile == path)
43- url: "http://127.0.0.1:9100", apiKey: "k",
44- startCommand: "rzb serve --config \(path)"))
45 44
46 _ = await world.rzb("tui", "--config", path, "--url", "http://[::1]:7000")45 _ = await world.rzb("tui", "--config", path, "--url", "http://[::1]:7000")
47 #expect(world.tuis.opened.last?.url == "http://[::1]:7000")46 #expect(world.tuis.opened.last?.url == "http://[::1]:7000")
@@ -56,6 +55,42 @@ import Testing
56 #expect(world.tuis.opened.last?.apiKey == "m")55 #expect(world.tuis.opened.last?.apiKey == "m")
57 }56 }
58 57
58+ @Test func preferencesComeAfterTheOptionsAndBeforeTheConfig() async throws {
59+ var world = try World()
60+ world.variables = ["PREF_KEY": "p", "OPT_KEY": "o"]
61+ let yaml = """
62+ server_url: http://localhost:8100/v1
63+ api_key_env: PREF_KEY
64+ colors: false
65+ chat: { temperature: 0.3 }
66+ """
67+ try yaml.write(toFile: world.preferencesFile, atomically: true, encoding: .utf8)
68+ _ = await world.rzb("tui")
69+ let launch = try #require(world.tuis.opened.first)
70+ #expect(launch.url == "http://localhost:8100" && launch.apiKey == "p" && !launch.colors)
71+ #expect(launch.preferences.chat.temperature == 0.3)
72+ _ = await world.rzb("tui", "--url", "http://localhost:9", "--api-key-env", "OPT_KEY")
73+ #expect(world.tuis.opened.last?.url == "http://localhost:9")
74+ #expect(world.tuis.opened.last?.apiKey == "o")
75+ }
76+
77+ @Test func invalidPreferencesAreReportedWithTheirLine() async throws {
78+ let world = try World()
79+ try "reasoning: loud\n".write(
80+ toFile: world.preferencesFile, atomically: true, encoding: .utf8)
81+ let result = await world.rzb("tui")
82+ #expect(result.exitCode == 2)
83+ #expect(result.stderr.contains("line 1: reasoning"))
84+ #expect(world.tuis.opened.isEmpty)
85+ }
86+
87+ @Test func noColorWins() async throws {
88+ var world = try World()
89+ world.variables = ["NO_COLOR": "1"]
90+ _ = await world.rzb("tui")
91+ #expect(world.tuis.opened.first?.colors == false)
92+ }
93+
59 @Test func invalidConfigIsReported() async throws {94 @Test func invalidConfigIsReported() async throws {
60 let world = try World()95 let world = try World()
61 let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path96 let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path
added Tests/RazorbillCoreTests/TUIPreferencesTests.swift +81 -0
new file mode 100644
@@ -0,0 +1,81 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@Suite struct TUIPreferencesTests {
6+ let loader = TUIPreferencesLoader()
7+
8+ @Test func everyKey() throws {
9+ let preferences = try loader.parse(
10+ """
11+ server_url: http://127.0.0.1:8000
12+ api_key_env: TEAM_KEY
13+ reasoning: hidden
14+ colors: false
15+ poll_interval: 500ms
16+ chat:
17+ temperature: 0.7
18+ top_p: 0.9
19+ top_k: 40
20+ min_p: 0.05
21+ max_tokens: 1024
22+ thinking: false
23+ """)
24+ #expect(preferences.serverURL == "http://127.0.0.1:8000")
25+ #expect(preferences.apiKeyVariable == "TEAM_KEY")
26+ #expect(preferences.reasoning == "hidden" && preferences.colors == false)
27+ #expect(preferences.pollInterval == .milliseconds(500))
28+ #expect(preferences.chat.temperature == 0.7 && preferences.chat.topK == 40)
29+ #expect(preferences.chat.maxTokens == 1024 && preferences.chat.thinking == false)
30+ }
31+
32+ @Test func emptyOrMissingFileIsTheDefault() throws {
33+ #expect(try loader.parse("") == TUIPreferences())
34+ let missing = FileManager.default.temporaryDirectory.appendingPathComponent(
35+ "rzb-none-\(UUID().uuidString).yaml")
36+ #expect(try loader.load(file: missing.path) == TUIPreferences())
37+ }
38+
39+ @Test func problemsAreReportedTogetherWithTheirLines() {
40+ do {
41+ _ = try loader.parse(
42+ """
43+ server_url: http://x
44+ colour: true
45+ reasoning: maybe
46+ poll_interval: soon
47+ chat:
48+ temperature: 5
49+ seed: 1
50+ """, file: "tui.yaml")
51+ Issue.record("accepted")
52+ } catch let error as ConfigError {
53+ let paths = error.issues.map(\.keyPath)
54+ #expect(paths.prefix(3) == ["colour", "reasoning", "poll_interval"])
55+ #expect(paths.suffix(2) == ["chat.seed", "chat.temperature"])
56+ #expect(error.issues.first?.line == 2)
57+ } catch {
58+ Issue.record("\(error)")
59+ }
60+ }
61+
62+ @Test func savedFileReadsBack() throws {
63+ var preferences = TUIPreferences()
64+ preferences.serverURL = "http://127.0.0.1:7920"
65+ preferences.reasoning = "shown"
66+ preferences.pollInterval = .seconds(2)
67+ preferences.chat.temperature = 0.4
68+ preferences.chat.thinking = true
69+ let file = FileManager.default.temporaryDirectory.appendingPathComponent(
70+ "rzb-tui-\(UUID().uuidString)/razorbill/tui.yaml"
71+ ).path
72+ try preferences.save(to: file)
73+ #expect(try loader.load(file: file) == preferences)
74+ #expect(TUIPreferences().yaml.hasPrefix("# rzb tui preferences"))
75+ }
76+
77+ @Test func defaultFileIsUnderDotConfig() {
78+ let file = TUIPreferences.defaultFile(home: "/Users/a")
79+ #expect(file == "/Users/a/.config/razorbill/tui.yaml")
80+ }
81+}
new file mode 100644
@@ -0,0 +1,81 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@Suite struct TUIPreferencesTests {
6+ let loader = TUIPreferencesLoader()
7+
8+ @Test func everyKey() throws {
9+ let preferences = try loader.parse(
10+ """
11+ server_url: http://127.0.0.1:8000
12+ api_key_env: TEAM_KEY
13+ reasoning: hidden
14+ colors: false
15+ poll_interval: 500ms
16+ chat:
17+ temperature: 0.7
18+ top_p: 0.9
19+ top_k: 40
20+ min_p: 0.05
21+ max_tokens: 1024
22+ thinking: false
23+ """)
24+ #expect(preferences.serverURL == "http://127.0.0.1:8000")
25+ #expect(preferences.apiKeyVariable == "TEAM_KEY")
26+ #expect(preferences.reasoning == "hidden" && preferences.colors == false)
27+ #expect(preferences.pollInterval == .milliseconds(500))
28+ #expect(preferences.chat.temperature == 0.7 && preferences.chat.topK == 40)
29+ #expect(preferences.chat.maxTokens == 1024 && preferences.chat.thinking == false)
30+ }
31+
32+ @Test func emptyOrMissingFileIsTheDefault() throws {
33+ #expect(try loader.parse("") == TUIPreferences())
34+ let missing = FileManager.default.temporaryDirectory.appendingPathComponent(
35+ "rzb-none-\(UUID().uuidString).yaml")
36+ #expect(try loader.load(file: missing.path) == TUIPreferences())
37+ }
38+
39+ @Test func problemsAreReportedTogetherWithTheirLines() {
40+ do {
41+ _ = try loader.parse(
42+ """
43+ server_url: http://x
44+ colour: true
45+ reasoning: maybe
46+ poll_interval: soon
47+ chat:
48+ temperature: 5
49+ seed: 1
50+ """, file: "tui.yaml")
51+ Issue.record("accepted")
52+ } catch let error as ConfigError {
53+ let paths = error.issues.map(\.keyPath)
54+ #expect(paths.prefix(3) == ["colour", "reasoning", "poll_interval"])
55+ #expect(paths.suffix(2) == ["chat.seed", "chat.temperature"])
56+ #expect(error.issues.first?.line == 2)
57+ } catch {
58+ Issue.record("\(error)")
59+ }
60+ }
61+
62+ @Test func savedFileReadsBack() throws {
63+ var preferences = TUIPreferences()
64+ preferences.serverURL = "http://127.0.0.1:7920"
65+ preferences.reasoning = "shown"
66+ preferences.pollInterval = .seconds(2)
67+ preferences.chat.temperature = 0.4
68+ preferences.chat.thinking = true
69+ let file = FileManager.default.temporaryDirectory.appendingPathComponent(
70+ "rzb-tui-\(UUID().uuidString)/razorbill/tui.yaml"
71+ ).path
72+ try preferences.save(to: file)
73+ #expect(try loader.load(file: file) == preferences)
74+ #expect(TUIPreferences().yaml.hasPrefix("# rzb tui preferences"))
75+ }
76+
77+ @Test func defaultFileIsUnderDotConfig() {
78+ let file = TUIPreferences.defaultFile(home: "/Users/a")
79+ #expect(file == "/Users/a/.config/razorbill/tui.yaml")
80+ }
81+}
modified Tests/RazorbillServerTests/ConfigReloadTests.swift +2 -0
@@ -197,6 +197,8 @@ func withReloadableServer(
197197 #expect(body["unloaded"] as? [String] == [])
198198 #expect(body["unload_when_idle"] as? [String] == [])
199199 #expect(models.catalog.config.models.map(\.id) == ["a"])
200+ let serverStatus = try await fetchStatus(client)
201+ #expect(serverStatus["config_file"] as? String == URL(fileURLWithPath: file.path).path)
200202 }
201203 }
202204
@@ -197,6 +197,8 @@ func withReloadableServer(
197 #expect(body["unloaded"] as? [String] == [])197 #expect(body["unloaded"] as? [String] == [])
198 #expect(body["unload_when_idle"] as? [String] == [])198 #expect(body["unload_when_idle"] as? [String] == [])
199 #expect(models.catalog.config.models.map(\.id) == ["a"])199 #expect(models.catalog.config.models.map(\.id) == ["a"])
200+ let serverStatus = try await fetchStatus(client)
201+ #expect(serverStatus["config_file"] as? String == URL(fileURLWithPath: file.path).path)
200 }202 }
201 }203 }
202 204
modified Tests/RazorbillServerTests/LocalRoutesTests.swift +1 -0
@@ -144,6 +144,7 @@ func record(_ path: String) -> RequestRecord {
144144 #expect((status["models"] as? [Any])?.isEmpty == true)
145145 #expect((status["recent_requests"] as? [Any])?.isEmpty == true)
146146 #expect(status["memory"] is NSNull)
147+ #expect(status["config_file"] is NSNull)
147148 }
148149 }
149150
@@ -144,6 +144,7 @@ func record(_ path: String) -> RequestRecord {
144 #expect((status["models"] as? [Any])?.isEmpty == true)144 #expect((status["models"] as? [Any])?.isEmpty == true)
145 #expect((status["recent_requests"] as? [Any])?.isEmpty == true)145 #expect((status["recent_requests"] as? [Any])?.isEmpty == true)
146 #expect(status["memory"] is NSNull)146 #expect(status["memory"] is NSNull)
147+ #expect(status["config_file"] is NSNull)
147 }148 }
148 }149 }
149 150
modified Tests/RazorbillTUITests/AppShellTests.swift +0 -4
@@ -97,10 +97,6 @@ import Testing
9797 #expect(!screen.hidesCursor && screen.cursorRow == 1 && screen.cursorColumn == 3)
9898 }
9999
100- @Test func placeholdersNameTheirTicket() {
101- #expect(AppRenderer.placeholder(for: .chat).joined().contains("#55"))
102- #expect(AppRenderer.placeholder(for: .settings).joined().contains("#58"))
103- }
104100 }
105101
106102 @Suite struct ListViewTests {
@@ -97,10 +97,6 @@ import Testing
97 #expect(!screen.hidesCursor && screen.cursorRow == 1 && screen.cursorColumn == 3)97 #expect(!screen.hidesCursor && screen.cursorRow == 1 && screen.cursorColumn == 3)
98 }98 }
99 99
100- @Test func placeholdersNameTheirTicket() {
101- #expect(AppRenderer.placeholder(for: .chat).joined().contains("#55"))
102- #expect(AppRenderer.placeholder(for: .settings).joined().contains("#58"))
103- }
104 }100 }
105 101
106 @Suite struct ListViewTests {102 @Suite struct ListViewTests {
modified Tests/RazorbillTUITests/DashboardAndChatTests.swift +2 -1
@@ -1,4 +1,5 @@
11 import Foundation
2+import RazorbillCore
23 import Testing
34
45 @testable import RazorbillTUI
@@ -284,7 +285,7 @@ let plain = Style(colors: false)
284285 func app(_ terminal: FakeTerminal, _ server: ScriptedServer) -> TUIApp {
285286 TUIApp(
286287 terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
287- pollInterval: .milliseconds(10))
288+ pollInterval: .milliseconds(10), environment: testEnvironment())
288289 }
289290
290291 @Test func chatStreamsTheAnswerWithItsStats() async throws {
@@ -1,4 +1,5 @@
1 import Foundation1 import Foundation
2+import RazorbillCore
2 import Testing3 import Testing
3 4
4 @testable import RazorbillTUI5 @testable import RazorbillTUI
@@ -284,7 +285,7 @@ let plain = Style(colors: false)
284 func app(_ terminal: FakeTerminal, _ server: ScriptedServer) -> TUIApp {285 func app(_ terminal: FakeTerminal, _ server: ScriptedServer) -> TUIApp {
285 TUIApp(286 TUIApp(
286 terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,287 terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
287- pollInterval: .milliseconds(10))288+ pollInterval: .milliseconds(10), environment: testEnvironment())
288 }289 }
289 290
290 @Test func chatStreamsTheAnswerWithItsStats() async throws {291 @Test func chatStreamsTheAnswerWithItsStats() async throws {
modified Tests/RazorbillTUITests/FakeTerminal.swift +6 -0
@@ -15,6 +15,8 @@ final class FakeTerminal: Terminal, @unchecked Sendable {
1515 private var drawn: [Screen] = []
1616 private var entered = 0
1717 private var left = 0
18+ private var suspended = 0
19+ private var resumed = 0
1820 private let stream: AsyncStream<Key>
1921 private let sender: AsyncStream<Key>.Continuation
2022 let size: (rows: Int, columns: Int)
@@ -28,6 +30,10 @@ final class FakeTerminal: Terminal, @unchecked Sendable {
2830 func leave() { lock.withLock { left += 1 } }
2931 func keys() -> AsyncStream<Key> { stream }
3032 func draw(_ screen: Screen) { lock.withLock { drawn.append(screen) } }
33+ func suspend() { lock.withLock { suspended += 1 } }
34+ func resume() { lock.withLock { resumed += 1 } }
35+ var suspendCount: Int { lock.withLock { suspended } }
36+ var resumeCount: Int { lock.withLock { resumed } }
3137
3238 func press(_ keys: Key...) { for key in keys { sender.yield(key) } }
3339 func type(_ text: String) { for character in text { sender.yield(.character(character)) } }
@@ -15,6 +15,8 @@ final class FakeTerminal: Terminal, @unchecked Sendable {
15 private var drawn: [Screen] = []15 private var drawn: [Screen] = []
16 private var entered = 016 private var entered = 0
17 private var left = 017 private var left = 0
18+ private var suspended = 0
19+ private var resumed = 0
18 private let stream: AsyncStream<Key>20 private let stream: AsyncStream<Key>
19 private let sender: AsyncStream<Key>.Continuation21 private let sender: AsyncStream<Key>.Continuation
20 let size: (rows: Int, columns: Int)22 let size: (rows: Int, columns: Int)
@@ -28,6 +30,10 @@ final class FakeTerminal: Terminal, @unchecked Sendable {
28 func leave() { lock.withLock { left += 1 } }30 func leave() { lock.withLock { left += 1 } }
29 func keys() -> AsyncStream<Key> { stream }31 func keys() -> AsyncStream<Key> { stream }
30 func draw(_ screen: Screen) { lock.withLock { drawn.append(screen) } }32 func draw(_ screen: Screen) { lock.withLock { drawn.append(screen) } }
33+ func suspend() { lock.withLock { suspended += 1 } }
34+ func resume() { lock.withLock { resumed += 1 } }
35+ var suspendCount: Int { lock.withLock { suspended } }
36+ var resumeCount: Int { lock.withLock { resumed } }
31 37
32 func press(_ keys: Key...) { for key in keys { sender.yield(key) } }38 func press(_ keys: Key...) { for key in keys { sender.yield(key) } }
33 func type(_ text: String) { for character in text { sender.yield(.character(character)) } }39 func type(_ text: String) { for character in text { sender.yield(.character(character)) } }
added Tests/RazorbillTUITests/ModelsAndSettingsTests.swift +315 -0
new file mode 100644
@@ -0,0 +1,315 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@testable import RazorbillTUI
6+
7+/// Puts an MLX model of `size` bytes in `store`'s cache, as a download leaves it.
8+func cache(_ id: String, size: Int, in store: ModelStore) throws {
9+ let snapshot = store.directory(for: id).appendingPathComponent("snapshots/c1")
10+ let refs = store.directory(for: id).appendingPathComponent("refs")
11+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
12+ try FileManager.default.createDirectory(at: refs, withIntermediateDirectories: true)
13+ try "c1".write(to: refs.appendingPathComponent("main"), atomically: true, encoding: .utf8)
14+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
15+ try Data(count: size).write(to: snapshot.appendingPathComponent("model.safetensors"))
16+}
17+
18+func stored(_ id: String, size: Int64 = 1 << 30, loadable: Bool = true) -> StoredModel {
19+ StoredModel(
20+ id: id, sizeInBytes: size, revisions: ["main"],
21+ directory: URL(fileURLWithPath: "/tmp/\(id)"), isLoadable: loadable)
22+}
23+
24+@Suite struct ModelRowTests {
25+ @Test func marksLoadedDeclaredAndKind() {
26+ var embed = qwen
27+ embed.key = "org/embed#embedding"
28+ let status = snapshot(models: [qwen, embed])
29+ let config = ServerConfig(models: [
30+ ModelEntry(id: "q", source: .huggingFace(id: "org/qwen", revision: "main")),
31+ ModelEntry(
32+ id: "small", source: .huggingFace(id: "org/small", revision: "main"),
33+ kind: .embedding),
34+ ])
35+ let cache = [
36+ stored("org/qwen"), stored("org/embed"), stored("org/small"),
37+ stored("x/gguf", loadable: false),
38+ ]
39+ let rows = ModelRow.rows(cache, status: status, config: config)
40+ #expect(rows.map(\.id) == ["org/qwen", "org/embed", "org/small"])
41+ #expect(rows[0].loaded && rows[0].kind == "chat" && rows[0].declaredAs == ["q"])
42+ #expect(rows[1].loaded && rows[1].kind == "embedding" && rows[1].declaredAs.isEmpty)
43+ #expect(!rows[2].loaded && rows[2].kind == "embedding" && rows[2].declaredAs == ["small"])
44+ #expect(ModelRow.rows([stored("a/b")], status: nil, config: nil).first?.kind == nil)
45+ }
46+}
47+
48+@Suite struct ModelsScreenTests {
49+ func screen(_ ids: [String] = ["org/a", "org/b"]) -> ModelsScreen {
50+ var screen = ModelsScreen()
51+ screen.setRows(ModelRow.rows(ids.map { stored($0) }, status: nil, config: nil))
52+ return screen
53+ }
54+
55+ @Test func pTypesAnIdAndEnterDownloadsIt() {
56+ var screen = screen()
57+ #expect(screen.handle(.character("p")) == .redraw)
58+ for character in "org/new" { _ = screen.handle(.character(character)) }
59+ #expect(screen.handle(.enter) == .pull("org/new"))
60+ #expect(screen.mode == .browsing)
61+ }
62+
63+ @Test func aBadIdIsExplainedAndEscapeLeaves() {
64+ var screen = screen()
65+ _ = screen.handle(.character("p"))
66+ _ = screen.handle(.character("x"))
67+ #expect(screen.handle(.enter) == .redraw)
68+ #expect(screen.notice == "a Hugging Face id looks like org/name")
69+ _ = screen.handle(.escape)
70+ #expect(screen.mode == .browsing)
71+ }
72+
73+ @Test func removalNeedsAYes() {
74+ var screen = screen()
75+ _ = screen.handle(.arrowDown)
76+ #expect(screen.handle(.character("d")) == .redraw)
77+ #expect(screen.mode == .confirmingRemoval("org/b"))
78+ #expect(screen.handle(.character("n")) == .redraw)
79+ #expect(screen.notice == "kept org/b")
80+ _ = screen.handle(.delete)
81+ #expect(screen.handle(.character("y")) == .remove("org/b"))
82+ #expect(screen.handle(.character("r")) == .refresh)
83+ var empty = ModelsScreen()
84+ #expect(empty.handle(.character("d")) == .none)
85+ }
86+
87+ @Test func rendersColumnsDownloadsHintAndPrompt() {
88+ var screen = screen(["org/big"])
89+ screen.downloads["org/new"] = 0.42
90+ let memory = EngineMemory(
91+ activeBytes: (31 << 30) - (1 << 29), cacheBytes: 0, peakBytes: 0, limitBytes: 31 << 30)
92+ let renderer = ModelsRenderer(style: plain)
93+ var (lines, cursor) = renderer.render(screen, memory: memory, width: 120, height: 14)
94+ #expect(lines.count == 14 && cursor == nil)
95+ #expect(lines.contains { $0.contains("org/big") && $0.contains("1.0 GB") })
96+ #expect(lines.contains { $0.contains("↓ org/new") && $0.hasSuffix("42%") })
97+ #expect(lines.contains { $0.contains("more than is free now") })
98+ _ = screen.handle(.character("p"))
99+ _ = screen.handle(.character("o"))
100+ (lines, cursor) = renderer.render(screen, memory: nil, width: 120, height: 14)
101+ #expect(lines.last == " Download (Enter, Esc): o")
102+ #expect(cursor?.row == 13 && cursor?.column == " Download (Enter, Esc): o".count)
103+ _ = screen.handle(.escape)
104+ _ = screen.handle(.character("d"))
105+ (lines, _) = renderer.render(screen, memory: nil, width: 120, height: 14)
106+ #expect(lines.last == " Remove org/big from the disk? y / n")
107+ }
108+
109+ @Test func emptyCacheSaysHowToStart() {
110+ let lines = ModelsRenderer(style: plain).render(
111+ ModelsScreen(), memory: nil, width: 100, height: 10
112+ ).lines
113+ #expect(lines.contains { $0.contains("p to download one") })
114+ }
115+}
116+
117+@Suite struct SettingsScreenTests {
118+ @Test func formShowsThePreferencesAndReadsThemBack() throws {
119+ var preferences = TUIPreferences()
120+ preferences.serverURL = "http://127.0.0.1:8000"
121+ preferences.reasoning = "shown"
122+ preferences.colors = false
123+ preferences.pollInterval = .milliseconds(500)
124+ preferences.chat.temperature = 0.4
125+ preferences.chat.thinking = false
126+ let values = SettingsScreen.text(of: preferences)
127+ #expect(values[0] == "http://127.0.0.1:8000" && values[4] == "500ms")
128+ #expect(values[3] == "off" && values[10] == "off")
129+ #expect(try SettingsScreen.preferences(from: values) == preferences)
130+ #expect(SettingsScreen.durationText(.seconds(2)) == "2s")
131+ }
132+
133+ @Test func enterSavesAndAWrongFieldIsNamed() {
134+ var settings = SettingsScreen(preferences: TUIPreferences())
135+ #expect(settings.handle(.enter) == .save(TUIPreferences()))
136+ for _ in 0 ..< 2 { _ = settings.handle(.tab) }
137+ for character in "loud" { _ = settings.handle(.character(character)) }
138+ #expect(settings.handle(.enter) == .redraw)
139+ #expect(settings.notice == "Reasoning is shown, folded or hidden")
140+ #expect(settings.handle(.escape) == .redraw)
141+ #expect(settings.form.values[2] == "" && settings.notice == "changes undone")
142+ }
143+
144+ @Test(arguments: [
145+ (0, "ftp://x", "Server URL must start with http://"), (3, "maybe", "Colours is on or off"),
146+ (4, "soon", "Poll interval is a duration: 500ms, 2s"),
147+ (5, "9", "temperature is a number from 0 to 2"),
148+ ])
149+ func invalidFields(_ index: Int, _ value: String, _ message: String) {
150+ var values = Array(repeating: "", count: SettingsScreen.fields.count)
151+ values[index] = value
152+ #expect(throws: ChatOptions.Invalid(description: message)) {
153+ try SettingsScreen.preferences(from: values)
154+ }
155+ }
156+
157+ @Test func controlKeysForTheServerFile() {
158+ var settings = SettingsScreen(preferences: TUIPreferences())
159+ #expect(settings.handle(.control("o")) == .editServerConfig)
160+ #expect(settings.handle(.control("r")) == .reloadServer)
161+ #expect(settings.handle(.function(7)) == .none)
162+ }
163+
164+ @Test func rendersBothSections() {
165+ let settings = SettingsScreen(preferences: TUIPreferences())
166+ let (lines, cursor) = SettingsRenderer(style: plain).render(
167+ settings, preferencesFile: "/home/a/tui.yaml", serverConfigFile: nil, width: 120,
168+ height: 30)
169+ #expect(lines[1].contains("TUI preferences") && lines[2] == " file: /home/a/tui.yaml")
170+ #expect(lines.contains { $0.contains("Server URL:") })
171+ #expect(lines.contains { $0.contains("the server runs without --config") })
172+ #expect(cursor?.row == 4)
173+ }
174+}
175+
176+@Suite struct TUIAppModelsAndSettingsTests {
177+ func app(
178+ _ terminal: FakeTerminal, _ server: ScriptedServer, _ environment: TUIEnvironment
179+ ) -> TUIApp {
180+ TUIApp(
181+ terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
182+ pollInterval: .milliseconds(10), environment: environment)
183+ }
184+
185+ @Test func downloadShowsItsProgressThenTheModel() async throws {
186+ let terminal = FakeTerminal(rows: 24, columns: 120)
187+ let started = AsyncStream<Void>.makeStream()
188+ let finish = AsyncStream<Void>.makeStream()
189+ var environment = testEnvironment()
190+ let store = environment.store
191+ environment.download = { model, progress in
192+ progress(0.5)
193+ started.continuation.yield()
194+ for await _ in finish.stream { break }
195+ try cache(model.description, size: 2048, in: store)
196+ progress(1)
197+ }
198+ let app = app(terminal, ScriptedServer(.success(snapshot())), environment)
199+ let running = Task { await app.run() }
200+ terminal.press(.function(3))
201+ try await waitForScreen(terminal, containing: "no MLX model in the cache yet")
202+ terminal.press(.character("p"))
203+ terminal.type("org/new")
204+ terminal.press(.enter)
205+ for await _ in started.stream { break }
206+ try await waitForScreen(terminal, containing: "↓ org/new")
207+ finish.continuation.yield()
208+ try await waitForScreen(terminal, containing: "downloaded org/new")
209+ #expect(terminal.lastText.contains { $0.hasPrefix(" org/new") })
210+ terminal.press(.control("q"))
211+ await running.value
212+ }
213+
214+ @Test func removingALoadedModelUnloadsItFirst() async throws {
215+ let terminal = FakeTerminal(rows: 24, columns: 120)
216+ let environment = testEnvironment()
217+ try cache("org/qwen", size: 1024, in: environment.store)
218+ let server = ScriptedServer(.success(snapshot(models: [qwen])))
219+ let app = app(terminal, server, environment)
220+ let running = Task { await app.run() }
221+ try await waitForScreen(terminal, containing: "unloads in")
222+ terminal.press(.function(3))
223+ try await waitForScreen(terminal, containing: "org/qwen")
224+ server.unloadAnswer = .failure(
225+ .server(status: 409, code: "model_busy", message: "'org/qwen' is in use"))
226+ terminal.type("dy")
227+ try await waitForScreen(terminal, containing: "not removed: 'org/qwen' is in use")
228+ #expect(try environment.store.list().map(\.id) == ["org/qwen"])
229+ server.unloadAnswer = .success(
230+ UnloadReply(model: "org/qwen", status: "unloaded", unloaded: ["org/qwen"]))
231+ terminal.type("dy")
232+ try await waitForScreen(terminal, containing: "removed org/qwen")
233+ #expect(try environment.store.list().isEmpty)
234+ #expect(server.unloads == ["org/qwen", "org/qwen"])
235+ terminal.press(.control("q"))
236+ await running.value
237+ }
238+
239+ @Test func savedPreferencesAreWrittenAndApplied() async throws {
240+ let terminal = FakeTerminal(rows: 30, columns: 120)
241+ let environment = testEnvironment()
242+ let app = app(terminal, ScriptedServer(.success(snapshot())), environment)
243+ let running = Task { await app.run() }
244+ terminal.press(.function(4))
245+ try await waitForScreen(terminal, containing: "TUI preferences")
246+ for _ in 0 ..< 2 { terminal.press(.tab) }
247+ terminal.type("hidden")
248+ for _ in 0 ..< 3 { terminal.press(.tab) }
249+ terminal.type("0.3")
250+ terminal.press(.enter)
251+ try await waitForScreen(terminal, containing: "saved to")
252+ let saved = try TUIPreferencesLoader().load(file: environment.preferencesFile)
253+ #expect(saved.reasoning == "hidden" && saved.chat.temperature == 0.3)
254+ #expect(await app.chatScreen.reasoning == .hidden)
255+ #expect(await app.chatScreen.options.temperature == 0.3)
256+ terminal.press(.control("q"))
257+ await running.value
258+ }
259+
260+ @Test func editedServerFileIsCheckedThenReloaded() async throws {
261+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
262+ "rzb-edit-\(UUID().uuidString)")
263+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
264+ let file = folder.appendingPathComponent("server.yaml").path
265+ try "{}\n".write(toFile: file, atomically: true, encoding: .utf8)
266+ let edits = EditQueue(["limits: { max_queue: 0 }\n", "limits: { max_queue: 2 }\n"])
267+ let environment = testEnvironment(configFile: file) { path in
268+ try? edits.next().write(toFile: path, atomically: true, encoding: .utf8)
269+ }
270+ let terminal = FakeTerminal(rows: 30, columns: 120)
271+ let server = ScriptedServer(.success(snapshot()))
272+ let app = app(terminal, server, environment)
273+ let running = Task { await app.run() }
274+ terminal.press(.function(4))
275+ try await waitForScreen(terminal, containing: file)
276+ terminal.press(.control("o"))
277+ try await waitForScreen(terminal, containing: "limits.max_queue")
278+ try await waitForScreen(terminal, containing: "The server keeps its configuration")
279+ #expect(server.reloads == 0)
280+ terminal.press(.control("o"))
281+ try await waitForScreen(terminal, containing: "restart the server to apply port")
282+ #expect(server.reloads == 1)
283+ #expect(terminal.suspendCount == 2 && terminal.resumeCount == 2)
284+ terminal.press(.control("q"))
285+ await running.value
286+ }
287+
288+ @Test func withoutAServerFileThereIsNothingToEdit() async throws {
289+ let terminal = FakeTerminal(rows: 30, columns: 120)
290+ let server = ScriptedServer(.success(snapshot()))
291+ server.reloadAnswer = .failure(
292+ .server(status: 409, code: "no_config_file", message: "no file to reload"))
293+ let app = app(terminal, server, testEnvironment())
294+ let running = Task { await app.run() }
295+ terminal.press(.function(4))
296+ try await waitForScreen(terminal, containing: "the server runs without --config")
297+ terminal.press(.control("o"))
298+ try await waitForScreen(terminal, containing: "there is no file to edit")
299+ terminal.press(.control("r"))
300+ try await waitForScreen(terminal, containing: "no file to reload")
301+ #expect(terminal.suspendCount == 0)
302+ terminal.press(.control("q"))
303+ await running.value
304+ }
305+}
306+
307+/// The texts a fake editor writes, one per call.
308+final class EditQueue: @unchecked Sendable {
309+ private let lock = NSLock()
310+ private var texts: [String]
311+
312+ init(_ texts: [String]) { self.texts = texts }
313+
314+ func next() -> String { lock.withLock { texts.isEmpty ? "" : texts.removeFirst() } }
315+}
new file mode 100644
@@ -0,0 +1,315 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@testable import RazorbillTUI
6+
7+/// Puts an MLX model of `size` bytes in `store`'s cache, as a download leaves it.
8+func cache(_ id: String, size: Int, in store: ModelStore) throws {
9+ let snapshot = store.directory(for: id).appendingPathComponent("snapshots/c1")
10+ let refs = store.directory(for: id).appendingPathComponent("refs")
11+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
12+ try FileManager.default.createDirectory(at: refs, withIntermediateDirectories: true)
13+ try "c1".write(to: refs.appendingPathComponent("main"), atomically: true, encoding: .utf8)
14+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
15+ try Data(count: size).write(to: snapshot.appendingPathComponent("model.safetensors"))
16+}
17+
18+func stored(_ id: String, size: Int64 = 1 << 30, loadable: Bool = true) -> StoredModel {
19+ StoredModel(
20+ id: id, sizeInBytes: size, revisions: ["main"],
21+ directory: URL(fileURLWithPath: "/tmp/\(id)"), isLoadable: loadable)
22+}
23+
24+@Suite struct ModelRowTests {
25+ @Test func marksLoadedDeclaredAndKind() {
26+ var embed = qwen
27+ embed.key = "org/embed#embedding"
28+ let status = snapshot(models: [qwen, embed])
29+ let config = ServerConfig(models: [
30+ ModelEntry(id: "q", source: .huggingFace(id: "org/qwen", revision: "main")),
31+ ModelEntry(
32+ id: "small", source: .huggingFace(id: "org/small", revision: "main"),
33+ kind: .embedding),
34+ ])
35+ let cache = [
36+ stored("org/qwen"), stored("org/embed"), stored("org/small"),
37+ stored("x/gguf", loadable: false),
38+ ]
39+ let rows = ModelRow.rows(cache, status: status, config: config)
40+ #expect(rows.map(\.id) == ["org/qwen", "org/embed", "org/small"])
41+ #expect(rows[0].loaded && rows[0].kind == "chat" && rows[0].declaredAs == ["q"])
42+ #expect(rows[1].loaded && rows[1].kind == "embedding" && rows[1].declaredAs.isEmpty)
43+ #expect(!rows[2].loaded && rows[2].kind == "embedding" && rows[2].declaredAs == ["small"])
44+ #expect(ModelRow.rows([stored("a/b")], status: nil, config: nil).first?.kind == nil)
45+ }
46+}
47+
48+@Suite struct ModelsScreenTests {
49+ func screen(_ ids: [String] = ["org/a", "org/b"]) -> ModelsScreen {
50+ var screen = ModelsScreen()
51+ screen.setRows(ModelRow.rows(ids.map { stored($0) }, status: nil, config: nil))
52+ return screen
53+ }
54+
55+ @Test func pTypesAnIdAndEnterDownloadsIt() {
56+ var screen = screen()
57+ #expect(screen.handle(.character("p")) == .redraw)
58+ for character in "org/new" { _ = screen.handle(.character(character)) }
59+ #expect(screen.handle(.enter) == .pull("org/new"))
60+ #expect(screen.mode == .browsing)
61+ }
62+
63+ @Test func aBadIdIsExplainedAndEscapeLeaves() {
64+ var screen = screen()
65+ _ = screen.handle(.character("p"))
66+ _ = screen.handle(.character("x"))
67+ #expect(screen.handle(.enter) == .redraw)
68+ #expect(screen.notice == "a Hugging Face id looks like org/name")
69+ _ = screen.handle(.escape)
70+ #expect(screen.mode == .browsing)
71+ }
72+
73+ @Test func removalNeedsAYes() {
74+ var screen = screen()
75+ _ = screen.handle(.arrowDown)
76+ #expect(screen.handle(.character("d")) == .redraw)
77+ #expect(screen.mode == .confirmingRemoval("org/b"))
78+ #expect(screen.handle(.character("n")) == .redraw)
79+ #expect(screen.notice == "kept org/b")
80+ _ = screen.handle(.delete)
81+ #expect(screen.handle(.character("y")) == .remove("org/b"))
82+ #expect(screen.handle(.character("r")) == .refresh)
83+ var empty = ModelsScreen()
84+ #expect(empty.handle(.character("d")) == .none)
85+ }
86+
87+ @Test func rendersColumnsDownloadsHintAndPrompt() {
88+ var screen = screen(["org/big"])
89+ screen.downloads["org/new"] = 0.42
90+ let memory = EngineMemory(
91+ activeBytes: (31 << 30) - (1 << 29), cacheBytes: 0, peakBytes: 0, limitBytes: 31 << 30)
92+ let renderer = ModelsRenderer(style: plain)
93+ var (lines, cursor) = renderer.render(screen, memory: memory, width: 120, height: 14)
94+ #expect(lines.count == 14 && cursor == nil)
95+ #expect(lines.contains { $0.contains("org/big") && $0.contains("1.0 GB") })
96+ #expect(lines.contains { $0.contains("↓ org/new") && $0.hasSuffix("42%") })
97+ #expect(lines.contains { $0.contains("more than is free now") })
98+ _ = screen.handle(.character("p"))
99+ _ = screen.handle(.character("o"))
100+ (lines, cursor) = renderer.render(screen, memory: nil, width: 120, height: 14)
101+ #expect(lines.last == " Download (Enter, Esc): o")
102+ #expect(cursor?.row == 13 && cursor?.column == " Download (Enter, Esc): o".count)
103+ _ = screen.handle(.escape)
104+ _ = screen.handle(.character("d"))
105+ (lines, _) = renderer.render(screen, memory: nil, width: 120, height: 14)
106+ #expect(lines.last == " Remove org/big from the disk? y / n")
107+ }
108+
109+ @Test func emptyCacheSaysHowToStart() {
110+ let lines = ModelsRenderer(style: plain).render(
111+ ModelsScreen(), memory: nil, width: 100, height: 10
112+ ).lines
113+ #expect(lines.contains { $0.contains("p to download one") })
114+ }
115+}
116+
117+@Suite struct SettingsScreenTests {
118+ @Test func formShowsThePreferencesAndReadsThemBack() throws {
119+ var preferences = TUIPreferences()
120+ preferences.serverURL = "http://127.0.0.1:8000"
121+ preferences.reasoning = "shown"
122+ preferences.colors = false
123+ preferences.pollInterval = .milliseconds(500)
124+ preferences.chat.temperature = 0.4
125+ preferences.chat.thinking = false
126+ let values = SettingsScreen.text(of: preferences)
127+ #expect(values[0] == "http://127.0.0.1:8000" && values[4] == "500ms")
128+ #expect(values[3] == "off" && values[10] == "off")
129+ #expect(try SettingsScreen.preferences(from: values) == preferences)
130+ #expect(SettingsScreen.durationText(.seconds(2)) == "2s")
131+ }
132+
133+ @Test func enterSavesAndAWrongFieldIsNamed() {
134+ var settings = SettingsScreen(preferences: TUIPreferences())
135+ #expect(settings.handle(.enter) == .save(TUIPreferences()))
136+ for _ in 0 ..< 2 { _ = settings.handle(.tab) }
137+ for character in "loud" { _ = settings.handle(.character(character)) }
138+ #expect(settings.handle(.enter) == .redraw)
139+ #expect(settings.notice == "Reasoning is shown, folded or hidden")
140+ #expect(settings.handle(.escape) == .redraw)
141+ #expect(settings.form.values[2] == "" && settings.notice == "changes undone")
142+ }
143+
144+ @Test(arguments: [
145+ (0, "ftp://x", "Server URL must start with http://"), (3, "maybe", "Colours is on or off"),
146+ (4, "soon", "Poll interval is a duration: 500ms, 2s"),
147+ (5, "9", "temperature is a number from 0 to 2"),
148+ ])
149+ func invalidFields(_ index: Int, _ value: String, _ message: String) {
150+ var values = Array(repeating: "", count: SettingsScreen.fields.count)
151+ values[index] = value
152+ #expect(throws: ChatOptions.Invalid(description: message)) {
153+ try SettingsScreen.preferences(from: values)
154+ }
155+ }
156+
157+ @Test func controlKeysForTheServerFile() {
158+ var settings = SettingsScreen(preferences: TUIPreferences())
159+ #expect(settings.handle(.control("o")) == .editServerConfig)
160+ #expect(settings.handle(.control("r")) == .reloadServer)
161+ #expect(settings.handle(.function(7)) == .none)
162+ }
163+
164+ @Test func rendersBothSections() {
165+ let settings = SettingsScreen(preferences: TUIPreferences())
166+ let (lines, cursor) = SettingsRenderer(style: plain).render(
167+ settings, preferencesFile: "/home/a/tui.yaml", serverConfigFile: nil, width: 120,
168+ height: 30)
169+ #expect(lines[1].contains("TUI preferences") && lines[2] == " file: /home/a/tui.yaml")
170+ #expect(lines.contains { $0.contains("Server URL:") })
171+ #expect(lines.contains { $0.contains("the server runs without --config") })
172+ #expect(cursor?.row == 4)
173+ }
174+}
175+
176+@Suite struct TUIAppModelsAndSettingsTests {
177+ func app(
178+ _ terminal: FakeTerminal, _ server: ScriptedServer, _ environment: TUIEnvironment
179+ ) -> TUIApp {
180+ TUIApp(
181+ terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
182+ pollInterval: .milliseconds(10), environment: environment)
183+ }
184+
185+ @Test func downloadShowsItsProgressThenTheModel() async throws {
186+ let terminal = FakeTerminal(rows: 24, columns: 120)
187+ let started = AsyncStream<Void>.makeStream()
188+ let finish = AsyncStream<Void>.makeStream()
189+ var environment = testEnvironment()
190+ let store = environment.store
191+ environment.download = { model, progress in
192+ progress(0.5)
193+ started.continuation.yield()
194+ for await _ in finish.stream { break }
195+ try cache(model.description, size: 2048, in: store)
196+ progress(1)
197+ }
198+ let app = app(terminal, ScriptedServer(.success(snapshot())), environment)
199+ let running = Task { await app.run() }
200+ terminal.press(.function(3))
201+ try await waitForScreen(terminal, containing: "no MLX model in the cache yet")
202+ terminal.press(.character("p"))
203+ terminal.type("org/new")
204+ terminal.press(.enter)
205+ for await _ in started.stream { break }
206+ try await waitForScreen(terminal, containing: "↓ org/new")
207+ finish.continuation.yield()
208+ try await waitForScreen(terminal, containing: "downloaded org/new")
209+ #expect(terminal.lastText.contains { $0.hasPrefix(" org/new") })
210+ terminal.press(.control("q"))
211+ await running.value
212+ }
213+
214+ @Test func removingALoadedModelUnloadsItFirst() async throws {
215+ let terminal = FakeTerminal(rows: 24, columns: 120)
216+ let environment = testEnvironment()
217+ try cache("org/qwen", size: 1024, in: environment.store)
218+ let server = ScriptedServer(.success(snapshot(models: [qwen])))
219+ let app = app(terminal, server, environment)
220+ let running = Task { await app.run() }
221+ try await waitForScreen(terminal, containing: "unloads in")
222+ terminal.press(.function(3))
223+ try await waitForScreen(terminal, containing: "org/qwen")
224+ server.unloadAnswer = .failure(
225+ .server(status: 409, code: "model_busy", message: "'org/qwen' is in use"))
226+ terminal.type("dy")
227+ try await waitForScreen(terminal, containing: "not removed: 'org/qwen' is in use")
228+ #expect(try environment.store.list().map(\.id) == ["org/qwen"])
229+ server.unloadAnswer = .success(
230+ UnloadReply(model: "org/qwen", status: "unloaded", unloaded: ["org/qwen"]))
231+ terminal.type("dy")
232+ try await waitForScreen(terminal, containing: "removed org/qwen")
233+ #expect(try environment.store.list().isEmpty)
234+ #expect(server.unloads == ["org/qwen", "org/qwen"])
235+ terminal.press(.control("q"))
236+ await running.value
237+ }
238+
239+ @Test func savedPreferencesAreWrittenAndApplied() async throws {
240+ let terminal = FakeTerminal(rows: 30, columns: 120)
241+ let environment = testEnvironment()
242+ let app = app(terminal, ScriptedServer(.success(snapshot())), environment)
243+ let running = Task { await app.run() }
244+ terminal.press(.function(4))
245+ try await waitForScreen(terminal, containing: "TUI preferences")
246+ for _ in 0 ..< 2 { terminal.press(.tab) }
247+ terminal.type("hidden")
248+ for _ in 0 ..< 3 { terminal.press(.tab) }
249+ terminal.type("0.3")
250+ terminal.press(.enter)
251+ try await waitForScreen(terminal, containing: "saved to")
252+ let saved = try TUIPreferencesLoader().load(file: environment.preferencesFile)
253+ #expect(saved.reasoning == "hidden" && saved.chat.temperature == 0.3)
254+ #expect(await app.chatScreen.reasoning == .hidden)
255+ #expect(await app.chatScreen.options.temperature == 0.3)
256+ terminal.press(.control("q"))
257+ await running.value
258+ }
259+
260+ @Test func editedServerFileIsCheckedThenReloaded() async throws {
261+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
262+ "rzb-edit-\(UUID().uuidString)")
263+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
264+ let file = folder.appendingPathComponent("server.yaml").path
265+ try "{}\n".write(toFile: file, atomically: true, encoding: .utf8)
266+ let edits = EditQueue(["limits: { max_queue: 0 }\n", "limits: { max_queue: 2 }\n"])
267+ let environment = testEnvironment(configFile: file) { path in
268+ try? edits.next().write(toFile: path, atomically: true, encoding: .utf8)
269+ }
270+ let terminal = FakeTerminal(rows: 30, columns: 120)
271+ let server = ScriptedServer(.success(snapshot()))
272+ let app = app(terminal, server, environment)
273+ let running = Task { await app.run() }
274+ terminal.press(.function(4))
275+ try await waitForScreen(terminal, containing: file)
276+ terminal.press(.control("o"))
277+ try await waitForScreen(terminal, containing: "limits.max_queue")
278+ try await waitForScreen(terminal, containing: "The server keeps its configuration")
279+ #expect(server.reloads == 0)
280+ terminal.press(.control("o"))
281+ try await waitForScreen(terminal, containing: "restart the server to apply port")
282+ #expect(server.reloads == 1)
283+ #expect(terminal.suspendCount == 2 && terminal.resumeCount == 2)
284+ terminal.press(.control("q"))
285+ await running.value
286+ }
287+
288+ @Test func withoutAServerFileThereIsNothingToEdit() async throws {
289+ let terminal = FakeTerminal(rows: 30, columns: 120)
290+ let server = ScriptedServer(.success(snapshot()))
291+ server.reloadAnswer = .failure(
292+ .server(status: 409, code: "no_config_file", message: "no file to reload"))
293+ let app = app(terminal, server, testEnvironment())
294+ let running = Task { await app.run() }
295+ terminal.press(.function(4))
296+ try await waitForScreen(terminal, containing: "the server runs without --config")
297+ terminal.press(.control("o"))
298+ try await waitForScreen(terminal, containing: "there is no file to edit")
299+ terminal.press(.control("r"))
300+ try await waitForScreen(terminal, containing: "no file to reload")
301+ #expect(terminal.suspendCount == 0)
302+ terminal.press(.control("q"))
303+ await running.value
304+ }
305+}
306+
307+/// The texts a fake editor writes, one per call.
308+final class EditQueue: @unchecked Sendable {
309+ private let lock = NSLock()
310+ private var texts: [String]
311+
312+ init(_ texts: [String]) { self.texts = texts }
313+
314+ func next() -> String { lock.withLock { texts.isEmpty ? "" : texts.removeFirst() } }
315+}
modified Tests/RazorbillTUITests/ServerClientTests.swift +2 -2
@@ -171,7 +171,7 @@ extension ServerClientError {
171171 let terminal = FakeTerminal(rows: 20, columns: 100)
172172 let app = TUIApp(
173173 terminal: terminal, server: client, serverURL: url, colors: false,
174- pollInterval: .milliseconds(10))
174+ pollInterval: .milliseconds(10), environment: testEnvironment())
175175 let running = Task { await app.run() }
176176 try await waitForScreen(terminal, containing: "none loaded")
177177 let ping = [ChatTurn(role: "user", content: "ping")]
@@ -195,7 +195,7 @@ extension ServerClientError {
195195 let terminal = FakeTerminal(rows: 20, columns: 100)
196196 let app = TUIApp(
197197 terminal: terminal, server: client, serverURL: url, colors: false,
198- pollInterval: .milliseconds(10))
198+ pollInterval: .milliseconds(10), environment: testEnvironment())
199199 let running = Task { await app.run() }
200200 terminal.press(.function(1))
201201 try await waitForScreen(terminal, containing: "Ctrl-P model: echo")
@@ -171,7 +171,7 @@ extension ServerClientError {
171 let terminal = FakeTerminal(rows: 20, columns: 100)171 let terminal = FakeTerminal(rows: 20, columns: 100)
172 let app = TUIApp(172 let app = TUIApp(
173 terminal: terminal, server: client, serverURL: url, colors: false,173 terminal: terminal, server: client, serverURL: url, colors: false,
174- pollInterval: .milliseconds(10))174+ pollInterval: .milliseconds(10), environment: testEnvironment())
175 let running = Task { await app.run() }175 let running = Task { await app.run() }
176 try await waitForScreen(terminal, containing: "none loaded")176 try await waitForScreen(terminal, containing: "none loaded")
177 let ping = [ChatTurn(role: "user", content: "ping")]177 let ping = [ChatTurn(role: "user", content: "ping")]
@@ -195,7 +195,7 @@ extension ServerClientError {
195 let terminal = FakeTerminal(rows: 20, columns: 100)195 let terminal = FakeTerminal(rows: 20, columns: 100)
196 let app = TUIApp(196 let app = TUIApp(
197 terminal: terminal, server: client, serverURL: url, colors: false,197 terminal: terminal, server: client, serverURL: url, colors: false,
198- pollInterval: .milliseconds(10))198+ pollInterval: .milliseconds(10), environment: testEnvironment())
199 let running = Task { await app.run() }199 let running = Task { await app.run() }
200 terminal.press(.function(1))200 terminal.press(.function(1))
201 try await waitForScreen(terminal, containing: "Ctrl-P model: echo")201 try await waitForScreen(terminal, containing: "Ctrl-P model: echo")
modified Tests/RazorbillTUITests/TUIAppTests.swift +33 -4
@@ -1,4 +1,5 @@
11 import Foundation
2+import RazorbillCore
23 import Testing
34
45 @testable import RazorbillTUI
@@ -39,6 +40,18 @@ final class ScriptedServer: TUIServer, @unchecked Sendable {
3940
4041 func models() async throws -> [ServedModel] { served }
4142
43+ var reloadAnswer: Result<ReloadReply, ServerClientError> = .success(
44+ ReloadReply(
45+ file: "/srv/server.yaml", declaredModels: 2, unloaded: ["org/old"], unloadWhenIdle: [],
46+ restartRequired: ["port"]))
47+ private var reloaded = 0
48+ var reloads: Int { lock.withLock { reloaded } }
49+
50+ func reload() async throws -> ReloadReply {
51+ lock.withLock { reloaded += 1 }
52+ return try reloadAnswer.get()
53+ }
54+
4255 func unload(_ id: String) async throws -> UnloadReply {
4356 lock.withLock { unloaded.append(id) }
4457 return try unloadAnswer.get()
@@ -62,6 +75,21 @@ final class ScriptedServer: TUIServer, @unchecked Sendable {
6275 }
6376 }
6477
78+/// An environment in temporary folders: an empty model cache and a preferences file that does not
79+/// exist yet, so tests never touch the real ones.
80+func testEnvironment(
81+ download: TUIEnvironment.Downloader? = nil, configFile: String? = nil,
82+ edit: @escaping TUIEnvironment.Editor = { _ in }
83+) -> TUIEnvironment {
84+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
85+ "rzb-tui-env-\(UUID().uuidString)")
86+ return TUIEnvironment(
87+ store: ModelStore(cacheDirectory: folder.appendingPathComponent("hub")),
88+ download: download,
89+ preferencesFile: folder.appendingPathComponent("tui.yaml").path, configFile: configFile,
90+ edit: edit)
91+}
92+
6593 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
6694 let chat = RecentRequest(
6795 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
@@ -90,7 +118,8 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
90118 TUIApp(
91119 terminal: terminal, server: source, serverURL: "http://127.0.0.1:7920",
92120 startCommand: "rzb serve --config s.yaml", colors: false,
93- pollInterval: .milliseconds(10), now: { Date(timeIntervalSince1970: 60) })
121+ pollInterval: .milliseconds(10), environment: testEnvironment(),
122+ now: { Date(timeIntervalSince1970: 60) })
94123 }
95124
96125 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
@@ -142,15 +171,15 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
142171 #expect(await app.currentState.connection == .connected(version: "0.2.0"))
143172 }
144173
145- @Test func otherScreensWaitForTheirTickets() async throws {
174+ @Test func functionKeysAndControlTReachEveryScreen() async throws {
146175 let terminal = FakeTerminal(rows: 20, columns: 100)
147176 let app = app(terminal, ScriptedServer(.success(snapshot())))
148177 let running = Task { await app.run() }
149178 try await waitForScreen(terminal, containing: "Server rzb")
150179 terminal.press(.function(3))
151- try await waitForScreen(terminal, containing: "Models: coming with #57.")
180+ try await waitForScreen(terminal, containing: "Models in the Hugging Face cache")
152181 terminal.press(.control("t"))
153- try await waitForScreen(terminal, containing: "Settings: coming with #58.")
182+ try await waitForScreen(terminal, containing: "TUI preferences")
154183 terminal.press(.control("c"))
155184 await running.value
156185 #expect(await app.currentState.screen == .settings)
@@ -1,4 +1,5 @@
1 import Foundation1 import Foundation
2+import RazorbillCore
2 import Testing3 import Testing
3 4
4 @testable import RazorbillTUI5 @testable import RazorbillTUI
@@ -39,6 +40,18 @@ final class ScriptedServer: TUIServer, @unchecked Sendable {
39 40
40 func models() async throws -> [ServedModel] { served }41 func models() async throws -> [ServedModel] { served }
41 42
43+ var reloadAnswer: Result<ReloadReply, ServerClientError> = .success(
44+ ReloadReply(
45+ file: "/srv/server.yaml", declaredModels: 2, unloaded: ["org/old"], unloadWhenIdle: [],
46+ restartRequired: ["port"]))
47+ private var reloaded = 0
48+ var reloads: Int { lock.withLock { reloaded } }
49+
50+ func reload() async throws -> ReloadReply {
51+ lock.withLock { reloaded += 1 }
52+ return try reloadAnswer.get()
53+ }
54+
42 func unload(_ id: String) async throws -> UnloadReply {55 func unload(_ id: String) async throws -> UnloadReply {
43 lock.withLock { unloaded.append(id) }56 lock.withLock { unloaded.append(id) }
44 return try unloadAnswer.get()57 return try unloadAnswer.get()
@@ -62,6 +75,21 @@ final class ScriptedServer: TUIServer, @unchecked Sendable {
62 }75 }
63 }76 }
64 77
78+/// An environment in temporary folders: an empty model cache and a preferences file that does not
79+/// exist yet, so tests never touch the real ones.
80+func testEnvironment(
81+ download: TUIEnvironment.Downloader? = nil, configFile: String? = nil,
82+ edit: @escaping TUIEnvironment.Editor = { _ in }
83+) -> TUIEnvironment {
84+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
85+ "rzb-tui-env-\(UUID().uuidString)")
86+ return TUIEnvironment(
87+ store: ModelStore(cacheDirectory: folder.appendingPathComponent("hub")),
88+ download: download,
89+ preferencesFile: folder.appendingPathComponent("tui.yaml").path, configFile: configFile,
90+ edit: edit)
91+}
92+
65 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {93 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
66 let chat = RecentRequest(94 let chat = RecentRequest(
67 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,95 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
@@ -90,7 +118,8 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
90 TUIApp(118 TUIApp(
91 terminal: terminal, server: source, serverURL: "http://127.0.0.1:7920",119 terminal: terminal, server: source, serverURL: "http://127.0.0.1:7920",
92 startCommand: "rzb serve --config s.yaml", colors: false,120 startCommand: "rzb serve --config s.yaml", colors: false,
93- pollInterval: .milliseconds(10), now: { Date(timeIntervalSince1970: 60) })121+ pollInterval: .milliseconds(10), environment: testEnvironment(),
122+ now: { Date(timeIntervalSince1970: 60) })
94 }123 }
95 124
96 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {125 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
@@ -142,15 +171,15 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
142 #expect(await app.currentState.connection == .connected(version: "0.2.0"))171 #expect(await app.currentState.connection == .connected(version: "0.2.0"))
143 }172 }
144 173
145- @Test func otherScreensWaitForTheirTickets() async throws {174+ @Test func functionKeysAndControlTReachEveryScreen() async throws {
146 let terminal = FakeTerminal(rows: 20, columns: 100)175 let terminal = FakeTerminal(rows: 20, columns: 100)
147 let app = app(terminal, ScriptedServer(.success(snapshot())))176 let app = app(terminal, ScriptedServer(.success(snapshot())))
148 let running = Task { await app.run() }177 let running = Task { await app.run() }
149 try await waitForScreen(terminal, containing: "Server rzb")178 try await waitForScreen(terminal, containing: "Server rzb")
150 terminal.press(.function(3))179 terminal.press(.function(3))
151- try await waitForScreen(terminal, containing: "Models: coming with #57.")180+ try await waitForScreen(terminal, containing: "Models in the Hugging Face cache")
152 terminal.press(.control("t"))181 terminal.press(.control("t"))
153- try await waitForScreen(terminal, containing: "Settings: coming with #58.")182+ try await waitForScreen(terminal, containing: "TUI preferences")
154 terminal.press(.control("c"))183 terminal.press(.control("c"))
155 await running.value184 await running.value
156 #expect(await app.currentState.screen == .settings)185 #expect(await app.currentState.screen == .settings)