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

#56 #55: TUI Dashboard (select, unload, columns) and Chat screen (stream, stop, picker, /set)

Server: streamed answers now record their tokens, and the request history
is written once the last byte is sent (duration_ms to the end, new
first_byte_ms), so the dashboard can show tokens and tok/s for streams.

TUI: DashboardScreen (models list with selection, u unloads, the server's
409 message shown; requests with age, tokens, cached, tok/s, time; memory
gauge). ChatScreen + ChatRenderer (conversation resent whole, streamed
answers, Esc / Ctrl-C stop, Ctrl-N new, Ctrl-P model picker, Ctrl-R
reasoning shown/folded/hidden, stats line, /set sampling, /help, /clear).
TUIApp routes keys to the current screen and runs their actions.
Tests: Linux 300, Mac 326.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-27T05:37:11+01:00 Browse files
d628c4a parent: 47383cb
modified Sources/RazorbillServer/Chat/ChatCompletionChunk.swift +4 -2
@@ -143,10 +143,11 @@ struct ChunkBuilder: Sendable {
143143
144144 extension ChatCompletionRoute {
145145 /// The chunks of a streamed answer. The model stays held until the stream ends, fails or is
146- /// cancelled (client gone); then the lease is released and a summary is logged.
146+ /// cancelled (client gone); then the lease is released and a summary is logged. The token
147+ /// counts go to `usage` for the request history.
147148 static func chunks(
148149 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, plan: ChatPlan,
149- logger: Logger
150+ usage requestUsage: RequestUsage, logger: Logger
150151 ) -> AsyncThrowingStream<ChatCompletionChunk, Error> {
151152 AsyncThrowingStream { continuation in
152153 let task = Task {
@@ -157,6 +158,7 @@ extension ChatCompletionRoute {
157158 for try await piece in pieces {
158159 if case .finished(let reason, let usage) = piece {
159160 outcome = "\(reason.rawValue) \(usage.logDescription)"
161+ requestUsage.record(plan.model, usage)
160162 }
161163 for chunk in builder.chunks(for: piece) { continuation.yield(chunk) }
162164 }
@@ -143,10 +143,11 @@ struct ChunkBuilder: Sendable {
143 143
144 extension ChatCompletionRoute {144 extension ChatCompletionRoute {
145 /// The chunks of a streamed answer. The model stays held until the stream ends, fails or is145 /// The chunks of a streamed answer. The model stays held until the stream ends, fails or is
146- /// cancelled (client gone); then the lease is released and a summary is logged.146+ /// cancelled (client gone); then the lease is released and a summary is logged. The token
147+ /// counts go to `usage` for the request history.
147 static func chunks(148 static func chunks(
148 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, plan: ChatPlan,149 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, plan: ChatPlan,
149- logger: Logger150+ usage requestUsage: RequestUsage, logger: Logger
150 ) -> AsyncThrowingStream<ChatCompletionChunk, Error> {151 ) -> AsyncThrowingStream<ChatCompletionChunk, Error> {
151 AsyncThrowingStream { continuation in152 AsyncThrowingStream { continuation in
152 let task = Task {153 let task = Task {
@@ -157,6 +158,7 @@ extension ChatCompletionRoute {
157 for try await piece in pieces {158 for try await piece in pieces {
158 if case .finished(let reason, let usage) = piece {159 if case .finished(let reason, let usage) = piece {
159 outcome = "\(reason.rawValue) \(usage.logDescription)"160 outcome = "\(reason.rawValue) \(usage.logDescription)"
161+ requestUsage.record(plan.model, usage)
160 }162 }
161 for chunk in builder.chunks(for: piece) { continuation.yield(chunk) }163 for chunk in builder.chunks(for: piece) { continuation.yield(chunk) }
162 }164 }
modified Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +2 -1
@@ -110,7 +110,8 @@ struct ChatCompletionRoute {
110110 throw error
111111 }
112112 context.usage.record(model: plan.model)
113- let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger)
113+ let chunks = Self.chunks(
114+ pieces, lease: lease, plan: plan, usage: context.usage, logger: context.logger)
114115 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)
115116 }
116117
@@ -110,7 +110,8 @@ struct ChatCompletionRoute {
110 throw error110 throw error
111 }111 }
112 context.usage.record(model: plan.model)112 context.usage.record(model: plan.model)
113- let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger)113+ let chunks = Self.chunks(
114+ pieces, lease: lease, plan: plan, usage: context.usage, logger: context.logger)
114 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)115 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)
115 }116 }
116 117
modified Sources/RazorbillServer/CompletionsRoute.swift +6 -3
@@ -197,7 +197,8 @@ struct CompletionsRoute {
197197 throw error
198198 }
199199 context.usage.record(model: plan.model)
200- let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger)
200+ let chunks = Self.chunks(
201+ pieces, lease: lease, plan: plan, usage: context.usage, logger: context.logger)
201202 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)
202203 }
203204
@@ -228,10 +229,11 @@ struct CompletionsRoute {
228229 }
229230
230231 /// The stream's chunks: the prompt first with `echo`, the text pieces, a last chunk with
231- /// `finish_reason`, then the usage chunk if asked. The lease is released at the end.
232+ /// `finish_reason`, then the usage chunk if asked. The lease is released at the end, and the
233+ /// token counts go to `usage` for the request history.
232234 static func chunks(
233235 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease,
234- plan: CompletionPlan, logger: Logger
236+ plan: CompletionPlan, usage requestUsage: RequestUsage, logger: Logger
235237 ) -> AsyncThrowingStream<TextCompletion, Error> {
236238 let id = newID()
237239 let created = Int(Date().timeIntervalSince1970)
@@ -251,6 +253,7 @@ struct CompletionsRoute {
251253 case .content(let text): continuation.yield(chunk(text))
252254 case .finished(let reason, let usage):
253255 outcome = "\(reason.rawValue) \(usage.logDescription)"
256+ requestUsage.record(plan.model, usage)
254257 continuation.yield(chunk("", reason))
255258 if plan.includeUsage {
256259 continuation.yield(
@@ -197,7 +197,8 @@ struct CompletionsRoute {
197 throw error197 throw error
198 }198 }
199 context.usage.record(model: plan.model)199 context.usage.record(model: plan.model)
200- let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger)200+ let chunks = Self.chunks(
201+ pieces, lease: lease, plan: plan, usage: context.usage, logger: context.logger)
201 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)202 return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive)
202 }203 }
203 204
@@ -228,10 +229,11 @@ struct CompletionsRoute {
228 }229 }
229 230
230 /// The stream's chunks: the prompt first with `echo`, the text pieces, a last chunk with231 /// The stream's chunks: the prompt first with `echo`, the text pieces, a last chunk with
231- /// `finish_reason`, then the usage chunk if asked. The lease is released at the end.232+ /// `finish_reason`, then the usage chunk if asked. The lease is released at the end, and the
233+ /// token counts go to `usage` for the request history.
232 static func chunks(234 static func chunks(
233 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease,235 _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease,
234- plan: CompletionPlan, logger: Logger236+ plan: CompletionPlan, usage requestUsage: RequestUsage, logger: Logger
235 ) -> AsyncThrowingStream<TextCompletion, Error> {237 ) -> AsyncThrowingStream<TextCompletion, Error> {
236 let id = newID()238 let id = newID()
237 let created = Int(Date().timeIntervalSince1970)239 let created = Int(Date().timeIntervalSince1970)
@@ -251,6 +253,7 @@ struct CompletionsRoute {
251 case .content(let text): continuation.yield(chunk(text))253 case .content(let text): continuation.yield(chunk(text))
252 case .finished(let reason, let usage):254 case .finished(let reason, let usage):
253 outcome = "\(reason.rawValue) \(usage.logDescription)"255 outcome = "\(reason.rawValue) \(usage.logDescription)"
256+ requestUsage.record(plan.model, usage)
254 continuation.yield(chunk("", reason))257 continuation.yield(chunk("", reason))
255 if plan.includeUsage {258 if plan.includeUsage {
256 continuation.yield(259 continuation.yield(
modified Sources/RazorbillServer/Middlewares.swift +37 -10
@@ -65,8 +65,10 @@ struct APIKeyMiddleware: RouterMiddleware {
6565 ///
6666 /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40`
6767 ///
68-/// For a streamed answer the duration is the time to the first byte. The same facts go into
69-/// `history` for `GET /rzb/status`, except for the `/rzb/` routes themselves.
68+/// For a streamed answer the duration is the time to the first byte (its tokens are in the
69+/// `stream … tokens=` line written when it ends). The same facts go into `history` for
70+/// `GET /rzb/status` once the last byte is written, with the whole duration and the stream's
71+/// tokens, except for the `/rzb/` routes themselves.
7072 struct RequestLogMiddleware: RouterMiddleware {
7173 let history: RequestHistory
7274
@@ -75,19 +77,44 @@ struct RequestLogMiddleware: RouterMiddleware {
7577 next: (Request, ServerContext) async throws -> Response
7678 ) async throws -> Response {
7779 let start = ContinuousClock.now
78- let response = try await next(request, context)
79- let elapsed = ContinuousClock.now - start
80- let milliseconds = Int(elapsed / .milliseconds(1))
80+ var response = try await next(request, context)
81+ let firstByte = Self.milliseconds(since: start)
8182 let path = request.uri.path
8283 context.logger.info(
83- "\(request.method) \(path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)"
84+ "\(request.method) \(path) \(response.status.code) \(firstByte)ms\(context.usage.logSuffix)"
8485 )
85- if RequestHistory.records(path: path) {
86+ guard RequestHistory.records(path: path) else { return response }
87+ let method = request.method.rawValue
88+ let status = Int(response.status.code)
89+ let usage = context.usage
90+ let history = history
91+ response.body = response.body.afterWriting {
92+ let timing = RequestTiming(
93+ firstByteMs: firstByte, durationMs: Self.milliseconds(since: start))
8694 history.append(
87- context.usage.record(
88- method: request.method.rawValue, path: path, status: Int(response.status.code),
89- durationMs: milliseconds, finishedAt: Date()))
95+ usage.record(
96+ method: method, path: path, status: status, timing: timing, finishedAt: Date()))
9097 }
9198 return response
9299 }
100+
101+ static func milliseconds(since start: ContinuousClock.Instant) -> Int {
102+ Int((ContinuousClock.now - start) / .milliseconds(1))
103+ }
104+}
105+
106+extension ResponseBody {
107+ /// The same body, calling `done` once it is written to the client, or failed to be.
108+ func afterWriting(_ done: @escaping @Sendable () -> Void) -> ResponseBody {
109+ let body = self
110+ return ResponseBody(contentLength: body.contentLength) { writer in
111+ do {
112+ try await body.write(writer)
113+ done()
114+ } catch {
115+ done()
116+ throw error
117+ }
118+ }
119+ }
93120 }
@@ -65,8 +65,10 @@ struct APIKeyMiddleware: RouterMiddleware {
65 ///65 ///
66 /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40`66 /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40`
67 ///67 ///
68-/// For a streamed answer the duration is the time to the first byte. The same facts go into68+/// For a streamed answer the duration is the time to the first byte (its tokens are in the
69-/// `history` for `GET /rzb/status`, except for the `/rzb/` routes themselves.69+/// `stream … tokens=` line written when it ends). The same facts go into `history` for
70+/// `GET /rzb/status` once the last byte is written, with the whole duration and the stream's
71+/// tokens, except for the `/rzb/` routes themselves.
70 struct RequestLogMiddleware: RouterMiddleware {72 struct RequestLogMiddleware: RouterMiddleware {
71 let history: RequestHistory73 let history: RequestHistory
72 74
@@ -75,19 +77,44 @@ struct RequestLogMiddleware: RouterMiddleware {
75 next: (Request, ServerContext) async throws -> Response77 next: (Request, ServerContext) async throws -> Response
76 ) async throws -> Response {78 ) async throws -> Response {
77 let start = ContinuousClock.now79 let start = ContinuousClock.now
78- let response = try await next(request, context)80+ var response = try await next(request, context)
79- let elapsed = ContinuousClock.now - start81+ let firstByte = Self.milliseconds(since: start)
80- let milliseconds = Int(elapsed / .milliseconds(1))
81 let path = request.uri.path82 let path = request.uri.path
82 context.logger.info(83 context.logger.info(
83- "\(request.method) \(path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)"84+ "\(request.method) \(path) \(response.status.code) \(firstByte)ms\(context.usage.logSuffix)"
84 )85 )
85- if RequestHistory.records(path: path) {86+ guard RequestHistory.records(path: path) else { return response }
87+ let method = request.method.rawValue
88+ let status = Int(response.status.code)
89+ let usage = context.usage
90+ let history = history
91+ response.body = response.body.afterWriting {
92+ let timing = RequestTiming(
93+ firstByteMs: firstByte, durationMs: Self.milliseconds(since: start))
86 history.append(94 history.append(
87- context.usage.record(95+ usage.record(
88- method: request.method.rawValue, path: path, status: Int(response.status.code),96+ method: method, path: path, status: status, timing: timing, finishedAt: Date()))
89- durationMs: milliseconds, finishedAt: Date()))
90 }97 }
91 return response98 return response
92 }99 }
100+
101+ static func milliseconds(since start: ContinuousClock.Instant) -> Int {
102+ Int((ContinuousClock.now - start) / .milliseconds(1))
103+ }
104+}
105+
106+extension ResponseBody {
107+ /// The same body, calling `done` once it is written to the client, or failed to be.
108+ func afterWriting(_ done: @escaping @Sendable () -> Void) -> ResponseBody {
109+ let body = self
110+ return ResponseBody(contentLength: body.contentLength) { writer in
111+ do {
112+ try await body.write(writer)
113+ done()
114+ } catch {
115+ done()
116+ throw error
117+ }
118+ }
119+ }
93 }120 }
modified Sources/RazorbillServer/RequestHistory.swift +11 -1
@@ -11,7 +11,9 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
1111 public let completionTokens: Int?
1212 /// Prompt tokens reused from the previous request's cache.
1313 public let cachedTokens: Int
14- /// Time to the response head (for a streamed answer: to the first byte).
14+ /// Time to the response head: for a streamed answer, to its first byte.
15+ public let firstByteMs: Int
16+ /// Time to the last byte of the answer.
1517 public let durationMs: Int
1618 /// Unix time, in seconds, like OpenAI's `created`.
1719 public let finishedAt: Int
@@ -21,6 +23,7 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
2123 case promptTokens = "prompt_tokens"
2224 case completionTokens = "completion_tokens"
2325 case cachedTokens = "cached_tokens"
26+ case firstByteMs = "first_byte_ms"
2427 case durationMs = "duration_ms"
2528 case finishedAt = "finished_at"
2629 }
@@ -35,11 +38,18 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
3538 try container.encode(promptTokens, forKey: .promptTokens)
3639 try container.encode(completionTokens, forKey: .completionTokens)
3740 try container.encode(cachedTokens, forKey: .cachedTokens)
41+ try container.encode(firstByteMs, forKey: .firstByteMs)
3842 try container.encode(durationMs, forKey: .durationMs)
3943 try container.encode(finishedAt, forKey: .finishedAt)
4044 }
4145 }
4246
47+/// How long a request took, in milliseconds.
48+struct RequestTiming {
49+ let firstByteMs: Int
50+ let durationMs: Int
51+}
52+
4353 /// The last requests the server answered, newest first, for `GET /rzb/status`.
4454 ///
4555 /// ```swift
@@ -11,7 +11,9 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
11 public let completionTokens: Int?11 public let completionTokens: Int?
12 /// Prompt tokens reused from the previous request's cache.12 /// Prompt tokens reused from the previous request's cache.
13 public let cachedTokens: Int13 public let cachedTokens: Int
14- /// Time to the response head (for a streamed answer: to the first byte).14+ /// Time to the response head: for a streamed answer, to its first byte.
15+ public let firstByteMs: Int
16+ /// Time to the last byte of the answer.
15 public let durationMs: Int17 public let durationMs: Int
16 /// Unix time, in seconds, like OpenAI's `created`.18 /// Unix time, in seconds, like OpenAI's `created`.
17 public let finishedAt: Int19 public let finishedAt: Int
@@ -21,6 +23,7 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
21 case promptTokens = "prompt_tokens"23 case promptTokens = "prompt_tokens"
22 case completionTokens = "completion_tokens"24 case completionTokens = "completion_tokens"
23 case cachedTokens = "cached_tokens"25 case cachedTokens = "cached_tokens"
26+ case firstByteMs = "first_byte_ms"
24 case durationMs = "duration_ms"27 case durationMs = "duration_ms"
25 case finishedAt = "finished_at"28 case finishedAt = "finished_at"
26 }29 }
@@ -35,11 +38,18 @@ public struct RequestRecord: Sendable, Equatable, Encodable {
35 try container.encode(promptTokens, forKey: .promptTokens)38 try container.encode(promptTokens, forKey: .promptTokens)
36 try container.encode(completionTokens, forKey: .completionTokens)39 try container.encode(completionTokens, forKey: .completionTokens)
37 try container.encode(cachedTokens, forKey: .cachedTokens)40 try container.encode(cachedTokens, forKey: .cachedTokens)
41+ try container.encode(firstByteMs, forKey: .firstByteMs)
38 try container.encode(durationMs, forKey: .durationMs)42 try container.encode(durationMs, forKey: .durationMs)
39 try container.encode(finishedAt, forKey: .finishedAt)43 try container.encode(finishedAt, forKey: .finishedAt)
40 }44 }
41 }45 }
42 46
47+/// How long a request took, in milliseconds.
48+struct RequestTiming {
49+ let firstByteMs: Int
50+ let durationMs: Int
51+}
52+
43 /// The last requests the server answered, newest first, for `GET /rzb/status`.53 /// The last requests the server answered, newest first, for `GET /rzb/status`.
44 ///54 ///
45 /// ```swift55 /// ```swift
modified Sources/RazorbillServer/ServerContext.swift +10 -3
@@ -61,16 +61,23 @@ public final class RequestUsage: @unchecked Sendable {
6161 }
6262 }
6363
64+ /// Records a stream's final counts, once its last piece is known.
65+ func record(_ model: String, _ usage: Usage) {
66+ record(
67+ model: model, promptTokens: usage.promptTokens,
68+ completionTokens: usage.completionTokens, cachedTokens: usage.cachedTokens)
69+ }
70+
6471 /// The finished request as ``RequestHistory`` keeps it.
6572 func record(
66- method: String, path: String, status: Int, durationMs: Int, finishedAt: Date
73+ method: String, path: String, status: Int, timing: RequestTiming, finishedAt: Date
6774 ) -> RequestRecord {
6875 lock.withLock {
6976 RequestRecord(
7077 method: method, path: path, status: status, model: storedModel,
7178 promptTokens: storedTokens?.prompt, completionTokens: storedTokens?.completion,
72- cachedTokens: storedTokens?.cached ?? 0, durationMs: durationMs,
73- finishedAt: Int(finishedAt.timeIntervalSince1970))
79+ cachedTokens: storedTokens?.cached ?? 0, firstByteMs: timing.firstByteMs,
80+ durationMs: timing.durationMs, finishedAt: Int(finishedAt.timeIntervalSince1970))
7481 }
7582 }
7683
@@ -61,16 +61,23 @@ public final class RequestUsage: @unchecked Sendable {
61 }61 }
62 }62 }
63 63
64+ /// Records a stream's final counts, once its last piece is known.
65+ func record(_ model: String, _ usage: Usage) {
66+ record(
67+ model: model, promptTokens: usage.promptTokens,
68+ completionTokens: usage.completionTokens, cachedTokens: usage.cachedTokens)
69+ }
70+
64 /// The finished request as ``RequestHistory`` keeps it.71 /// The finished request as ``RequestHistory`` keeps it.
65 func record(72 func record(
66- method: String, path: String, status: Int, durationMs: Int, finishedAt: Date73+ method: String, path: String, status: Int, timing: RequestTiming, finishedAt: Date
67 ) -> RequestRecord {74 ) -> RequestRecord {
68 lock.withLock {75 lock.withLock {
69 RequestRecord(76 RequestRecord(
70 method: method, path: path, status: status, model: storedModel,77 method: method, path: path, status: status, model: storedModel,
71 promptTokens: storedTokens?.prompt, completionTokens: storedTokens?.completion,78 promptTokens: storedTokens?.prompt, completionTokens: storedTokens?.completion,
72- cachedTokens: storedTokens?.cached ?? 0, durationMs: durationMs,79+ cachedTokens: storedTokens?.cached ?? 0, firstByteMs: timing.firstByteMs,
73- finishedAt: Int(finishedAt.timeIntervalSince1970))80+ durationMs: timing.durationMs, finishedAt: Int(finishedAt.timeIntervalSince1970))
74 }81 }
75 }82 }
76 83
modified Sources/RazorbillTUI/ChatChunk.swift +8 -1
@@ -26,6 +26,11 @@ struct ChatChunk: Decodable {
2626 struct Usage: Decodable {
2727 let promptTokens: Int
2828 let completionTokens: Int
29+ let promptTokensDetails: PromptDetails?
30+ }
31+
32+ struct PromptDetails: Decodable {
33+ let cachedTokens: Int?
2934 }
3035
3136 let choices: [Choice]?
@@ -54,7 +59,9 @@ struct ChatChunk: Decodable {
5459 }
5560 if let usage = chunk.usage {
5661 events.append(
57- .usage(promptTokens: usage.promptTokens, completionTokens: usage.completionTokens))
62+ .usage(
63+ promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
64+ cachedTokens: usage.promptTokensDetails?.cachedTokens ?? 0))
5865 }
5966 return events
6067 }
@@ -26,6 +26,11 @@ struct ChatChunk: Decodable {
26 struct Usage: Decodable {26 struct Usage: Decodable {
27 let promptTokens: Int27 let promptTokens: Int
28 let completionTokens: Int28 let completionTokens: Int
29+ let promptTokensDetails: PromptDetails?
30+ }
31+
32+ struct PromptDetails: Decodable {
33+ let cachedTokens: Int?
29 }34 }
30 35
31 let choices: [Choice]?36 let choices: [Choice]?
@@ -54,7 +59,9 @@ struct ChatChunk: Decodable {
54 }59 }
55 if let usage = chunk.usage {60 if let usage = chunk.usage {
56 events.append(61 events.append(
57- .usage(promptTokens: usage.promptTokens, completionTokens: usage.completionTokens))62+ .usage(
63+ promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
64+ cachedTokens: usage.promptTokensDetails?.cachedTokens ?? 0))
58 }65 }
59 return events66 return events
60 }67 }
added Sources/RazorbillTUI/ChatRenderer.swift +131 -0
new file mode 100644
@@ -0,0 +1,131 @@
1+/// Draws the Chat screen: the conversation (wrapped, scrolled to the end unless scrolled back),
2+/// a help line and the input line — or the model picker while it is open.
3+///
4+/// ```swift
5+/// let (lines, cursor) = ChatRenderer(style: style).render(chat, width: 80, height: 20)
6+/// ```
7+public struct ChatRenderer: Sendable {
8+ public var style: Style
9+
10+ public init(style: Style) {
11+ self.style = style
12+ }
13+
14+ /// `height` lines, and the cursor's position in them (on the input line).
15+ public func render(_ chat: ChatScreen, width: Int, height: Int) -> (
16+ lines: [String], cursor: FormView.Cursor
17+ ) {
18+ let width = max(width, 20)
19+ let height = max(height, 3)
20+ if chat.picking { return (picker(chat, width: width, height: height), (0, 0)) }
21+ let conversationHeight = height - 2
22+ let all = conversation(chat, width: width)
23+ let bottom = max(0, all.count - conversationHeight)
24+ let start = max(0, bottom - min(chat.scrollBack, bottom))
25+ var lines = Array(all[start ..< min(all.count, start + conversationHeight)])
26+ lines += Array(repeating: "", count: conversationHeight - lines.count)
27+ lines.append(style.dim(TextLayout.truncate(help(chat), width: width)))
28+ let (input, column) = inputLine(chat, width: width)
29+ return (lines + [input], (height - 1, column))
30+ }
31+
32+ // MARK: Parts
33+
34+ func conversation(_ chat: ChatScreen, width: Int) -> [String] {
35+ guard !chat.entries.isEmpty else {
36+ return [
37+ "", " Type a message and press Enter. /help lists the keys and commands.",
38+ " Model: \(chat.model ?? "none yet (Ctrl-P)") · settings: \(chat.options.summary)",
39+ ]
40+ }
41+ var lines: [String] = []
42+ for (index, entry) in chat.entries.enumerated() {
43+ let streaming = chat.generating && index == chat.answeringIndex
44+ lines += self.entry(entry, chat: chat, streaming: streaming, width: width) + [""]
45+ }
46+ return lines
47+ }
48+
49+ func entry(_ entry: ChatEntry, chat: ChatScreen, streaming: Bool, width: Int) -> [String] {
50+ switch entry.role {
51+ case .user:
52+ return labelled(style.bold("you › "), plainLabel: "you › ", entry.content, width: width)
53+ case .notice:
54+ return TextLayout.wrap(entry.content, width: width - 2).map { style.dim(" " + $0) }
55+ case .assistant:
56+ return answer(entry, display: chat.reasoning, streaming: streaming, width: width)
57+ }
58+ }
59+
60+ func answer(
61+ _ entry: ChatEntry, display: ChatScreen.ReasoningDisplay, streaming: Bool, width: Int
62+ ) -> [String] {
63+ let name = "\(entry.model ?? "model") › "
64+ var lines: [String] = []
65+ if !entry.reasoning.isEmpty {
66+ lines += reasoning(entry.reasoning, display: display, width: width)
67+ } else if streaming && entry.content.isEmpty {
68+ lines.append(style.dim(" ⋯ waiting for the model…"))
69+ }
70+ if !entry.content.isEmpty || !streaming {
71+ lines += labelled(style.bold(name), plainLabel: name, entry.content, width: width)
72+ }
73+ if entry.stopped { lines.append(style.dim(" (stopped)")) }
74+ if let failure = entry.failure {
75+ lines += TextLayout.wrap("error: \(failure)", width: width - 2).map {
76+ style.red(" " + $0)
77+ }
78+ }
79+ if let stats = entry.stats { lines.append(style.dim(" " + stats)) }
80+ return lines
81+ }
82+
83+ func reasoning(_ text: String, display: ChatScreen.ReasoningDisplay, width: Int) -> [String] {
84+ switch display {
85+ case .hidden:
86+ return []
87+ case .folded:
88+ let words = text.split(whereSeparator: \.isWhitespace).count
89+ return [style.dim(" ⋯ thinking (\(words) words) · Ctrl-R to show")]
90+ case .shown:
91+ return TextLayout.wrap(text, width: width - 4).map { style.dim(" ⋯ " + $0) }
92+ }
93+ }
94+
95+ /// `label` on the first line, the following lines indented under the text.
96+ func labelled(_ label: String, plainLabel: String, _ text: String, width: Int) -> [String] {
97+ let indent = String(repeating: " ", count: plainLabel.count)
98+ let wrapped = TextLayout.wrap(text, width: max(10, width - plainLabel.count))
99+ return wrapped.enumerated().map { index, line in (index == 0 ? label : indent) + line }
100+ }
101+
102+ func help(_ chat: ChatScreen) -> String {
103+ let reasoning = "Ctrl-R reasoning: \(chat.reasoning.rawValue)"
104+ if chat.generating { return " Esc stop · \(reasoning)" }
105+ return " Enter send · Ctrl-N new · Ctrl-P model: \(chat.model ?? "none") · \(reasoning)"
106+ + " · /help"
107+ }
108+
109+ /// `› text`, showing the end of a text longer than the line, and the cursor's column.
110+ func inputLine(_ chat: ChatScreen, width: Int) -> (String, Int) {
111+ let prompt = "› "
112+ let room = width - prompt.count - 1
113+ let text = Array(chat.input.text)
114+ let start = max(0, chat.input.cursor - room)
115+ let visible = String(text[start ..< min(text.count, start + room)])
116+ return (prompt + visible, prompt.count + chat.input.cursor - start)
117+ }
118+
119+ func picker(_ chat: ChatScreen, width: Int, height: Int) -> [String] {
120+ let title = style.bold(" Choose a model") + style.dim(" ↑↓ · Enter choose · Esc back")
121+ var head = ["", title, ""]
122+ guard !chat.models.isEmpty else {
123+ return head + [" (asking the server for its models…)"]
124+ }
125+ var list = chat.picker
126+ head += list.render(
127+ chat.models.map { " " + $0 + ($0 == chat.model ? " (current)" : "") },
128+ width: width, height: max(1, height - head.count), style: style)
129+ return head
130+ }
131+}
new file mode 100644
@@ -0,0 +1,131 @@
1+/// Draws the Chat screen: the conversation (wrapped, scrolled to the end unless scrolled back),
2+/// a help line and the input line — or the model picker while it is open.
3+///
4+/// ```swift
5+/// let (lines, cursor) = ChatRenderer(style: style).render(chat, width: 80, height: 20)
6+/// ```
7+public struct ChatRenderer: Sendable {
8+ public var style: Style
9+
10+ public init(style: Style) {
11+ self.style = style
12+ }
13+
14+ /// `height` lines, and the cursor's position in them (on the input line).
15+ public func render(_ chat: ChatScreen, width: Int, height: Int) -> (
16+ lines: [String], cursor: FormView.Cursor
17+ ) {
18+ let width = max(width, 20)
19+ let height = max(height, 3)
20+ if chat.picking { return (picker(chat, width: width, height: height), (0, 0)) }
21+ let conversationHeight = height - 2
22+ let all = conversation(chat, width: width)
23+ let bottom = max(0, all.count - conversationHeight)
24+ let start = max(0, bottom - min(chat.scrollBack, bottom))
25+ var lines = Array(all[start ..< min(all.count, start + conversationHeight)])
26+ lines += Array(repeating: "", count: conversationHeight - lines.count)
27+ lines.append(style.dim(TextLayout.truncate(help(chat), width: width)))
28+ let (input, column) = inputLine(chat, width: width)
29+ return (lines + [input], (height - 1, column))
30+ }
31+
32+ // MARK: Parts
33+
34+ func conversation(_ chat: ChatScreen, width: Int) -> [String] {
35+ guard !chat.entries.isEmpty else {
36+ return [
37+ "", " Type a message and press Enter. /help lists the keys and commands.",
38+ " Model: \(chat.model ?? "none yet (Ctrl-P)") · settings: \(chat.options.summary)",
39+ ]
40+ }
41+ var lines: [String] = []
42+ for (index, entry) in chat.entries.enumerated() {
43+ let streaming = chat.generating && index == chat.answeringIndex
44+ lines += self.entry(entry, chat: chat, streaming: streaming, width: width) + [""]
45+ }
46+ return lines
47+ }
48+
49+ func entry(_ entry: ChatEntry, chat: ChatScreen, streaming: Bool, width: Int) -> [String] {
50+ switch entry.role {
51+ case .user:
52+ return labelled(style.bold("you › "), plainLabel: "you › ", entry.content, width: width)
53+ case .notice:
54+ return TextLayout.wrap(entry.content, width: width - 2).map { style.dim(" " + $0) }
55+ case .assistant:
56+ return answer(entry, display: chat.reasoning, streaming: streaming, width: width)
57+ }
58+ }
59+
60+ func answer(
61+ _ entry: ChatEntry, display: ChatScreen.ReasoningDisplay, streaming: Bool, width: Int
62+ ) -> [String] {
63+ let name = "\(entry.model ?? "model") › "
64+ var lines: [String] = []
65+ if !entry.reasoning.isEmpty {
66+ lines += reasoning(entry.reasoning, display: display, width: width)
67+ } else if streaming && entry.content.isEmpty {
68+ lines.append(style.dim(" ⋯ waiting for the model…"))
69+ }
70+ if !entry.content.isEmpty || !streaming {
71+ lines += labelled(style.bold(name), plainLabel: name, entry.content, width: width)
72+ }
73+ if entry.stopped { lines.append(style.dim(" (stopped)")) }
74+ if let failure = entry.failure {
75+ lines += TextLayout.wrap("error: \(failure)", width: width - 2).map {
76+ style.red(" " + $0)
77+ }
78+ }
79+ if let stats = entry.stats { lines.append(style.dim(" " + stats)) }
80+ return lines
81+ }
82+
83+ func reasoning(_ text: String, display: ChatScreen.ReasoningDisplay, width: Int) -> [String] {
84+ switch display {
85+ case .hidden:
86+ return []
87+ case .folded:
88+ let words = text.split(whereSeparator: \.isWhitespace).count
89+ return [style.dim(" ⋯ thinking (\(words) words) · Ctrl-R to show")]
90+ case .shown:
91+ return TextLayout.wrap(text, width: width - 4).map { style.dim(" ⋯ " + $0) }
92+ }
93+ }
94+
95+ /// `label` on the first line, the following lines indented under the text.
96+ func labelled(_ label: String, plainLabel: String, _ text: String, width: Int) -> [String] {
97+ let indent = String(repeating: " ", count: plainLabel.count)
98+ let wrapped = TextLayout.wrap(text, width: max(10, width - plainLabel.count))
99+ return wrapped.enumerated().map { index, line in (index == 0 ? label : indent) + line }
100+ }
101+
102+ func help(_ chat: ChatScreen) -> String {
103+ let reasoning = "Ctrl-R reasoning: \(chat.reasoning.rawValue)"
104+ if chat.generating { return " Esc stop · \(reasoning)" }
105+ return " Enter send · Ctrl-N new · Ctrl-P model: \(chat.model ?? "none") · \(reasoning)"
106+ + " · /help"
107+ }
108+
109+ /// `› text`, showing the end of a text longer than the line, and the cursor's column.
110+ func inputLine(_ chat: ChatScreen, width: Int) -> (String, Int) {
111+ let prompt = "› "
112+ let room = width - prompt.count - 1
113+ let text = Array(chat.input.text)
114+ let start = max(0, chat.input.cursor - room)
115+ let visible = String(text[start ..< min(text.count, start + room)])
116+ return (prompt + visible, prompt.count + chat.input.cursor - start)
117+ }
118+
119+ func picker(_ chat: ChatScreen, width: Int, height: Int) -> [String] {
120+ let title = style.bold(" Choose a model") + style.dim(" ↑↓ · Enter choose · Esc back")
121+ var head = ["", title, ""]
122+ guard !chat.models.isEmpty else {
123+ return head + [" (asking the server for its models…)"]
124+ }
125+ var list = chat.picker
126+ head += list.render(
127+ chat.models.map { " " + $0 + ($0 == chat.model ? " (current)" : "") },
128+ width: width, height: max(1, height - head.count), style: style)
129+ return head
130+ }
131+}
added Sources/RazorbillTUI/ChatScreen.swift +280 -0
new file mode 100644
@@ -0,0 +1,280 @@
1+import Foundation
2+
3+/// One line of the conversation as the Chat screen keeps it.
4+public struct ChatEntry: Sendable, Equatable {
5+ public enum Role: Sendable, Equatable {
6+ case user
7+ case assistant
8+ /// A message of the TUI itself (command output, errors); never sent to the model.
9+ case notice
10+ }
11+
12+ public var role: Role
13+ public var content: String
14+ public var reasoning = ""
15+ /// The model that answered (assistant entries).
16+ public var model: String?
17+ /// `14+9 tokens · 3 cached · 42.1 tok/s`, once the answer is complete.
18+ public var stats: String?
19+ /// The answer was stopped before its end (Esc).
20+ public var stopped = false
21+ /// Why the answer failed.
22+ public var failure: String?
23+
24+ public init(role: Role, content: String, model: String? = nil) {
25+ self.role = role
26+ self.content = content
27+ self.model = model
28+ }
29+}
30+
31+/// The Chat screen (#55): a conversation kept here and resent whole to the server (its prompt
32+/// cache makes that cheap), streamed answers, a model picker, reasoning shown, folded or hidden,
33+/// and per-session sampling settings (`/set`).
34+///
35+/// ```swift
36+/// var chat = ChatScreen()
37+/// chat.setModels(["qwen3"])
38+/// for key in "hello".map(Key.character) { _ = chat.handle(key) }
39+/// chat.handle(.enter) // .send(model: "qwen3", messages: [user "hello"], options: …)
40+/// chat.receive(.content("Hi!"))
41+/// chat.finish(generationSeconds: 0.5)
42+/// ```
43+public struct ChatScreen: Sendable, Equatable {
44+ /// How reasoning is shown; Ctrl-R goes to the next one.
45+ public enum ReasoningDisplay: String, Sendable, CaseIterable {
46+ case shown, folded, hidden
47+
48+ var next: ReasoningDisplay {
49+ let all = Self.allCases
50+ return all[(all.firstIndex(of: self)! + 1) % all.count]
51+ }
52+ }
53+
54+ /// What a key asks the app to do.
55+ public enum Action: Sendable, Equatable {
56+ case none
57+ case redraw
58+ /// Stream the answer to this conversation.
59+ case send(model: String, messages: [ChatTurn], options: ChatOptions)
60+ /// Stop the answer being generated.
61+ case cancel
62+ /// Fetch the server's models (then call ``setModels(_:)``).
63+ case loadModels
64+ }
65+
66+ public private(set) var entries: [ChatEntry] = []
67+ public private(set) var input = TextField()
68+ /// The model the next message goes to.
69+ public private(set) var model: String?
70+ /// The chat models the server offers.
71+ public private(set) var models: [String] = []
72+ /// The model list is open (Ctrl-P).
73+ public private(set) var picking = false
74+ var picker = ListView()
75+ /// An answer is streaming.
76+ public private(set) var generating = false
77+ public private(set) var reasoning = ReasoningDisplay.folded
78+ public private(set) var options = ChatOptions()
79+ /// Lines scrolled back from the bottom.
80+ var scrollBack = 0
81+ private var usage: Usage?
82+ /// The entry the streamed answer goes into: notices may be added after it meanwhile.
83+ private var answering: Int?
84+ var answeringIndex: Int? { answering }
85+
86+ /// The token counts of the answer being streamed.
87+ private struct Usage: Sendable, Equatable {
88+ let prompt: Int
89+ let completion: Int
90+ let cached: Int
91+ }
92+
93+ public init() {}
94+
95+ /// The server's chat models. The first loaded one becomes current when none is chosen.
96+ public mutating func setModels(_ served: [ServedModel]) {
97+ let chatModels = served.filter { ($0.kind ?? "chat") == "chat" }
98+ models = chatModels.map(\.id)
99+ if model == nil || !models.contains(model ?? "") {
100+ model = chatModels.first { $0.loaded == true }?.id ?? models.first
101+ }
102+ picker.resize(to: models.count)
103+ if let model, let index = models.firstIndex(of: model) { picker.select(index) }
104+ }
105+
106+ /// Same, from bare ids (tests, servers without `kind`).
107+ public mutating func setModels(_ ids: [String]) {
108+ setModels(ids.map { ServedModel(id: $0, loaded: nil, kind: nil) })
109+ }
110+
111+ // MARK: Keys
112+
113+ public mutating func handle(_ key: Key) -> Action {
114+ if picking { return handlePicker(key) }
115+ switch key {
116+ case .enter: return submit()
117+ case .escape: return generating ? .cancel : .none
118+ case .control("n"): return newConversation()
119+ case .control("p"):
120+ picking = true
121+ picker.resize(to: models.count)
122+ if let model, let index = models.firstIndex(of: model) { picker.select(index) }
123+ return .loadModels
124+ case .control("r"):
125+ reasoning = reasoning.next
126+ return .redraw
127+ case .pageUp:
128+ scrollBack += 10
129+ return .redraw
130+ case .pageDown:
131+ scrollBack = max(0, scrollBack - 10)
132+ return .redraw
133+ default:
134+ return input.handle(key) ? .redraw : .none
135+ }
136+ }
137+
138+ private mutating func handlePicker(_ key: Key) -> Action {
139+ switch key {
140+ case .escape:
141+ picking = false
142+ case .enter:
143+ picking = false
144+ if picker.selected < models.count {
145+ model = models[picker.selected]
146+ note("model: \(models[picker.selected])")
147+ }
148+ default:
149+ return picker.handle(key, pageSize: 10) ? .redraw : .none
150+ }
151+ return .redraw
152+ }
153+
154+ private mutating func submit() -> Action {
155+ let text = input.text.trimmingCharacters(in: .whitespaces)
156+ guard !text.isEmpty else { return .none }
157+ if text.hasPrefix("/") {
158+ input = TextField()
159+ return command(text)
160+ }
161+ guard !generating else {
162+ note("an answer is still coming: wait, or Esc to stop it")
163+ return .redraw
164+ }
165+ guard let model else {
166+ note("no chat model yet: Ctrl-P to choose one")
167+ return .loadModels
168+ }
169+ input = TextField()
170+ entries.append(ChatEntry(role: .user, content: text))
171+ let messages = turns()
172+ entries.append(ChatEntry(role: .assistant, content: "", model: model))
173+ answering = entries.count - 1
174+ generating = true
175+ scrollBack = 0
176+ usage = nil
177+ return .send(model: model, messages: messages, options: options)
178+ }
179+
180+ private mutating func newConversation() -> Action {
181+ guard !generating else {
182+ note("an answer is still coming: Esc to stop it first")
183+ return .redraw
184+ }
185+ entries = []
186+ scrollBack = 0
187+ return .redraw
188+ }
189+
190+ /// `/set <name> <value>`, `/set`, `/clear`, `/help`.
191+ private mutating func command(_ text: String) -> Action {
192+ let words = text.split(separator: " ").map(String.init)
193+ switch words.first {
194+ case "/set" where words.count == 1:
195+ note("settings: \(options.summary)")
196+ case "/set":
197+ do {
198+ try options.set(words[1], to: words.count > 2 ? words[2] : "")
199+ note("settings: \(options.summary)")
200+ } catch {
201+ note("\(error)")
202+ }
203+ case "/clear":
204+ return newConversation()
205+ case "/help":
206+ note(Self.help)
207+ default:
208+ note("unknown command \(words.first ?? ""): /help lists them")
209+ }
210+ return .redraw
211+ }
212+
213+ static let help =
214+ "Enter sends · Esc stops the answer · Ctrl-N new conversation · Ctrl-P model · "
215+ + "Ctrl-R reasoning shown/folded/hidden · PgUp/PgDn scroll · /set <name> <value> "
216+ + "(\(ChatOptions.names.joined(separator: ", ")); no value: server default) · /set · /clear"
217+
218+ /// Adds a line of the TUI's own to the conversation (errors, command output).
219+ public mutating func note(_ text: String) {
220+ entries.append(ChatEntry(role: .notice, content: text))
221+ }
222+
223+ /// The conversation as the server gets it: user messages and answers, without notices,
224+ /// reasoning or failed answers.
225+ public func turns() -> [ChatTurn] {
226+ entries.compactMap { entry in
227+ switch entry.role {
228+ case .user: ChatTurn(role: "user", content: entry.content)
229+ case .assistant where entry.failure == nil && !entry.content.isEmpty:
230+ ChatTurn(role: "assistant", content: entry.content)
231+ default: nil
232+ }
233+ }
234+ }
235+
236+ // MARK: The answer
237+
238+ /// A piece of the answer being streamed.
239+ public mutating func receive(_ event: ChatEvent) {
240+ guard generating, let index = answering else { return }
241+ switch event {
242+ case .content(let text): entries[index].content += text
243+ case .reasoning(let text): entries[index].reasoning += text
244+ case .finished: break
245+ case .usage(let prompt, let completion, let cached):
246+ usage = Usage(prompt: prompt, completion: completion, cached: cached)
247+ }
248+ }
249+
250+ /// The stream ended. `generationSeconds`: from the first piece to the last.
251+ public mutating func finish(generationSeconds: Double?) {
252+ let usage = self.usage
253+ endAnswer { entry in
254+ guard let usage else { return }
255+ var stats = "\(usage.prompt)+\(usage.completion) tokens"
256+ if usage.cached > 0 { stats += " · \(usage.cached) cached" }
257+ if let seconds = generationSeconds, seconds > 0, usage.completion > 0 {
258+ stats += String(format: " · %.1f tok/s", Double(usage.completion) / seconds)
259+ }
260+ entry.stats = stats
261+ }
262+ }
263+
264+ /// The answer was stopped (Esc): what came so far stays.
265+ public mutating func stop() {
266+ endAnswer { $0.stopped = true }
267+ }
268+
269+ /// The request failed.
270+ public mutating func fail(_ message: String) {
271+ endAnswer { $0.failure = message }
272+ }
273+
274+ private mutating func endAnswer(_ change: (inout ChatEntry) -> Void) {
275+ generating = false
276+ guard let index = answering else { return }
277+ answering = nil
278+ change(&entries[index])
279+ }
280+}
new file mode 100644
@@ -0,0 +1,280 @@
1+import Foundation
2+
3+/// One line of the conversation as the Chat screen keeps it.
4+public struct ChatEntry: Sendable, Equatable {
5+ public enum Role: Sendable, Equatable {
6+ case user
7+ case assistant
8+ /// A message of the TUI itself (command output, errors); never sent to the model.
9+ case notice
10+ }
11+
12+ public var role: Role
13+ public var content: String
14+ public var reasoning = ""
15+ /// The model that answered (assistant entries).
16+ public var model: String?
17+ /// `14+9 tokens · 3 cached · 42.1 tok/s`, once the answer is complete.
18+ public var stats: String?
19+ /// The answer was stopped before its end (Esc).
20+ public var stopped = false
21+ /// Why the answer failed.
22+ public var failure: String?
23+
24+ public init(role: Role, content: String, model: String? = nil) {
25+ self.role = role
26+ self.content = content
27+ self.model = model
28+ }
29+}
30+
31+/// The Chat screen (#55): a conversation kept here and resent whole to the server (its prompt
32+/// cache makes that cheap), streamed answers, a model picker, reasoning shown, folded or hidden,
33+/// and per-session sampling settings (`/set`).
34+///
35+/// ```swift
36+/// var chat = ChatScreen()
37+/// chat.setModels(["qwen3"])
38+/// for key in "hello".map(Key.character) { _ = chat.handle(key) }
39+/// chat.handle(.enter) // .send(model: "qwen3", messages: [user "hello"], options: …)
40+/// chat.receive(.content("Hi!"))
41+/// chat.finish(generationSeconds: 0.5)
42+/// ```
43+public struct ChatScreen: Sendable, Equatable {
44+ /// How reasoning is shown; Ctrl-R goes to the next one.
45+ public enum ReasoningDisplay: String, Sendable, CaseIterable {
46+ case shown, folded, hidden
47+
48+ var next: ReasoningDisplay {
49+ let all = Self.allCases
50+ return all[(all.firstIndex(of: self)! + 1) % all.count]
51+ }
52+ }
53+
54+ /// What a key asks the app to do.
55+ public enum Action: Sendable, Equatable {
56+ case none
57+ case redraw
58+ /// Stream the answer to this conversation.
59+ case send(model: String, messages: [ChatTurn], options: ChatOptions)
60+ /// Stop the answer being generated.
61+ case cancel
62+ /// Fetch the server's models (then call ``setModels(_:)``).
63+ case loadModels
64+ }
65+
66+ public private(set) var entries: [ChatEntry] = []
67+ public private(set) var input = TextField()
68+ /// The model the next message goes to.
69+ public private(set) var model: String?
70+ /// The chat models the server offers.
71+ public private(set) var models: [String] = []
72+ /// The model list is open (Ctrl-P).
73+ public private(set) var picking = false
74+ var picker = ListView()
75+ /// An answer is streaming.
76+ public private(set) var generating = false
77+ public private(set) var reasoning = ReasoningDisplay.folded
78+ public private(set) var options = ChatOptions()
79+ /// Lines scrolled back from the bottom.
80+ var scrollBack = 0
81+ private var usage: Usage?
82+ /// The entry the streamed answer goes into: notices may be added after it meanwhile.
83+ private var answering: Int?
84+ var answeringIndex: Int? { answering }
85+
86+ /// The token counts of the answer being streamed.
87+ private struct Usage: Sendable, Equatable {
88+ let prompt: Int
89+ let completion: Int
90+ let cached: Int
91+ }
92+
93+ public init() {}
94+
95+ /// The server's chat models. The first loaded one becomes current when none is chosen.
96+ public mutating func setModels(_ served: [ServedModel]) {
97+ let chatModels = served.filter { ($0.kind ?? "chat") == "chat" }
98+ models = chatModels.map(\.id)
99+ if model == nil || !models.contains(model ?? "") {
100+ model = chatModels.first { $0.loaded == true }?.id ?? models.first
101+ }
102+ picker.resize(to: models.count)
103+ if let model, let index = models.firstIndex(of: model) { picker.select(index) }
104+ }
105+
106+ /// Same, from bare ids (tests, servers without `kind`).
107+ public mutating func setModels(_ ids: [String]) {
108+ setModels(ids.map { ServedModel(id: $0, loaded: nil, kind: nil) })
109+ }
110+
111+ // MARK: Keys
112+
113+ public mutating func handle(_ key: Key) -> Action {
114+ if picking { return handlePicker(key) }
115+ switch key {
116+ case .enter: return submit()
117+ case .escape: return generating ? .cancel : .none
118+ case .control("n"): return newConversation()
119+ case .control("p"):
120+ picking = true
121+ picker.resize(to: models.count)
122+ if let model, let index = models.firstIndex(of: model) { picker.select(index) }
123+ return .loadModels
124+ case .control("r"):
125+ reasoning = reasoning.next
126+ return .redraw
127+ case .pageUp:
128+ scrollBack += 10
129+ return .redraw
130+ case .pageDown:
131+ scrollBack = max(0, scrollBack - 10)
132+ return .redraw
133+ default:
134+ return input.handle(key) ? .redraw : .none
135+ }
136+ }
137+
138+ private mutating func handlePicker(_ key: Key) -> Action {
139+ switch key {
140+ case .escape:
141+ picking = false
142+ case .enter:
143+ picking = false
144+ if picker.selected < models.count {
145+ model = models[picker.selected]
146+ note("model: \(models[picker.selected])")
147+ }
148+ default:
149+ return picker.handle(key, pageSize: 10) ? .redraw : .none
150+ }
151+ return .redraw
152+ }
153+
154+ private mutating func submit() -> Action {
155+ let text = input.text.trimmingCharacters(in: .whitespaces)
156+ guard !text.isEmpty else { return .none }
157+ if text.hasPrefix("/") {
158+ input = TextField()
159+ return command(text)
160+ }
161+ guard !generating else {
162+ note("an answer is still coming: wait, or Esc to stop it")
163+ return .redraw
164+ }
165+ guard let model else {
166+ note("no chat model yet: Ctrl-P to choose one")
167+ return .loadModels
168+ }
169+ input = TextField()
170+ entries.append(ChatEntry(role: .user, content: text))
171+ let messages = turns()
172+ entries.append(ChatEntry(role: .assistant, content: "", model: model))
173+ answering = entries.count - 1
174+ generating = true
175+ scrollBack = 0
176+ usage = nil
177+ return .send(model: model, messages: messages, options: options)
178+ }
179+
180+ private mutating func newConversation() -> Action {
181+ guard !generating else {
182+ note("an answer is still coming: Esc to stop it first")
183+ return .redraw
184+ }
185+ entries = []
186+ scrollBack = 0
187+ return .redraw
188+ }
189+
190+ /// `/set <name> <value>`, `/set`, `/clear`, `/help`.
191+ private mutating func command(_ text: String) -> Action {
192+ let words = text.split(separator: " ").map(String.init)
193+ switch words.first {
194+ case "/set" where words.count == 1:
195+ note("settings: \(options.summary)")
196+ case "/set":
197+ do {
198+ try options.set(words[1], to: words.count > 2 ? words[2] : "")
199+ note("settings: \(options.summary)")
200+ } catch {
201+ note("\(error)")
202+ }
203+ case "/clear":
204+ return newConversation()
205+ case "/help":
206+ note(Self.help)
207+ default:
208+ note("unknown command \(words.first ?? ""): /help lists them")
209+ }
210+ return .redraw
211+ }
212+
213+ static let help =
214+ "Enter sends · Esc stops the answer · Ctrl-N new conversation · Ctrl-P model · "
215+ + "Ctrl-R reasoning shown/folded/hidden · PgUp/PgDn scroll · /set <name> <value> "
216+ + "(\(ChatOptions.names.joined(separator: ", ")); no value: server default) · /set · /clear"
217+
218+ /// Adds a line of the TUI's own to the conversation (errors, command output).
219+ public mutating func note(_ text: String) {
220+ entries.append(ChatEntry(role: .notice, content: text))
221+ }
222+
223+ /// The conversation as the server gets it: user messages and answers, without notices,
224+ /// reasoning or failed answers.
225+ public func turns() -> [ChatTurn] {
226+ entries.compactMap { entry in
227+ switch entry.role {
228+ case .user: ChatTurn(role: "user", content: entry.content)
229+ case .assistant where entry.failure == nil && !entry.content.isEmpty:
230+ ChatTurn(role: "assistant", content: entry.content)
231+ default: nil
232+ }
233+ }
234+ }
235+
236+ // MARK: The answer
237+
238+ /// A piece of the answer being streamed.
239+ public mutating func receive(_ event: ChatEvent) {
240+ guard generating, let index = answering else { return }
241+ switch event {
242+ case .content(let text): entries[index].content += text
243+ case .reasoning(let text): entries[index].reasoning += text
244+ case .finished: break
245+ case .usage(let prompt, let completion, let cached):
246+ usage = Usage(prompt: prompt, completion: completion, cached: cached)
247+ }
248+ }
249+
250+ /// The stream ended. `generationSeconds`: from the first piece to the last.
251+ public mutating func finish(generationSeconds: Double?) {
252+ let usage = self.usage
253+ endAnswer { entry in
254+ guard let usage else { return }
255+ var stats = "\(usage.prompt)+\(usage.completion) tokens"
256+ if usage.cached > 0 { stats += " · \(usage.cached) cached" }
257+ if let seconds = generationSeconds, seconds > 0, usage.completion > 0 {
258+ stats += String(format: " · %.1f tok/s", Double(usage.completion) / seconds)
259+ }
260+ entry.stats = stats
261+ }
262+ }
263+
264+ /// The answer was stopped (Esc): what came so far stays.
265+ public mutating func stop() {
266+ endAnswer { $0.stopped = true }
267+ }
268+
269+ /// The request failed.
270+ public mutating func fail(_ message: String) {
271+ endAnswer { $0.failure = message }
272+ }
273+
274+ private mutating func endAnswer(_ change: (inout ChatEntry) -> Void) {
275+ generating = false
276+ guard let index = answering else { return }
277+ answering = nil
278+ change(&entries[index])
279+ }
280+}
added Sources/RazorbillTUI/ConnectionView.swift +30 -0
new file mode 100644
@@ -0,0 +1,30 @@
1+/// What every screen shows while the server cannot be used: what is wrong and what to do.
2+public enum ConnectionView {
3+ /// `startCommand` is how this user starts the server (`rzb serve --config server.yaml`).
4+ public static func lines(_ state: Connection, url: String, startCommand: String) -> [String]? {
5+ switch state {
6+ case .connected:
7+ return nil
8+ case .connecting:
9+ return ["", " Connecting to \(url)…"]
10+ case .unreachable:
11+ return [
12+ "", " No razorbill server answers at \(url).", "",
13+ " Start one in another terminal:", "", " \(startCommand)", "",
14+ " This screen follows as soon as it answers.",
15+ ]
16+ case .unauthorized:
17+ return [
18+ "", " \(url) needs an API key, and rzb tui sent none or another one.", "",
19+ " Give rzb tui the variable that holds it, as rzb serve has it:", "",
20+ " rzb tui --api-key-env RZB_API_KEY",
21+ ]
22+ case .notLocal:
23+ return [
24+ "", " \(url) is not this machine.", "",
25+ " rzb tui watches a server running on the same machine; run it there,",
26+ " or forward the port: ssh -L 7920:127.0.0.1:7920 <host>",
27+ ]
28+ }
29+ }
30+}
new file mode 100644
@@ -0,0 +1,30 @@
1+/// What every screen shows while the server cannot be used: what is wrong and what to do.
2+public enum ConnectionView {
3+ /// `startCommand` is how this user starts the server (`rzb serve --config server.yaml`).
4+ public static func lines(_ state: Connection, url: String, startCommand: String) -> [String]? {
5+ switch state {
6+ case .connected:
7+ return nil
8+ case .connecting:
9+ return ["", " Connecting to \(url)…"]
10+ case .unreachable:
11+ return [
12+ "", " No razorbill server answers at \(url).", "",
13+ " Start one in another terminal:", "", " \(startCommand)", "",
14+ " This screen follows as soon as it answers.",
15+ ]
16+ case .unauthorized:
17+ return [
18+ "", " \(url) needs an API key, and rzb tui sent none or another one.", "",
19+ " Give rzb tui the variable that holds it, as rzb serve has it:", "",
20+ " rzb tui --api-key-env RZB_API_KEY",
21+ ]
22+ case .notLocal:
23+ return [
24+ "", " \(url) is not this machine.", "",
25+ " rzb tui watches a server running on the same machine; run it there,",
26+ " or forward the port: ssh -L 7920:127.0.0.1:7920 <host>",
27+ ]
28+ }
29+ }
30+}
added Sources/RazorbillTUI/DashboardScreen.swift +146 -0
new file mode 100644
@@ -0,0 +1,146 @@
1+import Foundation
2+
3+/// The Dashboard screen (#56): the server, the engine's memory, the loaded models — one of them
4+/// selected, `u` unloads it — and the last requests, from one ``StatusSnapshot``.
5+///
6+/// ```swift
7+/// var dashboard = DashboardScreen()
8+/// dashboard.handle(.arrowDown, snapshot: snapshot) // selects the second model
9+/// dashboard.handle(.character("u"), snapshot: snapshot) // .unload("qwen")
10+/// let lines = dashboard.render(snapshot, width: 100, height: 30, now: Date(), style: style)
11+/// ```
12+public struct DashboardScreen: Sendable, Equatable {
13+ /// What a key asks the app to do.
14+ public enum Action: Sendable, Equatable {
15+ case none
16+ case redraw
17+ /// Unload this model (its name, as `POST /rzb/models/{id}/unload` takes it).
18+ case unload(String)
19+ }
20+
21+ public private(set) var models = ListView()
22+ /// The outcome of the last action, shown under the requests.
23+ public var notice: String?
24+
25+ public init() {}
26+
27+ /// ↑ ↓ Page Up/Down Home End select a model; `u` unloads the selected one.
28+ public mutating func handle(_ key: Key, snapshot: StatusSnapshot?) -> Action {
29+ let loaded = snapshot?.models ?? []
30+ models.resize(to: loaded.count)
31+ if models.handle(key, pageSize: 5) { return .redraw }
32+ guard key == .character("u"), models.selected < loaded.count else { return .none }
33+ let model = loaded[models.selected]
34+ notice = "unloading \(model.name)…"
35+ return .unload(model.name)
36+ }
37+
38+ /// Exactly `height` lines (or fewer when the terminal is tiny).
39+ public mutating func render(
40+ _ snapshot: StatusSnapshot, width: Int, height: Int, now: Date, style: Style
41+ ) -> [String] {
42+ var top = [
43+ " Server rzb \(snapshot.version) · up \(Self.duration(snapshot.uptimeSeconds))"
44+ + " · \(snapshot.host):\(snapshot.port)",
45+ " Memory " + Self.memory(snapshot.memory),
46+ "",
47+ style.bold(" Models") + style.dim(" ↑↓ select · u unload"),
48+ style.dim(Self.modelHeader),
49+ ]
50+ let modelRows = snapshot.models.map(Self.modelRow)
51+ let room = max(1, (height - top.count - 4) / 2)
52+ if modelRows.isEmpty {
53+ top.append(" none loaded")
54+ } else {
55+ let shown = min(modelRows.count, room)
56+ top += models.render(modelRows, width: width, height: shown, style: style)
57+ }
58+ top += ["", style.bold(" Last requests"), style.dim(Self.requestHeader)]
59+ let left = max(0, height - top.count - (notice == nil ? 0 : 2))
60+ let requests = snapshot.recentRequests.prefix(left).map { Self.requestRow($0, now: now) }
61+ top += requests.isEmpty ? [" none yet"] : requests
62+ if let notice { top += ["", " " + notice] }
63+ return top.prefix(height).map { TextLayout.truncate($0, width: width) }
64+ }
65+
66+ // MARK: Rows
67+
68+ static let modelHeader =
69+ " " + columns(["NAME", "KIND", "STATE", "SIZE", "ACTIVITY"], widths: modelWidths)
70+ static let modelWidths = [24, 10, 8, 9, 0]
71+
72+ /// `qwen chat loaded 1.0 GB idle 7s, unloads in 9m 52s`, in columns.
73+ static func modelRow(_ model: LoadedModel) -> String {
74+ var activity: String
75+ if model.busy || model.queued > 0 {
76+ activity = model.queued > 0 ? "busy, \(model.queued) waiting" : "busy"
77+ } else {
78+ activity = "idle \(duration(Int(model.idleSeconds)))"
79+ if let left = model.keepAliveLeftSeconds {
80+ activity += ", unloads in \(duration(Int(left)))"
81+ }
82+ }
83+ let size = model.sizeBytes > 0 ? AppRenderer.gigabytes(model.sizeBytes) : "?"
84+ return " "
85+ + columns([model.name, model.kind, model.state, size, activity], widths: modelWidths)
86+ }
87+
88+ static let requestHeader =
89+ " "
90+ + columns(
91+ ["AGE", "REQUEST", "STATUS", "MODEL", "TOKENS", "CACHED", "TOK/S", "TIME"],
92+ widths: requestWidths)
93+ static let requestWidths = [7, 30, 7, 18, 11, 7, 7, 0]
94+
95+ /// `12s POST /v1/chat/completions 200 qwen 14+9 0 17.0 529ms`, in columns.
96+ static func requestRow(_ request: RecentRequest, now: Date) -> String {
97+ let age = Int(now.timeIntervalSince1970) - request.finishedAt
98+ let tokens = request.promptTokens.map { "\($0)+\(request.completionTokens ?? 0)" } ?? ""
99+ let cached = request.promptTokens == nil ? "" : "\(request.cachedTokens)"
100+ let speed = request.tokensPerSecond.map { String(format: "%.1f", $0) } ?? ""
101+ let fields = [
102+ duration(age), "\(request.method) \(request.path)", "\(request.status)",
103+ request.model ?? "", tokens, cached, speed, milliseconds(request.durationMs),
104+ ]
105+ return " " + columns(fields, widths: requestWidths)
106+ }
107+
108+ /// The memory line: a gauge of active / limit, then cache and peak.
109+ static func memory(_ memory: EngineMemory?) -> String {
110+ guard let memory else { return "not reported by this engine" }
111+ let used = AppRenderer.gigabytes(memory.activeBytes)
112+ let limit = AppRenderer.gigabytes(memory.limitBytes)
113+ return gauge(memory.activeBytes, of: memory.limitBytes) + " \(used) / \(limit) active"
114+ + " · cache \(AppRenderer.gigabytes(memory.cacheBytes))"
115+ + " · peak \(AppRenderer.gigabytes(memory.peakBytes))"
116+ }
117+
118+ /// `[████░░░░░░░░░░░░░░░░]`, 20 cells.
119+ static func gauge(_ value: Int64, of limit: Int64, cells: Int = 20) -> String {
120+ let ratio = limit > 0 ? min(1, max(0, Double(value) / Double(limit))) : 0
121+ let full = Int((ratio * Double(cells)).rounded())
122+ return "[" + String(repeating: "█", count: full)
123+ + String(repeating: "░", count: cells - full) + "]"
124+ }
125+
126+ /// Each field cut or padded to its width; a width of 0 takes the rest.
127+ static func columns(_ fields: [String], widths: [Int]) -> String {
128+ zip(fields, widths).map { field, width in
129+ width == 0 ? field : TextLayout.fit(field, width: width - 1) + " "
130+ }.joined()
131+ }
132+
133+ /// `45s`, `3m 12s`, `2h 05m`.
134+ static func duration(_ seconds: Int) -> String {
135+ let seconds = max(0, seconds)
136+ if seconds < 60 { return "\(seconds)s" }
137+ if seconds < 3600 { return "\(seconds / 60)m \(seconds % 60)s" }
138+ let minutes = (seconds % 3600) / 60
139+ return "\(seconds / 3600)h " + (minutes < 10 ? "0\(minutes)" : "\(minutes)") + "m"
140+ }
141+
142+ /// `529ms`, `2.1s`.
143+ static func milliseconds(_ value: Int) -> String {
144+ value < 1000 ? "\(value)ms" : String(format: "%.1fs", Double(value) / 1000)
145+ }
146+}
new file mode 100644
@@ -0,0 +1,146 @@
1+import Foundation
2+
3+/// The Dashboard screen (#56): the server, the engine's memory, the loaded models — one of them
4+/// selected, `u` unloads it — and the last requests, from one ``StatusSnapshot``.
5+///
6+/// ```swift
7+/// var dashboard = DashboardScreen()
8+/// dashboard.handle(.arrowDown, snapshot: snapshot) // selects the second model
9+/// dashboard.handle(.character("u"), snapshot: snapshot) // .unload("qwen")
10+/// let lines = dashboard.render(snapshot, width: 100, height: 30, now: Date(), style: style)
11+/// ```
12+public struct DashboardScreen: Sendable, Equatable {
13+ /// What a key asks the app to do.
14+ public enum Action: Sendable, Equatable {
15+ case none
16+ case redraw
17+ /// Unload this model (its name, as `POST /rzb/models/{id}/unload` takes it).
18+ case unload(String)
19+ }
20+
21+ public private(set) var models = ListView()
22+ /// The outcome of the last action, shown under the requests.
23+ public var notice: String?
24+
25+ public init() {}
26+
27+ /// ↑ ↓ Page Up/Down Home End select a model; `u` unloads the selected one.
28+ public mutating func handle(_ key: Key, snapshot: StatusSnapshot?) -> Action {
29+ let loaded = snapshot?.models ?? []
30+ models.resize(to: loaded.count)
31+ if models.handle(key, pageSize: 5) { return .redraw }
32+ guard key == .character("u"), models.selected < loaded.count else { return .none }
33+ let model = loaded[models.selected]
34+ notice = "unloading \(model.name)…"
35+ return .unload(model.name)
36+ }
37+
38+ /// Exactly `height` lines (or fewer when the terminal is tiny).
39+ public mutating func render(
40+ _ snapshot: StatusSnapshot, width: Int, height: Int, now: Date, style: Style
41+ ) -> [String] {
42+ var top = [
43+ " Server rzb \(snapshot.version) · up \(Self.duration(snapshot.uptimeSeconds))"
44+ + " · \(snapshot.host):\(snapshot.port)",
45+ " Memory " + Self.memory(snapshot.memory),
46+ "",
47+ style.bold(" Models") + style.dim(" ↑↓ select · u unload"),
48+ style.dim(Self.modelHeader),
49+ ]
50+ let modelRows = snapshot.models.map(Self.modelRow)
51+ let room = max(1, (height - top.count - 4) / 2)
52+ if modelRows.isEmpty {
53+ top.append(" none loaded")
54+ } else {
55+ let shown = min(modelRows.count, room)
56+ top += models.render(modelRows, width: width, height: shown, style: style)
57+ }
58+ top += ["", style.bold(" Last requests"), style.dim(Self.requestHeader)]
59+ let left = max(0, height - top.count - (notice == nil ? 0 : 2))
60+ let requests = snapshot.recentRequests.prefix(left).map { Self.requestRow($0, now: now) }
61+ top += requests.isEmpty ? [" none yet"] : requests
62+ if let notice { top += ["", " " + notice] }
63+ return top.prefix(height).map { TextLayout.truncate($0, width: width) }
64+ }
65+
66+ // MARK: Rows
67+
68+ static let modelHeader =
69+ " " + columns(["NAME", "KIND", "STATE", "SIZE", "ACTIVITY"], widths: modelWidths)
70+ static let modelWidths = [24, 10, 8, 9, 0]
71+
72+ /// `qwen chat loaded 1.0 GB idle 7s, unloads in 9m 52s`, in columns.
73+ static func modelRow(_ model: LoadedModel) -> String {
74+ var activity: String
75+ if model.busy || model.queued > 0 {
76+ activity = model.queued > 0 ? "busy, \(model.queued) waiting" : "busy"
77+ } else {
78+ activity = "idle \(duration(Int(model.idleSeconds)))"
79+ if let left = model.keepAliveLeftSeconds {
80+ activity += ", unloads in \(duration(Int(left)))"
81+ }
82+ }
83+ let size = model.sizeBytes > 0 ? AppRenderer.gigabytes(model.sizeBytes) : "?"
84+ return " "
85+ + columns([model.name, model.kind, model.state, size, activity], widths: modelWidths)
86+ }
87+
88+ static let requestHeader =
89+ " "
90+ + columns(
91+ ["AGE", "REQUEST", "STATUS", "MODEL", "TOKENS", "CACHED", "TOK/S", "TIME"],
92+ widths: requestWidths)
93+ static let requestWidths = [7, 30, 7, 18, 11, 7, 7, 0]
94+
95+ /// `12s POST /v1/chat/completions 200 qwen 14+9 0 17.0 529ms`, in columns.
96+ static func requestRow(_ request: RecentRequest, now: Date) -> String {
97+ let age = Int(now.timeIntervalSince1970) - request.finishedAt
98+ let tokens = request.promptTokens.map { "\($0)+\(request.completionTokens ?? 0)" } ?? ""
99+ let cached = request.promptTokens == nil ? "" : "\(request.cachedTokens)"
100+ let speed = request.tokensPerSecond.map { String(format: "%.1f", $0) } ?? ""
101+ let fields = [
102+ duration(age), "\(request.method) \(request.path)", "\(request.status)",
103+ request.model ?? "", tokens, cached, speed, milliseconds(request.durationMs),
104+ ]
105+ return " " + columns(fields, widths: requestWidths)
106+ }
107+
108+ /// The memory line: a gauge of active / limit, then cache and peak.
109+ static func memory(_ memory: EngineMemory?) -> String {
110+ guard let memory else { return "not reported by this engine" }
111+ let used = AppRenderer.gigabytes(memory.activeBytes)
112+ let limit = AppRenderer.gigabytes(memory.limitBytes)
113+ return gauge(memory.activeBytes, of: memory.limitBytes) + " \(used) / \(limit) active"
114+ + " · cache \(AppRenderer.gigabytes(memory.cacheBytes))"
115+ + " · peak \(AppRenderer.gigabytes(memory.peakBytes))"
116+ }
117+
118+ /// `[████░░░░░░░░░░░░░░░░]`, 20 cells.
119+ static func gauge(_ value: Int64, of limit: Int64, cells: Int = 20) -> String {
120+ let ratio = limit > 0 ? min(1, max(0, Double(value) / Double(limit))) : 0
121+ let full = Int((ratio * Double(cells)).rounded())
122+ return "[" + String(repeating: "█", count: full)
123+ + String(repeating: "░", count: cells - full) + "]"
124+ }
125+
126+ /// Each field cut or padded to its width; a width of 0 takes the rest.
127+ static func columns(_ fields: [String], widths: [Int]) -> String {
128+ zip(fields, widths).map { field, width in
129+ width == 0 ? field : TextLayout.fit(field, width: width - 1) + " "
130+ }.joined()
131+ }
132+
133+ /// `45s`, `3m 12s`, `2h 05m`.
134+ static func duration(_ seconds: Int) -> String {
135+ let seconds = max(0, seconds)
136+ if seconds < 60 { return "\(seconds)s" }
137+ if seconds < 3600 { return "\(seconds / 60)m \(seconds % 60)s" }
138+ let minutes = (seconds % 3600) / 60
139+ return "\(seconds / 3600)h " + (minutes < 10 ? "0\(minutes)" : "\(minutes)") + "m"
140+ }
141+
142+ /// `529ms`, `2.1s`.
143+ static func milliseconds(_ value: Int) -> String {
144+ value < 1000 ? "\(value)ms" : String(format: "%.1fs", Double(value) / 1000)
145+ }
146+}
deleted Sources/RazorbillTUI/DashboardView.swift +0 -98
deleted file mode 100644
@@ -1,98 +0,0 @@
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-}
deleted file mode 100644
@@ -1,98 +0,0 @@
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-}
modified Sources/RazorbillTUI/ListView.swift +2 -1
@@ -57,7 +57,8 @@ public struct ListView: Sendable, Equatable {
5757 return lines + Array(repeating: "", count: max(0, height - lines.count))
5858 }
5959
60- private mutating func select(_ row: Int) {
60+ /// Selects `row`, kept within the list.
61+ public mutating func select(_ row: Int) {
6162 selected = count == 0 ? 0 : min(max(row, 0), count - 1)
6263 }
6364
@@ -57,7 +57,8 @@ public struct ListView: Sendable, Equatable {
57 return lines + Array(repeating: "", count: max(0, height - lines.count))57 return lines + Array(repeating: "", count: max(0, height - lines.count))
58 }58 }
59 59
60- private mutating func select(_ row: Int) {60+ /// Selects `row`, kept within the list.
61+ public mutating func select(_ row: Int) {
61 selected = count == 0 ? 0 : min(max(row, 0), count - 1)62 selected = count == 0 ? 0 : min(max(row, 0), count - 1)
62 }63 }
63 64
modified Sources/RazorbillTUI/ServerAPI.swift +95 -1
@@ -36,8 +36,18 @@ public struct RecentRequest: Sendable, Equatable, Decodable {
3636 public var promptTokens: Int?
3737 public var completionTokens: Int?
3838 public var cachedTokens: Int
39+ /// Time to the first byte; absent from servers before razorbill 0.3.
40+ public var firstByteMs: Int?
41+ /// Time to the last byte (to the first, before razorbill 0.3).
3942 public var durationMs: Int
43+ /// Unix seconds.
4044 public var finishedAt: Int
45+
46+ /// Completion tokens per second over the whole request, prompt processing included.
47+ public var tokensPerSecond: Double? {
48+ guard let completionTokens, completionTokens > 0, durationMs > 0 else { return nil }
49+ return Double(completionTokens) / (Double(durationMs) / 1000)
50+ }
4151 }
4252
4353 /// ``StatusSnapshot/memory``, in bytes.
@@ -91,5 +101,89 @@ public enum ChatEvent: Sendable, Equatable {
91101 case reasoning(String)
92102 /// `stop`, `length`, `tool_calls`…
93103 case finished(reason: String)
94- case usage(promptTokens: Int, completionTokens: Int)
104+ /// `cachedTokens`: prompt tokens the server reused from its prompt cache.
105+ case usage(promptTokens: Int, completionTokens: Int, cachedTokens: Int)
106+}
107+
108+/// Sampling settings of a chat request; `nil` leaves the server's value.
109+///
110+/// ```swift
111+/// var options = ChatOptions()
112+/// try options.set("temperature", to: "0.7")
113+/// try options.set("thinking", to: "off")
114+/// options.summary // "temperature 0.7 · thinking off"
115+/// ```
116+public struct ChatOptions: Sendable, Equatable {
117+ public var temperature: Double?
118+ public var topP: Double?
119+ public var topK: Int?
120+ public var minP: Double?
121+ public var maxTokens: Int?
122+ /// Turns the model's reasoning on or off (`chat_template_kwargs.enable_thinking`).
123+ public var thinking: Bool?
124+
125+ public init() {}
126+
127+ /// The names ``set(_:to:)`` takes, in display order.
128+ public static let names = ["temperature", "top_p", "top_k", "min_p", "max_tokens", "thinking"]
129+
130+ /// Why a setting was refused.
131+ public struct Invalid: Error, Equatable, CustomStringConvertible {
132+ public let description: String
133+ }
134+
135+ /// Sets `name` from text; an empty `value` (or `default`) gives the setting back to the server.
136+ public mutating func set(_ name: String, to value: String) throws {
137+ let cleared = value.isEmpty || value == "default"
138+ switch name {
139+ case "temperature": temperature = try cleared ? nil : Self.number(value, name, 0 ... 2)
140+ case "top_p": topP = try cleared ? nil : Self.number(value, name, 0 ... 1)
141+ case "min_p": minP = try cleared ? nil : Self.number(value, name, 0 ... 1)
142+ case "top_k": topK = try cleared ? nil : Self.whole(value, name, 0 ... 1_000_000)
143+ case "max_tokens": maxTokens = try cleared ? nil : Self.whole(value, name, 1 ... 1_000_000)
144+ case "thinking":
145+ guard cleared || ["on", "off"].contains(value) else {
146+ throw Invalid(description: "thinking is on, off or default")
147+ }
148+ thinking = cleared ? nil : value == "on"
149+ default:
150+ let known = Self.names.joined(separator: ", ")
151+ throw Invalid(description: "unknown setting \(name) (one of: \(known))")
152+ }
153+ }
154+
155+ /// `temperature 0.7 · max_tokens 400`, or `server defaults` when nothing is set.
156+ public var summary: String {
157+ var parts: [String] = []
158+ if let temperature { parts.append("temperature \(Self.text(temperature))") }
159+ if let topP { parts.append("top_p \(Self.text(topP))") }
160+ if let topK { parts.append("top_k \(topK)") }
161+ if let minP { parts.append("min_p \(Self.text(minP))") }
162+ if let maxTokens { parts.append("max_tokens \(maxTokens)") }
163+ if let thinking { parts.append("thinking \(thinking ? "on" : "off")") }
164+ return parts.isEmpty ? "server defaults" : parts.joined(separator: " · ")
165+ }
166+
167+ private static func number(
168+ _ value: String, _ name: String, _ range: ClosedRange<Double>
169+ ) throws -> Double {
170+ guard let number = Double(value), range.contains(number) else {
171+ let bounds = "\(text(range.lowerBound)) to \(text(range.upperBound))"
172+ throw Invalid(description: "\(name) is a number from \(bounds)")
173+ }
174+ return number
175+ }
176+
177+ private static func whole(
178+ _ value: String, _ name: String, _ range: ClosedRange<Int>
179+ ) throws -> Int {
180+ guard let number = Int(value), range.contains(number) else {
181+ throw Invalid(description: "\(name) is a whole number from \(range.lowerBound)")
182+ }
183+ return number
184+ }
185+
186+ private static func text(_ value: Double) -> String {
187+ value == value.rounded() ? String(Int(value)) : String(value)
188+ }
95189 }
@@ -36,8 +36,18 @@ public struct RecentRequest: Sendable, Equatable, Decodable {
36 public var promptTokens: Int?36 public var promptTokens: Int?
37 public var completionTokens: Int?37 public var completionTokens: Int?
38 public var cachedTokens: Int38 public var cachedTokens: Int
39+ /// Time to the first byte; absent from servers before razorbill 0.3.
40+ public var firstByteMs: Int?
41+ /// Time to the last byte (to the first, before razorbill 0.3).
39 public var durationMs: Int42 public var durationMs: Int
43+ /// Unix seconds.
40 public var finishedAt: Int44 public var finishedAt: Int
45+
46+ /// Completion tokens per second over the whole request, prompt processing included.
47+ public var tokensPerSecond: Double? {
48+ guard let completionTokens, completionTokens > 0, durationMs > 0 else { return nil }
49+ return Double(completionTokens) / (Double(durationMs) / 1000)
50+ }
41 }51 }
42 52
43 /// ``StatusSnapshot/memory``, in bytes.53 /// ``StatusSnapshot/memory``, in bytes.
@@ -91,5 +101,89 @@ public enum ChatEvent: Sendable, Equatable {
91 case reasoning(String)101 case reasoning(String)
92 /// `stop`, `length`, `tool_calls`…102 /// `stop`, `length`, `tool_calls`…
93 case finished(reason: String)103 case finished(reason: String)
94- case usage(promptTokens: Int, completionTokens: Int)104+ /// `cachedTokens`: prompt tokens the server reused from its prompt cache.
105+ case usage(promptTokens: Int, completionTokens: Int, cachedTokens: Int)
106+}
107+
108+/// Sampling settings of a chat request; `nil` leaves the server's value.
109+///
110+/// ```swift
111+/// var options = ChatOptions()
112+/// try options.set("temperature", to: "0.7")
113+/// try options.set("thinking", to: "off")
114+/// options.summary // "temperature 0.7 · thinking off"
115+/// ```
116+public struct ChatOptions: Sendable, Equatable {
117+ public var temperature: Double?
118+ public var topP: Double?
119+ public var topK: Int?
120+ public var minP: Double?
121+ public var maxTokens: Int?
122+ /// Turns the model's reasoning on or off (`chat_template_kwargs.enable_thinking`).
123+ public var thinking: Bool?
124+
125+ public init() {}
126+
127+ /// The names ``set(_:to:)`` takes, in display order.
128+ public static let names = ["temperature", "top_p", "top_k", "min_p", "max_tokens", "thinking"]
129+
130+ /// Why a setting was refused.
131+ public struct Invalid: Error, Equatable, CustomStringConvertible {
132+ public let description: String
133+ }
134+
135+ /// Sets `name` from text; an empty `value` (or `default`) gives the setting back to the server.
136+ public mutating func set(_ name: String, to value: String) throws {
137+ let cleared = value.isEmpty || value == "default"
138+ switch name {
139+ case "temperature": temperature = try cleared ? nil : Self.number(value, name, 0 ... 2)
140+ case "top_p": topP = try cleared ? nil : Self.number(value, name, 0 ... 1)
141+ case "min_p": minP = try cleared ? nil : Self.number(value, name, 0 ... 1)
142+ case "top_k": topK = try cleared ? nil : Self.whole(value, name, 0 ... 1_000_000)
143+ case "max_tokens": maxTokens = try cleared ? nil : Self.whole(value, name, 1 ... 1_000_000)
144+ case "thinking":
145+ guard cleared || ["on", "off"].contains(value) else {
146+ throw Invalid(description: "thinking is on, off or default")
147+ }
148+ thinking = cleared ? nil : value == "on"
149+ default:
150+ let known = Self.names.joined(separator: ", ")
151+ throw Invalid(description: "unknown setting \(name) (one of: \(known))")
152+ }
153+ }
154+
155+ /// `temperature 0.7 · max_tokens 400`, or `server defaults` when nothing is set.
156+ public var summary: String {
157+ var parts: [String] = []
158+ if let temperature { parts.append("temperature \(Self.text(temperature))") }
159+ if let topP { parts.append("top_p \(Self.text(topP))") }
160+ if let topK { parts.append("top_k \(topK)") }
161+ if let minP { parts.append("min_p \(Self.text(minP))") }
162+ if let maxTokens { parts.append("max_tokens \(maxTokens)") }
163+ if let thinking { parts.append("thinking \(thinking ? "on" : "off")") }
164+ return parts.isEmpty ? "server defaults" : parts.joined(separator: " · ")
165+ }
166+
167+ private static func number(
168+ _ value: String, _ name: String, _ range: ClosedRange<Double>
169+ ) throws -> Double {
170+ guard let number = Double(value), range.contains(number) else {
171+ let bounds = "\(text(range.lowerBound)) to \(text(range.upperBound))"
172+ throw Invalid(description: "\(name) is a number from \(bounds)")
173+ }
174+ return number
175+ }
176+
177+ private static func whole(
178+ _ value: String, _ name: String, _ range: ClosedRange<Int>
179+ ) throws -> Int {
180+ guard let number = Int(value), range.contains(number) else {
181+ throw Invalid(description: "\(name) is a whole number from \(range.lowerBound)")
182+ }
183+ return number
184+ }
185+
186+ private static func text(_ value: Double) -> String {
187+ value == value.rounded() ? String(Int(value)) : String(value)
188+ }
95 }189 }
modified Sources/RazorbillTUI/ServerClient.swift +28 -6
@@ -104,8 +104,10 @@ public struct ServerClient: Sendable {
104104
105105 /// Streams the answer to `messages`. Cancelling the consuming task closes the connection,
106106 /// which stops the generation on the server.
107- public func chat(model: String, messages: [ChatTurn]) -> ChatStream {
108- let body = ChatBody(model: model, messages: messages)
107+ public func chat(
108+ model: String, messages: [ChatTurn], options: ChatOptions = ChatOptions()
109+ ) -> ChatStream {
110+ let body = ChatBody(model: model, messages: messages, options: options)
109111 return AsyncThrowingStream { continuation in
110112 let task = Task {
111113 do {
@@ -200,16 +202,36 @@ public struct ServerClient: Sendable {
200202 }()
201203 }
202204
203-/// The body of a streamed chat request.
205+/// The body of a streamed chat request: only the options that are set are sent.
204206 private struct ChatBody: Encodable {
205207 let model: String
206208 let messages: [ChatTurn]
207- let stream = true
208- let streamOptions = StreamOptions()
209+ let options: ChatOptions
209210
210211 enum CodingKeys: String, CodingKey {
211- case model, messages, stream
212+ case model, messages, stream, temperature
212213 case streamOptions = "stream_options"
214+ case topP = "top_p"
215+ case topK = "top_k"
216+ case minP = "min_p"
217+ case maxTokens = "max_tokens"
218+ case templateArguments = "chat_template_kwargs"
219+ }
220+
221+ func encode(to encoder: any Encoder) throws {
222+ var container = encoder.container(keyedBy: CodingKeys.self)
223+ try container.encode(model, forKey: .model)
224+ try container.encode(messages, forKey: .messages)
225+ try container.encode(true, forKey: .stream)
226+ try container.encode(StreamOptions(), forKey: .streamOptions)
227+ try container.encodeIfPresent(options.temperature, forKey: .temperature)
228+ try container.encodeIfPresent(options.topP, forKey: .topP)
229+ try container.encodeIfPresent(options.topK, forKey: .topK)
230+ try container.encodeIfPresent(options.minP, forKey: .minP)
231+ try container.encodeIfPresent(options.maxTokens, forKey: .maxTokens)
232+ if let thinking = options.thinking {
233+ try container.encode(["enable_thinking": thinking], forKey: .templateArguments)
234+ }
213235 }
214236 }
215237
@@ -104,8 +104,10 @@ public struct ServerClient: Sendable {
104 104
105 /// Streams the answer to `messages`. Cancelling the consuming task closes the connection,105 /// Streams the answer to `messages`. Cancelling the consuming task closes the connection,
106 /// which stops the generation on the server.106 /// which stops the generation on the server.
107- public func chat(model: String, messages: [ChatTurn]) -> ChatStream {107+ public func chat(
108- let body = ChatBody(model: model, messages: messages)108+ model: String, messages: [ChatTurn], options: ChatOptions = ChatOptions()
109+ ) -> ChatStream {
110+ let body = ChatBody(model: model, messages: messages, options: options)
109 return AsyncThrowingStream { continuation in111 return AsyncThrowingStream { continuation in
110 let task = Task {112 let task = Task {
111 do {113 do {
@@ -200,16 +202,36 @@ public struct ServerClient: Sendable {
200 }()202 }()
201 }203 }
202 204
203-/// The body of a streamed chat request.205+/// The body of a streamed chat request: only the options that are set are sent.
204 private struct ChatBody: Encodable {206 private struct ChatBody: Encodable {
205 let model: String207 let model: String
206 let messages: [ChatTurn]208 let messages: [ChatTurn]
207- let stream = true209+ let options: ChatOptions
208- let streamOptions = StreamOptions()
209 210
210 enum CodingKeys: String, CodingKey {211 enum CodingKeys: String, CodingKey {
211- case model, messages, stream212+ case model, messages, stream, temperature
212 case streamOptions = "stream_options"213 case streamOptions = "stream_options"
214+ case topP = "top_p"
215+ case topK = "top_k"
216+ case minP = "min_p"
217+ case maxTokens = "max_tokens"
218+ case templateArguments = "chat_template_kwargs"
219+ }
220+
221+ func encode(to encoder: any Encoder) throws {
222+ var container = encoder.container(keyedBy: CodingKeys.self)
223+ try container.encode(model, forKey: .model)
224+ try container.encode(messages, forKey: .messages)
225+ try container.encode(true, forKey: .stream)
226+ try container.encode(StreamOptions(), forKey: .streamOptions)
227+ try container.encodeIfPresent(options.temperature, forKey: .temperature)
228+ try container.encodeIfPresent(options.topP, forKey: .topP)
229+ try container.encodeIfPresent(options.topK, forKey: .topK)
230+ try container.encodeIfPresent(options.minP, forKey: .minP)
231+ try container.encodeIfPresent(options.maxTokens, forKey: .maxTokens)
232+ if let thinking = options.thinking {
233+ try container.encode(["enable_thinking": thinking], forKey: .templateArguments)
234+ }
213 }235 }
214 }236 }
215 237
modified Sources/RazorbillTUI/TUIApp.swift +160 -24
@@ -1,45 +1,66 @@
1+import Foundation
2+
13 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
24 public protocol StatusSource: Sendable {
35 func status() async throws -> StatusSnapshot
46 }
57
6-extension ServerClient: StatusSource {}
8+/// Everything the TUI asks the server.
9+public protocol TUIServer: StatusSource {
10+ func models() async throws -> [ServedModel]
11+ func unload(_ id: String) async throws -> UnloadReply
12+ func chat(model: String, messages: [ChatTurn], options: ChatOptions) -> ServerClient.ChatStream
13+}
14+
15+extension ServerClient: TUIServer {}
716
8-/// The full-screen app: reads keys, polls the server's status every `pollInterval`, draws.
17+/// The full-screen app: reads keys, polls the server's status every `pollInterval`, runs the
18+/// screens' actions (unload, chat) and draws.
919 ///
1020 /// ```swift
1121 /// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil)
12-/// await TUIApp(terminal: PosixTerminal(), source: client, serverURL: client.baseURL).run()
22+/// await TUIApp(terminal: PosixTerminal(), server: client, serverURL: client.baseURL).run()
1323 /// ```
1424 public actor TUIApp {
1525 private let terminal: any Terminal
16- private let source: any StatusSource
26+ private let server: any TUIServer
1727 private let renderer: AppRenderer
28+ private let chatRenderer: ChatRenderer
1829 private let pollInterval: Duration
1930 private let startCommand: String
31+ private let now: @Sendable () -> Date
2032 private var state: AppState
2133 private var snapshot: StatusSnapshot?
22- /// False once `run` returns: a poll still in flight must not draw on the restored terminal.
34+ private var dashboard = DashboardScreen()
35+ private var chat = ChatScreen()
36+ private var answer: Task<Void, Never>?
37+ private var modelsRequested = false
38+ /// False once `run` returns: work still in flight must not draw on the restored terminal.
2339 private var running = false
2440
2541 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
2642 public init(
27- terminal: any Terminal, source: any StatusSource, serverURL: String,
43+ terminal: any Terminal, server: any TUIServer, serverURL: String,
2844 startCommand: String = "rzb serve", colors: Bool = true,
29- pollInterval: Duration = .seconds(1)
45+ pollInterval: Duration = .seconds(1), now: @escaping @Sendable () -> Date = { Date() }
3046 ) {
3147 self.terminal = terminal
32- self.source = source
48+ self.server = server
3349 self.renderer = AppRenderer(style: Style(colors: colors))
50+ self.chatRenderer = ChatRenderer(style: Style(colors: colors))
3451 self.pollInterval = pollInterval
3552 self.startCommand = startCommand
53+ self.now = now
3654 self.state = AppState(serverURL: serverURL)
3755 }
3856
3957 /// The current state (tests).
4058 public var currentState: AppState { state }
59+ public var chatScreen: ChatScreen { chat }
60+ public var dashboardScreen: DashboardScreen { dashboard }
4161
42- /// Runs until Ctrl-C / Ctrl-Q or the end of input; the terminal is always restored.
62+ /// Runs until Ctrl-Q (or Ctrl-C outside a generation) or the end of input; the terminal is
63+ /// always restored.
4364 public func run() async {
4465 terminal.enter()
4566 running = true
@@ -47,18 +68,122 @@ public actor TUIApp {
4768 defer {
4869 running = false
4970 polling.cancel()
71+ answer?.cancel()
5072 terminal.leave()
5173 }
5274 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
75+ for await key in terminal.keys() where !press(key) {
76+ return
77+ }
78+ }
79+
80+ /// Handles one key; `false` means quit.
81+ func press(_ key: Key) -> Bool {
82+ if key == .control("c"), state.screen == .chat, chat.generating {
83+ answer?.cancel()
84+ return true
85+ }
86+ switch state.handle(key) {
87+ case .quit:
88+ return false
89+ case .redraw:
90+ screenShown()
91+ case .none:
92+ forward(key)
93+ }
94+ redraw()
95+ return true
96+ }
97+
98+ /// A key the frame does not use goes to the current screen.
99+ private func forward(_ key: Key) {
100+ switch state.screen {
101+ case .dashboard:
102+ if case .unload(let name) = dashboard.handle(key, snapshot: snapshot) {
103+ Task { await unload(name) }
104+ }
105+ case .chat:
106+ perform(chat.handle(key))
107+ case .models, .settings:
108+ break
109+ }
110+ }
111+
112+ private func screenShown() {
113+ if state.screen == .chat && !modelsRequested { loadModels() }
114+ }
115+
116+ // MARK: Actions
117+
118+ private func perform(_ action: ChatScreen.Action) {
119+ switch action {
120+ case .none, .redraw:
121+ break
122+ case .send(let model, let messages, let options):
123+ answer = Task { await stream(model: model, messages: messages, options: options) }
124+ case .cancel:
125+ answer?.cancel()
126+ case .loadModels:
127+ loadModels()
128+ }
129+ }
130+
131+ private func loadModels() {
132+ modelsRequested = true
133+ Task { await fetchModels() }
134+ }
135+
136+ func fetchModels() async {
137+ do {
138+ chat.setModels(try await server.models())
139+ } catch {
140+ modelsRequested = false
141+ chat.note("cannot list the models: \(error)")
142+ }
143+ redraw()
144+ }
145+
146+ /// Streams one answer into the Chat screen. Cancelling the task stops reading, which closes
147+ /// the connection and stops the generation on the server.
148+ func stream(model: String, messages: [ChatTurn], options: ChatOptions) async {
149+ var firstPiece: ContinuousClock.Instant?
150+ do {
151+ for try await event in server.chat(model: model, messages: messages, options: options) {
152+ if firstPiece == nil { firstPiece = .now }
153+ chat.receive(event)
154+ redraw()
58155 }
156+ if Task.isCancelled {
157+ chat.stop()
158+ } else {
159+ let seconds = firstPiece.map { (ContinuousClock.now - $0) / .seconds(1) }
160+ chat.finish(generationSeconds: seconds)
161+ }
162+ } catch is CancellationError {
163+ chat.stop()
164+ } catch {
165+ chat.fail("\(error)")
166+ }
167+ redraw()
168+ }
169+
170+ func unload(_ name: String) async {
171+ do {
172+ let reply = try await server.unload(name)
173+ dashboard.notice =
174+ reply.status == "unloaded"
175+ ? "unloaded \(name) (\(reply.unloaded.joined(separator: ", ")))"
176+ : "\(name) was not loaded"
177+ } catch let ServerClientError.server(_, _, message) {
178+ dashboard.notice = message
179+ } catch {
180+ dashboard.notice = "cannot unload \(name): \(error)"
59181 }
182+ await refresh()
60183 }
61184
185+ // MARK: Status
186+
62187 private func poll() async {
63188 while !Task.isCancelled {
64189 await refresh()
@@ -69,8 +194,7 @@ public actor TUIApp {
69194 /// Asks the server once and updates the status bar and the Dashboard.
70195 func refresh() async {
71196 do {
72- let status = try await source.status()
73- apply(status)
197+ apply(try await server.status())
74198 } catch let error as ServerClientError {
75199 if let connection = error.connection { lose(connection) }
76200 } catch {
@@ -80,10 +204,12 @@ public actor TUIApp {
80204 }
81205
82206 private func apply(_ status: StatusSnapshot) {
207+ let wasConnected = if case .connected = state.connection { true } else { false }
83208 snapshot = status
84209 state.connection = .connected(version: status.version)
85210 state.model = status.models.first?.name
86211 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
212+ if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() }
87213 }
88214
89215 private func lose(_ connection: Connection) {
@@ -93,23 +219,33 @@ public actor TUIApp {
93219 state.memory = nil
94220 }
95221
222+ // MARK: Drawing
223+
96224 private func redraw() {
97225 guard running else { return }
98226 let size = terminal.size
99- let bodyHeight = max(1, size.rows - 2)
227+ let height = max(1, size.rows - 2)
228+ let (body, cursor) = body(width: size.columns, height: height)
100229 terminal.draw(
101230 renderer.render(
102- state, body: body(width: size.columns, height: bodyHeight), rows: size.rows,
103- columns: size.columns))
231+ state, body: body, cursor: cursor, rows: size.rows, columns: size.columns))
104232 }
105233
106- private func body(width: Int, height: Int) -> [String] {
234+ private func body(width: Int, height: Int) -> ([String], FormView.Cursor?) {
107235 let problem = ConnectionView.lines(
108236 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)
237+ if let problem { return (problem, nil) }
238+ switch state.screen {
239+ case .dashboard:
240+ guard let snapshot else { return (["", " Waiting for the server's status…"], nil) }
241+ let lines = dashboard.render(
242+ snapshot, width: width, height: height - 1, now: now(), style: renderer.style)
243+ return ([""] + lines, nil)
244+ 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)
112249 }
113- return [""] + DashboardView.lines(snapshot, width: width, height: height - 1)
114250 }
115251 }
@@ -1,45 +1,66 @@
1+import Foundation
2+
1 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.3 /// Where the TUI reads the server's state. ``ServerClient`` is the real one; tests script it.
2 public protocol StatusSource: Sendable {4 public protocol StatusSource: Sendable {
3 func status() async throws -> StatusSnapshot5 func status() async throws -> StatusSnapshot
4 }6 }
5 7
6-extension ServerClient: StatusSource {}8+/// Everything the TUI asks the server.
9+public protocol TUIServer: StatusSource {
10+ func models() async throws -> [ServedModel]
11+ func unload(_ id: String) async throws -> UnloadReply
12+ func chat(model: String, messages: [ChatTurn], options: ChatOptions) -> ServerClient.ChatStream
13+}
14+
15+extension ServerClient: TUIServer {}
7 16
8-/// The full-screen app: reads keys, polls the server's status every `pollInterval`, draws.17+/// The full-screen app: reads keys, polls the server's status every `pollInterval`, runs the
18+/// screens' actions (unload, chat) and draws.
9 ///19 ///
10 /// ```swift20 /// ```swift
11 /// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil)21 /// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil)
12-/// await TUIApp(terminal: PosixTerminal(), source: client, serverURL: client.baseURL).run()22+/// await TUIApp(terminal: PosixTerminal(), server: client, serverURL: client.baseURL).run()
13 /// ```23 /// ```
14 public actor TUIApp {24 public actor TUIApp {
15 private let terminal: any Terminal25 private let terminal: any Terminal
16- private let source: any StatusSource26+ private let server: any TUIServer
17 private let renderer: AppRenderer27 private let renderer: AppRenderer
28+ private let chatRenderer: ChatRenderer
18 private let pollInterval: Duration29 private let pollInterval: Duration
19 private let startCommand: String30 private let startCommand: String
31+ private let now: @Sendable () -> Date
20 private var state: AppState32 private var state: AppState
21 private var snapshot: StatusSnapshot?33 private var snapshot: StatusSnapshot?
22- /// False once `run` returns: a poll still in flight must not draw on the restored terminal.34+ private var dashboard = DashboardScreen()
35+ private var chat = ChatScreen()
36+ private var answer: Task<Void, Never>?
37+ private var modelsRequested = false
38+ /// False once `run` returns: work still in flight must not draw on the restored terminal.
23 private var running = false39 private var running = false
24 40
25 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.41 /// - Parameter startCommand: shown when no server answers, e.g. `rzb serve --config s.yaml`.
26 public init(42 public init(
27- terminal: any Terminal, source: any StatusSource, serverURL: String,43+ terminal: any Terminal, server: any TUIServer, serverURL: String,
28 startCommand: String = "rzb serve", colors: Bool = true,44 startCommand: String = "rzb serve", colors: Bool = true,
29- pollInterval: Duration = .seconds(1)45+ pollInterval: Duration = .seconds(1), now: @escaping @Sendable () -> Date = { Date() }
30 ) {46 ) {
31 self.terminal = terminal47 self.terminal = terminal
32- self.source = source48+ self.server = server
33 self.renderer = AppRenderer(style: Style(colors: colors))49 self.renderer = AppRenderer(style: Style(colors: colors))
50+ self.chatRenderer = ChatRenderer(style: Style(colors: colors))
34 self.pollInterval = pollInterval51 self.pollInterval = pollInterval
35 self.startCommand = startCommand52 self.startCommand = startCommand
53+ self.now = now
36 self.state = AppState(serverURL: serverURL)54 self.state = AppState(serverURL: serverURL)
37 }55 }
38 56
39 /// The current state (tests).57 /// The current state (tests).
40 public var currentState: AppState { state }58 public var currentState: AppState { state }
59+ public var chatScreen: ChatScreen { chat }
60+ public var dashboardScreen: DashboardScreen { dashboard }
41 61
42- /// Runs until Ctrl-C / Ctrl-Q or the end of input; the terminal is always restored.62+ /// Runs until Ctrl-Q (or Ctrl-C outside a generation) or the end of input; the terminal is
63+ /// always restored.
43 public func run() async {64 public func run() async {
44 terminal.enter()65 terminal.enter()
45 running = true66 running = true
@@ -47,18 +68,122 @@ public actor TUIApp {
47 defer {68 defer {
48 running = false69 running = false
49 polling.cancel()70 polling.cancel()
71+ answer?.cancel()
50 terminal.leave()72 terminal.leave()
51 }73 }
52 redraw()74 redraw()
53- for await key in terminal.keys() {75+ for await key in terminal.keys() where !press(key) {
54- switch state.handle(key) {76+ return
55- case .quit: return77+ }
56- case .redraw: redraw()78+ }
57- case .none: break79+
80+ /// Handles one key; `false` means quit.
81+ func press(_ key: Key) -> Bool {
82+ if key == .control("c"), state.screen == .chat, chat.generating {
83+ answer?.cancel()
84+ return true
85+ }
86+ switch state.handle(key) {
87+ case .quit:
88+ return false
89+ case .redraw:
90+ screenShown()
91+ case .none:
92+ forward(key)
93+ }
94+ redraw()
95+ return true
96+ }
97+
98+ /// A key the frame does not use goes to the current screen.
99+ private func forward(_ key: Key) {
100+ switch state.screen {
101+ case .dashboard:
102+ if case .unload(let name) = dashboard.handle(key, snapshot: snapshot) {
103+ Task { await unload(name) }
104+ }
105+ case .chat:
106+ perform(chat.handle(key))
107+ case .models, .settings:
108+ break
109+ }
110+ }
111+
112+ private func screenShown() {
113+ if state.screen == .chat && !modelsRequested { loadModels() }
114+ }
115+
116+ // MARK: Actions
117+
118+ private func perform(_ action: ChatScreen.Action) {
119+ switch action {
120+ case .none, .redraw:
121+ break
122+ case .send(let model, let messages, let options):
123+ answer = Task { await stream(model: model, messages: messages, options: options) }
124+ case .cancel:
125+ answer?.cancel()
126+ case .loadModels:
127+ loadModels()
128+ }
129+ }
130+
131+ private func loadModels() {
132+ modelsRequested = true
133+ Task { await fetchModels() }
134+ }
135+
136+ func fetchModels() async {
137+ do {
138+ chat.setModels(try await server.models())
139+ } catch {
140+ modelsRequested = false
141+ chat.note("cannot list the models: \(error)")
142+ }
143+ redraw()
144+ }
145+
146+ /// Streams one answer into the Chat screen. Cancelling the task stops reading, which closes
147+ /// the connection and stops the generation on the server.
148+ func stream(model: String, messages: [ChatTurn], options: ChatOptions) async {
149+ var firstPiece: ContinuousClock.Instant?
150+ do {
151+ for try await event in server.chat(model: model, messages: messages, options: options) {
152+ if firstPiece == nil { firstPiece = .now }
153+ chat.receive(event)
154+ redraw()
58 }155 }
156+ if Task.isCancelled {
157+ chat.stop()
158+ } else {
159+ let seconds = firstPiece.map { (ContinuousClock.now - $0) / .seconds(1) }
160+ chat.finish(generationSeconds: seconds)
161+ }
162+ } catch is CancellationError {
163+ chat.stop()
164+ } catch {
165+ chat.fail("\(error)")
166+ }
167+ redraw()
168+ }
169+
170+ func unload(_ name: String) async {
171+ do {
172+ let reply = try await server.unload(name)
173+ dashboard.notice =
174+ reply.status == "unloaded"
175+ ? "unloaded \(name) (\(reply.unloaded.joined(separator: ", ")))"
176+ : "\(name) was not loaded"
177+ } catch let ServerClientError.server(_, _, message) {
178+ dashboard.notice = message
179+ } catch {
180+ dashboard.notice = "cannot unload \(name): \(error)"
59 }181 }
182+ await refresh()
60 }183 }
61 184
185+ // MARK: Status
186+
62 private func poll() async {187 private func poll() async {
63 while !Task.isCancelled {188 while !Task.isCancelled {
64 await refresh()189 await refresh()
@@ -69,8 +194,7 @@ public actor TUIApp {
69 /// Asks the server once and updates the status bar and the Dashboard.194 /// Asks the server once and updates the status bar and the Dashboard.
70 func refresh() async {195 func refresh() async {
71 do {196 do {
72- let status = try await source.status()197+ apply(try await server.status())
73- apply(status)
74 } catch let error as ServerClientError {198 } catch let error as ServerClientError {
75 if let connection = error.connection { lose(connection) }199 if let connection = error.connection { lose(connection) }
76 } catch {200 } catch {
@@ -80,10 +204,12 @@ public actor TUIApp {
80 }204 }
81 205
82 private func apply(_ status: StatusSnapshot) {206 private func apply(_ status: StatusSnapshot) {
207+ let wasConnected = if case .connected = state.connection { true } else { false }
83 snapshot = status208 snapshot = status
84 state.connection = .connected(version: status.version)209 state.connection = .connected(version: status.version)
85 state.model = status.models.first?.name210 state.model = status.models.first?.name
86 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }211 state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) }
212+ if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() }
87 }213 }
88 214
89 private func lose(_ connection: Connection) {215 private func lose(_ connection: Connection) {
@@ -93,23 +219,33 @@ public actor TUIApp {
93 state.memory = nil219 state.memory = nil
94 }220 }
95 221
222+ // MARK: Drawing
223+
96 private func redraw() {224 private func redraw() {
97 guard running else { return }225 guard running else { return }
98 let size = terminal.size226 let size = terminal.size
99- let bodyHeight = max(1, size.rows - 2)227+ let height = max(1, size.rows - 2)
228+ let (body, cursor) = body(width: size.columns, height: height)
100 terminal.draw(229 terminal.draw(
101 renderer.render(230 renderer.render(
102- state, body: body(width: size.columns, height: bodyHeight), rows: size.rows,231+ state, body: body, cursor: cursor, rows: size.rows, columns: size.columns))
103- columns: size.columns))
104 }232 }
105 233
106- private func body(width: Int, height: Int) -> [String] {234+ private func body(width: Int, height: Int) -> ([String], FormView.Cursor?) {
107 let problem = ConnectionView.lines(235 let problem = ConnectionView.lines(
108 state.connection, url: state.serverURL, startCommand: startCommand)236 state.connection, url: state.serverURL, startCommand: startCommand)
109- if let problem { return problem }237+ if let problem { return (problem, nil) }
110- guard state.screen == .dashboard, let snapshot else {238+ switch state.screen {
111- return AppRenderer.placeholder(for: state.screen)239+ case .dashboard:
240+ guard let snapshot else { return (["", " Waiting for the server's status…"], nil) }
241+ let lines = dashboard.render(
242+ snapshot, width: width, height: height - 1, now: now(), style: renderer.style)
243+ return ([""] + lines, nil)
244+ 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)
112 }249 }
113- return [""] + DashboardView.lines(snapshot, width: width, height: height - 1)
114 }250 }
115 }251 }
modified Sources/RazorbillTUI/TUILaunch.swift +1 -1
@@ -21,7 +21,7 @@ public struct TUILaunch: Sendable, Equatable {
2121 public func run(colors: Bool) async {
2222 let client = ServerClient(baseURL: url, apiKey: apiKey)
2323 let app = TUIApp(
24- terminal: PosixTerminal(), source: client, serverURL: client.baseURL,
24+ terminal: PosixTerminal(), server: client, serverURL: client.baseURL,
2525 startCommand: startCommand, colors: colors)
2626 await app.run()
2727 }
@@ -21,7 +21,7 @@ public struct TUILaunch: Sendable, Equatable {
21 public func run(colors: Bool) async {21 public func run(colors: Bool) async {
22 let client = ServerClient(baseURL: url, apiKey: apiKey)22 let client = ServerClient(baseURL: url, apiKey: apiKey)
23 let app = TUIApp(23 let app = TUIApp(
24- terminal: PosixTerminal(), source: client, serverURL: client.baseURL,24+ terminal: PosixTerminal(), server: client, serverURL: client.baseURL,
25 startCommand: startCommand, colors: colors)25 startCommand: startCommand, colors: colors)
26 await app.run()26 await app.run()
27 }27 }
modified Tests/RazorbillMLXTests/ChatSmokeTests.swift +3 -2
@@ -60,7 +60,7 @@ struct ChatSmokeTests {
6060 let lease = try await models.acquire(smokeModel)
6161 let pieces = try await ChatCompletionRoute.generate(plan, with: lease)
6262 let chunks = ChatCompletionRoute.chunks(
63- pieces, lease: lease, plan: plan, logger: .init(label: "test"))
63+ pieces, lease: lease, plan: plan, usage: RequestUsage(), logger: .init(label: "test"))
6464 var deltas: [(reasoning: Bool, text: String)] = []
6565 for try await chunk in chunks {
6666 guard let delta = chunk.choices.first?.delta else { continue }
@@ -145,7 +145,8 @@ struct ChatSmokeTests {
145145 var contents: [String] = []
146146 var usage: Usage?
147147 let chunks = ChatCompletionRoute.chunks(
148- pieces, lease: lease, plan: streaming, logger: .init(label: "test"))
148+ pieces, lease: lease, plan: streaming, usage: RequestUsage(),
149+ logger: .init(label: "test"))
149150 for try await chunk in chunks {
150151 contents += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }
151152 usage = chunk.usage ?? usage
@@ -60,7 +60,7 @@ struct ChatSmokeTests {
60 let lease = try await models.acquire(smokeModel)60 let lease = try await models.acquire(smokeModel)
61 let pieces = try await ChatCompletionRoute.generate(plan, with: lease)61 let pieces = try await ChatCompletionRoute.generate(plan, with: lease)
62 let chunks = ChatCompletionRoute.chunks(62 let chunks = ChatCompletionRoute.chunks(
63- pieces, lease: lease, plan: plan, logger: .init(label: "test"))63+ pieces, lease: lease, plan: plan, usage: RequestUsage(), logger: .init(label: "test"))
64 var deltas: [(reasoning: Bool, text: String)] = []64 var deltas: [(reasoning: Bool, text: String)] = []
65 for try await chunk in chunks {65 for try await chunk in chunks {
66 guard let delta = chunk.choices.first?.delta else { continue }66 guard let delta = chunk.choices.first?.delta else { continue }
@@ -145,7 +145,8 @@ struct ChatSmokeTests {
145 var contents: [String] = []145 var contents: [String] = []
146 var usage: Usage?146 var usage: Usage?
147 let chunks = ChatCompletionRoute.chunks(147 let chunks = ChatCompletionRoute.chunks(
148- pieces, lease: lease, plan: streaming, logger: .init(label: "test"))148+ pieces, lease: lease, plan: streaming, usage: RequestUsage(),
149+ logger: .init(label: "test"))
149 for try await chunk in chunks {150 for try await chunk in chunks {
150 contents += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }151 contents += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }
151 usage = chunk.usage ?? usage152 usage = chunk.usage ?? usage
modified Tests/RazorbillMLXTests/ConstrainedSmokeTests.swift +2 -1
@@ -85,7 +85,8 @@ struct ConstrainedSmokeTests {
8585 let lease = try await models.acquire(smokeModel)
8686 let pieces = try await ChatCompletionRoute.generate(streaming, with: lease)
8787 let chunks = ChatCompletionRoute.chunks(
88- pieces, lease: lease, plan: streaming, logger: .init(label: "test"))
88+ pieces, lease: lease, plan: streaming, usage: RequestUsage(),
89+ logger: .init(label: "test"))
8990 var parts: [String] = []
9091 for try await chunk in chunks {
9192 parts += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }
@@ -85,7 +85,8 @@ struct ConstrainedSmokeTests {
85 let lease = try await models.acquire(smokeModel)85 let lease = try await models.acquire(smokeModel)
86 let pieces = try await ChatCompletionRoute.generate(streaming, with: lease)86 let pieces = try await ChatCompletionRoute.generate(streaming, with: lease)
87 let chunks = ChatCompletionRoute.chunks(87 let chunks = ChatCompletionRoute.chunks(
88- pieces, lease: lease, plan: streaming, logger: .init(label: "test"))88+ pieces, lease: lease, plan: streaming, usage: RequestUsage(),
89+ logger: .init(label: "test"))
89 var parts: [String] = []90 var parts: [String] = []
90 for try await chunk in chunks {91 for try await chunk in chunks {
91 parts += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }92 parts += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty }
modified Tests/RazorbillServerTests/LocalRoutesTests.swift +30 -2
@@ -76,6 +76,19 @@ func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any]
7676 return object
7777 }
7878
79+/// The status once `count` requests are in its history: the server records a request just after
80+/// its last byte, so a fast client can ask before that.
81+func statusAfter(
82+ _ count: Int, requests client: any TestClientProtocol
83+) async throws -> [String: Any] {
84+ for _ in 0 ..< 200 {
85+ let status = try await fetchStatus(client)
86+ if (status["recent_requests"] as? [Any])?.count == count { return status }
87+ try await Task.sleep(for: .milliseconds(5))
88+ }
89+ return try await fetchStatus(client)
90+}
91+
7992 /// Calls `uri` on a new connection to `client`'s server and decodes the JSON object it answers.
8093 func freshRequest(
8194 _ client: any TestClientProtocol, _ uri: String, method: HTTPRequest.Method = .get
@@ -97,7 +110,7 @@ func errorDetail(_ body: [String: Any]) -> [String: Any] {
97110 func record(_ path: String) -> RequestRecord {
98111 RequestRecord(
99112 method: "GET", path: path, status: 200, model: nil, promptTokens: nil,
100- completionTokens: nil, cachedTokens: 0, durationMs: 1, finishedAt: 0)
113+ completionTokens: nil, cachedTokens: 0, firstByteMs: 1, durationMs: 1, finishedAt: 0)
101114 }
102115
103116 @Suite struct RequestHistoryTests {
@@ -139,7 +152,7 @@ func record(_ path: String) -> RequestRecord {
139152 let answer = try await post(client, simpleRequest())
140153 #expect(answer.status == .ok)
141154 _ = try await fetchStatus(client) // not recorded itself
142- let status = try await fetchStatus(client)
155+ let status = try await statusAfter(1, requests: client)
143156
144157 let models = try #require(status["models"] as? [[String: Any]])
145158 #expect(models.count == 1)
@@ -157,6 +170,21 @@ func record(_ path: String) -> RequestRecord {
157170 }
158171 }
159172
173+ @Test func streamedAnswersAreRecordedWithTheirTokensOnceTheyEnd() async throws {
174+ try await withLiveServer { client in
175+ let streamed = simpleRequest(extra: #","stream":true"#)
176+ let answer = try await post(client, streamed)
177+ #expect(answer.status == .ok)
178+ let requests = try #require(
179+ try await statusAfter(1, requests: client)["recent_requests"] as? [[String: Any]])
180+ let record = try #require(requests.first)
181+ #expect(record["model"] as? String == "org/m")
182+ #expect(record["prompt_tokens"] is Int && record["completion_tokens"] is Int)
183+ let firstByte = try #require(record["first_byte_ms"] as? Int)
184+ #expect(try #require(record["duration_ms"] as? Int) >= firstByte)
185+ }
186+ }
187+
160188 @Test func reportsTheEngineMemory() async throws {
161189 let models = testModels()
162190 let router = RazorbillServer.makeRouter(testSettings, models: models) {
@@ -76,6 +76,19 @@ func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any]
76 return object76 return object
77 }77 }
78 78
79+/// The status once `count` requests are in its history: the server records a request just after
80+/// its last byte, so a fast client can ask before that.
81+func statusAfter(
82+ _ count: Int, requests client: any TestClientProtocol
83+) async throws -> [String: Any] {
84+ for _ in 0 ..< 200 {
85+ let status = try await fetchStatus(client)
86+ if (status["recent_requests"] as? [Any])?.count == count { return status }
87+ try await Task.sleep(for: .milliseconds(5))
88+ }
89+ return try await fetchStatus(client)
90+}
91+
79 /// Calls `uri` on a new connection to `client`'s server and decodes the JSON object it answers.92 /// Calls `uri` on a new connection to `client`'s server and decodes the JSON object it answers.
80 func freshRequest(93 func freshRequest(
81 _ client: any TestClientProtocol, _ uri: String, method: HTTPRequest.Method = .get94 _ client: any TestClientProtocol, _ uri: String, method: HTTPRequest.Method = .get
@@ -97,7 +110,7 @@ func errorDetail(_ body: [String: Any]) -> [String: Any] {
97 func record(_ path: String) -> RequestRecord {110 func record(_ path: String) -> RequestRecord {
98 RequestRecord(111 RequestRecord(
99 method: "GET", path: path, status: 200, model: nil, promptTokens: nil,112 method: "GET", path: path, status: 200, model: nil, promptTokens: nil,
100- completionTokens: nil, cachedTokens: 0, durationMs: 1, finishedAt: 0)113+ completionTokens: nil, cachedTokens: 0, firstByteMs: 1, durationMs: 1, finishedAt: 0)
101 }114 }
102 115
103 @Suite struct RequestHistoryTests {116 @Suite struct RequestHistoryTests {
@@ -139,7 +152,7 @@ func record(_ path: String) -> RequestRecord {
139 let answer = try await post(client, simpleRequest())152 let answer = try await post(client, simpleRequest())
140 #expect(answer.status == .ok)153 #expect(answer.status == .ok)
141 _ = try await fetchStatus(client) // not recorded itself154 _ = try await fetchStatus(client) // not recorded itself
142- let status = try await fetchStatus(client)155+ let status = try await statusAfter(1, requests: client)
143 156
144 let models = try #require(status["models"] as? [[String: Any]])157 let models = try #require(status["models"] as? [[String: Any]])
145 #expect(models.count == 1)158 #expect(models.count == 1)
@@ -157,6 +170,21 @@ func record(_ path: String) -> RequestRecord {
157 }170 }
158 }171 }
159 172
173+ @Test func streamedAnswersAreRecordedWithTheirTokensOnceTheyEnd() async throws {
174+ try await withLiveServer { client in
175+ let streamed = simpleRequest(extra: #","stream":true"#)
176+ let answer = try await post(client, streamed)
177+ #expect(answer.status == .ok)
178+ let requests = try #require(
179+ try await statusAfter(1, requests: client)["recent_requests"] as? [[String: Any]])
180+ let record = try #require(requests.first)
181+ #expect(record["model"] as? String == "org/m")
182+ #expect(record["prompt_tokens"] is Int && record["completion_tokens"] is Int)
183+ let firstByte = try #require(record["first_byte_ms"] as? Int)
184+ #expect(try #require(record["duration_ms"] as? Int) >= firstByte)
185+ }
186+ }
187+
160 @Test func reportsTheEngineMemory() async throws {188 @Test func reportsTheEngineMemory() async throws {
161 let models = testModels()189 let models = testModels()
162 let router = RazorbillServer.makeRouter(testSettings, models: models) {190 let router = RazorbillServer.makeRouter(testSettings, models: models) {
added Tests/RazorbillTUITests/DashboardAndChatTests.swift +348 -0
new file mode 100644
@@ -0,0 +1,348 @@
1+import Foundation
2+import Testing
3+
4+@testable import RazorbillTUI
5+
6+let plain = Style(colors: false)
7+
8+@Suite struct DashboardScreenTests {
9+ func render(_ dashboard: inout DashboardScreen, _ status: StatusSnapshot) -> [String] {
10+ dashboard.render(
11+ status, width: 120, height: 30, now: Date(timeIntervalSince1970: 60), style: plain)
12+ }
13+
14+ @Test func modelsAndRequestsInColumns() {
15+ var dashboard = DashboardScreen()
16+ let memory = EngineMemory(
17+ activeBytes: 8 << 30, cacheBytes: 0, peakBytes: 9 << 30, limitBytes: 32 << 30)
18+ let lines = render(&dashboard, snapshot(models: [qwen], memory: memory))
19+ #expect(lines[0] == " Server rzb 0.2.0 · up 3m 12s · 127.0.0.1:7920")
20+ #expect(
21+ lines[1] == " Memory [█████░░░░░░░░░░░░░░░] 8.0 GB / 32.0 GB active · cache 0.0 GB"
22+ + " · peak 9.0 GB")
23+ #expect(lines.contains { $0.hasPrefix(" NAME ") && $0.contains("ACTIVITY") })
24+ let model = lines.first { $0.contains("qwen") && $0.contains("unloads in 9m 52s") }
25+ #expect(model?.contains("chat") == true && model?.contains("1.0 GB") == true)
26+ let request = lines.first { $0.contains("POST /v1/chat/completions") }
27+ // age 12s, 14+9 tokens, 4 cached, 9 / 0.529 s = 17.0 tok/s, 529ms
28+ #expect(request?.hasPrefix(" 12s") == true)
29+ for column in ["200", "14+9", " 4 ", "17.0", "529ms"] {
30+ #expect(request?.contains(column) == true, "missing \(column)")
31+ }
32+ }
33+
34+ @Test func arrowsSelectAndUUnloadsTheSelectedModel() {
35+ var second = qwen
36+ second.name = "embed"
37+ second.key = "org/embed#embedding"
38+ let status = snapshot(models: [qwen, second])
39+ var dashboard = DashboardScreen()
40+ #expect(dashboard.handle(.arrowDown, snapshot: status) == .redraw)
41+ #expect(dashboard.handle(.character("u"), snapshot: status) == .unload("embed"))
42+ #expect(dashboard.notice == "unloading embed…")
43+ #expect(render(&dashboard, status).last == " unloading embed…")
44+ }
45+
46+ @Test func nothingToUnloadWithoutModels() {
47+ var dashboard = DashboardScreen()
48+ #expect(dashboard.handle(.character("u"), snapshot: snapshot()) == .none)
49+ #expect(dashboard.handle(.character("u"), snapshot: nil) == .none)
50+ }
51+
52+ @Test func busyModelShowsItsQueue() {
53+ var busy = qwen
54+ busy.busy = true
55+ busy.queued = 2
56+ #expect(DashboardScreen.modelRow(busy).hasSuffix("busy, 2 waiting"))
57+ }
58+
59+ @Test func tinyTerminalKeepsTheHeight() {
60+ var dashboard = DashboardScreen()
61+ var many = snapshot(models: [qwen])
62+ many.recentRequests = Array(repeating: many.recentRequests[0], count: 50)
63+ let lines = dashboard.render(many, width: 40, height: 10, now: Date(), style: plain)
64+ #expect(lines.count == 10 && lines.allSatisfy { $0.count <= 40 })
65+ }
66+
67+ @Test(arguments: [(45, "45s"), (192, "3m 12s"), (7500, "2h 05m"), (-3, "0s")])
68+ func durations(_ seconds: Int, _ text: String) {
69+ #expect(DashboardScreen.duration(seconds) == text)
70+ }
71+
72+ @Test func gaugeAndMilliseconds() {
73+ #expect(DashboardScreen.gauge(1, of: 4, cells: 8) == "[██░░░░░░]")
74+ #expect(DashboardScreen.gauge(9, of: 0, cells: 2) == "[░░]")
75+ #expect(DashboardScreen.milliseconds(529) == "529ms")
76+ #expect(DashboardScreen.milliseconds(2140) == "2.1s")
77+ }
78+}
79+
80+@Suite struct ChatOptionsTests {
81+ @Test func validSettingsAndTheirSummary() throws {
82+ var options = ChatOptions()
83+ #expect(options.summary == "server defaults")
84+ try options.set("temperature", to: "0.7")
85+ try options.set("max_tokens", to: "400")
86+ try options.set("top_k", to: "40")
87+ try options.set("thinking", to: "off")
88+ #expect(options.summary == "temperature 0.7 · top_k 40 · max_tokens 400 · thinking off")
89+ try options.set("temperature", to: "default")
90+ try options.set("thinking", to: "")
91+ #expect(options.temperature == nil && options.thinking == nil)
92+ }
93+
94+ @Test(arguments: [
95+ ("temperature", "3"), ("top_p", "x"), ("max_tokens", "0"), ("thinking", "maybe"),
96+ ("seed", "1"),
97+ ])
98+ func invalidSettingsAreRefused(_ name: String, _ value: String) {
99+ var options = ChatOptions()
100+ #expect(throws: ChatOptions.Invalid.self) { try options.set(name, to: value) }
101+ }
102+}
103+
104+@Suite struct ChatScreenTests {
105+ func typed(_ text: String, into chat: inout ChatScreen) {
106+ for character in text { _ = chat.handle(.character(character)) }
107+ }
108+
109+ @Test func enterSendsTheWholeConversation() {
110+ var chat = ChatScreen()
111+ chat.setModels(["qwen"])
112+ typed("hello", into: &chat)
113+ let first = chat.handle(.enter)
114+ let hello = [ChatTurn(role: "user", content: "hello")]
115+ #expect(first == .send(model: "qwen", messages: hello, options: ChatOptions()))
116+ #expect(chat.generating && chat.input.text.isEmpty)
117+ chat.receive(.reasoning("hmm"))
118+ chat.receive(.content("Hi!"))
119+ chat.receive(.usage(promptTokens: 5, completionTokens: 4, cachedTokens: 2))
120+ chat.finish(generationSeconds: 0.5)
121+ #expect(!chat.generating)
122+ #expect(chat.entries.last?.stats == "5+4 tokens · 2 cached · 8.0 tok/s")
123+ typed("again", into: &chat)
124+ guard case .send(_, let messages, _) = chat.handle(.enter) else {
125+ Issue.record("not sent")
126+ return
127+ }
128+ #expect(messages.map(\.role) == ["user", "assistant", "user"])
129+ #expect(messages[1].content == "Hi!")
130+ }
131+
132+ @Test func noModelAsksForTheList() {
133+ var chat = ChatScreen()
134+ typed("hi", into: &chat)
135+ #expect(chat.handle(.enter) == .loadModels)
136+ #expect(chat.entries.last?.content.contains("Ctrl-P") == true)
137+ }
138+
139+ @Test func setModelsPrefersALoadedChatModel() {
140+ var chat = ChatScreen()
141+ chat.setModels([
142+ ServedModel(id: "embed", loaded: true, kind: "embedding"),
143+ ServedModel(id: "a", loaded: false, kind: "chat"),
144+ ServedModel(id: "b", loaded: true, kind: "chat"),
145+ ])
146+ #expect(chat.models == ["a", "b"] && chat.model == "b")
147+ }
148+
149+ @Test func escapeStopsAndControlNNeedsNoAnswerRunning() {
150+ var chat = ChatScreen()
151+ chat.setModels(["qwen"])
152+ #expect(chat.handle(.escape) == .none)
153+ typed("hi", into: &chat)
154+ _ = chat.handle(.enter)
155+ #expect(chat.handle(.escape) == .cancel)
156+ _ = chat.handle(.control("n"))
157+ #expect(chat.entries.last?.content.contains("Esc") == true)
158+ chat.stop()
159+ #expect(chat.entries.contains { $0.stopped })
160+ _ = chat.handle(.control("n"))
161+ #expect(chat.entries.isEmpty)
162+ }
163+
164+ @Test func pickerChoosesTheModel() {
165+ var chat = ChatScreen()
166+ chat.setModels(["a", "b"])
167+ #expect(chat.handle(.control("p")) == .loadModels)
168+ #expect(chat.picking)
169+ _ = chat.handle(.arrowDown)
170+ _ = chat.handle(.enter)
171+ #expect(!chat.picking && chat.model == "b")
172+ _ = chat.handle(.control("p"))
173+ _ = chat.handle(.escape)
174+ #expect(!chat.picking && chat.model == "b")
175+ }
176+
177+ @Test func commandsSetOptionsAndExplainMistakes() {
178+ var chat = ChatScreen()
179+ typed("/set temperature 0.2", into: &chat)
180+ #expect(chat.handle(.enter) == .redraw)
181+ #expect(chat.options.temperature == 0.2)
182+ #expect(chat.entries.last?.content == "settings: temperature 0.2")
183+ typed("/set temperature 9", into: &chat)
184+ _ = chat.handle(.enter)
185+ #expect(chat.entries.last?.content.contains("from 0 to 2") == true)
186+ typed("/nope", into: &chat)
187+ _ = chat.handle(.enter)
188+ #expect(chat.entries.last?.content.contains("/help") == true)
189+ typed("/help", into: &chat)
190+ _ = chat.handle(.enter)
191+ #expect(chat.entries.last?.content.contains("Ctrl-R") == true)
192+ #expect(chat.turns().isEmpty)
193+ }
194+
195+ @Test func failedAnswersAreNotResent() {
196+ var chat = ChatScreen()
197+ chat.setModels(["qwen"])
198+ typed("hi", into: &chat)
199+ _ = chat.handle(.enter)
200+ chat.fail("boom")
201+ #expect(chat.turns() == [ChatTurn(role: "user", content: "hi")])
202+ #expect(chat.entries.last?.failure == "boom")
203+ }
204+
205+ @Test func controlRCyclesTheReasoningDisplay() {
206+ var chat = ChatScreen()
207+ #expect(chat.reasoning == .folded)
208+ _ = chat.handle(.control("r"))
209+ #expect(chat.reasoning == .hidden)
210+ _ = chat.handle(.control("r"))
211+ #expect(chat.reasoning == .shown)
212+ }
213+}
214+
215+@Suite struct ChatRendererTests {
216+ let renderer = ChatRenderer(style: plain)
217+
218+ func answered(reasoning display: Int = 0) -> ChatScreen {
219+ var chat = ChatScreen()
220+ chat.setModels(["qwen"])
221+ for character in "hello" { _ = chat.handle(.character(character)) }
222+ _ = chat.handle(.enter)
223+ chat.receive(.reasoning("one two three"))
224+ chat.receive(.content("Hi there"))
225+ chat.finish(generationSeconds: nil)
226+ for _ in 0 ..< display { _ = chat.handle(.control("r")) }
227+ return chat
228+ }
229+
230+ @Test func conversationWithFoldedReasoning() {
231+ let (lines, cursor) = renderer.render(answered(), width: 60, height: 10)
232+ #expect(lines.count == 10)
233+ #expect(lines.contains("you › hello"))
234+ #expect(lines.contains(" ⋯ thinking (3 words) · Ctrl-R to show"))
235+ #expect(lines.contains("qwen › Hi there"))
236+ #expect(lines[9] == "› " && cursor.row == 9 && cursor.column == 2)
237+ #expect(lines[8].contains("Enter send"))
238+ }
239+
240+ @Test func hiddenAndShownReasoning() {
241+ let hidden = renderer.render(answered(reasoning: 1), width: 60, height: 10).lines
242+ #expect(!hidden.contains { $0.contains("⋯") })
243+ let shown = renderer.render(answered(reasoning: 2), width: 60, height: 10).lines
244+ #expect(shown.contains(" ⋯ one two three"))
245+ }
246+
247+ @Test func emptyConversationExplainsWhatToDo() {
248+ let lines = renderer.render(ChatScreen(), width: 80, height: 8).lines
249+ #expect(lines.contains { $0.contains("Type a message") })
250+ #expect(lines.contains { $0.contains("none yet (Ctrl-P)") })
251+ }
252+
253+ @Test func waitingLineWhileTheFirstPieceIsAwaited() {
254+ var chat = ChatScreen()
255+ chat.setModels(["qwen"])
256+ _ = chat.handle(.character("x"))
257+ _ = chat.handle(.enter)
258+ let lines = renderer.render(chat, width: 60, height: 8).lines
259+ #expect(lines.contains(" ⋯ waiting for the model…"))
260+ #expect(lines[6].contains("Esc stop"))
261+ }
262+
263+ @Test func longInputShowsItsEnd() {
264+ var chat = ChatScreen()
265+ for character in String(repeating: "a", count: 50) + "XYZ" {
266+ _ = chat.handle(.character(character))
267+ }
268+ let (lines, cursor) = renderer.render(chat, width: 20, height: 4)
269+ #expect(lines[3].hasSuffix("XYZ") && lines[3].count <= 20)
270+ #expect(cursor.column == lines[3].count)
271+ }
272+
273+ @Test func pickerListsTheModels() {
274+ var chat = ChatScreen()
275+ chat.setModels(["a", "b"])
276+ _ = chat.handle(.control("p"))
277+ let lines = renderer.render(chat, width: 60, height: 8).lines
278+ #expect(lines.contains { $0.contains("Choose a model") })
279+ #expect(lines.contains { $0.contains("a (current)") })
280+ }
281+}
282+
283+@Suite struct TUIAppScreensTests {
284+ func app(_ terminal: FakeTerminal, _ server: ScriptedServer) -> TUIApp {
285+ TUIApp(
286+ terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
287+ pollInterval: .milliseconds(10))
288+ }
289+
290+ @Test func chatStreamsTheAnswerWithItsStats() async throws {
291+ let terminal = FakeTerminal(rows: 20, columns: 100)
292+ let server = ScriptedServer(.success(snapshot()))
293+ let app = app(terminal, server)
294+ let running = Task { await app.run() }
295+ terminal.press(.function(1))
296+ try await waitForScreen(terminal, containing: "Ctrl-P model: qwen")
297+ terminal.type("hello")
298+ terminal.press(.enter)
299+ try await waitForScreen(terminal, containing: "qwen › Hi!")
300+ try await waitForScreen(terminal, containing: "5+2 tokens · 3 cached")
301+ #expect(server.conversations == [[ChatTurn(role: "user", content: "hello")]])
302+ terminal.press(.control("q"))
303+ await running.value
304+ }
305+
306+ @Test func escapeAndControlCStopTheAnswerWithoutQuitting() async throws {
307+ let terminal = FakeTerminal(rows: 20, columns: 100)
308+ let server = ScriptedServer(.success(snapshot()))
309+ server.script = [.content("partial")]
310+ server.hangs = true
311+ let app = app(terminal, server)
312+ let running = Task { await app.run() }
313+ terminal.press(.function(1))
314+ try await waitForScreen(terminal, containing: "Ctrl-P model: qwen")
315+ terminal.type("hi")
316+ terminal.press(.enter)
317+ try await waitForScreen(terminal, containing: "qwen › partial")
318+ terminal.press(.control("c"))
319+ try await waitForScreen(terminal, containing: "(stopped)")
320+ #expect(server.cancellations == 1)
321+ terminal.type("again")
322+ terminal.press(.enter)
323+ try await waitForScreen(terminal, containing: "Esc stop")
324+ terminal.press(.escape)
325+ try await waitForScreen(terminal, containing: "Enter send")
326+ #expect(server.cancellations == 2)
327+ #expect(server.conversations.last?.map(\.content) == ["hi", "partial", "again"])
328+ terminal.press(.control("q"))
329+ await running.value
330+ }
331+
332+ @Test func dashboardUnloadShowsTheServersAnswer() async throws {
333+ let terminal = FakeTerminal(rows: 30, columns: 120)
334+ let server = ScriptedServer(.success(snapshot(models: [qwen])))
335+ let app = app(terminal, server)
336+ let running = Task { await app.run() }
337+ try await waitForScreen(terminal, containing: "unloads in")
338+ terminal.type("u")
339+ try await waitForScreen(terminal, containing: "unloaded qwen (org/qwen)")
340+ server.unloadAnswer = .failure(
341+ .server(status: 409, code: "model_busy", message: "'qwen' is in use"))
342+ terminal.type("u")
343+ try await waitForScreen(terminal, containing: "'qwen' is in use")
344+ #expect(server.unloads == ["qwen", "qwen"])
345+ terminal.press(.control("q"))
346+ await running.value
347+ }
348+}
new file mode 100644
@@ -0,0 +1,348 @@
1+import Foundation
2+import Testing
3+
4+@testable import RazorbillTUI
5+
6+let plain = Style(colors: false)
7+
8+@Suite struct DashboardScreenTests {
9+ func render(_ dashboard: inout DashboardScreen, _ status: StatusSnapshot) -> [String] {
10+ dashboard.render(
11+ status, width: 120, height: 30, now: Date(timeIntervalSince1970: 60), style: plain)
12+ }
13+
14+ @Test func modelsAndRequestsInColumns() {
15+ var dashboard = DashboardScreen()
16+ let memory = EngineMemory(
17+ activeBytes: 8 << 30, cacheBytes: 0, peakBytes: 9 << 30, limitBytes: 32 << 30)
18+ let lines = render(&dashboard, snapshot(models: [qwen], memory: memory))
19+ #expect(lines[0] == " Server rzb 0.2.0 · up 3m 12s · 127.0.0.1:7920")
20+ #expect(
21+ lines[1] == " Memory [█████░░░░░░░░░░░░░░░] 8.0 GB / 32.0 GB active · cache 0.0 GB"
22+ + " · peak 9.0 GB")
23+ #expect(lines.contains { $0.hasPrefix(" NAME ") && $0.contains("ACTIVITY") })
24+ let model = lines.first { $0.contains("qwen") && $0.contains("unloads in 9m 52s") }
25+ #expect(model?.contains("chat") == true && model?.contains("1.0 GB") == true)
26+ let request = lines.first { $0.contains("POST /v1/chat/completions") }
27+ // age 12s, 14+9 tokens, 4 cached, 9 / 0.529 s = 17.0 tok/s, 529ms
28+ #expect(request?.hasPrefix(" 12s") == true)
29+ for column in ["200", "14+9", " 4 ", "17.0", "529ms"] {
30+ #expect(request?.contains(column) == true, "missing \(column)")
31+ }
32+ }
33+
34+ @Test func arrowsSelectAndUUnloadsTheSelectedModel() {
35+ var second = qwen
36+ second.name = "embed"
37+ second.key = "org/embed#embedding"
38+ let status = snapshot(models: [qwen, second])
39+ var dashboard = DashboardScreen()
40+ #expect(dashboard.handle(.arrowDown, snapshot: status) == .redraw)
41+ #expect(dashboard.handle(.character("u"), snapshot: status) == .unload("embed"))
42+ #expect(dashboard.notice == "unloading embed…")
43+ #expect(render(&dashboard, status).last == " unloading embed…")
44+ }
45+
46+ @Test func nothingToUnloadWithoutModels() {
47+ var dashboard = DashboardScreen()
48+ #expect(dashboard.handle(.character("u"), snapshot: snapshot()) == .none)
49+ #expect(dashboard.handle(.character("u"), snapshot: nil) == .none)
50+ }
51+
52+ @Test func busyModelShowsItsQueue() {
53+ var busy = qwen
54+ busy.busy = true
55+ busy.queued = 2
56+ #expect(DashboardScreen.modelRow(busy).hasSuffix("busy, 2 waiting"))
57+ }
58+
59+ @Test func tinyTerminalKeepsTheHeight() {
60+ var dashboard = DashboardScreen()
61+ var many = snapshot(models: [qwen])
62+ many.recentRequests = Array(repeating: many.recentRequests[0], count: 50)
63+ let lines = dashboard.render(many, width: 40, height: 10, now: Date(), style: plain)
64+ #expect(lines.count == 10 && lines.allSatisfy { $0.count <= 40 })
65+ }
66+
67+ @Test(arguments: [(45, "45s"), (192, "3m 12s"), (7500, "2h 05m"), (-3, "0s")])
68+ func durations(_ seconds: Int, _ text: String) {
69+ #expect(DashboardScreen.duration(seconds) == text)
70+ }
71+
72+ @Test func gaugeAndMilliseconds() {
73+ #expect(DashboardScreen.gauge(1, of: 4, cells: 8) == "[██░░░░░░]")
74+ #expect(DashboardScreen.gauge(9, of: 0, cells: 2) == "[░░]")
75+ #expect(DashboardScreen.milliseconds(529) == "529ms")
76+ #expect(DashboardScreen.milliseconds(2140) == "2.1s")
77+ }
78+}
79+
80+@Suite struct ChatOptionsTests {
81+ @Test func validSettingsAndTheirSummary() throws {
82+ var options = ChatOptions()
83+ #expect(options.summary == "server defaults")
84+ try options.set("temperature", to: "0.7")
85+ try options.set("max_tokens", to: "400")
86+ try options.set("top_k", to: "40")
87+ try options.set("thinking", to: "off")
88+ #expect(options.summary == "temperature 0.7 · top_k 40 · max_tokens 400 · thinking off")
89+ try options.set("temperature", to: "default")
90+ try options.set("thinking", to: "")
91+ #expect(options.temperature == nil && options.thinking == nil)
92+ }
93+
94+ @Test(arguments: [
95+ ("temperature", "3"), ("top_p", "x"), ("max_tokens", "0"), ("thinking", "maybe"),
96+ ("seed", "1"),
97+ ])
98+ func invalidSettingsAreRefused(_ name: String, _ value: String) {
99+ var options = ChatOptions()
100+ #expect(throws: ChatOptions.Invalid.self) { try options.set(name, to: value) }
101+ }
102+}
103+
104+@Suite struct ChatScreenTests {
105+ func typed(_ text: String, into chat: inout ChatScreen) {
106+ for character in text { _ = chat.handle(.character(character)) }
107+ }
108+
109+ @Test func enterSendsTheWholeConversation() {
110+ var chat = ChatScreen()
111+ chat.setModels(["qwen"])
112+ typed("hello", into: &chat)
113+ let first = chat.handle(.enter)
114+ let hello = [ChatTurn(role: "user", content: "hello")]
115+ #expect(first == .send(model: "qwen", messages: hello, options: ChatOptions()))
116+ #expect(chat.generating && chat.input.text.isEmpty)
117+ chat.receive(.reasoning("hmm"))
118+ chat.receive(.content("Hi!"))
119+ chat.receive(.usage(promptTokens: 5, completionTokens: 4, cachedTokens: 2))
120+ chat.finish(generationSeconds: 0.5)
121+ #expect(!chat.generating)
122+ #expect(chat.entries.last?.stats == "5+4 tokens · 2 cached · 8.0 tok/s")
123+ typed("again", into: &chat)
124+ guard case .send(_, let messages, _) = chat.handle(.enter) else {
125+ Issue.record("not sent")
126+ return
127+ }
128+ #expect(messages.map(\.role) == ["user", "assistant", "user"])
129+ #expect(messages[1].content == "Hi!")
130+ }
131+
132+ @Test func noModelAsksForTheList() {
133+ var chat = ChatScreen()
134+ typed("hi", into: &chat)
135+ #expect(chat.handle(.enter) == .loadModels)
136+ #expect(chat.entries.last?.content.contains("Ctrl-P") == true)
137+ }
138+
139+ @Test func setModelsPrefersALoadedChatModel() {
140+ var chat = ChatScreen()
141+ chat.setModels([
142+ ServedModel(id: "embed", loaded: true, kind: "embedding"),
143+ ServedModel(id: "a", loaded: false, kind: "chat"),
144+ ServedModel(id: "b", loaded: true, kind: "chat"),
145+ ])
146+ #expect(chat.models == ["a", "b"] && chat.model == "b")
147+ }
148+
149+ @Test func escapeStopsAndControlNNeedsNoAnswerRunning() {
150+ var chat = ChatScreen()
151+ chat.setModels(["qwen"])
152+ #expect(chat.handle(.escape) == .none)
153+ typed("hi", into: &chat)
154+ _ = chat.handle(.enter)
155+ #expect(chat.handle(.escape) == .cancel)
156+ _ = chat.handle(.control("n"))
157+ #expect(chat.entries.last?.content.contains("Esc") == true)
158+ chat.stop()
159+ #expect(chat.entries.contains { $0.stopped })
160+ _ = chat.handle(.control("n"))
161+ #expect(chat.entries.isEmpty)
162+ }
163+
164+ @Test func pickerChoosesTheModel() {
165+ var chat = ChatScreen()
166+ chat.setModels(["a", "b"])
167+ #expect(chat.handle(.control("p")) == .loadModels)
168+ #expect(chat.picking)
169+ _ = chat.handle(.arrowDown)
170+ _ = chat.handle(.enter)
171+ #expect(!chat.picking && chat.model == "b")
172+ _ = chat.handle(.control("p"))
173+ _ = chat.handle(.escape)
174+ #expect(!chat.picking && chat.model == "b")
175+ }
176+
177+ @Test func commandsSetOptionsAndExplainMistakes() {
178+ var chat = ChatScreen()
179+ typed("/set temperature 0.2", into: &chat)
180+ #expect(chat.handle(.enter) == .redraw)
181+ #expect(chat.options.temperature == 0.2)
182+ #expect(chat.entries.last?.content == "settings: temperature 0.2")
183+ typed("/set temperature 9", into: &chat)
184+ _ = chat.handle(.enter)
185+ #expect(chat.entries.last?.content.contains("from 0 to 2") == true)
186+ typed("/nope", into: &chat)
187+ _ = chat.handle(.enter)
188+ #expect(chat.entries.last?.content.contains("/help") == true)
189+ typed("/help", into: &chat)
190+ _ = chat.handle(.enter)
191+ #expect(chat.entries.last?.content.contains("Ctrl-R") == true)
192+ #expect(chat.turns().isEmpty)
193+ }
194+
195+ @Test func failedAnswersAreNotResent() {
196+ var chat = ChatScreen()
197+ chat.setModels(["qwen"])
198+ typed("hi", into: &chat)
199+ _ = chat.handle(.enter)
200+ chat.fail("boom")
201+ #expect(chat.turns() == [ChatTurn(role: "user", content: "hi")])
202+ #expect(chat.entries.last?.failure == "boom")
203+ }
204+
205+ @Test func controlRCyclesTheReasoningDisplay() {
206+ var chat = ChatScreen()
207+ #expect(chat.reasoning == .folded)
208+ _ = chat.handle(.control("r"))
209+ #expect(chat.reasoning == .hidden)
210+ _ = chat.handle(.control("r"))
211+ #expect(chat.reasoning == .shown)
212+ }
213+}
214+
215+@Suite struct ChatRendererTests {
216+ let renderer = ChatRenderer(style: plain)
217+
218+ func answered(reasoning display: Int = 0) -> ChatScreen {
219+ var chat = ChatScreen()
220+ chat.setModels(["qwen"])
221+ for character in "hello" { _ = chat.handle(.character(character)) }
222+ _ = chat.handle(.enter)
223+ chat.receive(.reasoning("one two three"))
224+ chat.receive(.content("Hi there"))
225+ chat.finish(generationSeconds: nil)
226+ for _ in 0 ..< display { _ = chat.handle(.control("r")) }
227+ return chat
228+ }
229+
230+ @Test func conversationWithFoldedReasoning() {
231+ let (lines, cursor) = renderer.render(answered(), width: 60, height: 10)
232+ #expect(lines.count == 10)
233+ #expect(lines.contains("you › hello"))
234+ #expect(lines.contains(" ⋯ thinking (3 words) · Ctrl-R to show"))
235+ #expect(lines.contains("qwen › Hi there"))
236+ #expect(lines[9] == "› " && cursor.row == 9 && cursor.column == 2)
237+ #expect(lines[8].contains("Enter send"))
238+ }
239+
240+ @Test func hiddenAndShownReasoning() {
241+ let hidden = renderer.render(answered(reasoning: 1), width: 60, height: 10).lines
242+ #expect(!hidden.contains { $0.contains("⋯") })
243+ let shown = renderer.render(answered(reasoning: 2), width: 60, height: 10).lines
244+ #expect(shown.contains(" ⋯ one two three"))
245+ }
246+
247+ @Test func emptyConversationExplainsWhatToDo() {
248+ let lines = renderer.render(ChatScreen(), width: 80, height: 8).lines
249+ #expect(lines.contains { $0.contains("Type a message") })
250+ #expect(lines.contains { $0.contains("none yet (Ctrl-P)") })
251+ }
252+
253+ @Test func waitingLineWhileTheFirstPieceIsAwaited() {
254+ var chat = ChatScreen()
255+ chat.setModels(["qwen"])
256+ _ = chat.handle(.character("x"))
257+ _ = chat.handle(.enter)
258+ let lines = renderer.render(chat, width: 60, height: 8).lines
259+ #expect(lines.contains(" ⋯ waiting for the model…"))
260+ #expect(lines[6].contains("Esc stop"))
261+ }
262+
263+ @Test func longInputShowsItsEnd() {
264+ var chat = ChatScreen()
265+ for character in String(repeating: "a", count: 50) + "XYZ" {
266+ _ = chat.handle(.character(character))
267+ }
268+ let (lines, cursor) = renderer.render(chat, width: 20, height: 4)
269+ #expect(lines[3].hasSuffix("XYZ") && lines[3].count <= 20)
270+ #expect(cursor.column == lines[3].count)
271+ }
272+
273+ @Test func pickerListsTheModels() {
274+ var chat = ChatScreen()
275+ chat.setModels(["a", "b"])
276+ _ = chat.handle(.control("p"))
277+ let lines = renderer.render(chat, width: 60, height: 8).lines
278+ #expect(lines.contains { $0.contains("Choose a model") })
279+ #expect(lines.contains { $0.contains("a (current)") })
280+ }
281+}
282+
283+@Suite struct TUIAppScreensTests {
284+ func app(_ terminal: FakeTerminal, _ server: ScriptedServer) -> TUIApp {
285+ TUIApp(
286+ terminal: terminal, server: server, serverURL: "http://127.0.0.1:7920", colors: false,
287+ pollInterval: .milliseconds(10))
288+ }
289+
290+ @Test func chatStreamsTheAnswerWithItsStats() async throws {
291+ let terminal = FakeTerminal(rows: 20, columns: 100)
292+ let server = ScriptedServer(.success(snapshot()))
293+ let app = app(terminal, server)
294+ let running = Task { await app.run() }
295+ terminal.press(.function(1))
296+ try await waitForScreen(terminal, containing: "Ctrl-P model: qwen")
297+ terminal.type("hello")
298+ terminal.press(.enter)
299+ try await waitForScreen(terminal, containing: "qwen › Hi!")
300+ try await waitForScreen(terminal, containing: "5+2 tokens · 3 cached")
301+ #expect(server.conversations == [[ChatTurn(role: "user", content: "hello")]])
302+ terminal.press(.control("q"))
303+ await running.value
304+ }
305+
306+ @Test func escapeAndControlCStopTheAnswerWithoutQuitting() async throws {
307+ let terminal = FakeTerminal(rows: 20, columns: 100)
308+ let server = ScriptedServer(.success(snapshot()))
309+ server.script = [.content("partial")]
310+ server.hangs = true
311+ let app = app(terminal, server)
312+ let running = Task { await app.run() }
313+ terminal.press(.function(1))
314+ try await waitForScreen(terminal, containing: "Ctrl-P model: qwen")
315+ terminal.type("hi")
316+ terminal.press(.enter)
317+ try await waitForScreen(terminal, containing: "qwen › partial")
318+ terminal.press(.control("c"))
319+ try await waitForScreen(terminal, containing: "(stopped)")
320+ #expect(server.cancellations == 1)
321+ terminal.type("again")
322+ terminal.press(.enter)
323+ try await waitForScreen(terminal, containing: "Esc stop")
324+ terminal.press(.escape)
325+ try await waitForScreen(terminal, containing: "Enter send")
326+ #expect(server.cancellations == 2)
327+ #expect(server.conversations.last?.map(\.content) == ["hi", "partial", "again"])
328+ terminal.press(.control("q"))
329+ await running.value
330+ }
331+
332+ @Test func dashboardUnloadShowsTheServersAnswer() async throws {
333+ let terminal = FakeTerminal(rows: 30, columns: 120)
334+ let server = ScriptedServer(.success(snapshot(models: [qwen])))
335+ let app = app(terminal, server)
336+ let running = Task { await app.run() }
337+ try await waitForScreen(terminal, containing: "unloads in")
338+ terminal.type("u")
339+ try await waitForScreen(terminal, containing: "unloaded qwen (org/qwen)")
340+ server.unloadAnswer = .failure(
341+ .server(status: 409, code: "model_busy", message: "'qwen' is in use"))
342+ terminal.type("u")
343+ try await waitForScreen(terminal, containing: "'qwen' is in use")
344+ #expect(server.unloads == ["qwen", "qwen"])
345+ terminal.press(.control("q"))
346+ await running.value
347+ }
348+}
modified Tests/RazorbillTUITests/ServerClientTests.swift +34 -6
@@ -11,10 +11,11 @@ import Testing
1111 /// A real `rzb serve` on a random port with the fake engine (`echo: <last message>`), and a
1212 /// client pointed at it.
1313 func withServer(
14- apiKey: String? = nil,
14+ apiKey: String? = nil, models declared: [ModelEntry] = [],
1515 _ test: @Sendable (_ baseURL: String) async throws -> Void
1616 ) async throws {
17- let settings = ServerSettings(port: 0, apiKey: apiKey)
17+ let settings = ServerSettings(
18+ port: 0, apiKey: apiKey, config: ServerConfig(models: declared))
1819 let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
1920 "rzb-tui-\(UUID().uuidString)")
2021 let models = ModelManager(
@@ -86,7 +87,7 @@ func withServer(
8687 #expect(
8788 try ChatChunk.events(from: chunk) == [
8889 .reasoning("hm"), .content("Hi"), .finished(reason: "stop"),
89- .usage(promptTokens: 3, completionTokens: 2),
90+ .usage(promptTokens: 3, completionTokens: 2, cachedTokens: 0),
9091 ])
9192 }
9293 }
@@ -169,14 +170,41 @@ extension ServerClientError {
169170 let client = ServerClient(baseURL: url, apiKey: nil)
170171 let terminal = FakeTerminal(rows: 20, columns: 100)
171172 let app = TUIApp(
172- terminal: terminal, source: client, serverURL: url, colors: false,
173+ terminal: terminal, server: client, serverURL: url, colors: false,
173174 pollInterval: .milliseconds(10))
174175 let running = Task { await app.run() }
175176 try await waitForScreen(terminal, containing: "none loaded")
176177 let ping = [ChatTurn(role: "user", content: "ping")]
177178 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")
179+ try await waitForScreen(terminal, containing: "org/m")
180+ try await waitForScreen(terminal, containing: "loaded")
181+ try await waitForScreen(terminal, containing: "POST /v1/chat/completions")
182+ // A streamed answer's tokens reach the history once it ends.
183+ try await waitForScreen(terminal, containing: "1+1")
184+ terminal.press(.control("q"))
185+ await running.value
186+ }
187+ }
188+}
189+
190+@Suite struct ChatLiveTests {
191+ @Test func chatScreenTalksToARealServer() async throws {
192+ let echo = ModelEntry(id: "echo", source: .huggingFace(id: "org/echo", revision: "main"))
193+ try await withServer(models: [echo]) { url in
194+ let client = ServerClient(baseURL: url, apiKey: nil)
195+ let terminal = FakeTerminal(rows: 20, columns: 100)
196+ let app = TUIApp(
197+ terminal: terminal, server: client, serverURL: url, colors: false,
198+ pollInterval: .milliseconds(10))
199+ let running = Task { await app.run() }
200+ terminal.press(.function(1))
201+ try await waitForScreen(terminal, containing: "Ctrl-P model: echo")
202+ terminal.type("/set temperature 0.2")
203+ terminal.press(.enter)
204+ terminal.type("ping")
205+ terminal.press(.enter)
206+ try await waitForScreen(terminal, containing: "echo › echo: ping")
207+ try await waitForScreen(terminal, containing: "tokens")
180208 terminal.press(.control("q"))
181209 await running.value
182210 }
@@ -11,10 +11,11 @@ import Testing
11 /// A real `rzb serve` on a random port with the fake engine (`echo: <last message>`), and a11 /// A real `rzb serve` on a random port with the fake engine (`echo: <last message>`), and a
12 /// client pointed at it.12 /// client pointed at it.
13 func withServer(13 func withServer(
14- apiKey: String? = nil,14+ apiKey: String? = nil, models declared: [ModelEntry] = [],
15 _ test: @Sendable (_ baseURL: String) async throws -> Void15 _ test: @Sendable (_ baseURL: String) async throws -> Void
16 ) async throws {16 ) async throws {
17- let settings = ServerSettings(port: 0, apiKey: apiKey)17+ let settings = ServerSettings(
18+ port: 0, apiKey: apiKey, config: ServerConfig(models: declared))
18 let cache = FileManager.default.temporaryDirectory.appendingPathComponent(19 let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
19 "rzb-tui-\(UUID().uuidString)")20 "rzb-tui-\(UUID().uuidString)")
20 let models = ModelManager(21 let models = ModelManager(
@@ -86,7 +87,7 @@ func withServer(
86 #expect(87 #expect(
87 try ChatChunk.events(from: chunk) == [88 try ChatChunk.events(from: chunk) == [
88 .reasoning("hm"), .content("Hi"), .finished(reason: "stop"),89 .reasoning("hm"), .content("Hi"), .finished(reason: "stop"),
89- .usage(promptTokens: 3, completionTokens: 2),90+ .usage(promptTokens: 3, completionTokens: 2, cachedTokens: 0),
90 ])91 ])
91 }92 }
92 }93 }
@@ -169,14 +170,41 @@ extension ServerClientError {
169 let client = ServerClient(baseURL: url, apiKey: nil)170 let client = ServerClient(baseURL: url, apiKey: nil)
170 let terminal = FakeTerminal(rows: 20, columns: 100)171 let terminal = FakeTerminal(rows: 20, columns: 100)
171 let app = TUIApp(172 let app = TUIApp(
172- terminal: terminal, source: client, serverURL: url, colors: false,173+ terminal: terminal, server: client, serverURL: url, colors: false,
173 pollInterval: .milliseconds(10))174 pollInterval: .milliseconds(10))
174 let running = Task { await app.run() }175 let running = Task { await app.run() }
175 try await waitForScreen(terminal, containing: "none loaded")176 try await waitForScreen(terminal, containing: "none loaded")
176 let ping = [ChatTurn(role: "user", content: "ping")]177 let ping = [ChatTurn(role: "user", content: "ping")]
177 for try await _ in client.chat(model: "org/m", messages: ping) {}178 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: "org/m")
179- try await waitForScreen(terminal, containing: "POST /v1/chat/completions 200")180+ try await waitForScreen(terminal, containing: "loaded")
181+ try await waitForScreen(terminal, containing: "POST /v1/chat/completions")
182+ // A streamed answer's tokens reach the history once it ends.
183+ try await waitForScreen(terminal, containing: "1+1")
184+ terminal.press(.control("q"))
185+ await running.value
186+ }
187+ }
188+}
189+
190+@Suite struct ChatLiveTests {
191+ @Test func chatScreenTalksToARealServer() async throws {
192+ let echo = ModelEntry(id: "echo", source: .huggingFace(id: "org/echo", revision: "main"))
193+ try await withServer(models: [echo]) { url in
194+ let client = ServerClient(baseURL: url, apiKey: nil)
195+ let terminal = FakeTerminal(rows: 20, columns: 100)
196+ let app = TUIApp(
197+ terminal: terminal, server: client, serverURL: url, colors: false,
198+ pollInterval: .milliseconds(10))
199+ let running = Task { await app.run() }
200+ terminal.press(.function(1))
201+ try await waitForScreen(terminal, containing: "Ctrl-P model: echo")
202+ terminal.type("/set temperature 0.2")
203+ terminal.press(.enter)
204+ terminal.type("ping")
205+ terminal.press(.enter)
206+ try await waitForScreen(terminal, containing: "echo › echo: ping")
207+ try await waitForScreen(terminal, containing: "tokens")
180 terminal.press(.control("q"))208 terminal.press(.control("q"))
181 await running.value209 await running.value
182 }210 }
modified Tests/RazorbillTUITests/TUIAppTests.swift +57 -53
@@ -3,10 +3,23 @@ import Testing
33
44 @testable import RazorbillTUI
55
6-/// A status source that answers what the test sets, one call at a time.
7-final class ScriptedSource: StatusSource, @unchecked Sendable {
6+/// A server for tests: status answers what the test sets, chat streams a script (and can hang
7+/// until cancelled), unloads are recorded.
8+final class ScriptedServer: TUIServer, @unchecked Sendable {
89 private let lock = NSLock()
910 private var answer: Result<StatusSnapshot, ServerClientError>
11+ private var unloaded: [String] = []
12+ private var chats: [[ChatTurn]] = []
13+ private var cancelledChats = 0
14+ var served: [ServedModel] = [ServedModel(id: "qwen", loaded: true, kind: "chat")]
15+ var unloadAnswer: Result<UnloadReply, ServerClientError> = .success(
16+ UnloadReply(model: "qwen", status: "unloaded", unloaded: ["org/qwen"]))
17+ var script: [ChatEvent] = [
18+ .content("Hi"), .content("!"), .finished(reason: "stop"),
19+ .usage(promptTokens: 5, completionTokens: 2, cachedTokens: 3),
20+ ]
21+ /// Chat streams send the script, then wait until cancelled.
22+ var hangs = false
1023
1124 init(_ answer: Result<StatusSnapshot, ServerClientError>) {
1225 self.answer = answer
@@ -16,15 +29,43 @@ final class ScriptedSource: StatusSource, @unchecked Sendable {
1629 lock.withLock { self.answer = answer }
1730 }
1831
32+ var unloads: [String] { lock.withLock { unloaded } }
33+ var conversations: [[ChatTurn]] { lock.withLock { chats } }
34+ var cancellations: Int { lock.withLock { cancelledChats } }
35+
1936 func status() async throws -> StatusSnapshot {
2037 try lock.withLock { answer }.get()
2138 }
39+
40+ func models() async throws -> [ServedModel] { served }
41+
42+ func unload(_ id: String) async throws -> UnloadReply {
43+ lock.withLock { unloaded.append(id) }
44+ return try unloadAnswer.get()
45+ }
46+
47+ func chat(
48+ model: String, messages: [ChatTurn], options: ChatOptions
49+ ) -> ServerClient.ChatStream {
50+ lock.withLock { chats.append(messages) }
51+ let (script, hangs) = (self.script, self.hangs)
52+ return ServerClient.ChatStream { continuation in
53+ for event in script { continuation.yield(event) }
54+ if hangs {
55+ continuation.onTermination = { _ in
56+ self.lock.withLock { self.cancelledChats += 1 }
57+ }
58+ } else {
59+ continuation.finish()
60+ }
61+ }
62+ }
2263 }
2364
2465 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
2566 let chat = RecentRequest(
2667 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
27- completionTokens: 9, cachedTokens: 0, durationMs: 529, finishedAt: 0)
68+ completionTokens: 9, cachedTokens: 4, firstByteMs: 120, durationMs: 529, finishedAt: 48)
2869 return StatusSnapshot(
2970 version: "0.2.0", uptimeSeconds: 192, host: "127.0.0.1", port: 7920, models: models,
3071 recentRequests: [chat], memory: memory)
@@ -39,64 +80,27 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
3980 for _ in 0 ..< 400 where !terminal.lastText.joined(separator: "\n").contains(text) {
4081 try await Task.sleep(for: .milliseconds(5))
4182 }
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- }
83+ #expect(
84+ terminal.lastText.joined(separator: "\n").contains(text),
85+ "\(text) not in:\n\(terminal.lastText.joined(separator: "\n"))")
8286 }
8387
8488 @Suite struct TUIAppTests {
85- func app(_ terminal: FakeTerminal, _ source: ScriptedSource) -> TUIApp {
89+ func app(_ terminal: FakeTerminal, _ source: ScriptedServer) -> TUIApp {
8690 TUIApp(
87- terminal: terminal, source: source, serverURL: "http://127.0.0.1:7920",
91+ terminal: terminal, server: source, serverURL: "http://127.0.0.1:7920",
8892 startCommand: "rzb serve --config s.yaml", colors: false,
89- pollInterval: .milliseconds(10))
93+ pollInterval: .milliseconds(10), now: { Date(timeIntervalSince1970: 60) })
9094 }
9195
9296 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
9397 let terminal = FakeTerminal(rows: 20, columns: 100)
9498 let memory = EngineMemory(
9599 activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 1 << 30, limitBytes: 32 << 30)
96- let source = ScriptedSource(.success(snapshot(models: [qwen], memory: memory)))
100+ let source = ScriptedServer(.success(snapshot(models: [qwen], memory: memory)))
97101 let app = app(terminal, source)
98102 let running = Task { await app.run() }
99- try await waitForScreen(terminal, containing: "qwen chat loaded")
103+ try await waitForScreen(terminal, containing: "idle 7s, unloads in 9m 52s")
100104 #expect(
101105 terminal.lastText.last?.hasPrefix(
102106 "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB") == true)
@@ -107,7 +111,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
107111
108112 @Test func stoppedServerShowsHowToStartItThenFollowsWhenItAnswers() async throws {
109113 let terminal = FakeTerminal(rows: 20, columns: 100)
110- let source = ScriptedSource(.failure(.unreachable("refused")))
114+ let source = ScriptedServer(.failure(.unreachable("refused")))
111115 let app = app(terminal, source)
112116 let running = Task { await app.run() }
113117 try await waitForScreen(terminal, containing: "rzb serve --config s.yaml")
@@ -121,7 +125,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
121125
122126 @Test func keyProblemsAreExplained() async throws {
123127 let terminal = FakeTerminal(rows: 20, columns: 100)
124- let app = app(terminal, ScriptedSource(.failure(.unauthorized)))
128+ let app = app(terminal, ScriptedServer(.failure(.unauthorized)))
125129 let running = Task { await app.run() }
126130 try await waitForScreen(terminal, containing: "rzb tui --api-key-env RZB_API_KEY")
127131 terminal.close()
@@ -130,7 +134,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
130134
131135 @Test func requestErrorsDoNotChangeTheConnection() async throws {
132136 let terminal = FakeTerminal()
133- let source = ScriptedSource(.success(snapshot()))
137+ let source = ScriptedServer(.success(snapshot()))
134138 let app = app(terminal, source)
135139 await app.refresh()
136140 source.set(.failure(.server(status: 500, code: nil, message: "x")))
@@ -140,7 +144,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
140144
141145 @Test func otherScreensWaitForTheirTickets() async throws {
142146 let terminal = FakeTerminal(rows: 20, columns: 100)
143- let app = app(terminal, ScriptedSource(.success(snapshot())))
147+ let app = app(terminal, ScriptedServer(.success(snapshot())))
144148 let running = Task { await app.run() }
145149 try await waitForScreen(terminal, containing: "Server rzb")
146150 terminal.press(.function(3))
@@ -154,7 +158,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
154158
155159 @Test func nothingIsDrawnAfterTheAppReturns() async throws {
156160 let terminal = FakeTerminal()
157- let app = app(terminal, ScriptedSource(.success(snapshot())))
161+ let app = app(terminal, ScriptedServer(.success(snapshot())))
158162 let running = Task { await app.run() }
159163 terminal.close()
160164 await running.value
@@ -3,10 +3,23 @@ import Testing
3 3
4 @testable import RazorbillTUI4 @testable import RazorbillTUI
5 5
6-/// A status source that answers what the test sets, one call at a time.6+/// A server for tests: status answers what the test sets, chat streams a script (and can hang
7-final class ScriptedSource: StatusSource, @unchecked Sendable {7+/// until cancelled), unloads are recorded.
8+final class ScriptedServer: TUIServer, @unchecked Sendable {
8 private let lock = NSLock()9 private let lock = NSLock()
9 private var answer: Result<StatusSnapshot, ServerClientError>10 private var answer: Result<StatusSnapshot, ServerClientError>
11+ private var unloaded: [String] = []
12+ private var chats: [[ChatTurn]] = []
13+ private var cancelledChats = 0
14+ var served: [ServedModel] = [ServedModel(id: "qwen", loaded: true, kind: "chat")]
15+ var unloadAnswer: Result<UnloadReply, ServerClientError> = .success(
16+ UnloadReply(model: "qwen", status: "unloaded", unloaded: ["org/qwen"]))
17+ var script: [ChatEvent] = [
18+ .content("Hi"), .content("!"), .finished(reason: "stop"),
19+ .usage(promptTokens: 5, completionTokens: 2, cachedTokens: 3),
20+ ]
21+ /// Chat streams send the script, then wait until cancelled.
22+ var hangs = false
10 23
11 init(_ answer: Result<StatusSnapshot, ServerClientError>) {24 init(_ answer: Result<StatusSnapshot, ServerClientError>) {
12 self.answer = answer25 self.answer = answer
@@ -16,15 +29,43 @@ final class ScriptedSource: StatusSource, @unchecked Sendable {
16 lock.withLock { self.answer = answer }29 lock.withLock { self.answer = answer }
17 }30 }
18 31
32+ var unloads: [String] { lock.withLock { unloaded } }
33+ var conversations: [[ChatTurn]] { lock.withLock { chats } }
34+ var cancellations: Int { lock.withLock { cancelledChats } }
35+
19 func status() async throws -> StatusSnapshot {36 func status() async throws -> StatusSnapshot {
20 try lock.withLock { answer }.get()37 try lock.withLock { answer }.get()
21 }38 }
39+
40+ func models() async throws -> [ServedModel] { served }
41+
42+ func unload(_ id: String) async throws -> UnloadReply {
43+ lock.withLock { unloaded.append(id) }
44+ return try unloadAnswer.get()
45+ }
46+
47+ func chat(
48+ model: String, messages: [ChatTurn], options: ChatOptions
49+ ) -> ServerClient.ChatStream {
50+ lock.withLock { chats.append(messages) }
51+ let (script, hangs) = (self.script, self.hangs)
52+ return ServerClient.ChatStream { continuation in
53+ for event in script { continuation.yield(event) }
54+ if hangs {
55+ continuation.onTermination = { _ in
56+ self.lock.withLock { self.cancelledChats += 1 }
57+ }
58+ } else {
59+ continuation.finish()
60+ }
61+ }
62+ }
22 }63 }
23 64
24 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {65 func snapshot(models: [LoadedModel] = [], memory: EngineMemory? = nil) -> StatusSnapshot {
25 let chat = RecentRequest(66 let chat = RecentRequest(
26 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,67 method: "POST", path: "/v1/chat/completions", status: 200, model: "qwen", promptTokens: 14,
27- completionTokens: 9, cachedTokens: 0, durationMs: 529, finishedAt: 0)68+ completionTokens: 9, cachedTokens: 4, firstByteMs: 120, durationMs: 529, finishedAt: 48)
28 return StatusSnapshot(69 return StatusSnapshot(
29 version: "0.2.0", uptimeSeconds: 192, host: "127.0.0.1", port: 7920, models: models,70 version: "0.2.0", uptimeSeconds: 192, host: "127.0.0.1", port: 7920, models: models,
30 recentRequests: [chat], memory: memory)71 recentRequests: [chat], memory: memory)
@@ -39,64 +80,27 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
39 for _ in 0 ..< 400 where !terminal.lastText.joined(separator: "\n").contains(text) {80 for _ in 0 ..< 400 where !terminal.lastText.joined(separator: "\n").contains(text) {
40 try await Task.sleep(for: .milliseconds(5))81 try await Task.sleep(for: .milliseconds(5))
41 }82 }
42- #expect(terminal.lastText.joined(separator: "\n").contains(text))83+ #expect(
43-}84+ terminal.lastText.joined(separator: "\n").contains(text),
44-85+ "\(text) not in:\n\(terminal.lastText.joined(separator: "\n"))")
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 }86 }
83 87
84 @Suite struct TUIAppTests {88 @Suite struct TUIAppTests {
85- func app(_ terminal: FakeTerminal, _ source: ScriptedSource) -> TUIApp {89+ func app(_ terminal: FakeTerminal, _ source: ScriptedServer) -> TUIApp {
86 TUIApp(90 TUIApp(
87- terminal: terminal, source: source, serverURL: "http://127.0.0.1:7920",91+ terminal: terminal, server: source, serverURL: "http://127.0.0.1:7920",
88 startCommand: "rzb serve --config s.yaml", colors: false,92 startCommand: "rzb serve --config s.yaml", colors: false,
89- pollInterval: .milliseconds(10))93+ pollInterval: .milliseconds(10), now: { Date(timeIntervalSince1970: 60) })
90 }94 }
91 95
92 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {96 @Test func connectedServerFillsTheStatusBarAndTheDashboard() async throws {
93 let terminal = FakeTerminal(rows: 20, columns: 100)97 let terminal = FakeTerminal(rows: 20, columns: 100)
94 let memory = EngineMemory(98 let memory = EngineMemory(
95 activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 1 << 30, limitBytes: 32 << 30)99 activeBytes: 1 << 30, cacheBytes: 0, peakBytes: 1 << 30, limitBytes: 32 << 30)
96- let source = ScriptedSource(.success(snapshot(models: [qwen], memory: memory)))100+ let source = ScriptedServer(.success(snapshot(models: [qwen], memory: memory)))
97 let app = app(terminal, source)101 let app = app(terminal, source)
98 let running = Task { await app.run() }102 let running = Task { await app.run() }
99- try await waitForScreen(terminal, containing: "qwen chat loaded")103+ try await waitForScreen(terminal, containing: "idle 7s, unloads in 9m 52s")
100 #expect(104 #expect(
101 terminal.lastText.last?.hasPrefix(105 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)106 "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB") == true)
@@ -107,7 +111,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
107 111
108 @Test func stoppedServerShowsHowToStartItThenFollowsWhenItAnswers() async throws {112 @Test func stoppedServerShowsHowToStartItThenFollowsWhenItAnswers() async throws {
109 let terminal = FakeTerminal(rows: 20, columns: 100)113 let terminal = FakeTerminal(rows: 20, columns: 100)
110- let source = ScriptedSource(.failure(.unreachable("refused")))114+ let source = ScriptedServer(.failure(.unreachable("refused")))
111 let app = app(terminal, source)115 let app = app(terminal, source)
112 let running = Task { await app.run() }116 let running = Task { await app.run() }
113 try await waitForScreen(terminal, containing: "rzb serve --config s.yaml")117 try await waitForScreen(terminal, containing: "rzb serve --config s.yaml")
@@ -121,7 +125,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
121 125
122 @Test func keyProblemsAreExplained() async throws {126 @Test func keyProblemsAreExplained() async throws {
123 let terminal = FakeTerminal(rows: 20, columns: 100)127 let terminal = FakeTerminal(rows: 20, columns: 100)
124- let app = app(terminal, ScriptedSource(.failure(.unauthorized)))128+ let app = app(terminal, ScriptedServer(.failure(.unauthorized)))
125 let running = Task { await app.run() }129 let running = Task { await app.run() }
126 try await waitForScreen(terminal, containing: "rzb tui --api-key-env RZB_API_KEY")130 try await waitForScreen(terminal, containing: "rzb tui --api-key-env RZB_API_KEY")
127 terminal.close()131 terminal.close()
@@ -130,7 +134,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
130 134
131 @Test func requestErrorsDoNotChangeTheConnection() async throws {135 @Test func requestErrorsDoNotChangeTheConnection() async throws {
132 let terminal = FakeTerminal()136 let terminal = FakeTerminal()
133- let source = ScriptedSource(.success(snapshot()))137+ let source = ScriptedServer(.success(snapshot()))
134 let app = app(terminal, source)138 let app = app(terminal, source)
135 await app.refresh()139 await app.refresh()
136 source.set(.failure(.server(status: 500, code: nil, message: "x")))140 source.set(.failure(.server(status: 500, code: nil, message: "x")))
@@ -140,7 +144,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
140 144
141 @Test func otherScreensWaitForTheirTickets() async throws {145 @Test func otherScreensWaitForTheirTickets() async throws {
142 let terminal = FakeTerminal(rows: 20, columns: 100)146 let terminal = FakeTerminal(rows: 20, columns: 100)
143- let app = app(terminal, ScriptedSource(.success(snapshot())))147+ let app = app(terminal, ScriptedServer(.success(snapshot())))
144 let running = Task { await app.run() }148 let running = Task { await app.run() }
145 try await waitForScreen(terminal, containing: "Server rzb")149 try await waitForScreen(terminal, containing: "Server rzb")
146 terminal.press(.function(3))150 terminal.press(.function(3))
@@ -154,7 +158,7 @@ func waitForScreen(_ terminal: FakeTerminal, containing text: String) async thro
154 158
155 @Test func nothingIsDrawnAfterTheAppReturns() async throws {159 @Test func nothingIsDrawnAfterTheAppReturns() async throws {
156 let terminal = FakeTerminal()160 let terminal = FakeTerminal()
157- let app = app(terminal, ScriptedSource(.success(snapshot())))161+ let app = app(terminal, ScriptedServer(.success(snapshot())))
158 let running = Task { await app.run() }162 let running = Task { await app.run() }
159 terminal.close()163 terminal.close()
160 await running.value164 await running.value