SPB Git

Repository Public

NodesPane.swift 11.8 KB 210 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/NodesPane.swift3// Description: Remote nodes: trusted Macs and OpenAI-compatible servers, with health, latency, connection diagnostics and Keychain-stored keys.4import SwiftUI5import LocalChatCore6import LocalChatNetworking7import RemoteInference89struct NodesPane: View {10    @Environment(AppModel.self) private var app11    @State private var nodes: [RemoteNode] = []12    @State private var editing: NodeDraft?13    @State private var diagnostics: [UUID: [DiagnosticCheck]] = [:]14    @State private var testing: Set<UUID> = []15    @State private var refreshing = false16    @State private var error: String?1718    var body: some View {19        InlineNotice(.privacy, "A node only receives a prompt when you choose one of its models. Local Chat works fully without any node.")20        HStack(spacing: 8) {21            Button { editing = NodeDraft() } label: { Label("Add node", systemImage: "plus") }.buttonStyle(.lcPrimaryCompact)22            Button { editing = .macLustr } label: { Label("MacLustr", systemImage: "square.stack.3d.up") }.buttonStyle(.lcSecondaryCompact)23                .help("Pre-fills the MacLustr endpoint. You still paste your key.")24            Spacer(minLength: 0)25            if refreshing { ProgressView().controlSize(.small) }26            Button { Task { await refresh() } } label: { Label("Refresh", systemImage: "arrow.clockwise") }.buttonStyle(.lcSecondaryCompact).disabled(refreshing)27        }28        if let error { InlineNotice(.error, error) }29        if nodes.isEmpty {30            EmptyStateView(symbol: "network", title: "No remote node", message: "Add a Mac running Local Chat (turn on its Local API server) or any OpenAI-compatible endpoint to run larger models from this device.")31                .frame(minHeight: 260).card()32        }33        ForEach(nodes) { node in nodeCard(node) }34            .task { await load() }35            .sheet(item: $editing) { draft in36                NodeEditor(draft: draft) { saved in Task { await save(saved) } }37            }38    }3940    private func status(_ node: RemoteNode) -> RemoteNodeStatus? { app.nodeStatuses.first { $0.node.id == node.id } }4142    private func nodeCard(_ node: RemoteNode) -> some View {43        let s = status(node)44        return VStack(alignment: .leading, spacing: 10) {45            HStack(alignment: .top, spacing: 10) {46                VStack(alignment: .leading, spacing: 3) {47                    HStack(spacing: 6) {48                        Text(node.name).font(DS.F.headline).foregroundStyle(DS.C.text)49                        healthPill(node, s?.health)50                    }51                    Text(node.baseURL).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted).lineLimit(1).truncationMode(.middle).textSelection(.enabled)52                }53                Spacer(minLength: 8)54                Toggle("Enabled", isOn: Binding(get: { node.isEnabled }, set: { v in Task { await setEnabled(node, v) } })).labelsHidden()55                    .accessibilityLabel("Enable \(node.name)")56            }57            HStack(spacing: 6) {58                Pill(node.kind == .localChat ? "Local Chat" : "OpenAI-compatible", symbol: node.kind == .localChat ? "desktopcomputer" : "curlybraces")59                if let latency = s?.health.latency { Pill(MetricFormat.seconds(latency), symbol: "timer") }60                if let s, s.health.state == .online { Pill("\(s.models.count) model\(s.models.count == 1 ? "" : "s")", symbol: "shippingbox") }61                if node.allowInsecureHTTP { Pill("Insecure HTTP allowed", symbol: "exclamationmark.triangle.fill", tone: .warn) }62            }63            if let detail = s?.health.detail, s?.health.state != .online { Text(detail).font(DS.F.caption).foregroundStyle(DS.C.text2) }64            if let checks = diagnostics[node.id] {65                VStack(alignment: .leading, spacing: 5) {66                    ForEach(checks) { check in67                        HStack(alignment: .firstTextBaseline, spacing: 7) {68                            Image(systemName: check.outcome == .passed ? "checkmark.circle.fill" : check.outcome == .failed ? "xmark.circle.fill" : "minus.circle")69                                .foregroundStyle(check.outcome == .passed ? DS.C.ok : check.outcome == .failed ? DS.C.danger : DS.C.muted).font(.system(size: 12))70                            Text(check.name).font(DS.F.caption.weight(.semibold)).foregroundStyle(DS.C.text)71                            Text(check.detail).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)72                        }73                        .accessibilityElement(children: .combine)74                    }75                }76                .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))77            }78            HStack(spacing: 8) {79                Button { Task { await test(node) } } label: {80                    HStack(spacing: 5) { if testing.contains(node.id) { ProgressView().controlSize(.mini) }; Text("Test connection") }81                }.buttonStyle(.lcSecondaryCompact).disabled(testing.contains(node.id))82                Button("Edit") { editing = NodeDraft(node: node) }.buttonStyle(.lcSecondaryCompact)83                Spacer(minLength: 0)84                Button("Remove") { Task { await remove(node) } }.buttonStyle(.lcDestructive)85            }86        }87        .card()88    }8990    private func healthPill(_ node: RemoteNode, _ health: NodeHealth?) -> some View {91        guard node.isEnabled else { return Pill("Disabled", symbol: "pause.circle") }92        switch health?.state {93        case .online: return Pill("Online", symbol: "circle.fill", tone: .ok)94        case .unauthorized: return Pill("Key refused", symbol: "key.slash", tone: .warn)95        case .offline: return Pill("Offline", symbol: "circle.fill", tone: .danger)96        default: return Pill("Not checked", symbol: "circle.dotted")97        }98    }99100    private func load() async { nodes = await app.nodes.allNodes() }101    private func refresh() async { refreshing = true; await app.refreshNodes(); await load(); refreshing = false }102103    private func save(_ draft: NodeDraft) async {104        error = nil105        var node = draft.existing ?? RemoteNode(name: draft.name, baseURL: draft.baseURL)106        node.name = draft.name.trimmingCharacters(in: .whitespaces); node.baseURL = draft.normalizedURL107        node.kind = draft.kind; node.allowInsecureHTTP = draft.allowInsecureHTTP108        do {109            if draft.existing == nil { node = try await app.nodes.add(node) } else { try await app.nodes.update(node) }110            let key = draft.apiKey.trimmingCharacters(in: .whitespacesAndNewlines)111            if !key.isEmpty { try app.keychain.set(key, for: node.keychainAccount) }112            else if draft.clearKey { _ = try? app.keychain.delete(node.keychainAccount) }113        } catch { self.error = "The node could not be saved: \(error.localizedDescription)" }114        diagnostics[node.id] = nil115        await refresh()116    }117    private func setEnabled(_ node: RemoteNode, _ on: Bool) async {118        var n = node; n.isEnabled = on119        try? await app.nodes.update(n); await refresh()120    }121    private func remove(_ node: RemoteNode) async {122        try? await app.nodes.remove(id: node.id)123        _ = try? app.keychain.delete(node.keychainAccount)124        diagnostics[node.id] = nil125        await refresh()126    }127    private func test(_ node: RemoteNode) async {128        testing.insert(node.id)129        diagnostics[node.id] = await app.nodes.diagnostics(id: node.id)130        testing.remove(node.id)131        await app.refreshNodes()132    }133}134135struct NodeDraft: Identifiable {136    var id = UUID()137    var existing: RemoteNode?138    var name = ""139    var baseURL = ""140    var kind: RemoteNode.Kind = .localChat141    var allowInsecureHTTP = false142    var apiKey = ""143    var clearKey = false144145    init() {}146    init(node: RemoteNode) { existing = node; name = node.name; baseURL = node.baseURL; kind = node.kind; allowInsecureHTTP = node.allowInsecureHTTP }147    static var macLustr: NodeDraft { var d = NodeDraft(); d.name = "MacLustr"; d.baseURL = "https://llm.spboucher.ai/v1"; d.kind = .openAICompatible; return d }148149    var normalizedURL: String {150        var s = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)151        while s.hasSuffix("/") { s.removeLast() }152        return s153    }154    /// nil when the address is acceptable, otherwise the reason.155    var urlProblem: String? {156        if normalizedURL.isEmpty { return "Enter the base URL, for example http://studio.local:8765/v1" }157        do { _ = try URLPolicy.validate(normalizedURL, allowInsecureHTTP: allowInsecureHTTP); return nil }158        catch { return (error as? LocalizedError)?.errorDescription ?? "This address is not accepted." }159    }160    var nameProblem: String? { name.trimmingCharacters(in: .whitespaces).isEmpty ? "Give the node a name." : nil }161    var isValid: Bool { urlProblem == nil && nameProblem == nil }162}163164struct NodeEditor: View {165    @State var draft: NodeDraft166    let onSave: (NodeDraft) -> Void167    @Environment(\.dismiss) private var dismiss168    @State private var touched = false169170    var body: some View {171        ScrollView {172            VStack(alignment: .leading, spacing: DS.S.md) {173                Text(draft.existing == nil ? "Add a remote node" : "Edit node").font(DS.F.title).foregroundStyle(DS.C.text)174                field("Name") { TextField("Studio", text: $draft.name).textFieldStyle(.roundedBorder) }175                if touched, let p = draft.nameProblem { InlineNotice(.error, p) }176                field("Base URL") {177                    TextField("http://studio.local:8765/v1", text: $draft.baseURL).textFieldStyle(.roundedBorder).autocorrectionDisabled()178                    #if os(iOS)179                        .textInputAutocapitalization(.never).keyboardType(.URL)180                    #endif181                }182                if (touched || !draft.baseURL.isEmpty), let p = draft.urlProblem { InlineNotice(.error, p) }183                field("Kind") {184                    Picker("Kind", selection: $draft.kind) { Text("Local Chat").tag(RemoteNode.Kind.localChat); Text("OpenAI-compatible").tag(RemoteNode.Kind.openAICompatible) }185                        .pickerStyle(.segmented).labelsHidden()186                }187                field("API key") {188                    SecureField(draft.existing == nil ? "Paste the key" : "Leave empty to keep the saved key", text: $draft.apiKey).textFieldStyle(.roundedBorder)189                }190                Text("The key is stored in the Keychain of this device. It is never shown again and never synchronized.").font(DS.F.caption).foregroundStyle(DS.C.muted)191                if draft.existing != nil { Toggle("Remove the saved key", isOn: $draft.clearKey).font(DS.F.callout) }192                Toggle("Allow plain HTTP to a public address", isOn: $draft.allowInsecureHTTP).font(DS.F.callout)193                if draft.allowInsecureHTTP { InlineNotice(.warning, "Without TLS, your prompts and the key can be read on the network. Plain HTTP to a Mac on your private network does not need this option.") }194                HStack {195                    Spacer()196                    Button("Cancel") { dismiss() }.buttonStyle(.lcSecondaryCompact).keyboardShortcut(.cancelAction)197                    Button("Save") { touched = true; if draft.isValid { onSave(draft); dismiss() } }.buttonStyle(.lcPrimaryCompact).keyboardShortcut(.defaultAction)198                }199            }200            .padding(DS.S.xl)201        }202        .frame(minWidth: 320, idealWidth: 460, minHeight: 420)203        .screenBackground()204    }205206    private func field<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {207        VStack(alignment: .leading, spacing: 4) { Text(title).font(DS.F.caption.weight(.semibold)).foregroundStyle(DS.C.text2); content() }208    }209}210
Files main
Menu

Theme