bots-garden/razorbillpublic Fork
⑂ 19e3378
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

#54 step 4: TUIApp loop — status polling, status bar, minimal Dashboard, not-running screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-26T23:26:19+01:00 Browse files
19e3378 parent: 9d02f90
added Sources/RazorbillTUI/DashboardView.swift +98 -0
new file mode 100644
@@ -0,0 +1,98 @@
1+/// The body of the Dashboard screen for one ``StatusSnapshot``: the server, its memory, the
2+/// loaded models and the last requests. The full dashboard (selection, unload) comes with #56.
3+///
4+/// ```swift
5+/// let lines = DashboardView.lines(snapshot, width: 80, height: 20)
6+/// ```
7+public enum DashboardView {
8+ public static func lines(_ snapshot: StatusSnapshot, width: Int, height: Int) -> [String] {
9+ var lines = [
10+ " Server rzb \(snapshot.version) · up \(duration(seconds: snapshot.uptimeSeconds))"
11+ + " · \(snapshot.host):\(snapshot.port)",
12+ " Memory " + memory(snapshot.memory),
13+ "",
14+ " Models",
15+ ]
16+ lines += snapshot.models.isEmpty ? [" none loaded"] : snapshot.models.map(model)
17+ lines += ["", " Last requests"]
18+ let room = max(0, height - lines.count)
19+ let requests = snapshot.recentRequests.prefix(room).map(request)
20+ lines += requests.isEmpty ? [" none yet"] : requests
21+ return lines.prefix(height).map { TextLayout.truncate($0, width: width) }
22+ }
23+
24+ static func memory(_ memory: EngineMemory?) -> String {
25+ guard let memory else { return "not reported by this engine" }
26+ return [
27+ "active \(AppRenderer.gigabytes(memory.activeBytes))",
28+ "cache \(AppRenderer.gigabytes(memory.cacheBytes))",
29+ "peak \(AppRenderer.gigabytes(memory.peakBytes))",
30+ "limit \(AppRenderer.gigabytes(memory.limitBytes))",
31+ ].joined(separator: " · ")
32+ }
33+
34+ /// ` qwen chat loaded 0.3 GB idle 7s, unloads in 9m 52s`
35+ static func model(_ model: LoadedModel) -> String {
36+ var activity: String
37+ if model.busy || model.queued > 0 {
38+ activity = model.queued > 0 ? "busy, \(model.queued) waiting" : "busy"
39+ } else {
40+ activity = "idle \(duration(seconds: Int(model.idleSeconds)))"
41+ if let left = model.keepAliveLeftSeconds {
42+ activity += ", unloads in \(duration(seconds: Int(left)))"
43+ }
44+ }
45+ let size = model.sizeBytes > 0 ? AppRenderer.gigabytes(model.sizeBytes) : "size ?"
46+ return " \(model.name) \(model.kind) \(model.state) \(size) \(activity)"
47+ }
48+
49+ /// ` POST /v1/chat/completions 200 529ms qwen 14+9`
50+ static func request(_ request: RecentRequest) -> String {
51+ var line = " \(request.method) \(request.path) \(request.status) \(request.durationMs)ms"
52+ if let model = request.model { line += " \(model)" }
53+ if let prompt = request.promptTokens, let completion = request.completionTokens {
54+ line += " \(prompt)+\(completion)"
55+ }
56+ return line
57+ }
58+
59+ /// `45s`, `3m 12s`, `2h 05m`.
60+ static func duration(seconds: Int) -> String {
61+ let seconds = max(0, seconds)
62+ if seconds < 60 { return "\(seconds)s" }
63+ if seconds < 3600 { return "\(seconds / 60)m \(seconds % 60)s" }
64+ let minutes = (seconds % 3600) / 60
65+ return "\(seconds / 3600)h " + (minutes < 10 ? "0\(minutes)" : "\(minutes)") + "m"
66+ }
67+}
68+
69+/// What every screen shows while the server cannot be used: what is wrong and what to do.
70+public enum ConnectionView {
71+ /// `startCommand` is how this user starts the server (`rzb serve --config server.yaml`).
72+ public static func lines(_ state: Connection, url: String, startCommand: String) -> [String]? {
73+ switch state {
74+ case .connected:
75+ return nil
76+ case .connecting:
77+ return ["", " Connecting to \(url)…"]
78+ case .unreachable:
79+ return [
80+ "", " No razorbill server answers at \(url).", "",
81+ " Start one in another terminal:", "", " \(startCommand)", "",
82+ " This screen follows as soon as it answers.",
83+ ]
84+ case .unauthorized:
85+ return [
86+ "", " \(url) needs an API key, and rzb tui sent none or another one.", "",
87+ " Give rzb tui the variable that holds it, as rzb serve has it:", "",
88+ " rzb tui --api-key-env RZB_API_KEY",
89+ ]
90+ case .notLocal:
91+ return [
92+ "", " \(url) is not this machine.", "",
93+ " rzb tui watches a server running on the same machine; run it there,",
94+ " or forward the port: ssh -L 7920:127.0.0.1:7920 <host>",
95+ ]
96+ }
97+ }
98+}
new file mode 100644
@@ -0,0 +1,98 @@
1+/// The body of the Dashboard screen for one ``StatusSnapshot``: the server, its memory, the
2+/// loaded models and the last requests. The full dashboard (selection, unload) comes with #56.
3+///
4+/// ```swift
5+/// let lines = DashboardView.lines(snapshot, width: 80, height: 20)
6+/// ```
7+public enum DashboardView {
8+ public static func lines(_ snapshot: StatusSnapshot, width: Int, height: Int) -> [String] {
9+ var lines = [
10+ " Server rzb \(snapshot.version) · up \(duration(seconds: snapshot.uptimeSeconds))"
11+ + " · \(snapshot.host):\(snapshot.port)",
12+ " Memory " + memory(snapshot.memory),
13+ "",
14+ " Models",
15+ ]
16+ lines += snapshot.models.isEmpty ? [" none loaded"] : snapshot.models.map(model)
17+ lines += ["", " Last requests"]
18+ let room = max(0, height - lines.count)
19+ let requests = snapshot.recentRequests.prefix(room).map(request)
20+ lines += requests.isEmpty ? [" none yet"] : requests
21+ return lines.prefix(height).map { TextLayout.truncate($0, width: width) }
22+ }
23+
24+ static func memory(_ memory: EngineMemory?) -> String {
25+ guard let memory else { return "not reported by this engine" }
26+ return [
27+ "active \(AppRenderer.gigabytes(memory.activeBytes))",
28+ "cache \(AppRenderer.gigabytes(memory.cacheBytes))",
29+ "peak \(AppRenderer.gigabytes(memory.peakBytes))",
30+ "limit \(AppRenderer.gigabytes(memory.limitBytes))",
31+ ].joined(separator: " · ")
32+ }
33+
34+ /// ` qwen chat loaded 0.3 GB idle 7s, unloads in 9m 52s`
35+ static func model(_ model: LoadedModel) -> String {
36+ var activity: String
37+ if model.busy || model.queued > 0 {
38+ activity = model.queued > 0 ? "busy, \(model.queued) waiting" : "busy"
39+ } else {
40+ activity = "idle \(duration(seconds: Int(model.idleSeconds)))"
41+ if let left = model.keepAliveLeftSeconds {
42+ activity += ", unloads in \(duration(seconds: Int(left)))"
43+ }
44+ }
45+ let size = model.sizeBytes > 0 ? AppRenderer.gigabytes(model.sizeBytes) : "size ?"
46+ return " \(model.name) \(model.kind) \(model.state) \(size) \(activity)"
47+ }
48+
49+ /// ` POST /v1/chat/completions 200 529ms qwen 14+9`
50+ static func request(_ request: RecentRequest) -> String {
51+ var line = " \(request.method) \(request.path) \(request.status) \(request.durationMs)ms"
52+ if let model = request.model { line += " \(model)" }
53+ if let prompt = request.promptTokens, let completion = request.completionTokens {
54+ line += " \(prompt)+\(completion)"
55+ }
56+ return line
57+ }
58+
59+ /// `45s`, `3m 12s`, `2h 05m`.
60+ static func duration(seconds: Int) -> String {
61+ let seconds = max(0, seconds)
62+ if seconds < 60 { return "\(seconds)s" }
63+ if seconds < 3600 { return "\(seconds / 60)m \(seconds % 60)s" }
64+ let minutes = (seconds % 3600) / 60
65+ return "\(seconds / 3600)h " + (minutes < 10 ? "0\(minutes)" : "\(minutes)") + "m"
66+ }
67+}
68+
69+/// What every screen shows while the server cannot be used: what is wrong and what to do.
70+public enum ConnectionView {
71+ /// `startCommand` is how this user starts the server (`rzb serve --config server.yaml`).
72+ public static func lines(_ state: Connection, url: String, startCommand: String) -> [String]? {
73+ switch state {
74+ case .connected:
75+ return nil
76+ case .connecting:
77+ return ["", " Connecting to \(url)…"]
78+ case .unreachable:
79+ return [
80+ "", " No razorbill server answers at \(url).", "",
81+ " Start one in another terminal:", "", " \(startCommand)", "",
82+ " This screen follows as soon as it answers.",
83+ ]
84+ case .unauthorized:
85+ return [
86+ "", " \(url) needs an API key, and rzb tui sent none or another one.", "",
87+ " Give rzb tui the variable that holds it, as rzb serve has it:", "",
88+ " rzb tui --api-key-env RZB_API_KEY",
89+ ]
90+ case .notLocal:
91+ return [
92+ "", " \(url) is not this machine.", "",
93+ " rzb tui watches a server running on the same machine; run it there,",
94+ " or forward the port: ssh -L 7920:127.0.0.1:7920 <host>",
95+ ]
96+ }
97+ }
98+}
added Sources/RazorbillTUI/TUIApp.swift +115 -0
new file mode 100644
@@ -0,0 +1,115 @@
1+/// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
2+public protocol StatusSource: Sendable {
3+ func status() async throws -> StatusSnapshot
4+}
5+
6+extension ServerClient: StatusSource {}
7+
8+/// The full-screen app: reads keys, polls the server's status every `pollInterval`, draws.
9+///
10+/// ```swift
11+/// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil)
12+/// await TUIApp(terminal: PosixTerminal(), source: client, serverURL: client.baseURL).run()
13+/// ```
14+public actor TUIApp {
15+ private let terminal: any Terminal
16+ private let source: any StatusSource
17+ private let renderer: AppRenderer
18+ private let pollInterval: Duration
19+ private let startCommand: String
20+ private var state: AppState
21+ private var snapshot: StatusSnapshot?
22+ /// False once `run` returns: a poll still in flight must not draw on the restored terminal.
23+ private var running = false
24+
25+ /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
26+ public init(
27+ terminal: any Terminal, source: any StatusSource, serverURL: String,
28+ startCommand: String = "rzb serve", colors: Bool = true,
29+ pollInterval: Duration = .seconds(1)
30+ ) {
31+ self.terminal = terminal
32+ self.source = source
33+ self.renderer = AppRenderer(style: Style(colors: colors))
34+ self.pollInterval = pollInterval
35+ self.startCommand = startCommand
36+ self.state = AppState(serverURL: serverURL)
37+ }
38+
39+ /// The current state (tests).
40+ public var currentState: AppState { state }
41+
42+ /// Runs until Ctrl-C / Ctrl-Q or the end of input; the terminal is always restored.
43+ public func run() async {
44+ terminal.enter()
45+ running = true
46+ let polling = Task { await poll() }
47+ defer {
48+ running = false
49+ polling.cancel()
50+ terminal.leave()
51+ }
52+ redraw()
53+ for await key in terminal.keys() {
54+ switch state.handle(key) {
55+ case .quit: return
56+ case .redraw: redraw()
57+ case .none: break
58+ }
59+ }
60+ }
61+
62+ private func poll() async {
63+ while !Task.isCancelled {
64+ await refresh()
65+ try? await Task.sleep(for: pollInterval)
66+ }
67+ }
68+
69+ /// Asks the server once and updates the status bar and the Dashboard.
70+ func refresh() async {
71+ do {
72+ let status = try await source.status()
73+ apply(status)
74+ } catch let error as ServerClientError {
75+ if let connection = error.connection { lose(connection) }
76+ } catch {
77+ lose(.unreachable)
78+ }
79+ redraw()
80+ }
81+
82+ private func apply(_ status: StatusSnapshot) {
83+ snapshot = status
84+ state.connection = .connected(version: status.version)
85+ state.model = status.models.first?.name
86+ state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
87+ }
88+
89+ private func lose(_ connection: Connection) {
90+ snapshot = nil
91+ state.connection = connection
92+ state.model = nil
93+ state.memory = nil
94+ }
95+
96+ private func redraw() {
97+ guard running else { return }
98+ let size = terminal.size
99+ let bodyHeight = max(1, size.rows - 2)
100+ terminal.draw(
101+ renderer.render(
102+ state, body: body(width: size.columns, height: bodyHeight), rows: size.rows,
103+ columns: size.columns))
104+ }
105+
106+ private func body(width: Int, height: Int) -> [String] {
107+ let problem = ConnectionView.lines(
108+ state.connection, url: state.serverURL, startCommand: startCommand)
109+ if let problem { return problem }
110+ guard state.screen == .dashboard, let snapshot else {
111+ return AppRenderer.placeholder(for: state.screen)
112+ }
113+ return [""] + DashboardView.lines(snapshot, width: width, height: height - 1)
114+ }
115+}
new file mode 100644
@@ -0,0 +1,115 @@
1+/// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
2+public protocol StatusSource: Sendable {
3+ func status() async throws -> StatusSnapshot
4+}
5+
6+extension ServerClient: StatusSource {}
7+
8+/// The full-screen app: reads keys, polls the server's status every `pollInterval`, draws.
9+///
10+/// ```swift
11+/// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil)
12+/// await TUIApp(terminal: PosixTerminal(), source: client, serverURL: client.baseURL).run()
13+/// ```
14+public actor TUIApp {
15+ private let terminal: any Terminal
16+ private let source: any StatusSource
17+ private let renderer: AppRenderer
18+ private let pollInterval: Duration
19+ private let startCommand: String
20+ private var state: AppState
21+ private var snapshot: StatusSnapshot?
22+ /// False once `run` returns: a poll still in flight must not draw on the restored terminal.
23+ private var running = false
24+
25+ /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
26+ public init(
27+ terminal: any Terminal, source: any StatusSource, serverURL: String,
28+ startCommand: String = "rzb serve", colors: Bool = true,
29+ pollInterval: Duration = .seconds(1)
30+ ) {
31+ self.terminal = terminal
32+ self.source = source
33+ self.renderer = AppRenderer(style: Style(colors: colors))
34+ self.pollInterval = pollInterval
35+ self.startCommand = startCommand
36+ self.state = AppState(serverURL: serverURL)
37+ }
38+
39+ /// The current state (tests).
40+ public var currentState: AppState { state }
41+
42+ /// Runs until Ctrl-C / Ctrl-Q or the end of input; the terminal is always restored.
43+ public func run() async {
44+ terminal.enter()
45+ running = true
46+ let polling = Task { await poll() }
47+ defer {
48+ running = false
49+ polling.cancel()
50+ terminal.leave()
51+ }
52+ redraw()
53+ for await key in terminal.keys() {
54+ switch state.handle(key) {
55+ case .quit: return
56+ case .redraw: redraw()
57+ case .none: break
58+ }
59+ }
60+ }
61+
62+ private func poll() async {
63+ while !Task.isCancelled {
64+ await refresh()
65+ try? await Task.sleep(for: pollInterval)
66+ }
67+ }
68+
69+ /// Asks the server once and updates the status bar and the Dashboard.
70+ func refresh() async {
71+ do {
72+ let status = try await source.status()
73+ apply(status)
74+ } catch let error as ServerClientError {
75+ if let connection = error.connection { lose(connection) }
76+ } catch {
77+ lose(.unreachable)
78+ }
79+ redraw()
80+ }
81+
82+ private func apply(_ status: StatusSnapshot) {
83+ snapshot = status
84+ state.connection = .connected(version: status.version)
85+ state.model = status.models.first?.name
86+ state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
87+ }
88+
89+ private func lose(_ connection: Connection) {
90+ snapshot = nil
91+ state.connection = connection
92+ state.model = nil
93+ state.memory = nil
94+ }
95+
96+ private func redraw() {
97+ guard running else { return }
98+ let size = terminal.size
99+ let bodyHeight = max(1, size.rows - 2)
100+ terminal.draw(
101+ renderer.render(
102+ state, body: body(width: size.columns, height: bodyHeight), rows: size.rows,
103+ columns: size.columns))
104+ }
105+
106+ private func body(width: Int, height: Int) -> [String] {
107+ let problem = ConnectionView.lines(
108+ state.connection, url: state.serverURL, startCommand: startCommand)
109+ if let problem { return problem }
110+ guard state.screen == .dashboard, let snapshot else {
111+ return AppRenderer.placeholder(for: state.screen)
112+ }
113+ return [""] + DashboardView.lines(snapshot, width: width, height: height - 1)
114+ }
115+}
modified Tests/RazorbillTUITests/ServerClientTests.swift +20 -0
@@ -162,3 +162,23 @@ extension ServerClientError {
162162 return ""
163163 }
164164 }
165+
166+@Suite struct TUIAppLiveTests {
167+ @Test func dashboardShowsTheModelOfAChatSentByAnotherClient() async throws {
168+ try await withServer { url in
169+ let client = ServerClient(baseURL: url, apiKey: nil)
170+ let terminal = FakeTerminal(rows: 20, columns: 100)
171+ let app = TUIApp(
172+ terminal: terminal, source: client, serverURL: url, colors: false,
173+ pollInterval: .milliseconds(10))
174+ let running = Task { await app.run() }
175+ try await waitForScreen(terminal, containing: "none loaded")
176+ let ping = [ChatTurn(role: "user", content: "ping")]
177+ for try await _ in client.chat(model: "org/m", messages: ping) {}
178+ try await waitForScreen(terminal, containing: "org/m chat loaded")
179+ try await waitForScreen(terminal, containing: "POST /v1/chat/completions 200")
180+ terminal.press(.control("q"))
181+ await running.value
182+ }
183+ }
184+}
@@ -162,3 +162,23 @@ extension ServerClientError {
162 return ""162 return ""
163 }163 }
164 }164 }
165+
166+@Suite struct TUIAppLiveTests {
167+ @Test func dashboardShowsTheModelOfAChatSentByAnotherClient() async throws {
168+ try await withServer { url in
169+ let client = ServerClient(baseURL: url, apiKey: nil)
170+ let terminal = FakeTerminal(rows: 20, columns: 100)
171+ let app = TUIApp(
172+ terminal: terminal, source: client, serverURL: url, colors: false,
173+ pollInterval: .milliseconds(10))
174+ let running = Task { await app.run() }
175+ try await waitForScreen(terminal, containing: "none loaded")
176+ let ping = [ChatTurn(role: "user", content: "ping")]
177+ for try await _ in client.chat(model: "org/m", messages: ping) {}
178+ try await waitForScreen(terminal, containing: "org/m chat loaded")
179+ try await waitForScreen(terminal, containing: "POST /v1/chat/completions 200")
180+ terminal.press(.control("q"))
181+ await running.value
182+ }
183+ }
184+}
added Tests/RazorbillTUITests/TUIAppTests.swift +165 -0
new file mode 100644
@@ -0,0 +1,165 @@
1+import Foundation
2+import Testing
3+
4+@testable import RazorbillTUI
5+
6+/// A status source that answers what the test sets, one call at a time.
7+final class ScriptedSource: StatusSource, @unchecked Sendable {
8+ private let lock = NSLock()
9+ private var answer: Result<StatusSnapshot, ServerClientError>
10+
11+ init(_ answer: Result<StatusSnapshot, ServerClientError>) {
12+ self.answer = answer
13+ }
14+
15+ func set(_ answer: Result<StatusSnapshot, ServerClientError>) {
16+ lock.withLock { self.answer = answer }
17+ }
18+
19+ func status() async throws -> StatusSnapshot {
20+ try lock.withLock { answer }.get()
21+ }
22+}
23+
24+func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
25+ let chat = RecentRequest(
26+ method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
27+ completionTokens: 9, cachedTokens: 0, durationMs: 529, finishedAt: 0)
28+ return StatusSnapshot(
29+ version: "0.2.0", uptimeSeconds: 192, host: "127.0.0.1", port: 7920, models: models,
30+ recentRequests: [chat], memory: memory)
31+}
32+
33+let qwen = LoadedModel(
34+ key: "org/qwen", name: "qwen", kind: "chat", state: "loaded", sizeBytes: 1 << 30, busy: false,
35+ queued: 0, idleSeconds: 7, keepAliveLeftSeconds: 592.9)
36+
37+/// Waits until the last drawn screen contains `text`.
38+func waitForScreen(_ terminal: FakeTerminal, containing text: String) async throws {
39+ for _ in 0 ..< 400 where !terminal.lastText.joined(separator: "\n").contains(text) {
40+ try await Task.sleep(for: .milliseconds(5))
41+ }
42+ #expect(terminal.lastText.joined(separator: "\n").contains(text))
43+}
44+
45+@Suite struct DashboardViewTests {
46+ @Test func showsServerMemoryModelsAndRequests() {
47+ let memory = EngineMemory(
48+ activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 2 << 30, limitBytes: 32 << 30)
49+ let lines = DashboardView.lines(
50+ snapshot(models: [qwen], memory: memory), width: 100, height: 20)
51+ #expect(lines[0] == " Server rzb 0.2.0 · up 3m 12s · 127.0.0.1:7920")
52+ #expect(lines[1] == " Memory active 1.0 GB · cache 0.0 GB · peak 2.0 GB · limit 32.0 GB")
53+ #expect(lines[4] == " qwen chat loaded 1.0 GB idle 7s, unloads in 9m 52s")
54+ #expect(lines.last == " POST /v1/chat/completions 200 529ms qwen 14+9")
55+ }
56+
57+ @Test func emptyServerAndLinuxEngine() {
58+ var empty = snapshot()
59+ empty.recentRequests = []
60+ let lines = DashboardView.lines(empty, width: 100, height: 20)
61+ #expect(lines.contains(" Memory not reported by this engine"))
62+ #expect(lines.contains(" none loaded") && lines.contains(" none yet"))
63+ }
64+
65+ @Test func busyModelsShowTheirQueueInsteadOfTheCountdown() {
66+ var busy = qwen
67+ busy.busy = true
68+ busy.queued = 2
69+ #expect(DashboardView.model(busy).hasSuffix("busy, 2 waiting"))
70+ }
71+
72+ @Test func requestsFillOnlyTheRoomLeft() {
73+ var many = snapshot()
74+ many.recentRequests = Array(repeating: many.recentRequests[0], count: 50)
75+ #expect(DashboardView.lines(many, width: 80, height: 10).count == 10)
76+ }
77+
78+ @Test(arguments: [(45, "45s"), (192, "3m 12s"), (7500, "2h 05m"), (-3, "0s")])
79+ func durations(_ seconds: Int, _ text: String) {
80+ #expect(DashboardView.duration(seconds: seconds) == text)
81+ }
82+}
83+
84+@Suite struct TUIAppTests {
85+ func app(_ terminal: FakeTerminal, _ source: ScriptedSource) -> TUIApp {
86+ TUIApp(
87+ terminal: terminal, source: source, serverURL: "http://127.0.0.1:7920",
88+ startCommand: "rzb serve --config s.yaml", colors: false,
89+ pollInterval: .milliseconds(10))
90+ }
91+
92+ @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
93+ let terminal = FakeTerminal(rows: 20, columns: 100)
94+ let memory = EngineMemory(
95+ activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 1 << 30, limitBytes: 32 << 30)
96+ let source = ScriptedSource(.success(snapshot(models: [qwen], memory: memory)))
97+ let app = app(terminal, source)
98+ let running = Task { await app.run() }
99+ try await waitForScreen(terminal, containing: "qwen chat loaded")
100+ #expect(
101+ terminal.lastText.last?.hasPrefix(
102+ "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB") == true)
103+ terminal.press(.control("q"))
104+ await running.value
105+ #expect(terminal.enterCount == 1 && terminal.leaveCount == 1)
106+ }
107+
108+ @Test func stoppedServerShowsHowToStartItThenFollowsWhenItAnswers() async throws {
109+ let terminal = FakeTerminal(rows: 20, columns: 100)
110+ let source = ScriptedSource(.failure(.unreachable("refused")))
111+ let app = app(terminal, source)
112+ let running = Task { await app.run() }
113+ try await waitForScreen(terminal, containing: "rzb serve --config s.yaml")
114+ source.set(.success(snapshot()))
115+ try await waitForScreen(terminal, containing: "Server rzb 0.2.0")
116+ source.set(.failure(.unreachable("refused")))
117+ try await waitForScreen(terminal, containing: "No razorbill server answers")
118+ terminal.close()
119+ await running.value
120+ }
121+
122+ @Test func keyProblemsAreExplained() async throws {
123+ let terminal = FakeTerminal(rows: 20, columns: 100)
124+ let app = app(terminal, ScriptedSource(.failure(.unauthorized)))
125+ let running = Task { await app.run() }
126+ try await waitForScreen(terminal, containing: "rzb tui --api-key-env RZB_API_KEY")
127+ terminal.close()
128+ await running.value
129+ }
130+
131+ @Test func requestErrorsDoNotChangeTheConnection() async throws {
132+ let terminal = FakeTerminal()
133+ let source = ScriptedSource(.success(snapshot()))
134+ let app = app(terminal, source)
135+ await app.refresh()
136+ source.set(.failure(.server(status: 500, code: nil, message: "x")))
137+ await app.refresh()
138+ #expect(await app.currentState.connection == .connected(version: "0.2.0"))
139+ }
140+
141+ @Test func otherScreensWaitForTheirTickets() async throws {
142+ let terminal = FakeTerminal(rows: 20, columns: 100)
143+ let app = app(terminal, ScriptedSource(.success(snapshot())))
144+ let running = Task { await app.run() }
145+ try await waitForScreen(terminal, containing: "Server rzb")
146+ terminal.press(.function(3))
147+ try await waitForScreen(terminal, containing: "Models: coming with #57.")
148+ terminal.press(.control("t"))
149+ try await waitForScreen(terminal, containing: "Settings: coming with #58.")
150+ terminal.press(.control("c"))
151+ await running.value
152+ #expect(await app.currentState.screen == .settings)
153+ }
154+
155+ @Test func nothingIsDrawnAfterTheAppReturns() async throws {
156+ let terminal = FakeTerminal()
157+ let app = app(terminal, ScriptedSource(.success(snapshot())))
158+ let running = Task { await app.run() }
159+ terminal.close()
160+ await running.value
161+ let drawn = terminal.screens.count
162+ await app.refresh()
163+ #expect(terminal.screens.count == drawn)
164+ }
165+}
new file mode 100644
@@ -0,0 +1,165 @@
1+import Foundation
2+import Testing
3+
4+@testable import RazorbillTUI
5+
6+/// A status source that answers what the test sets, one call at a time.
7+final class ScriptedSource: StatusSource, @unchecked Sendable {
8+ private let lock = NSLock()
9+ private var answer: Result<StatusSnapshot, ServerClientError>
10+
11+ init(_ answer: Result<StatusSnapshot, ServerClientError>) {
12+ self.answer = answer
13+ }
14+
15+ func set(_ answer: Result<StatusSnapshot, ServerClientError>) {
16+ lock.withLock { self.answer = answer }
17+ }
18+
19+ func status() async throws -> StatusSnapshot {
20+ try lock.withLock { answer }.get()
21+ }
22+}
23+
24+func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
25+ let chat = RecentRequest(
26+ method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
27+ completionTokens: 9, cachedTokens: 0, durationMs: 529, finishedAt: 0)
28+ return StatusSnapshot(
29+ version: "0.2.0", uptimeSeconds: 192, host: "127.0.0.1", port: 7920, models: models,
30+ recentRequests: [chat], memory: memory)
31+}
32+
33+let qwen = LoadedModel(
34+ key: "org/qwen", name: "qwen", kind: "chat", state: "loaded", sizeBytes: 1 << 30, busy: false,
35+ queued: 0, idleSeconds: 7, keepAliveLeftSeconds: 592.9)
36+
37+/// Waits until the last drawn screen contains `text`.
38+func waitForScreen(_ terminal: FakeTerminal, containing text: String) async throws {
39+ for _ in 0 ..< 400 where !terminal.lastText.joined(separator: "\n").contains(text) {
40+ try await Task.sleep(for: .milliseconds(5))
41+ }
42+ #expect(terminal.lastText.joined(separator: "\n").contains(text))
43+}
44+
45+@Suite struct DashboardViewTests {
46+ @Test func showsServerMemoryModelsAndRequests() {
47+ let memory = EngineMemory(
48+ activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 2 << 30, limitBytes: 32 << 30)
49+ let lines = DashboardView.lines(
50+ snapshot(models: [qwen], memory: memory), width: 100, height: 20)
51+ #expect(lines[0] == " Server rzb 0.2.0 · up 3m 12s · 127.0.0.1:7920")
52+ #expect(lines[1] == " Memory active 1.0 GB · cache 0.0 GB · peak 2.0 GB · limit 32.0 GB")
53+ #expect(lines[4] == " qwen chat loaded 1.0 GB idle 7s, unloads in 9m 52s")
54+ #expect(lines.last == " POST /v1/chat/completions 200 529ms qwen 14+9")
55+ }
56+
57+ @Test func emptyServerAndLinuxEngine() {
58+ var empty = snapshot()
59+ empty.recentRequests = []
60+ let lines = DashboardView.lines(empty, width: 100, height: 20)
61+ #expect(lines.contains(" Memory not reported by this engine"))
62+ #expect(lines.contains(" none loaded") && lines.contains(" none yet"))
63+ }
64+
65+ @Test func busyModelsShowTheirQueueInsteadOfTheCountdown() {
66+ var busy = qwen
67+ busy.busy = true
68+ busy.queued = 2
69+ #expect(DashboardView.model(busy).hasSuffix("busy, 2 waiting"))
70+ }
71+
72+ @Test func requestsFillOnlyTheRoomLeft() {
73+ var many = snapshot()
74+ many.recentRequests = Array(repeating: many.recentRequests[0], count: 50)
75+ #expect(DashboardView.lines(many, width: 80, height: 10).count == 10)
76+ }
77+
78+ @Test(arguments: [(45, "45s"), (192, "3m 12s"), (7500, "2h 05m"), (-3, "0s")])
79+ func durations(_ seconds: Int, _ text: String) {
80+ #expect(DashboardView.duration(seconds: seconds) == text)
81+ }
82+}
83+
84+@Suite struct TUIAppTests {
85+ func app(_ terminal: FakeTerminal, _ source: ScriptedSource) -> TUIApp {
86+ TUIApp(
87+ terminal: terminal, source: source, serverURL: "http://127.0.0.1:7920",
88+ startCommand: "rzb serve --config s.yaml", colors: false,
89+ pollInterval: .milliseconds(10))
90+ }
91+
92+ @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
93+ let terminal = FakeTerminal(rows: 20, columns: 100)
94+ let memory = EngineMemory(
95+ activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 1 << 30, limitBytes: 32 << 30)
96+ let source = ScriptedSource(.success(snapshot(models: [qwen], memory: memory)))
97+ let app = app(terminal, source)
98+ let running = Task { await app.run() }
99+ try await waitForScreen(terminal, containing: "qwen chat loaded")
100+ #expect(
101+ terminal.lastText.last?.hasPrefix(
102+ "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB") == true)
103+ terminal.press(.control("q"))
104+ await running.value
105+ #expect(terminal.enterCount == 1 && terminal.leaveCount == 1)
106+ }
107+
108+ @Test func stoppedServerShowsHowToStartItThenFollowsWhenItAnswers() async throws {
109+ let terminal = FakeTerminal(rows: 20, columns: 100)
110+ let source = ScriptedSource(.failure(.unreachable("refused")))
111+ let app = app(terminal, source)
112+ let running = Task { await app.run() }
113+ try await waitForScreen(terminal, containing: "rzb serve --config s.yaml")
114+ source.set(.success(snapshot()))
115+ try await waitForScreen(terminal, containing: "Server rzb 0.2.0")
116+ source.set(.failure(.unreachable("refused")))
117+ try await waitForScreen(terminal, containing: "No razorbill server answers")
118+ terminal.close()
119+ await running.value
120+ }
121+
122+ @Test func keyProblemsAreExplained() async throws {
123+ let terminal = FakeTerminal(rows: 20, columns: 100)
124+ let app = app(terminal, ScriptedSource(.failure(.unauthorized)))
125+ let running = Task { await app.run() }
126+ try await waitForScreen(terminal, containing: "rzb tui --api-key-env RZB_API_KEY")
127+ terminal.close()
128+ await running.value
129+ }
130+
131+ @Test func requestErrorsDoNotChangeTheConnection() async throws {
132+ let terminal = FakeTerminal()
133+ let source = ScriptedSource(.success(snapshot()))
134+ let app = app(terminal, source)
135+ await app.refresh()
136+ source.set(.failure(.server(status: 500, code: nil, message: "x")))
137+ await app.refresh()
138+ #expect(await app.currentState.connection == .connected(version: "0.2.0"))
139+ }
140+
141+ @Test func otherScreensWaitForTheirTickets() async throws {
142+ let terminal = FakeTerminal(rows: 20, columns: 100)
143+ let app = app(terminal, ScriptedSource(.success(snapshot())))
144+ let running = Task { await app.run() }
145+ try await waitForScreen(terminal, containing: "Server rzb")
146+ terminal.press(.function(3))
147+ try await waitForScreen(terminal, containing: "Models: coming with #57.")
148+ terminal.press(.control("t"))
149+ try await waitForScreen(terminal, containing: "Settings: coming with #58.")
150+ terminal.press(.control("c"))
151+ await running.value
152+ #expect(await app.currentState.screen == .settings)
153+ }
154+
155+ @Test func nothingIsDrawnAfterTheAppReturns() async throws {
156+ let terminal = FakeTerminal()
157+ let app = app(terminal, ScriptedSource(.success(snapshot())))
158+ let running = Task { await app.run() }
159+ terminal.close()
160+ await running.value
161+ let drawn = terminal.screens.count
162+ await app.refresh()
163+ #expect(terminal.screens.count == drawn)
164+ }
165+}