SPB Git

Repository Public

ChatScreen.swift 18.1 KB 336 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Chat/ChatScreen.swift3// Description: The chat workspace for one conversation: header (model, context window), transcript with live streaming, composer, drag-and-drop.4import SwiftUI5import UniformTypeIdentifiers6import LocalChatAgents7import LocalChatCore89public struct ChatScreen: View {10    @Environment(AppModel.self) private var app11    let conversationID: UUID12    @Binding var showInspector: Bool13    var onOpenModels: (() -> Void)?14    var onOpenConversation: ((UUID) -> Void)?1516    public init(conversationID: UUID, showInspector: Binding<Bool>, onOpenModels: (() -> Void)? = nil, onOpenConversation: ((UUID) -> Void)? = nil) {17        self.conversationID = conversationID; _showInspector = showInspector; self.onOpenModels = onOpenModels; self.onOpenConversation = onOpenConversation18    }1920    public var body: some View {21        if let controller = app.controller(for: conversationID) {22            ChatWorkspace(controller: controller, showInspector: $showInspector, onOpenModels: onOpenModels, onOpenConversation: onOpenConversation)23                .id(conversationID)24        } else {25            EmptyStateView(symbol: "bubble.left.and.exclamationmark.bubble.right", title: "Conversation not found", message: "It may have been deleted on another device.")26        }27    }28}2930struct ChatWorkspace: View {31    @Environment(AppModel.self) private var app32    @Bindable var controller: ChatController33    @Binding var showInspector: Bool34    var onOpenModels: (() -> Void)?35    var onOpenConversation: ((UUID) -> Void)?36    @State private var showModelPicker = false37    @State private var dropTargeted = false38    @State private var editing: ChatMessage?39    @State private var speech = SpeechController()4041    var body: some View {42        VStack(spacing: 0) {43            ChatHeader(controller: controller, showModelPicker: $showModelPicker, showInspector: $showInspector)44            Divider().overlay(DS.C.border)45            ZStack(alignment: .bottom) {46                if controller.messages.isEmpty && !controller.isGenerating {47                    ChatEmptyState(controller: controller, onOpenModels: onOpenModels)48                } else {49                    Transcript(controller: controller, speech: speech, editing: $editing, onOpenConversation: onOpenConversation)50                }51            }52            .frame(maxWidth: .infinity, maxHeight: .infinity)53            if let error = controller.errorText {54                InlineNotice(.error, error).padding(.horizontal, DS.S.lg).padding(.top, 6)55                    .frame(maxWidth: DS.S.column).onTapGesture { controller.errorText = nil }56                    .transition(.move(edge: .bottom).combined(with: .opacity))57            }58            Composer(controller: controller, speech: speech)59        }60        .screenBackground()61        .animation(DS.M.smooth, value: controller.errorText)62        .overlay {63            if dropTargeted {64                RoundedRectangle(cornerRadius: DS.R.panel, style: .continuous).strokeBorder(DS.G.aurora, style: StrokeStyle(lineWidth: 2, dash: [8, 6]))65                    .background(DS.C.accent.opacity(0.06), in: RoundedRectangle(cornerRadius: DS.R.panel, style: .continuous))66                    .overlay(Label("Drop to attach", systemImage: "paperclip").font(DS.F.headline).foregroundStyle(DS.C.accent))67                    .padding(10).allowsHitTesting(false)68            }69        }70        .onDrop(of: [.fileURL, .image, .plainText], isTargeted: $dropTargeted) { providers in handleDrop(providers) }71        .sheet(item: $editing) { message in72            EditMessageSheet(text: message.content) { newText in controller.edit(message.id, newText: newText) }73        }74        .sheet(item: Binding(get: { controller.pendingApproval }, set: { if $0 == nil, controller.pendingApproval != nil { controller.resolveApproval(.deny(reason: nil)) } })) { request in75            ApprovalSheet(request: request) { controller.resolveApproval($0) }76        }77        .task(id: controller.conversation.modelID) { await controller.refreshContext() }78        .modelPickerPresentation(isPresented: $showModelPicker) {79            ModelPickerView(selectedID: controller.conversation.autoRoute ? nil : controller.conversation.modelID) { choice in80                showModelPicker = false81                if let choice { controller.setModel(choice.id) } else { controller.update { $0.autoRoute = true } }82            }83        }84    }8586    private func handleDrop(_ providers: [NSItemProvider]) -> Bool {87        var handled = false88        for provider in providers {89            if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {90                handled = true91                _ = provider.loadObject(ofClass: URL.self) { url, _ in92                    guard let url, let data = try? Data(contentsOf: url) else { return }93                    let name = url.lastPathComponent94                    Task { @MainActor in controller.attach(data: data, fileName: name) }95                }96            } else if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {97                handled = true98                provider.loadDataRepresentation(forTypeIdentifier: UTType.png.identifier) { data, _ in99                    guard let data else { return }100                    Task { @MainActor in controller.attach(data: data, fileName: "Image.png") }101                }102            } else if provider.canLoadObject(ofClass: String.self) {103                handled = true104                _ = provider.loadObject(ofClass: String.self) { text, _ in105                    guard let text else { return }106                    Task { @MainActor in controller.draft += (controller.draft.isEmpty ? "" : "\n") + text }107                }108            }109        }110        return handled111    }112}113114extension View {115    /// Popover on the Mac and iPad, sheet with detents on iPhone.116    func modelPickerPresentation<Picker: View>(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> Picker) -> some View {117        #if os(macOS)118        self.sheet(isPresented: isPresented) { content().frame(minWidth: 460, idealWidth: 520, minHeight: 420, idealHeight: 560) }119        #else120        self.sheet(isPresented: isPresented) { content().presentationDetents([.medium, .large]).presentationDragIndicator(.visible) }121        #endif122    }123}124125// MARK: Header126127struct ChatHeader: View {128    @Environment(AppModel.self) private var app129    @Bindable var controller: ChatController130    @Binding var showModelPicker: Bool131    @Binding var showInspector: Bool132    @Environment(\.horizontalSizeClass) private var sizeClass133134    var body: some View {135        HStack(spacing: 10) {136            Button { showModelPicker = true } label: {137                HStack(spacing: 7) {138                    Image(systemName: controller.conversation.autoRoute ? "wand.and.stars" : "cpu").font(.system(size: 12, weight: .semibold)).foregroundStyle(DS.G.accent)139                    VStack(alignment: .leading, spacing: 0) {140                        Text(modelTitle).font(.system(size: 13, weight: .semibold)).foregroundStyle(DS.C.text).lineLimit(1)141                        if let subtitle = modelSubtitle { Text(subtitle).font(DS.F.micro).foregroundStyle(DS.C.muted).lineLimit(1) }142                    }143                    Image(systemName: "chevron.up.chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(DS.C.muted)144                }145                .padding(.horizontal, 10).padding(.vertical, 6)146                .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control + 2, style: .continuous))147                .overlay(RoundedRectangle(cornerRadius: DS.R.control + 2, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))148            }149            .buttonStyle(.plain).accessibilityIdentifier("model-picker-button").accessibilityLabel("Model: \(modelTitle)")150            #if os(macOS)151            .keyboardShortcut("m", modifiers: [.command, .shift])152            #endif153154            if let model = controller.model, model.backend == .remote {155                Pill("Remote · \(app.nodeName(for: model) ?? "node")", symbol: "network", tone: .warn)156                    .help("Your messages are sent to this node for this conversation.")157            }158            Spacer(minLength: 4)159            if let context = controller.context, sizeClass != .compact {160                ContextWindowBar(context: context).frame(width: 190)161            }162            Menu {163                ForEach(InferencePreset.allCases) { preset in164                    Button { controller.setPreset(preset) } label: { Label(preset.title, systemImage: preset.symbol) }165                }166            } label: {167                Label(controller.conversation.preset?.title ?? "Custom", systemImage: controller.conversation.preset?.symbol ?? "slider.horizontal.3")168                    .font(.system(size: 12, weight: .medium)).labelStyle(.titleAndIcon)169            }170            .menuStyle(.borderlessButton).fixedSize().help("Inference preset")171            IconButton("sidebar.trailing", label: showInspector ? "Hide inspector" : "Show inspector", tint: showInspector ? DS.C.accent : DS.C.text2) {172                withAnimation(DS.M.snappy) { showInspector.toggle() }173            }174        }175        .padding(.horizontal, DS.S.lg).padding(.vertical, 8)176        .background(DS.C.surface.opacity(0.6))177    }178179    private var modelTitle: String {180        if controller.conversation.autoRoute { return "Auto" }181        return controller.model?.name ?? "Choose a model"182    }183    private var modelSubtitle: String? {184        if controller.conversation.autoRoute { return controller.routing?.reason ?? "The router picks a model per message" }185        guard let model = controller.model else { return nil }186        var parts = [model.backend.displayName]187        if let q = model.quantization { parts.append(q) }188        if app.snapshot.isLoaded(model.id) { parts.append("loaded") }189        return parts.joined(separator: " · ")190    }191}192193/// Segmented bar showing what fills the context window. Counts are exact when the tokenizer is loaded, estimated otherwise.194struct ContextWindowBar: View {195    let context: AssembledContext196    var body: some View {197        VStack(alignment: .trailing, spacing: 3) {198            GeometryReader { geo in199                HStack(spacing: 1) {200                    ForEach(context.segments.filter { $0.tokens > 0 }) { segment in201                        Rectangle().fill(color(segment.kind))202                            .frame(width: max(1, geo.size.width * CGFloat(segment.tokens) / CGFloat(max(1, context.contextLength))))203                            .help("\(label(segment.kind)): \(segment.tokens.formatted()) tokens")204                    }205                }206                .clipShape(Capsule())207            }208            .frame(height: 5).background(DS.C.surface3, in: Capsule())209            Text("\(context.tokensAreExact ? "" : "≈ ")\(context.usedTokens.formatted()) / \(context.contextLength.formatted()) tokens\(context.needsCompaction ? " · older turns outside the window" : "")")210                .font(DS.F.micro).foregroundStyle(context.needsCompaction ? DS.C.warn : DS.C.muted).lineLimit(1)211        }212        .accessibilityElement(children: .ignore)213        .accessibilityLabel("Context window: \(context.usedTokens) of \(context.contextLength) tokens used")214    }215    func color(_ kind: ContextSegment.Kind) -> Color {216        switch kind {217        case .system: DS.C.accent2; case .summary: DS.C.warn; case .knowledge: DS.C.ok; case .history: DS.C.accent218        case .attachments: DS.C.accent3; case .reservedOutput: DS.C.muted.opacity(0.45); case .free: .clear219        }220    }221    func label(_ kind: ContextSegment.Kind) -> String {222        switch kind {223        case .system: "System prompt"; case .summary: "Summary of older turns"; case .knowledge: "Knowledge sources"; case .history: "Conversation"224        case .attachments: "Attachments"; case .reservedOutput: "Reserved for the answer"; case .free: "Free"225        }226    }227}228229// MARK: Empty state230231struct ChatEmptyState: View {232    @Environment(AppModel.self) private var app233    @Bindable var controller: ChatController234    var onOpenModels: (() -> Void)?235    private let suggestions = [("lightbulb", "Explain a concept", "Explain how a transformer's attention mechanism works, with a small numeric example."),236                               ("chevron.left.forwardslash.chevron.right", "Write code", "Write a Swift function that merges overlapping date intervals, with tests."),237                               ("text.redaction", "Summarize a text", "Summarize the following text in five bullet points:\n\n"),238                               ("globe", "Translate", "Translate to French, keeping the tone:\n\n")]239    var body: some View {240        if app.chatModels.isEmpty {241            EmptyStateView(symbol: "shippingbox", title: "No model yet",242                           message: "Local Chat runs models on this device. Download one from the Model Library, or connect a Mac you trust as a remote node.") {243                if let onOpenModels { Button("Open Model Library", action: onOpenModels).buttonStyle(.lcPrimary).accessibilityIdentifier("open-models") }244            }245        } else {246            ScrollView {247                VStack(spacing: 22) {248                    VStack(spacing: 10) {249                        Image(systemName: "sparkles").font(.system(size: 34, weight: .medium)).foregroundStyle(DS.G.aurora)250                        Text("What can I help with?").font(DS.F.largeTitle).foregroundStyle(DS.C.text)251                        HStack(spacing: 6) {252                            Image(systemName: controller.model?.backend == .remote ? "network" : "lock.shield.fill").font(.system(size: 11))253                            Text(controller.model?.backend == .remote ? "This conversation uses a remote node." : "Runs on this device. Nothing leaves it.")254                        }255                        .font(DS.F.caption).foregroundStyle(controller.model?.backend == .remote ? DS.C.warn : DS.C.ok)256                    }257                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 230), spacing: 10)], spacing: 10) {258                        ForEach(suggestions, id: \.1) { symbol, title, prompt in259                            Button { controller.draft = prompt } label: {260                                HStack(spacing: 10) {261                                    Image(systemName: symbol).foregroundStyle(DS.G.accent).frame(width: 22)262                                    Text(title).font(DS.F.callout).foregroundStyle(DS.C.text)263                                    Spacer(minLength: 0)264                                }265                                .card(padding: 12)266                            }267                            .buttonStyle(.plain)268                        }269                    }270                    .frame(maxWidth: 520)271                }272                .padding(DS.S.xl).frame(maxWidth: .infinity).padding(.top, 40)273            }274        }275    }276}277278// MARK: Sheets279280struct EditMessageSheet: View {281    @State var text: String282    let onSubmit: (String) -> Void283    @Environment(\.dismiss) private var dismiss284    var body: some View {285        VStack(alignment: .leading, spacing: 12) {286            SectionHeader("Edit message", subtitle: "The original message and its answers are kept as another branch.", symbol: "pencil")287            TextEditor(text: $text).font(DS.F.body).scrollContentBackground(.hidden).padding(8)288                .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous)).frame(minHeight: 140)289            HStack {290                Spacer()291                Button("Cancel") { dismiss() }.buttonStyle(.lcSecondaryCompact).keyboardShortcut(.cancelAction)292                Button("Send edited message") { onSubmit(text); dismiss() }.buttonStyle(.lcPrimaryCompact)293                    .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).keyboardShortcut(.defaultAction)294            }295        }296        .padding(DS.S.lg).frame(minWidth: 320, idealWidth: 520).screenBackground()297        #if os(iOS)298        .presentationDetents([.medium, .large])299        #endif300    }301}302303/// Human approval checkpoint for an agent's tool call.304struct ApprovalSheet: View {305    let request: ApprovalRequest306    let decide: (ApprovalDecision) -> Void307    @State private var reason = ""308    var body: some View {309        VStack(alignment: .leading, spacing: 14) {310            HStack(spacing: 10) {311                Image(systemName: request.risk >= .execute ? "terminal.fill" : request.risk >= .write ? "square.and.pencil" : "eye")312                    .font(.system(size: 20)).foregroundStyle(request.risk >= .write ? DS.C.warn : DS.C.accent)313                VStack(alignment: .leading, spacing: 2) {314                    Text("The agent wants to use \(request.toolName)").font(DS.F.headline)315                    Text(request.summary).font(DS.F.caption).foregroundStyle(DS.C.text2)316                }317                Spacer()318                Pill(request.risk.label, tone: request.risk >= .write ? .warn : .neutral)319            }320            ScrollView { Text(request.arguments.serialized(pretty: true)).font(DS.F.mono(12)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }321                .frame(maxHeight: 200).padding(10).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))322            TextField("Reason for denying (optional, sent to the model)", text: $reason).textFieldStyle(.roundedBorder)323            HStack {324                Button("Deny") { decide(.deny(reason: reason.isEmpty ? nil : reason)) }.buttonStyle(.lcDestructive).keyboardShortcut(.cancelAction)325                Spacer()326                if request.canApproveForRun { Button("Allow for this run") { decide(.approveForRun) }.buttonStyle(.lcSecondaryCompact) }327                Button("Allow once") { decide(.approve) }.buttonStyle(.lcPrimaryCompact).keyboardShortcut(.defaultAction).accessibilityIdentifier("approve-once")328            }329        }330        .padding(DS.S.lg).frame(minWidth: 320, idealWidth: 520).screenBackground().interactiveDismissDisabled()331        #if os(iOS)332        .presentationDetents([.medium, .large])333        #endif334    }335}336
Files main
Menu

Theme