SPB Git

Repository Public MIT

ConversationTests.swift 14.1 KB 249 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraPersistenceTests/ConversationTests.swift10// Module           : AstraPersistenceTests11// 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 Foundation89import Testing90import AstraCore91@testable import AstraPersistence9293@Suite struct ConversationTests {94    @Test func createStoresEverySetting() async throws {95        let store = try makeStore()96        let preset = PresetRecord(name: "Terse", system: "Be brief.", parameters: GenerationParameters(temperature: 0.2))97        try await store.savePreset(preset)98        let routing = RoutingPreferences(providerOrder: ["a", "b"], allowFallbacks: false, denyDataCollection: true, fallbackModels: ["x/y"])99        let parameters = GenerationParameters(temperature: 0.7, topP: 0.9, maxOutputTokens: 512, reasoning: .high, seed: 7, stop: ["END"], contextLength: 4096)100        let created = try await store.createConversation(title: "Settings", model: ModelRef(provider: .custom, modelID: "m", endpointID: "e1"),101                                                         systemPrompt: "You are precise.", parameters: parameters, contextWindowCap: 8_000,102                                                         truncationStrategy: .keepFirstAndRecent, memoryEnabled: false, presetID: preset.id, routing: routing)103        let read = try #require(try await store.conversation(id: created.id))104        #expect(read == created)105        #expect(read.parameters == parameters)106        #expect(read.routing == routing)107        #expect(read.model.endpointID == "e1")108        #expect(read.contextBudget(modelWindow: 32_000, reservedForOutput: 512) == ContextBudget(window: 8_000, reservedForOutput: 512, strategy: .keepFirstAndRecent))109        // Deleting the preset only clears the link.110        try await store.deletePreset(id: preset.id)111        #expect(try await store.conversation(id: created.id)?.presetID == nil)112    }113114    @Test func listIsPinnedFirstThenMostRecent() async throws {115        let store = try makeStore()116        let a = try await store.createConversation(title: "a", model: gpt, at: t(1))117        let b = try await store.createConversation(title: "b", model: gpt, at: t(2))118        let c = try await store.createConversation(title: "c", model: gpt, at: t(3))119        let d = try await store.createConversation(title: "d", model: gpt, at: t(4))120        #expect(try await store.conversations().map(\.title) == ["d", "c", "b", "a"])121        try await store.setConversationPinned(id: a.id, true)122        try await store.appendUserMessage(conversationID: b.id, text: "bump", at: t(10))123        #expect(try await store.conversations().map(\.title) == ["a", "b", "d", "c"])124        try await store.setConversationArchived(id: d.id, true)125        #expect(try await store.conversations().map(\.title) == ["a", "b", "c"])126        #expect(try await store.conversations(.archived).map(\.title) == ["d"])127        #expect(try await store.conversations(.all).count == 4)128        #expect(try await store.conversations(.all, limit: 2).count == 2)129        #expect(try await store.conversationCount(.active) == 3)130        try await store.renameConversation(id: c.id, title: "  renamed \n")131        #expect(try await store.conversation(id: c.id)?.title == "renamed")132        // Renaming does not reorder the list; pinning neither.133        #expect(try await store.conversation(id: c.id)?.updatedAt == t(3))134    }135136    @Test func updateCannotMoveTheActiveLeafOrIdentity() async throws {137        let store = try makeStore()138        let conversation = try await store.createConversation(model: gpt, at: t(0))139        let pair = try await store.exchange(conversation.id, "q", "a")140        let updated = try await store.updateConversation(id: conversation.id, touch: true, at: t(50)) {141            $0.activeLeafID = "bogus"; $0.id = "other"; $0.model = claude; $0.systemPrompt = "new"142        }143        #expect(updated.id == conversation.id)144        #expect(updated.activeLeafID == pair.assistant.id)145        #expect(updated.model == claude)146        #expect(updated.updatedAt == t(50))147        await #expect(throws: AstraStoreError.self) { try await store.updateConversation(id: "missing") { $0.title = "x" } }148    }149150    @Test func autoTitleComesFromTheFirstUserMessage() async throws {151        let store = try makeStore()152        let conversation = try await store.createConversation(model: gpt)153        #expect(try await store.autoTitleIfNeeded(conversationID: conversation.id) == nil)154        try await store.exchange(conversation.id, "\n\n## How do   tides work?\nSecond line", "Gravity.")155        #expect(try await store.autoTitleIfNeeded(conversationID: conversation.id) == "How do tides work?")156        #expect(try await store.conversation(id: conversation.id)?.title == "How do tides work?")157        // A title that exists is never replaced.158        #expect(try await store.autoTitleIfNeeded(conversationID: conversation.id) == nil)159        #expect(try await store.searchConversations("tides").first?.matchedTitle == true)160    }161162    @Test func suggestedTitles() {163        #expect(AstraStore.suggestedTitle(from: "") == "")164        #expect(AstraStore.suggestedTitle(from: "   \n\n") == "")165        #expect(AstraStore.suggestedTitle(from: "***\nHello") == "Hello")166        #expect(AstraStore.suggestedTitle(from: "> quoted `code` thing") == "quoted `code` thing")167        let long = AstraStore.suggestedTitle(from: String(repeating: "word ", count: 40), maxLength: 30)168        #expect(long.count <= 31)169        #expect(long.hasSuffix("…"))170        #expect(!long.dropLast().hasSuffix(" "))171        let unbroken = AstraStore.suggestedTitle(from: String(repeating: "x", count: 100), maxLength: 20)172        #expect(unbroken.count == 21)173        #expect(AstraStore.suggestedTitle(from: "日本語のタイトル") == "日本語のタイトル")174    }175176    @Test func duplicateIsADeepCopy() async throws {177        let store = try makeStore()178        let source = try await store.createConversation(title: "Original", model: gpt, systemPrompt: "sys", at: t(0))179        let image = AttachmentDraft(kind: .image, filename: "a.png", mimeType: "image/png", data: Data([1, 2, 3]))180        let first = try await store.appendUserMessage(conversationID: source.id, text: "first", attachments: [image], at: t(1))181        let draft = try await store.beginAssistantMessage(conversationID: source.id, model: gpt, at: t(2))182        let answer = try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(text: "answer one"), at: t(3))183        let alternative = try await store.regenerate(assistantMessageID: answer.id, at: t(4))184        try await store.finalizeAssistantMessage(id: alternative.id, MessageCompletion(text: "answer two"), at: t(5))185        try await store.appendUserMessage(conversationID: source.id, text: "follow-up", at: t(6))186        try await store.toggleBookmark(messageID: answer.id)187        try await store.setConversationPinned(id: source.id, true)188189        let copy = try await store.duplicateConversation(id: source.id, at: t(100))190        #expect(copy.id != source.id)191        #expect(copy.title == "Original (copy)")192        #expect(copy.systemPrompt == "sys")193        #expect(!copy.pinned)194        let originals = try await store.allMessages(conversationID: source.id)195        let copies = try await store.allMessages(conversationID: copy.id)196        #expect(copies.count == originals.count)197        #expect(copies.count == 4)198        #expect(Set(copies.map(\.id)).isDisjoint(with: Set(originals.map(\.id))))199        #expect(copies.allSatisfy { $0.conversationID == copy.id })200        // Same tree shape: parents map to copies, never to the originals.201        let copyIDs = Set(copies.map(\.id))202        #expect(copies.allSatisfy { $0.parentID == nil || copyIDs.contains($0.parentID!) })203        #expect(try await store.activePath(conversationID: copy.id).map(\.text) == ["first", "answer two", "follow-up"])204        #expect(copies.filter(\.bookmarked).map(\.text) == ["answer one"])205        let copiedFirst = try #require(copies.first { $0.text == "first" })206        #expect(try await store.siblings(of: try #require(copies.first { $0.text == "answer one" }).id).map(\.text) == ["answer one", "answer two"])207        let attachments = try await store.attachments(messageID: copiedFirst.id)208        #expect(attachments.count == 1)209        #expect(attachments.first?.sha256 == (try await store.attachments(messageID: first.id)).first?.sha256)210        #expect(try await store.attachmentData(try #require(attachments.first)) == Data([1, 2, 3]))211212        // The copy is independent: deleting the original leaves it, and its file, intact.213        try await store.deleteConversation(id: source.id)214        #expect(try await store.conversation(id: source.id) == nil)215        #expect(try await store.allMessages(conversationID: copy.id).count == 4)216        #expect(try await store.attachmentData(try #require(attachments.first)) == Data([1, 2, 3]))217        await #expect(throws: AstraStoreError.self) { try await store.duplicateConversation(id: "missing") }218    }219220    @Test func deleteCascadesAndCleansOrphanFiles() async throws {221        let store = try makeStore()222        let keep = try await store.createConversation(title: "keep", model: gpt)223        let drop = try await store.createConversation(title: "drop", model: gpt)224        let shared = AttachmentDraft(kind: .pdf, filename: "shared.pdf", mimeType: "application/pdf", data: Data(repeating: 7, count: 1000), extractedText: "shared text")225        let unique = AttachmentDraft(kind: .text, filename: "only.txt", mimeType: "text/plain", data: Data(repeating: 9, count: 500))226        try await store.appendUserMessage(conversationID: keep.id, text: "k", attachments: [shared])227        try await store.appendUserMessage(conversationID: drop.id, text: "zebra crossing", attachments: [shared, unique])228        try await store.addMemory(text: "remembered", sourceConversationID: drop.id)229        #expect(try await store.attachmentStorageBytes() == 1500)230        #expect(try await store.searchConversations("zebra").count == 1)231232        let result = try await store.deleteConversation(id: drop.id)233        #expect(result.rowsDeleted == 1)234        #expect(result.bytesFreed >= 500)235        #expect(try await store.attachmentStorageBytes() == 1000)236        let counts = try await store.read { db in237            (try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM message") ?? -1, try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM attachment") ?? -1,238             try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM message_fts") ?? -1, try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM conversation_fts") ?? -1)239        }240        #expect(counts.0 == 1)241        #expect(counts.1 == 1)242        #expect(counts.2 == 1)243        #expect(counts.3 == 1)244        #expect(try await store.searchConversations("zebra").isEmpty)245        // The memory outlives its source conversation, without the dangling link.246        #expect(try await store.memories().map(\.sourceConversationID) == [nil])247    }248}249
Files main
Menu

Theme