Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/ServerPane.swift3// Description: Local API server pane: lifecycle, network exposure, API keys (secret shown once), curl example, request diagnostics. Explanatory card on iOS.4import SwiftUI5import LocalAPIServer6import LocalChatCore78struct ServerPane: View {9 @Environment(AppModel.self) private var app10 @Environment(\.openURL) private var openURL11 @State private var portText = ""12 @State private var rateText = ""13 @State private var originsText = ""14 @State private var newKeyLabel = ""15 @State private var loaded = false1617 var body: some View {18 if ServerController.isAvailable { macBody } else { iosBody }19 }2021 // MARK: iOS2223 private var iosBody: some View {24 VStack(alignment: .leading, spacing: DS.S.lg) {25 EmptyStateView(symbol: "server.rack", title: "The server runs on your Mac",26 message: "An iPhone or iPad cannot keep a server running in the background. Local Chat on the Mac can serve its models to this device instead.")27 .frame(minHeight: 240).card()28 SettingsGroup("Pair this device with a Mac", symbol: "link") {29 step(1, "On the Mac, open Settings › Local API server, create an API key and turn on \"Reachable from the network\".")30 step(2, "Start the server. The Mac shows the address to use, such as http://192.168.1.20:8765/v1.")31 step(3, "Here, open Settings › Remote nodes, add a node with that address and paste the key.")32 step(4, "The Mac's models then appear in the model picker, labelled as remote.")33 }34 }35 }36 private func step(_ n: Int, _ text: String) -> some View {37 HStack(alignment: .firstTextBaseline, spacing: 10) {38 Text("\(n)").font(DS.F.rounded(12)).foregroundStyle(.white).frame(width: 20, height: 20).background(DS.G.accent, in: Circle())39 Text(text).font(DS.F.callout).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)40 }41 }4243 // MARK: macOS4445 @ViewBuilder private var macBody: some View {46 let server = app.server47 VStack(alignment: .leading, spacing: 12) {48 HStack(spacing: 10) {49 Circle().fill(server.isRunning ? DS.C.ok : DS.C.muted).frame(width: 9, height: 9)50 VStack(alignment: .leading, spacing: 2) {51 Text(server.isRunning ? "Running" : "Stopped").font(DS.F.headline).foregroundStyle(DS.C.text)52 if let url = server.baseURL { Text(url).font(DS.F.mono(12)).foregroundStyle(DS.C.text2).textSelection(.enabled) }53 else { Text("OpenAI-compatible endpoints for your local models").font(DS.F.caption).foregroundStyle(DS.C.muted) }54 }55 Spacer(minLength: 8)56 if server.isBusy { ProgressView().controlSize(.small) }57 if server.isRunning {58 if let docs = server.docsURL { Button("API docs") { openURL(docs) }.buttonStyle(.lcSecondaryCompact) }59 Button("Stop") { Task { await server.stop() } }.buttonStyle(.lcSecondaryCompact)60 } else {61 Button("Start server") { Task { await commit(); await server.start() } }.buttonStyle(.lcPrimaryCompact).disabled(server.isBusy)62 }63 }64 if let error = server.lastError { InlineNotice(.error, error) }65 }66 .card()67 .onAppear { if !loaded { sync(from: server.configuration); loaded = true } }6869 SettingsGroup("Configuration", symbol: "slider.horizontal.3", footer: server.isRunning ? "Changes restart the server." : nil) {70 SettingRow("Port", detail: portProblem) {71 TextField("8765", text: $portText).textFieldStyle(.roundedBorder).frame(width: 90).multilineTextAlignment(.trailing).onSubmit { Task { await commit() } }72 }73 RowDivider()74 SettingRow("Start with Local Chat") { Toggle("", isOn: Binding(get: { server.startAtLaunch }, set: { server.setStartAtLaunch($0) })).labelsHidden() }75 RowDivider()76 SettingRow("Require an API key", detail: server.configuration.exposeOnLAN ? "Always required when the server is reachable from the network." : "Recommended even on this Mac: any local program can otherwise use the server.") {77 Toggle("", isOn: Binding(get: { server.configuration.authenticationRequired }, set: { v in update { $0.requireAuth = v } })).labelsHidden().disabled(server.configuration.exposeOnLAN)78 }79 RowDivider()80 SettingRow("Reachable from the network", detail: "Off: only programs on this Mac (127.0.0.1) can connect.") {81 Toggle("", isOn: Binding(get: { server.configuration.exposeOnLAN }, set: { v in update { $0.exposeOnLAN = v } })).labelsHidden()82 }83 if server.configuration.exposeOnLAN {84 InlineNotice(.warning, "Every device on your network can reach this Mac's models with a valid key. The server speaks plain HTTP: use it on a network you trust, never on the open internet.")85 let addresses = ServerController.lanAddresses(); let port = server.port ?? server.configuration.port86 if addresses.isEmpty { Text("No network address was found on this Mac.").font(DS.F.caption).foregroundStyle(DS.C.muted) }87 ForEach(addresses, id: \.self) { ip in copyLine("http://\(ip):\(port)/v1", caption: "Address for your iPhone or iPad") }88 }89 RowDivider()90 SettingRow("Rate limit", detail: "Requests per minute and per key. 0 = unlimited.") {91 TextField("120", text: $rateText).textFieldStyle(.roundedBorder).frame(width: 90).multilineTextAlignment(.trailing).onSubmit { Task { await commit() } }92 }93 RowDivider()94 SettingRow("Browser origins (CORS)", detail: "Comma-separated, e.g. http://localhost:3000. Empty = no browser access.") {95 TextField("none", text: $originsText).textFieldStyle(.roundedBorder).frame(maxWidth: 240).onSubmit { Task { await commit() } }96 }97 HStack { Spacer(); Button("Apply") { Task { await commit() } }.buttonStyle(.lcSecondaryCompact).disabled(portProblem != nil || !isDirty) }98 }99100 SettingsGroup("API keys", symbol: "key", footer: "Only a hash of each key is stored. A key is shown once, when it is created.") {101 if let secret = server.revealedSecret {102 VStack(alignment: .leading, spacing: 8) {103 InlineNotice(.warning, "Copy this key now. It will not be shown again.")104 copyLine(secret, caption: "New API key")105 Button("I saved it") { server.revealedSecret = nil }.buttonStyle(.lcPrimaryCompact)106 }107 .padding(10).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))108 }109 HStack(spacing: 8) {110 TextField("Label, e.g. iPhone", text: $newKeyLabel).textFieldStyle(.roundedBorder).onSubmit { createKey() }111 Button("Create key") { createKey() }.buttonStyle(.lcSecondaryCompact)112 }113 if server.keys.isEmpty { Text("No key yet.").font(DS.F.caption).foregroundStyle(DS.C.muted) }114 ForEach(server.keys) { key in115 HStack(spacing: 8) {116 VStack(alignment: .leading, spacing: 2) {117 HStack(spacing: 6) {118 Text(key.label).font(DS.F.body).foregroundStyle(DS.C.text)119 if !key.isActive { Pill("Revoked", tone: .danger) }120 }121 Text("\(key.hint)… · created \(key.createdAt.formatted(date: .abbreviated, time: .omitted))" + (key.lastUsedAt.map { " · last used \($0.formatted(.relative(presentation: .named)))" } ?? " · never used"))122 .font(DS.F.caption).foregroundStyle(DS.C.muted)123 }124 Spacer(minLength: 8)125 if key.isActive { Button("Revoke") { Task { await server.revokeKey(key.id) } }.buttonStyle(.lcSecondaryCompact) }126 Button("Delete") { Task { await server.deleteKey(key.id) } }.buttonStyle(.lcDestructive)127 }128 .padding(.vertical, 2)129 }130 }131132 SettingsGroup("Try it", symbol: "terminal") {133 Text(curlExample).font(DS.F.mono(11.5)).foregroundStyle(DS.C.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)134 .padding(10).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))135 HStack { Spacer(); Button { Pasteboard.copy(curlExample) } label: { Label("Copy", systemImage: "doc.on.doc") }.buttonStyle(.lcSecondaryCompact) }136 }137138 SettingsGroup("Request diagnostics", symbol: "list.bullet.rectangle", footer: "Prompts and answers are never recorded here.") {139 if server.log.isEmpty { Text(server.isRunning ? "No request yet." : "Start the server to see requests.").font(DS.F.caption).foregroundStyle(DS.C.muted) }140 else {141 HStack { Text("\(server.log.count) most recent").font(DS.F.caption).foregroundStyle(DS.C.muted); Spacer(); Button("Clear") { server.clearLog() }.buttonStyle(.lcSecondaryCompact) }142 ScrollView(.horizontal) {143 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {144 GridRow { ForEach(["Time", "Method", "Path", "Status", "Key", "Duration", "Tokens", "Tokens/s", "Client"], id: \.self) { Text($0.uppercased()).font(DS.F.micro).foregroundStyle(DS.C.muted) } }145 ForEach(server.log.prefix(80)) { e in146 GridRow {147 Text(e.time.formatted(date: .omitted, time: .standard))148 Text(e.method)149 Text(e.path).lineLimit(1)150 Text("\(e.status)").foregroundStyle(e.status < 400 ? DS.C.ok : DS.C.danger)151 Text(e.keyLabel ?? "—")152 Text(MetricFormat.seconds(e.duration))153 Text(e.promptTokens == nil && e.completionTokens == nil ? "—" : "\(e.promptTokens.map(String.init) ?? "—") → \(e.completionTokens.map(String.init) ?? "—")")154 Text(MetricFormat.rate(e.tokensPerSecond))155 Text(e.clientAddress ?? "—")156 }157 .font(DS.F.mono(11)).foregroundStyle(DS.C.text2)158 .help(e.error ?? "")159 }160 }161 .padding(.vertical, 2)162 }163 }164 }165 }166167 private func copyLine(_ text: String, caption: String) -> some View {168 HStack(spacing: 8) {169 VStack(alignment: .leading, spacing: 1) {170 Text(caption).font(DS.F.micro).foregroundStyle(DS.C.muted)171 Text(text).font(DS.F.mono(12)).foregroundStyle(DS.C.text).textSelection(.enabled).lineLimit(1).truncationMode(.middle)172 }173 Spacer(minLength: 6)174 IconButton("doc.on.doc", label: "Copy \(caption)") { Pasteboard.copy(text) }175 }176 }177178 private var curlExample: String {179 let port = app.server.port ?? app.server.configuration.port180 let auth = app.server.configuration.authenticationRequired ? " \\\n -H \"Authorization: Bearer $LOCALCHAT_API_KEY\"" : ""181 let model = app.chatModels.first { $0.backend != .remote }?.id ?? "MODEL_ID"182 return "curl http://127.0.0.1:\(port)/v1/chat/completions\(auth) \\\n -H \"Content-Type: application/json\" \\\n -d '{\"model\": \"\(model)\", \"stream\": true, \"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]}'"183 }184185 private var portProblem: String? {186 guard let p = Int(portText.trimmingCharacters(in: .whitespaces)), (1024...65535).contains(p) else { return "Enter a port between 1024 and 65535." }187 return nil188 }189 private var parsedOrigins: [String] { originsText.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } }190 private var isDirty: Bool {191 let c = app.server.configuration192 return UInt16(portText) != c.port || Int(rateText) != c.rateLimitPerMinute || parsedOrigins != c.allowedOrigins193 }194 private func sync(from c: ServerConfiguration) {195 portText = String(c.port); rateText = String(c.rateLimitPerMinute); originsText = c.allowedOrigins.joined(separator: ", ")196 }197 private func update(_ change: (inout ServerConfiguration) -> Void) {198 var c = pending(); change(&c)199 Task { await app.server.apply(c) }200 }201 private func pending() -> ServerConfiguration {202 var c = app.server.configuration203 if portProblem == nil, let p = UInt16(portText.trimmingCharacters(in: .whitespaces)) { c.port = p }204 if let r = Int(rateText.trimmingCharacters(in: .whitespaces)), r >= 0 { c.rateLimitPerMinute = r }205 c.allowedOrigins = parsedOrigins206 return c207 }208 private func commit() async { await app.server.apply(pending()); sync(from: app.server.configuration) }209 private func createKey() {210 let label = newKeyLabel; newKeyLabel = ""211 Task { await app.server.createKey(label: label) }212 }213}214