SPB Git

Repository Public MIT

ChatHome.swift 12.8 KB 260 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Chat/ChatHome.swift10// Module           : Chat11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraCore90import AstraDesign91import AstraPersistence9293/// The Chat tab: conversations (pinned first), search across titles and messages, and the way into a new chat.94struct ChatHome: View {95    @Environment(AppModel.self) private var app96    @State private var query = ""97    @State private var hits: [ConversationSearchHit] = []98    @State private var showArchived = false99    @State private var archived: [ConversationRecord] = []100    @State private var renaming: ConversationRecord?101    @State private var renameText = ""102    @State private var showNewChatPicker = false103    @State private var path: [String] = []104105    var body: some View {106        NavigationStack(path: $path) {107            Group {108                if !app.library.hasAnyUsableModel && app.conversations.isEmpty { noModelState }109                else if app.conversations.isEmpty && query.isEmpty { emptyState }110                else { list }111            }112            .background(Starfield(density: 0.5))113            .navigationTitle("Chat")114            .toolbar {115                ToolbarItem(placement: .topBarLeading) {116                    Menu {117                        Toggle(isOn: $showArchived) { Label("Show archived", systemImage: "archivebox") }118                    } label: { Image(systemName: "line.3.horizontal.decrease") }119                    .accessibilityLabel("Filter conversations")120                }121                ToolbarItem(placement: .topBarTrailing) {122                    Button { startNewChat() } label: { Image(systemName: "square.and.pencil") }123                        .accessibilityLabel("New chat").accessibilityIdentifier("new-chat")124                        .disabled(!app.library.hasAnyUsableModel)125                }126            }127            .navigationDestination(for: String.self) { id in128                if let chat = app.activeChat, chat.conversation.id == id { ChatScreen(chat: chat).id(id) }129                else { ProgressView().task { await openByID(id) } }130            }131            .searchable(text: $query, prompt: "Search conversations")132            .task(id: query) {133                let q = query.trimmingCharacters(in: .whitespaces)134                guard !q.isEmpty else { hits = []; return }135                try? await Task.sleep(nanoseconds: 180_000_000)136                guard !Task.isCancelled else { return }137                hits = (try? await app.store.searchConversations(q)) ?? []138            }139            .task(id: showArchived) { archived = showArchived ? ((try? await app.store.conversations(.archived)) ?? []) : [] }140            .sheet(isPresented: $showNewChatPicker) {141                ModelPickerSheet(selected: app.library.defaultModel(), title: "New chat with") { ref in142                    Task { if let chat = await app.newConversation(model: ref) { path = [chat.conversation.id] } }143                }144            }145            .alert("Rename conversation", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {146                TextField("Title", text: $renameText)147                Button("Save") { if let c = renaming { Task { try? await app.store.renameConversation(id: c.id, title: renameText); await app.reloadConversations() } } }148                Button("Cancel", role: .cancel) {}149            }150            .onChange(of: path) { _, new in if new.isEmpty { app.closeChat(); Task { await app.reloadConversations() } } }151            .task {152                #if DEBUG153                if app.options.autoSend != nil, app.activeChat == nil, path.isEmpty {154                    let ref = app.options.autoModel.flatMap { ModelRef(id: $0) }155                    if let chat = await app.newConversation(model: ref) { path = [chat.conversation.id] }156                }157                #endif158            }159        }160    }161162    private func startNewChat() {163        if app.library.selectable.count > 1 { showNewChatPicker = true }164        else { Task { if let chat = await app.newConversation() { path = [chat.conversation.id] } } }165    }166167    private func openByID(_ id: String) async {168        guard let record = try? await app.store.conversation(id: id) else { path = []; return }169        await app.open(record)170    }171172    private func open(_ c: ConversationRecord) { Task { await app.open(c); path = [c.id] } }173174    private var list: some View {175        List {176            if !query.trimmingCharacters(in: .whitespaces).isEmpty {177                Section(hits.isEmpty ? "No results" : "Results") {178                    ForEach(hits) { hit in179                        Button { open(hit.conversation) } label: {180                            VStack(alignment: .leading, spacing: 4) {181                                Text(hit.conversation.title.isEmpty ? "Untitled chat" : hit.conversation.title).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)182                                if !hit.snippet.isEmpty { Text(hit.snippet).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(2) }183                            }184                        }185                        .listRowBackground(AstraColor.surface)186                    }187                }188            } else {189                let pinned = app.conversations.filter(\.pinned), others = app.conversations.filter { !$0.pinned }190                if !pinned.isEmpty { Section("Pinned") { ForEach(pinned) { row($0) } } }191                if !others.isEmpty { Section(pinned.isEmpty ? "" : "Recent") { ForEach(others) { row($0) } } }192                if showArchived, !archived.isEmpty { Section("Archived") { ForEach(archived) { row($0) } } }193            }194        }195        .listStyle(.insetGrouped)196        .scrollContentBackground(.hidden)197        .refreshable { await app.reloadConversations() }198    }199200    private func row(_ c: ConversationRecord) -> some View {201        Button { open(c) } label: {202            HStack(spacing: 12) {203                ProviderLogo(ref: c.model, vendor: app.library.info(for: c.model)?.vendor, size: 34)204                VStack(alignment: .leading, spacing: 3) {205                    Text(c.title.isEmpty ? "New chat" : c.title).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)206                    HStack(spacing: 6) {207                        Text(app.library.displayName(for: c.model)).lineLimit(1)208                        Text("·")209                        Text(c.updatedAt, format: .relative(presentation: .named))210                    }211                    .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)212                }213                Spacer(minLength: 0)214                if c.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(AstraColor.violet).accessibilityLabel("Pinned") }215            }216            .padding(.vertical, 4).contentShape(Rectangle())217        }218        .buttonStyle(.plain)219        .listRowBackground(AstraColor.surface)220        .accessibilityIdentifier("conversation-row")221        .swipeActions(edge: .trailing) {222            Button(role: .destructive) { Task { await app.delete(c); await refreshArchived() } } label: { Label("Delete", systemImage: "trash") }223            Button { Task { try? await app.store.setConversationArchived(id: c.id, !c.archived); await app.reloadConversations(); await refreshArchived() } } label: {224                Label(c.archived ? "Unarchive" : "Archive", systemImage: "archivebox")225            }226            .tint(AstraColor.indigo)227        }228        .swipeActions(edge: .leading) {229            Button { Task { try? await app.store.setConversationPinned(id: c.id, !c.pinned); await app.reloadConversations() } } label: {230                Label(c.pinned ? "Unpin" : "Pin", systemImage: c.pinned ? "pin.slash" : "pin")231            }232            .tint(AstraColor.violet)233        }234        .contextMenu {235            Button { renameText = c.title; renaming = c } label: { Label("Rename", systemImage: "pencil") }236            Button { Task { _ = try? await app.store.duplicateConversation(id: c.id); await app.reloadConversations() } } label: { Label("Duplicate", systemImage: "plus.square.on.square") }237            Button { Task { try? await app.store.setConversationPinned(id: c.id, !c.pinned); await app.reloadConversations() } } label: { Label(c.pinned ? "Unpin" : "Pin", systemImage: "pin") }238            Divider()239            Button(role: .destructive) { Task { await app.delete(c) } } label: { Label("Delete", systemImage: "trash") }240        }241    }242243    private func refreshArchived() async { if showArchived { archived = (try? await app.store.conversations(.archived)) ?? [] } }244245    private var emptyState: some View {246        EmptyStateView(title: "Start a conversation", message: "Every chat is stored on this iPhone. Pick a model and ask your first question.") {247            Button("New chat") { startNewChat() }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("empty-new-chat")248        }249        .frame(maxWidth: .infinity, maxHeight: .infinity)250    }251252    private var noModelState: some View {253        EmptyStateView(title: "Choose your first model",254                       message: "Download a model that runs privately on this iPhone, or connect a provider with your own API key.") {255            Button("Open Models") { app.tab = .models }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("empty-open-models")256        }257        .frame(maxWidth: .infinity, maxHeight: .infinity)258    }259}260
Files main
Menu

Theme