#54 step 5: rzb tui command (--url, --config, --api-key-env)
The address comes from --url, else the config's server section, else 127.0.0.1:7920; the key variable likewise. No terminal: exit 1 with the server's address. The TUI's HTTP client no longer waits for connectivity on macOS (Network.framework), so a stopped server shows at once there too. Checked by hand on the Mac by the user (all six points). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
64c4687 parent: 19e3378 modified
Package.swift +5 -1 | @@ -93,6 +93,7 @@ let package = Package( | ||
| 93 | 93 | dependencies: [ |
| 94 | 94 | "RazorbillCore", |
| 95 | 95 | "RazorbillServer", |
| 96 | + "RazorbillTUI", | |
| 96 | 97 | .product(name: "Logging", package: "swift-log"), |
| 97 | 98 | .product(name: "ArgumentParser", package: "swift-argument-parser"), |
| 98 | 99 | ] |
| @@ -103,7 +104,10 @@ let package = Package( | ||
| 103 | 104 | dependencies: ["RazorbillCLI", "RazorbillMLX"] |
| 104 | 105 | ), |
| 105 | 106 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 106 | - .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]), | |
| 107 | + .testTarget( | |
| 108 | + name: "RazorbillCLITests", | |
| 109 | + dependencies: ["RazorbillCLI", "RazorbillServer", "RazorbillTUI"] | |
| 110 | + ), | |
| 107 | 111 | // RazorbillServer and HummingbirdTesting start a real server for the HTTP client's tests. |
| 108 | 112 | .testTarget( |
| 109 | 113 | name: "RazorbillTUITests", |
| @@ -93,6 +93,7 @@ let package = Package( | |||
| 93 | dependencies: [ | 93 | dependencies: [ |
| 94 | "RazorbillCore", | 94 | "RazorbillCore", |
| 95 | "RazorbillServer", | 95 | "RazorbillServer", |
| 96 | + "RazorbillTUI", | ||
| 96 | .product(name: "Logging", package: "swift-log"), | 97 | .product(name: "Logging", package: "swift-log"), |
| 97 | .product(name: "ArgumentParser", package: "swift-argument-parser"), | 98 | .product(name: "ArgumentParser", package: "swift-argument-parser"), |
| 98 | ] | 99 | ] |
| @@ -103,7 +104,10 @@ let package = Package( | |||
| 103 | dependencies: ["RazorbillCLI", "RazorbillMLX"] | 104 | dependencies: ["RazorbillCLI", "RazorbillMLX"] |
| 104 | ), | 105 | ), |
| 105 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), | 106 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 106 | - .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]), | 107 | + .testTarget( |
| 108 | + name: "RazorbillCLITests", | ||
| 109 | + dependencies: ["RazorbillCLI", "RazorbillServer", "RazorbillTUI"] | ||
| 110 | + ), | ||
| 107 | // RazorbillServer and HummingbirdTesting start a real server for the HTTP client's tests. | 111 | // RazorbillServer and HummingbirdTesting start a real server for the HTTP client's tests. |
| 108 | .testTarget( | 112 | .testTarget( |
| 109 | name: "RazorbillTUITests", | 113 | name: "RazorbillTUITests", |
modified
Sources/RazorbillCLI/CLIEnvironment.swift +13 -1 | @@ -2,6 +2,7 @@ import Foundation | ||
| 2 | 2 | import Logging |
| 3 | 3 | import RazorbillCore |
| 4 | 4 | import RazorbillServer |
| 5 | +import RazorbillTUI | |
| 5 | 6 | |
| 6 | 7 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests |
| 7 | 8 | /// replace it to run commands with a scripted console and a ``FakeEngine``. |
| @@ -20,6 +21,9 @@ public struct CLIEnvironment: Sendable { | ||
| 20 | 21 | async throws |
| 21 | 22 | -> Void |
| 22 | 23 | |
| 24 | + /// Runs `rzb tui` until the user quits; tests replace it to avoid taking the terminal. | |
| 25 | + public typealias TUIRunner = @Sendable (TUILaunch) async throws -> Void | |
| 26 | + | |
| 23 | 27 | public var engines: EngineRegistry |
| 24 | 28 | public var console: any Console |
| 25 | 29 | public var modelStore: ModelStore |
| @@ -27,10 +31,15 @@ public struct CLIEnvironment: Sendable { | ||
| 27 | 31 | public var variables: [String: String] |
| 28 | 32 | /// How `rzb serve` runs the server; tests replace it to avoid opening a port. |
| 29 | 33 | public var serve: ServerRunner |
| 34 | + /// Standard input and output are a terminal the TUI can take over. | |
| 35 | + public var hasTerminal: Bool | |
| 36 | + /// How `rzb tui` runs. | |
| 37 | + public var tui: TUIRunner | |
| 30 | 38 | |
| 31 | 39 | public init( |
| 32 | 40 | engines: EngineRegistry, console: any Console, modelStore: ModelStore, |
| 33 | - variables: [String: String] = [:], serve: ServerRunner? = nil | |
| 41 | + variables: [String: String] = [:], serve: ServerRunner? = nil, | |
| 42 | + hasTerminal: Bool = PosixTerminal.isAvailable, tui: TUIRunner? = nil | |
| 34 | 43 | ) { |
| 35 | 44 | self.engines = engines |
| 36 | 45 | self.console = console |
| @@ -41,6 +50,9 @@ public struct CLIEnvironment: Sendable { | ||
| 41 | 50 | try await Self.runServer( |
| 42 | 51 | settings, engines: engines, store: modelStore, onRunning: onRunning) |
| 43 | 52 | } |
| 53 | + self.hasTerminal = hasTerminal | |
| 54 | + let colors = variables["NO_COLOR"] == nil | |
| 55 | + self.tui = tui ?? { launch in await launch.run(colors: colors) } | |
| 44 | 56 | } |
| 45 | 57 | |
| 46 | 58 | /// The real terminal, model cache, environment variables and server, with the given engines. |
| @@ -2,6 +2,7 @@ import Foundation | |||
| 2 | import Logging | 2 | import Logging |
| 3 | import RazorbillCore | 3 | import RazorbillCore |
| 4 | import RazorbillServer | 4 | import RazorbillServer |
| 5 | +import RazorbillTUI | ||
| 5 | 6 | ||
| 6 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests | 7 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests |
| 7 | /// replace it to run commands with a scripted console and a ``FakeEngine``. | 8 | /// replace it to run commands with a scripted console and a ``FakeEngine``. |
| @@ -20,6 +21,9 @@ public struct CLIEnvironment: Sendable { | |||
| 20 | async throws | 21 | async throws |
| 21 | -> Void | 22 | -> Void |
| 22 | 23 | ||
| 24 | + /// Runs `rzb tui` until the user quits; tests replace it to avoid taking the terminal. | ||
| 25 | + public typealias TUIRunner = @Sendable (TUILaunch) async throws -> Void | ||
| 26 | + | ||
| 23 | public var engines: EngineRegistry | 27 | public var engines: EngineRegistry |
| 24 | public var console: any Console | 28 | public var console: any Console |
| 25 | public var modelStore: ModelStore | 29 | public var modelStore: ModelStore |
| @@ -27,10 +31,15 @@ public struct CLIEnvironment: Sendable { | |||
| 27 | public var variables: [String: String] | 31 | public var variables: [String: String] |
| 28 | /// How `rzb serve` runs the server; tests replace it to avoid opening a port. | 32 | /// How `rzb serve` runs the server; tests replace it to avoid opening a port. |
| 29 | public var serve: ServerRunner | 33 | public var serve: ServerRunner |
| 34 | + /// Standard input and output are a terminal the TUI can take over. | ||
| 35 | + public var hasTerminal: Bool | ||
| 36 | + /// How `rzb tui` runs. | ||
| 37 | + public var tui: TUIRunner | ||
| 30 | 38 | ||
| 31 | public init( | 39 | public init( |
| 32 | engines: EngineRegistry, console: any Console, modelStore: ModelStore, | 40 | engines: EngineRegistry, console: any Console, modelStore: ModelStore, |
| 33 | - variables: [String: String] = [:], serve: ServerRunner? = nil | 41 | + variables: [String: String] = [:], serve: ServerRunner? = nil, |
| 42 | + hasTerminal: Bool = PosixTerminal.isAvailable, tui: TUIRunner? = nil | ||
| 34 | ) { | 43 | ) { |
| 35 | self.engines = engines | 44 | self.engines = engines |
| 36 | self.console = console | 45 | self.console = console |
| @@ -41,6 +50,9 @@ public struct CLIEnvironment: Sendable { | |||
| 41 | try await Self.runServer( | 50 | try await Self.runServer( |
| 42 | settings, engines: engines, store: modelStore, onRunning: onRunning) | 51 | settings, engines: engines, store: modelStore, onRunning: onRunning) |
| 43 | } | 52 | } |
| 53 | + self.hasTerminal = hasTerminal | ||
| 54 | + let colors = variables["NO_COLOR"] == nil | ||
| 55 | + self.tui = tui ?? { launch in await launch.run(colors: colors) } | ||
| 44 | } | 56 | } |
| 45 | 57 | ||
| 46 | /// The real terminal, model cache, environment variables and server, with the given engines. | 58 | /// The real terminal, model cache, environment variables and server, with the given engines. |
modified
Sources/RazorbillCLI/Commands/Rzb.swift +2 -1 | @@ -12,7 +12,8 @@ public struct Rzb: AsyncParsableCommand { | ||
| 12 | 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", |
| 13 | 13 | version: Razorbill.version, |
| 14 | 14 | subcommands: [ |
| 15 | - ServeCommand.self, ConfigCommand.self, ModelsCommand.self, VersionCommand.self, | |
| 15 | + ServeCommand.self, TUICommand.self, ConfigCommand.self, ModelsCommand.self, | |
| 16 | + VersionCommand.self, | |
| 16 | 17 | ] |
| 17 | 18 | ) |
| 18 | 19 | |
| @@ -12,7 +12,8 @@ public struct Rzb: AsyncParsableCommand { | |||
| 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", | 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", |
| 13 | version: Razorbill.version, | 13 | version: Razorbill.version, |
| 14 | subcommands: [ | 14 | subcommands: [ |
| 15 | - ServeCommand.self, ConfigCommand.self, ModelsCommand.self, VersionCommand.self, | 15 | + ServeCommand.self, TUICommand.self, ConfigCommand.self, ModelsCommand.self, |
| 16 | + VersionCommand.self, | ||
| 16 | ] | 17 | ] |
| 17 | ) | 18 | ) |
| 18 | 19 | ||
added
Sources/RazorbillCLI/Commands/TUICommand.swift +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +import ArgumentParser | |
| 2 | +import RazorbillCore | |
| 3 | +import RazorbillServer | |
| 4 | +import RazorbillTUI | |
| 5 | + | |
| 6 | +/// `rzb tui`: the full-screen terminal interface to a `rzb serve` running on this machine. | |
| 7 | +/// | |
| 8 | +/// ```sh | |
| 9 | +/// rzb tui # the server at http://127.0.0.1:7920 | |
| 10 | +/// rzb tui --config server.yaml # the server that file describes (port, API key variable) | |
| 11 | +/// ``` | |
| 12 | +struct TUICommand: AsyncParsableCommand { | |
| 13 | + static let configuration = CommandConfiguration( | |
| 14 | + commandName: "tui", | |
| 15 | + abstract: "Open the full-screen interface to the server running on this machine.", | |
| 16 | + discussion: """ | |
| 17 | + Watches a running `rzb serve`: its models, memory and requests. Start the server \ | |
| 18 | + first, in another terminal. F1–F4 or Ctrl-T switch screens, Ctrl-Q quits. | |
| 19 | + """) | |
| 20 | + | |
| 21 | + @Option( | |
| 22 | + help: ArgumentHelp( | |
| 23 | + "Server address, http://host:port. (default: from --config, else http://127.0.0.1:7920)", | |
| 24 | + valueName: "url")) | |
| 25 | + var url: String? | |
| 26 | + | |
| 27 | + @Option( | |
| 28 | + help: ArgumentHelp( | |
| 29 | + "The server's configuration file: its server section gives the address and the API " | |
| 30 | + + "key variable.", | |
| 31 | + valueName: "file")) | |
| 32 | + var config: String? | |
| 33 | + | |
| 34 | + @Option( | |
| 35 | + name: .customLong("api-key-env"), | |
| 36 | + help: ArgumentHelp( | |
| 37 | + "Environment variable holding the server's API key. (default: from --config, else " | |
| 38 | + + "RZB_API_KEY)", | |
| 39 | + valueName: "name")) | |
| 40 | + var apiKeyVariable: String? | |
| 41 | + | |
| 42 | + func validate() throws { | |
| 43 | + if let url, Self.baseURL(url) == nil { | |
| 44 | + throw ValidationError("--url must look like http://host:port") | |
| 45 | + } | |
| 46 | + } | |
| 47 | + | |
| 48 | + func run() async throws { | |
| 49 | + let environment = CLIEnvironment.current | |
| 50 | + try await reportingErrors(environment.console) { | |
| 51 | + let section = try config.map { try ServerConfigLoader().load(file: $0).server } | |
| 52 | + let launch = launch( | |
| 53 | + section: section ?? ServerSection(), variables: environment.variables) | |
| 54 | + guard environment.hasTerminal else { | |
| 55 | + environment.console.writeErrorLine( | |
| 56 | + "error: rzb tui needs a terminal (standard input and output); " | |
| 57 | + + "the server is at \(launch.url)") | |
| 58 | + throw ExitStatus.failure | |
| 59 | + } | |
| 60 | + try await environment.tui(launch) | |
| 61 | + } | |
| 62 | + } | |
| 63 | + | |
| 64 | + /// The options first, then the file's `server:` section, then the defaults. | |
| 65 | + func launch(section: ServerSection, variables: [String: String]) -> TUILaunch { | |
| 66 | + let address = url.flatMap(Self.baseURL) ?? Self.address(of: section) | |
| 67 | + let variable = | |
| 68 | + apiKeyVariable ?? section.apiKeyVariable ?? ServeCommand.defaultAPIKeyVariable | |
| 69 | + let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 } | |
| 70 | + let start = config.map { "rzb serve --config \($0)" } ?? "rzb serve" | |
| 71 | + return TUILaunch(url: address, apiKey: key, startCommand: start) | |
| 72 | + } | |
| 73 | + | |
| 74 | + /// Where a server started with `section` answers on this machine. A wildcard address | |
| 75 | + /// (`0.0.0.0`, `::`) listens on loopback too. | |
| 76 | + static func address(of section: ServerSection) -> String { | |
| 77 | + let defaults = ServerSettings() | |
| 78 | + var host = section.host ?? defaults.host | |
| 79 | + if host == "0.0.0.0" || host == "::" { host = "127.0.0.1" } | |
| 80 | + let shown = host.contains(":") ? "[\(host)]" : host | |
| 81 | + return "http://\(shown):\(section.port ?? defaults.port)" | |
| 82 | + } | |
| 83 | + | |
| 84 | + /// `url` without a trailing `/` or `/v1`; `nil` when it is not an http(s) URL with a host. | |
| 85 | + static func baseURL(_ url: String) -> String? { | |
| 86 | + var base = url | |
| 87 | + while base.hasSuffix("/") { base.removeLast() } | |
| 88 | + if base.hasSuffix("/v1") { base.removeLast(3) } | |
| 89 | + let scheme = ["http://", "https://"].first { base.hasPrefix($0) } | |
| 90 | + guard let scheme, base.count > scheme.count else { return nil } | |
| 91 | + return base | |
| 92 | + } | |
| 93 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +import ArgumentParser | ||
| 2 | +import RazorbillCore | ||
| 3 | +import RazorbillServer | ||
| 4 | +import RazorbillTUI | ||
| 5 | + | ||
| 6 | +/// `rzb tui`: the full-screen terminal interface to a `rzb serve` running on this machine. | ||
| 7 | +/// | ||
| 8 | +/// ```sh | ||
| 9 | +/// rzb tui # the server at http://127.0.0.1:7920 | ||
| 10 | +/// rzb tui --config server.yaml # the server that file describes (port, API key variable) | ||
| 11 | +/// ``` | ||
| 12 | +struct TUICommand: AsyncParsableCommand { | ||
| 13 | + static let configuration = CommandConfiguration( | ||
| 14 | + commandName: "tui", | ||
| 15 | + abstract: "Open the full-screen interface to the server running on this machine.", | ||
| 16 | + discussion: """ | ||
| 17 | + Watches a running `rzb serve`: its models, memory and requests. Start the server \ | ||
| 18 | + first, in another terminal. F1–F4 or Ctrl-T switch screens, Ctrl-Q quits. | ||
| 19 | + """) | ||
| 20 | + | ||
| 21 | + @Option( | ||
| 22 | + help: ArgumentHelp( | ||
| 23 | + "Server address, http://host:port. (default: from --config, else http://127.0.0.1:7920)", | ||
| 24 | + valueName: "url")) | ||
| 25 | + var url: String? | ||
| 26 | + | ||
| 27 | + @Option( | ||
| 28 | + help: ArgumentHelp( | ||
| 29 | + "The server's configuration file: its server section gives the address and the API " | ||
| 30 | + + "key variable.", | ||
| 31 | + valueName: "file")) | ||
| 32 | + var config: String? | ||
| 33 | + | ||
| 34 | + @Option( | ||
| 35 | + name: .customLong("api-key-env"), | ||
| 36 | + help: ArgumentHelp( | ||
| 37 | + "Environment variable holding the server's API key. (default: from --config, else " | ||
| 38 | + + "RZB_API_KEY)", | ||
| 39 | + valueName: "name")) | ||
| 40 | + var apiKeyVariable: String? | ||
| 41 | + | ||
| 42 | + func validate() throws { | ||
| 43 | + if let url, Self.baseURL(url) == nil { | ||
| 44 | + throw ValidationError("--url must look like http://host:port") | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + func run() async throws { | ||
| 49 | + let environment = CLIEnvironment.current | ||
| 50 | + try await reportingErrors(environment.console) { | ||
| 51 | + let section = try config.map { try ServerConfigLoader().load(file: $0).server } | ||
| 52 | + let launch = launch( | ||
| 53 | + section: section ?? ServerSection(), variables: environment.variables) | ||
| 54 | + guard environment.hasTerminal else { | ||
| 55 | + environment.console.writeErrorLine( | ||
| 56 | + "error: rzb tui needs a terminal (standard input and output); " | ||
| 57 | + + "the server is at \(launch.url)") | ||
| 58 | + throw ExitStatus.failure | ||
| 59 | + } | ||
| 60 | + try await environment.tui(launch) | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// The options first, then the file's `server:` section, then the defaults. | ||
| 65 | + func launch(section: ServerSection, variables: [String: String]) -> TUILaunch { | ||
| 66 | + let address = url.flatMap(Self.baseURL) ?? Self.address(of: section) | ||
| 67 | + let variable = | ||
| 68 | + apiKeyVariable ?? section.apiKeyVariable ?? ServeCommand.defaultAPIKeyVariable | ||
| 69 | + let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 } | ||
| 70 | + let start = config.map { "rzb serve --config \($0)" } ?? "rzb serve" | ||
| 71 | + return TUILaunch(url: address, apiKey: key, startCommand: start) | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + /// Where a server started with `section` answers on this machine. A wildcard address | ||
| 75 | + /// (`0.0.0.0`, `::`) listens on loopback too. | ||
| 76 | + static func address(of section: ServerSection) -> String { | ||
| 77 | + let defaults = ServerSettings() | ||
| 78 | + var host = section.host ?? defaults.host | ||
| 79 | + if host == "0.0.0.0" || host == "::" { host = "127.0.0.1" } | ||
| 80 | + let shown = host.contains(":") ? "[\(host)]" : host | ||
| 81 | + return "http://\(shown):\(section.port ?? defaults.port)" | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + /// `url` without a trailing `/` or `/v1`; `nil` when it is not an http(s) URL with a host. | ||
| 85 | + static func baseURL(_ url: String) -> String? { | ||
| 86 | + var base = url | ||
| 87 | + while base.hasSuffix("/") { base.removeLast() } | ||
| 88 | + if base.hasSuffix("/v1") { base.removeLast(3) } | ||
| 89 | + let scheme = ["http://", "https://"].first { base.hasPrefix($0) } | ||
| 90 | + guard let scheme, base.count > scheme.count else { return nil } | ||
| 91 | + return base | ||
| 92 | + } | ||
| 93 | +} | ||
modified
Sources/RazorbillTUI/ServerClient.swift +5 -3 | @@ -180,12 +180,14 @@ public struct ServerClient: Sendable { | ||
| 180 | 180 | } |
| 181 | 181 | } |
| 182 | 182 | |
| 183 | - /// The HTTP client of the TUI. It does not retry a refused connection, which AsyncHTTPClient | |
| 184 | - /// does by default until the request's deadline: a server that is not running must show at | |
| 185 | - /// once, not after the timeout. Lives as long as the process, so it is never shut down. | |
| 183 | + /// The HTTP client of the TUI. A server that is not running must show at once, not after the | |
| 184 | + /// timeout, so a refused connection fails right away: AsyncHTTPClient retries it by default | |
| 185 | + /// until the request's deadline, and on macOS Network.framework also waits for the address | |
| 186 | + /// to become reachable. Lives as long as the process, so it is never shut down. | |
| 186 | 187 | public static let localHTTP: HTTPClient = { |
| 187 | 188 | var configuration = HTTPClient.Configuration() |
| 188 | 189 | configuration.connectionPool.retryConnectionEstablishment = false |
| 190 | + configuration.networkFrameworkWaitForConnectivity = false | |
| 189 | 191 | configuration.timeout.connect = .seconds(2) |
| 190 | 192 | return HTTPClient( |
| 191 | 193 | eventLoopGroup: HTTPClient.defaultEventLoopGroup, configuration: configuration) |
| @@ -180,12 +180,14 @@ public struct ServerClient: Sendable { | |||
| 180 | } | 180 | } |
| 181 | } | 181 | } |
| 182 | 182 | ||
| 183 | - /// The HTTP client of the TUI. It does not retry a refused connection, which AsyncHTTPClient | 183 | + /// The HTTP client of the TUI. A server that is not running must show at once, not after the |
| 184 | - /// does by default until the request's deadline: a server that is not running must show at | 184 | + /// timeout, so a refused connection fails right away: AsyncHTTPClient retries it by default |
| 185 | - /// once, not after the timeout. Lives as long as the process, so it is never shut down. | 185 | + /// until the request's deadline, and on macOS Network.framework also waits for the address |
| 186 | + /// to become reachable. Lives as long as the process, so it is never shut down. | ||
| 186 | public static let localHTTP: HTTPClient = { | 187 | public static let localHTTP: HTTPClient = { |
| 187 | var configuration = HTTPClient.Configuration() | 188 | var configuration = HTTPClient.Configuration() |
| 188 | configuration.connectionPool.retryConnectionEstablishment = false | 189 | configuration.connectionPool.retryConnectionEstablishment = false |
| 190 | + configuration.networkFrameworkWaitForConnectivity = false | ||
| 189 | configuration.timeout.connect = .seconds(2) | 191 | configuration.timeout.connect = .seconds(2) |
| 190 | return HTTPClient( | 192 | return HTTPClient( |
| 191 | eventLoopGroup: HTTPClient.defaultEventLoopGroup, configuration: configuration) | 193 | eventLoopGroup: HTTPClient.defaultEventLoopGroup, configuration: configuration) |
added
Sources/RazorbillTUI/TUILaunch.swift +28 -0 | new file mode 100644 | ||
| @@ -0,0 +1,28 @@ | ||
| 1 | +/// What `rzb tui` starts with: the server to watch, its API key, and how to start it. | |
| 2 | +/// | |
| 3 | +/// ```swift | |
| 4 | +/// let launch = TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve") | |
| 5 | +/// await launch.run(colors: true) // full screen until Ctrl-Q | |
| 6 | +/// ``` | |
| 7 | +public struct TUILaunch: Sendable, Equatable { | |
| 8 | + /// `http://host:port`, without `/v1`. | |
| 9 | + public var url: String | |
| 10 | + public var apiKey: String? | |
| 11 | + /// Shown when no server answers. | |
| 12 | + public var startCommand: String | |
| 13 | + | |
| 14 | + public init(url: String, apiKey: String?, startCommand: String) { | |
| 15 | + self.url = url | |
| 16 | + self.apiKey = apiKey | |
| 17 | + self.startCommand = startCommand | |
| 18 | + } | |
| 19 | + | |
| 20 | + /// Runs the TUI on the process's terminal until the user quits. | |
| 21 | + public func run(colors: Bool) async { | |
| 22 | + let client = ServerClient(baseURL: url, apiKey: apiKey) | |
| 23 | + let app = TUIApp( | |
| 24 | + terminal: PosixTerminal(), source: client, serverURL: client.baseURL, | |
| 25 | + startCommand: startCommand, colors: colors) | |
| 26 | + await app.run() | |
| 27 | + } | |
| 28 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | +/// What `rzb tui` starts with: the server to watch, its API key, and how to start it. | ||
| 2 | +/// | ||
| 3 | +/// ```swift | ||
| 4 | +/// let launch = TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve") | ||
| 5 | +/// await launch.run(colors: true) // full screen until Ctrl-Q | ||
| 6 | +/// ``` | ||
| 7 | +public struct TUILaunch: Sendable, Equatable { | ||
| 8 | + /// `http://host:port`, without `/v1`. | ||
| 9 | + public var url: String | ||
| 10 | + public var apiKey: String? | ||
| 11 | + /// Shown when no server answers. | ||
| 12 | + public var startCommand: String | ||
| 13 | + | ||
| 14 | + public init(url: String, apiKey: String?, startCommand: String) { | ||
| 15 | + self.url = url | ||
| 16 | + self.apiKey = apiKey | ||
| 17 | + self.startCommand = startCommand | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + /// Runs the TUI on the process's terminal until the user quits. | ||
| 21 | + public func run(colors: Bool) async { | ||
| 22 | + let client = ServerClient(baseURL: url, apiKey: apiKey) | ||
| 23 | + let app = TUIApp( | ||
| 24 | + terminal: PosixTerminal(), source: client, serverURL: client.baseURL, | ||
| 25 | + startCommand: startCommand, colors: colors) | ||
| 26 | + await app.run() | ||
| 27 | + } | ||
| 28 | +} | ||
modified
Tests/RazorbillCLITests/Harness.swift +17 -1 | @@ -2,6 +2,7 @@ import ArgumentParser | ||
| 2 | 2 | import Foundation |
| 3 | 3 | import RazorbillCore |
| 4 | 4 | import RazorbillServer |
| 5 | +import RazorbillTUI | |
| 5 | 6 | import Testing |
| 6 | 7 | |
| 7 | 8 | @testable import RazorbillCLI |
| @@ -48,6 +49,10 @@ struct World { | ||
| 48 | 49 | let servers = ServerRecorder() |
| 49 | 50 | /// Replaces the recording server (to simulate a failure). |
| 50 | 51 | var serve: CLIEnvironment.ServerRunner? |
| 52 | + /// What `rzb tui` was asked to open; the terminal is never taken. | |
| 53 | + let tuis = TUIRecorder() | |
| 54 | + /// Whether `rzb tui` finds a terminal. | |
| 55 | + var hasTerminal = true | |
| 51 | 56 | |
| 52 | 57 | init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws { |
| 53 | 58 | let url = FileManager.default.temporaryDirectory.appendingPathComponent( |
| @@ -65,13 +70,14 @@ struct World { | ||
| 65 | 70 | var engines = EngineRegistry() |
| 66 | 71 | engines.register("fake") { _ in engine } |
| 67 | 72 | let servers = self.servers |
| 73 | + let tuis = self.tuis | |
| 68 | 74 | return CLIEnvironment( |
| 69 | 75 | engines: engines, console: console, |
| 70 | 76 | modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables, |
| 71 | 77 | serve: serve ?? { settings, onRunning in |
| 72 | 78 | servers.append(settings) |
| 73 | 79 | await onRunning(settings.port) |
| 74 | - }) | |
| 80 | + }, hasTerminal: hasTerminal, tui: { launch in tuis.append(launch) }) | |
| 75 | 81 | } |
| 76 | 82 | |
| 77 | 83 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. |
| @@ -102,3 +108,13 @@ final class ServerRecorder: @unchecked Sendable { | ||
| 102 | 108 | |
| 103 | 109 | func append(_ settings: ServerSettings) { lock.withLock { stored.append(settings) } } |
| 104 | 110 | } |
| 111 | + | |
| 112 | +/// Records what `rzb tui` would have opened. | |
| 113 | +final class TUIRecorder: @unchecked Sendable { | |
| 114 | + private let lock = NSLock() | |
| 115 | + private var stored: [TUILaunch] = [] | |
| 116 | + | |
| 117 | + var opened: [TUILaunch] { lock.withLock { stored } } | |
| 118 | + | |
| 119 | + func append(_ launch: TUILaunch) { lock.withLock { stored.append(launch) } } | |
| 120 | +} | |
| @@ -2,6 +2,7 @@ import ArgumentParser | |||
| 2 | import Foundation | 2 | import Foundation |
| 3 | import RazorbillCore | 3 | import RazorbillCore |
| 4 | import RazorbillServer | 4 | import RazorbillServer |
| 5 | +import RazorbillTUI | ||
| 5 | import Testing | 6 | import Testing |
| 6 | 7 | ||
| 7 | @testable import RazorbillCLI | 8 | @testable import RazorbillCLI |
| @@ -48,6 +49,10 @@ struct World { | |||
| 48 | let servers = ServerRecorder() | 49 | let servers = ServerRecorder() |
| 49 | /// Replaces the recording server (to simulate a failure). | 50 | /// Replaces the recording server (to simulate a failure). |
| 50 | var serve: CLIEnvironment.ServerRunner? | 51 | var serve: CLIEnvironment.ServerRunner? |
| 52 | + /// What `rzb tui` was asked to open; the terminal is never taken. | ||
| 53 | + let tuis = TUIRecorder() | ||
| 54 | + /// Whether `rzb tui` finds a terminal. | ||
| 55 | + var hasTerminal = true | ||
| 51 | 56 | ||
| 52 | init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws { | 57 | init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws { |
| 53 | let url = FileManager.default.temporaryDirectory.appendingPathComponent( | 58 | let url = FileManager.default.temporaryDirectory.appendingPathComponent( |
| @@ -65,13 +70,14 @@ struct World { | |||
| 65 | var engines = EngineRegistry() | 70 | var engines = EngineRegistry() |
| 66 | engines.register("fake") { _ in engine } | 71 | engines.register("fake") { _ in engine } |
| 67 | let servers = self.servers | 72 | let servers = self.servers |
| 73 | + let tuis = self.tuis | ||
| 68 | return CLIEnvironment( | 74 | return CLIEnvironment( |
| 69 | engines: engines, console: console, | 75 | engines: engines, console: console, |
| 70 | modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables, | 76 | modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables, |
| 71 | serve: serve ?? { settings, onRunning in | 77 | serve: serve ?? { settings, onRunning in |
| 72 | servers.append(settings) | 78 | servers.append(settings) |
| 73 | await onRunning(settings.port) | 79 | await onRunning(settings.port) |
| 74 | - }) | 80 | + }, hasTerminal: hasTerminal, tui: { launch in tuis.append(launch) }) |
| 75 | } | 81 | } |
| 76 | 82 | ||
| 77 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. | 83 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. |
| @@ -102,3 +108,13 @@ final class ServerRecorder: @unchecked Sendable { | |||
| 102 | 108 | ||
| 103 | func append(_ settings: ServerSettings) { lock.withLock { stored.append(settings) } } | 109 | func append(_ settings: ServerSettings) { lock.withLock { stored.append(settings) } } |
| 104 | } | 110 | } |
| 111 | + | ||
| 112 | +/// Records what `rzb tui` would have opened. | ||
| 113 | +final class TUIRecorder: @unchecked Sendable { | ||
| 114 | + private let lock = NSLock() | ||
| 115 | + private var stored: [TUILaunch] = [] | ||
| 116 | + | ||
| 117 | + var opened: [TUILaunch] { lock.withLock { stored } } | ||
| 118 | + | ||
| 119 | + func append(_ launch: TUILaunch) { lock.withLock { stored.append(launch) } } | ||
| 120 | +} | ||
added
Tests/RazorbillCLITests/TUICommandTests.swift +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | +import RazorbillTUI | |
| 4 | +import Testing | |
| 5 | + | |
| 6 | +@testable import RazorbillCLI | |
| 7 | + | |
| 8 | +@Suite struct TUICommandTests { | |
| 9 | + @Test func defaultsToTheLocalServer() async throws { | |
| 10 | + let world = try World() | |
| 11 | + let result = await world.rzb("tui") | |
| 12 | + #expect(result.exitCode == 0) | |
| 13 | + #expect( | |
| 14 | + world.tuis.opened == [ | |
| 15 | + TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve") | |
| 16 | + ]) | |
| 17 | + } | |
| 18 | + | |
| 19 | + @Test func urlIsCleanedOfSlashAndV1() async throws { | |
| 20 | + let world = try World() | |
| 21 | + _ = await world.rzb("tui", "--url", "http://localhost:8000/v1/") | |
| 22 | + #expect(world.tuis.opened.first?.url == "http://localhost:8000") | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test(arguments: ["localhost:8000", "ftp://x", "http://"]) | |
| 26 | + func badURLIsAUsageError(_ url: String) async throws { | |
| 27 | + let world = try World() | |
| 28 | + let result = await world.rzb("tui", "--url", url) | |
| 29 | + #expect(result.exitCode == 64) | |
| 30 | + #expect(world.tuis.opened.isEmpty) | |
| 31 | + } | |
| 32 | + | |
| 33 | + @Test func configGivesTheAddressAndTheKeyVariable() async throws { | |
| 34 | + var world = try World() | |
| 35 | + world.variables = ["TEAM_KEY": "k"] | |
| 36 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | |
| 37 | + try "server: { host: 0.0.0.0, port: 9100, api_key_env: TEAM_KEY }\n".write( | |
| 38 | + toFile: path, atomically: true, encoding: .utf8) | |
| 39 | + _ = await world.rzb("tui", "--config", path) | |
| 40 | + #expect( | |
| 41 | + world.tuis.opened.first | |
| 42 | + == TUILaunch( | |
| 43 | + url: "http://127.0.0.1:9100", apiKey: "k", | |
| 44 | + startCommand: "rzb serve --config \(path)")) | |
| 45 | + | |
| 46 | + _ = await world.rzb("tui", "--config", path, "--url", "http://[::1]:7000") | |
| 47 | + #expect(world.tuis.opened.last?.url == "http://[::1]:7000") | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Test func keyVariableOptionWinsAndAnEmptyKeyIsNone() async throws { | |
| 51 | + var world = try World() | |
| 52 | + world.variables = ["RZB_API_KEY": "", "MINE": "m"] | |
| 53 | + _ = await world.rzb("tui") | |
| 54 | + #expect(world.tuis.opened.first?.apiKey == nil) | |
| 55 | + _ = await world.rzb("tui", "--api-key-env", "MINE") | |
| 56 | + #expect(world.tuis.opened.last?.apiKey == "m") | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Test func invalidConfigIsReported() async throws { | |
| 60 | + let world = try World() | |
| 61 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | |
| 62 | + try "server: { port: 0 }\n".write(toFile: path, atomically: true, encoding: .utf8) | |
| 63 | + let result = await world.rzb("tui", "--config", path) | |
| 64 | + #expect(result.exitCode == 2) | |
| 65 | + #expect(result.stderr.contains("server.port")) | |
| 66 | + #expect(world.tuis.opened.isEmpty) | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Test func withoutATerminalItSaysSo() async throws { | |
| 70 | + var world = try World() | |
| 71 | + world.hasTerminal = false | |
| 72 | + let result = await world.rzb("tui") | |
| 73 | + #expect(result.exitCode == 1) | |
| 74 | + #expect(result.stderr.contains("rzb tui needs a terminal")) | |
| 75 | + #expect(result.stderr.contains("http://127.0.0.1:7920")) | |
| 76 | + #expect(world.tuis.opened.isEmpty) | |
| 77 | + } | |
| 78 | + | |
| 79 | + @Test(arguments: [ | |
| 80 | + (ServerSectionCase(host: nil, port: nil), "http://127.0.0.1:7920"), | |
| 81 | + (ServerSectionCase(host: "::", port: 8080), "http://127.0.0.1:8080"), | |
| 82 | + (ServerSectionCase(host: "::1", port: nil), "http://[::1]:7920"), | |
| 83 | + (ServerSectionCase(host: "studio.local", port: 1), "http://studio.local:1"), | |
| 84 | + ]) | |
| 85 | + func addressOfAServerSection(_ section: ServerSectionCase, _ expected: String) { | |
| 86 | + #expect(TUICommand.address(of: .init(host: section.host, port: section.port)) == expected) | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +/// `ServerSection` fields for parameterized tests (the type itself is not `CustomTestStringConvertible`). | |
| 91 | +struct ServerSectionCase: Sendable, CustomStringConvertible { | |
| 92 | + let host: String? | |
| 93 | + let port: Int? | |
| 94 | + var description: String { "\(host ?? "-"):\(port.map(String.init) ?? "-")" } | |
| 95 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | +import RazorbillTUI | ||
| 4 | +import Testing | ||
| 5 | + | ||
| 6 | +@testable import RazorbillCLI | ||
| 7 | + | ||
| 8 | +@Suite struct TUICommandTests { | ||
| 9 | + @Test func defaultsToTheLocalServer() async throws { | ||
| 10 | + let world = try World() | ||
| 11 | + let result = await world.rzb("tui") | ||
| 12 | + #expect(result.exitCode == 0) | ||
| 13 | + #expect( | ||
| 14 | + world.tuis.opened == [ | ||
| 15 | + TUILaunch(url: "http://127.0.0.1:7920", apiKey: nil, startCommand: "rzb serve") | ||
| 16 | + ]) | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + @Test func urlIsCleanedOfSlashAndV1() async throws { | ||
| 20 | + let world = try World() | ||
| 21 | + _ = await world.rzb("tui", "--url", "http://localhost:8000/v1/") | ||
| 22 | + #expect(world.tuis.opened.first?.url == "http://localhost:8000") | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + @Test(arguments: ["localhost:8000", "ftp://x", "http://"]) | ||
| 26 | + func badURLIsAUsageError(_ url: String) async throws { | ||
| 27 | + let world = try World() | ||
| 28 | + let result = await world.rzb("tui", "--url", url) | ||
| 29 | + #expect(result.exitCode == 64) | ||
| 30 | + #expect(world.tuis.opened.isEmpty) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + @Test func configGivesTheAddressAndTheKeyVariable() async throws { | ||
| 34 | + var world = try World() | ||
| 35 | + world.variables = ["TEAM_KEY": "k"] | ||
| 36 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | ||
| 37 | + try "server: { host: 0.0.0.0, port: 9100, api_key_env: TEAM_KEY }\n".write( | ||
| 38 | + toFile: path, atomically: true, encoding: .utf8) | ||
| 39 | + _ = await world.rzb("tui", "--config", path) | ||
| 40 | + #expect( | ||
| 41 | + world.tuis.opened.first | ||
| 42 | + == TUILaunch( | ||
| 43 | + url: "http://127.0.0.1:9100", apiKey: "k", | ||
| 44 | + startCommand: "rzb serve --config \(path)")) | ||
| 45 | + | ||
| 46 | + _ = await world.rzb("tui", "--config", path, "--url", "http://[::1]:7000") | ||
| 47 | + #expect(world.tuis.opened.last?.url == "http://[::1]:7000") | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + @Test func keyVariableOptionWinsAndAnEmptyKeyIsNone() async throws { | ||
| 51 | + var world = try World() | ||
| 52 | + world.variables = ["RZB_API_KEY": "", "MINE": "m"] | ||
| 53 | + _ = await world.rzb("tui") | ||
| 54 | + #expect(world.tuis.opened.first?.apiKey == nil) | ||
| 55 | + _ = await world.rzb("tui", "--api-key-env", "MINE") | ||
| 56 | + #expect(world.tuis.opened.last?.apiKey == "m") | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + @Test func invalidConfigIsReported() async throws { | ||
| 60 | + let world = try World() | ||
| 61 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | ||
| 62 | + try "server: { port: 0 }\n".write(toFile: path, atomically: true, encoding: .utf8) | ||
| 63 | + let result = await world.rzb("tui", "--config", path) | ||
| 64 | + #expect(result.exitCode == 2) | ||
| 65 | + #expect(result.stderr.contains("server.port")) | ||
| 66 | + #expect(world.tuis.opened.isEmpty) | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + @Test func withoutATerminalItSaysSo() async throws { | ||
| 70 | + var world = try World() | ||
| 71 | + world.hasTerminal = false | ||
| 72 | + let result = await world.rzb("tui") | ||
| 73 | + #expect(result.exitCode == 1) | ||
| 74 | + #expect(result.stderr.contains("rzb tui needs a terminal")) | ||
| 75 | + #expect(result.stderr.contains("http://127.0.0.1:7920")) | ||
| 76 | + #expect(world.tuis.opened.isEmpty) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + @Test(arguments: [ | ||
| 80 | + (ServerSectionCase(host: nil, port: nil), "http://127.0.0.1:7920"), | ||
| 81 | + (ServerSectionCase(host: "::", port: 8080), "http://127.0.0.1:8080"), | ||
| 82 | + (ServerSectionCase(host: "::1", port: nil), "http://[::1]:7920"), | ||
| 83 | + (ServerSectionCase(host: "studio.local", port: 1), "http://studio.local:1"), | ||
| 84 | + ]) | ||
| 85 | + func addressOfAServerSection(_ section: ServerSectionCase, _ expected: String) { | ||
| 86 | + #expect(TUICommand.address(of: .init(host: section.host, port: section.port)) == expected) | ||
| 87 | + } | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// `ServerSection` fields for parameterized tests (the type itself is not `CustomTestStringConvertible`). | ||
| 91 | +struct ServerSectionCase: Sendable, CustomStringConvertible { | ||
| 92 | + let host: String? | ||
| 93 | + let port: Int? | ||
| 94 | + var description: String { "\(host ?? "-"):\(port.map(String.init) ?? "-")" } | ||
| 95 | +} | ||