Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Shell/RootView.swift3// Description: The root of every Local Chat scene. Wide layouts (Mac, iPad) use a sidebar + detail split; compact layouts (iPhone) use tabs. Same screens everywhere.4import SwiftUI5import LocalChatCore6import LocalChatSecurity78public struct RootView: View {9 @Environment(AppModel.self) private var app10 @State private var router = AppRouter()11 @Environment(\.horizontalSizeClass) private var sizeClass12 @Environment(\.scenePhase) private var scenePhase1314 public init() {}1516 public var body: some View {17 ZStack {18 if !app.isReady {19 LaunchView()20 } else if sizeClass == .compact {21 CompactRoot(router: router)22 } else {23 WideRoot(router: router)24 }25 if router.showPalette { CommandPalette(router: router).transition(.opacity.combined(with: .scale(scale: 0.98))).zIndex(5) }26 if app.lock.state != .unlocked { LockView().transition(.opacity).zIndex(10) }27 }28 .environment(router)29 .tint(DS.C.accent)30 .preferredColorScheme(app.colorScheme)31 .animation(DS.M.snappy, value: router.showPalette)32 .animation(DS.M.fade, value: app.lock.state)33 .task {34 await app.bootstrap()35 await app.server.startIfConfigured()36 await app.sync.syncIfEnabled()37 if router.conversationID == nil, let first = app.conversations.first(where: { !$0.isArchived }) { router.conversationID = first.id }38 #if DEBUG39 runLaunchAutomation()40 #endif41 }42 .onChange(of: scenePhase) { _, phase in43 switch phase {44 case .background: app.lock.didEnterBackground()45 case .active:46 app.lock.willEnterForeground(); app.refreshDevice()47 Task { await app.sync.syncIfEnabled() }48 default: break49 }50 }51 .onOpenURL { url in handle(url) }52 }5354 /// Files opened from the Finder / Files / Share sheet: conversation archives are imported, anything else becomes an attachment of a new chat.55 private func handle(_ url: URL) {56 let scoped = url.startAccessingSecurityScopedResource()57 defer { if scoped { url.stopAccessingSecurityScopedResource() } }58 guard url.isFileURL, let data = try? Data(contentsOf: url) else { return }59 if url.pathExtension.lowercased() == "json", let imported = try? app.store.importJSON(data) { router.open(conversation: imported.id); return }60 let conversation = app.newConversation()61 app.controller(for: conversation.id)?.attach(data: data, fileName: url.lastPathComponent)62 router.open(conversation: conversation.id)63 }64}6566#if DEBUG67extension RootView {68 /// Debug builds only: `-LCAutoSend "<prompt>"` starts a chat and sends the prompt, `-LCSection <name>` opens a section, `-LCInspector` shows the inspector (visual checks, screenshots).69 fileprivate func runLaunchAutomation() {70 let arguments = ProcessInfo.processInfo.arguments71 func value(_ flag: String) -> String? { arguments.firstIndex(of: flag).flatMap { arguments.indices.contains($0 + 1) ? arguments[$0 + 1] : nil } }72 if let prompt = value("-LCAutoSend") {73 router.newChat(in: app)74 if let id = router.conversationID, let controller = app.controller(for: id) { controller.draft = prompt; controller.send() }75 }76 if arguments.contains("-LCInspector") { router.showInspector = true }77 if let name = value("-LCSection"), let section = AppSection(rawValue: name) { router.open(section) }78 }79}80#endif8182struct LaunchView: View {83 @State private var pulse = false84 var body: some View {85 VStack(spacing: 16) {86 Image(systemName: "sparkles").font(.system(size: 44, weight: .medium)).foregroundStyle(DS.G.aurora).scaleEffect(pulse ? 1.06 : 0.94)87 Text("Local Chat").font(DS.F.largeTitle).foregroundStyle(DS.C.text)88 ThinkingDots()89 }90 .frame(maxWidth: .infinity, maxHeight: .infinity).screenBackground()91 .onAppear { withAnimation(.easeInOut(duration: 1.1).repeatForever()) { pulse = true } }92 }93}9495struct LockView: View {96 @Environment(AppModel.self) private var app97 var body: some View {98 VStack(spacing: 18) {99 Image(systemName: "lock.fill").font(.system(size: 40)).foregroundStyle(DS.G.accent)100 Text("Local Chat is locked").font(DS.F.title).foregroundStyle(DS.C.text)101 Button("Unlock") { Task { _ = await app.lock.unlock() } }.buttonStyle(.lcPrimary).keyboardShortcut(.defaultAction).accessibilityIdentifier("unlock")102 }103 .frame(maxWidth: .infinity, maxHeight: .infinity).background(.ultraThickMaterial).screenBackground()104 .task { _ = await app.lock.unlock() }105 }106}107108// MARK: Section content (shared)109110struct SectionContent: View {111 @Environment(AppModel.self) private var app112 @Bindable var router: AppRouter113 let section: AppSection114 var body: some View {115 switch section {116 case .chat:117 if let id = router.conversationID {118 ChatScreen(conversationID: id, showInspector: $router.showInspector, onOpenModels: { router.open(.models) }, onOpenConversation: { router.open(conversation: $0) })119 } else {120 EmptyStateView(symbol: "sparkles", title: "Local Chat", message: "Private AI on your own hardware. Start a conversation to begin.") {121 Button("New chat") { router.newChat(in: app) }.buttonStyle(.lcPrimary).accessibilityIdentifier("empty-new-chat")122 }123 .screenBackground()124 }125 case .models: ModelLibraryScreen()126 case .arena: ArenaScreen(onOpenModels: { router.open(.models) })127 case .observatory: ObservatoryScreen(onOpenModels: { router.open(.models) })128 case .knowledge: KnowledgeScreen()129 case .agents: AgentStudioScreen(onStartChat: { router.newChat(in: app, agent: $0) })130 case .settings: SettingsScreen()131 }132 }133}134135// MARK: Wide layout (Mac, iPad)136137struct WideRoot: View {138 @Environment(AppModel.self) private var app139 @Bindable var router: AppRouter140 @State private var columns: NavigationSplitViewVisibility = .all141142 var body: some View {143 NavigationSplitView(columnVisibility: $columns) {144 VStack(spacing: 0) {145 SectionSwitcher(router: router)146 Divider().overlay(DS.C.border)147 ConversationSidebar(selection: Binding(get: { router.conversationID }, set: { id in if let id { router.open(conversation: id) } else { router.conversationID = nil } }))148 EngineStatusBar(router: router)149 }150 .background(DS.C.surface.opacity(0.4))151 .navigationSplitViewColumnWidth(min: 250, ideal: 290, max: 380)152 } detail: {153 // A plain side panel instead of `.inspector`: the system inspector enters an AppKit constraint loop when the detail154 // re-lays out many times per second (token streaming) while it is open.155 HStack(spacing: 0) {156 SectionContent(router: router, section: router.section)157 .frame(maxWidth: .infinity, maxHeight: .infinity)158 if router.showInspector, router.section == .chat, let id = router.conversationID, let controller = app.controller(for: id) {159 Divider().overlay(DS.C.border)160 ChatInspector(controller: controller).frame(width: 330).transition(.move(edge: .trailing))161 }162 }163 .navigationTitle(title)164 .toolbar {165 ToolbarItem(placement: .primaryAction) {166 Button { router.showPalette = true } label: { Label("Command palette", systemImage: "command") }167 .keyboardShortcut("k", modifiers: .command).help("Command palette (⌘K)")168 }169 }170 }171 .navigationSplitViewStyle(.balanced)172 }173174 private var title: String {175 if router.section == .chat, let id = router.conversationID { return app.conversations.first { $0.id == id }?.title ?? "Chat" }176 return router.section.title177 }178}179180struct SectionSwitcher: View {181 @Bindable var router: AppRouter182 var body: some View {183 VStack(spacing: 2) {184 ForEach(AppSection.allCases) { section in185 Button { withAnimation(DS.M.snappy) { router.open(section) } } label: {186 HStack(spacing: 9) {187 Image(systemName: section.symbol).font(.system(size: 13, weight: .medium)).frame(width: 20)188 .foregroundStyle(router.section == section ? AnyShapeStyle(DS.G.accent) : AnyShapeStyle(DS.C.text2))189 Text(section.title).font(.system(size: 13, weight: router.section == section ? .semibold : .regular)).foregroundStyle(DS.C.text)190 Spacer()191 }192 .padding(.horizontal, 10).padding(.vertical, 6)193 .background(router.section == section ? DS.C.accent.opacity(0.13) : .clear, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))194 .contentShape(Rectangle())195 }196 .buttonStyle(.plain)197 .accessibilityIdentifier("section-\(section.rawValue)")198 .accessibilityAddTraits(router.section == section ? .isSelected : [])199 }200 }201 .padding(8)202 }203}204205/// Bottom of the sidebar: what the engine is doing right now (measured).206struct EngineStatusBar: View {207 @Environment(AppModel.self) private var app208 @Bindable var router: AppRouter209 var body: some View {210 Button { router.open(.observatory) } label: {211 HStack(spacing: 8) {212 Circle().fill(statusColor).frame(width: 7, height: 7)213 VStack(alignment: .leading, spacing: 1) {214 Text(statusTitle).font(.system(size: 11.5, weight: .medium)).foregroundStyle(DS.C.text).lineLimit(1)215 Text(statusDetail).font(DS.F.micro).foregroundStyle(DS.C.muted).lineLimit(1)216 }217 Spacer(minLength: 0)218 if let rate = app.snapshot.active.first?.liveRate { Text("\(MetricFormat.rate(rate)) /s").font(DS.F.mono(10.5)).foregroundStyle(DS.C.accent) }219 }220 .padding(.horizontal, 12).padding(.vertical, 9).contentShape(Rectangle())221 }222 .buttonStyle(.plain).background(DS.C.surface2.opacity(0.6))223 .help("Open the Inference Observatory").accessibilityIdentifier("engine-status")224 }225 private var statusColor: Color { !app.snapshot.active.isEmpty ? DS.C.accent : !app.snapshot.loading.isEmpty ? DS.C.warn : app.snapshot.loaded.isEmpty ? DS.C.muted : DS.C.ok }226 private var statusTitle: String {227 if let active = app.snapshot.active.first { return "Generating · \(active.modelName)" }228 if let loading = app.snapshot.loading.first { return "Loading \(app.model(loading.key)?.name ?? "model")…" }229 if let loaded = app.snapshot.loaded.last { return loaded.descriptor.name }230 return "No model loaded"231 }232 private var statusDetail: String {233 if let loading = app.snapshot.loading.first?.value.fraction { return "\(Int(loading * 100)) %" }234 if let bytes = app.snapshot.processFootprintBytes, !app.snapshot.loaded.isEmpty { return "\(ByteFormat.memory(bytes)) in use · \(app.snapshot.loaded.count) loaded" }235 return "\(app.device.chip ?? app.device.machine) · \(Int(app.device.memoryGB.rounded())) GB"236 }237}238239// MARK: Compact layout (iPhone)240241struct CompactRoot: View {242 @Environment(AppModel.self) private var app243 @Bindable var router: AppRouter244 @State private var tab: Tab = .chats245 @State private var studioPath: [AppSection] = []246 enum Tab: Hashable { case chats, models, studio, settings }247248 var body: some View {249 TabView(selection: $tab) {250 NavigationStack(path: $router.chatPath) {251 ConversationSidebar(selection: Binding(get: { router.chatPath.last }, set: { id in if let id { router.chatPath = [id]; router.conversationID = id } }))252 .navigationTitle("Chats").inlineTitle().screenBackground()253 .navigationDestination(for: UUID.self) { id in254 ChatScreen(conversationID: id, showInspector: $router.showInspector, onOpenModels: { tab = .models }, onOpenConversation: { router.chatPath = [$0] })255 .navigationTitle(app.conversations.first { $0.id == id }?.title ?? "Chat").inlineTitle()256 .sheet(isPresented: $router.showInspector) {257 if let controller = app.controller(for: id) {258 NavigationStack { ChatInspector(controller: controller).navigationTitle("Conversation").inlineTitle().toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { router.showInspector = false } } } }259 .presentationDetents([.medium, .large])260 }261 }262 }263 }264 .tabItem { Label("Chats", systemImage: AppSection.chat.symbol) }.tag(Tab.chats)265266 NavigationStack { ModelLibraryScreen().navigationTitle("Models").inlineTitle() }267 .tabItem { Label("Models", systemImage: AppSection.models.symbol) }.tag(Tab.models)268269 NavigationStack(path: $studioPath) {270 List {271 ForEach([AppSection.arena, .observatory, .knowledge, .agents]) { section in272 NavigationLink(value: section) {273 Label { VStack(alignment: .leading, spacing: 2) { Text(section.title).font(DS.F.headline); Text(Self.blurb(section)).font(DS.F.caption).foregroundStyle(DS.C.muted) } }274 icon: { Image(systemName: section.symbol).foregroundStyle(DS.G.accent) }275 }276 .accessibilityIdentifier("studio-\(section.rawValue)")277 }278 }279 .navigationTitle("Studio").inlineTitle()280 .navigationDestination(for: AppSection.self) { section in281 SectionContent(router: router, section: section).navigationTitle(section.title).inlineTitle()282 }283 }284 .tabItem { Label("Studio", systemImage: "square.grid.2x2") }.tag(Tab.studio)285286 SettingsScreen()287 .tabItem { Label("Settings", systemImage: AppSection.settings.symbol) }.tag(Tab.settings)288 }289 .onChange(of: router.section) { _, section in290 switch section {291 case .chat: tab = .chats292 case .models: tab = .models293 case .settings: tab = .settings294 default: tab = .studio; studioPath = [section]295 }296 }297 }298299 static func blurb(_ section: AppSection) -> String {300 switch section {301 case .arena: "Compare models on the same prompt"302 case .observatory: "Live, measured inference telemetry"303 case .knowledge: "Private document search (RAG)"304 case .agents: "Tools, permissions and multi-step tasks"305 default: ""306 }307 }308}309310extension View {311 func inlineTitle() -> some View {312 #if os(iOS)313 navigationBarTitleDisplayMode(.inline)314 #else315 self316 #endif317 }318}319