Files
KrisHD_AI/test/workspaceImport.test.js
T
2026-10-05 23:21:42 +02:00

164 lines
10 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import {createDatabase} from "../src/db/index.js";
import {createRepositories} from "../src/db/repositories.js";
import {createConfig} from "../src/config.js";
import {validateWorkspaceImport} from "../src/services/workspaceImportService.js";
import {createWorkspaceArchive, parseWorkspaceArchive} from "../src/services/workspaceArchive.js";
function fixture(t) {
const config = createConfig({dbPath: ":memory:", testMode: true});
const db = createDatabase(config);
t.after(() => db.close());
const repo = createRepositories(db, config);
for (const user of ["source", "destination", "second-copy"]) repo.insertUser(user, "unused");
return {db, repo};
}
function restore(repo, workspace, user = "destination") {
const validation = validateWorkspaceImport(workspace);
assert.deepEqual(validation.errors, []);
repo.importWorkspace(user, validation.workspace);
return repo.exportWorkspace(user);
}
for (const format of ["JSON", "archive"]) {
test(`${format} export/import round trips remap personas, branches, prompts, state, memories and versions`, t => {
const {db, repo} = fixture(t);
// Identical display names must not be used as relationship keys.
const assistant = repo.createPersona("source", {name: "Alex", details: "Guide"}, "assistant");
const userPersona = repo.createPersona("source", {name: "Alex", details: "Explorer"}, "user");
const original = repo.createChat("source", "Original", assistant.id, userPersona.id, "At the station", "Meeting");
const prompt = Number(repo.insertBranchChatMessage(original.id, "user", "Question").lastInsertRowid);
const answer = Number(repo.insertBranchChatMessage(original.id, "bot", "Answer", {
retryVariants: ["Answer"], retryPromptMessageId: prompt
}, "qwen3:14b", "complete", null, prompt).lastInsertRowid);
repo.updateChatMessageThinking(original.id, answer, "Reasoning");
repo.updateChatMessageSources(original.id, answer, [{title: "Source", url: "https://example.org/", snippet: "Evidence"}]);
repo.saveMessageVersion(original.id, answer, {content: "Revised", thinking: "Revised reasoning", sources: [], modelName: "qwen3:14b"});
repo.updateChatContextSummary(original.id, "source", "Summary", answer);
repo.updatePersonaChatState("source", original, {tone: "Curious", current_location: "Station"});
repo.createChatMemory("source", original, "Remember the station");
repo.createPromptTemplate("source", {name: "Guide prompt", personaId: assistant.id, promptText: "Begin here"});
const branch = repo.createChat("source", "Branch", assistant.id, userPersona.id);
repo.updateChatBranchSource(branch.id, "source", original.id, answer);
repo.updateChatGenerationSettings(branch.id, "source", {temperature: 0, contextLength: 4096, responseLength: 256});
repo.insertBranchChatMessage(branch.id, "bot", "Another root");
let workspace = repo.exportWorkspace("source");
if (format === "archive") workspace = parseWorkspaceArchive(createWorkspaceArchive(workspace, [])).workspace;
else workspace = JSON.parse(JSON.stringify(workspace));
// A branch can be exported before its source chat.
workspace.chats.sort((a, b) => b.id - a.id);
for (const destination of ["destination", "second-copy"]) {
const restored = restore(repo, workspace, destination);
const copied = restored.chats.find(chat => chat.stored_title === "Original");
const copiedBranch = restored.chats.find(chat => chat.stored_title === "Branch");
const copiedAssistant = restored.personas.find(persona => persona.persona_type === "assistant");
const copiedUser = restored.personas.find(persona => persona.persona_type === "user");
assert.notEqual(copied.id, original.id);
assert.notEqual(copiedAssistant.id, assistant.id);
assert.notEqual(copiedUser.id, userPersona.id);
for (const record of [copied, copiedBranch, copied.memories[0], copied.persona_state]) {
assert.equal(record.assistant_persona_id, copiedAssistant.id);
assert.equal(record.user_persona_id, copiedUser.id);
}
const question = copied.messages.find(message => message.role === "user");
const reply = copied.messages.find(message => message.role === "bot");
assert.equal(reply.parent_message_id, question.id);
assert.equal(reply.retry_prompt_message_id, question.id);
assert.equal(copied.active_leaf_message_id, reply.id);
assert.equal(copied.context_summary_message_id, reply.id);
assert.equal(copied.context_summary, "Summary");
assert.equal(copiedBranch.source_chat_id, copied.id);
assert.equal(copiedBranch.branched_from_message_id, reply.id);
assert.deepEqual(repo.listActiveBranchMessages(copied.id).map(message => message.content), ["Question", "Revised"]);
assert.deepEqual(reply.responseVersions, workspace.chats.find(chat => chat.stored_title === "Original").messages.find(message => message.role === "bot").responseVersions);
assert.equal(reply.thinking, "Revised reasoning");
assert.equal(copied.temperature, null);
assert.equal(copied.context_length, null);
assert.equal(copied.response_length, null);
assert.equal(copiedBranch.temperature, 0);
assert.equal(copiedBranch.context_length, 4096);
assert.equal(copiedBranch.response_length, 256);
assert.equal(copied.persona_state.tone, "Curious");
assert.equal(copied.memories[0].fact, "Remember the station");
assert.equal(restored.templates.find(template => template.name === "Guide prompt").persona_id, copiedAssistant.id);
assert.deepEqual(db.pragma("foreign_key_check"), []);
workspace = restored;
}
});
}
test("legacy two-message histories with and without IDs restore a complete active chain", t => {
const {repo} = fixture(t);
for (const withIds of [false, true]) {
const title = `Legacy ${withIds}`;
const restored = restore(repo, {chats: [{title, temperature: null, messages: [
{role: "user", content: "Question", ...(withIds ? {id: 41} : {})},
{role: "assistant", content: "Answer", ...(withIds ? {id: 42} : {})}
]}]});
const chat = restored.chats.find(item => item.stored_title === title);
assert.deepEqual(repo.listActiveBranchMessages(chat.id).map(message => message.content), ["Question", "Answer"]);
assert.equal(chat.messages[1].parent_message_id, chat.messages[0].id);
assert.equal(chat.active_leaf_message_id, chat.messages[1].id);
assert.equal(chat.temperature, null);
}
});
test("explicit roots stay separate and unmapped references never bind existing records", t => {
const {repo} = fixture(t);
const foreignPersona = repo.createPersona("source", {name: "Other account"}, "assistant");
const foreignChat = repo.createChat("source", "Other chat");
const foreignMessage = Number(repo.insertChatMessage(foreignChat.id, "user", "Private").lastInsertRowid);
const restored = restore(repo, {templates: [{name: "Detached", prompt_text: "Hello", persona_id: foreignPersona.id}], chats: [{
title: "Roots", assistant_persona_id: foreignPersona.id, source_chat_id: foreignChat.id, branched_from_message_id: foreignMessage,
active_leaf_message_id: 20, messages: [
{id: 10, role: "user", content: "Root one", parent_message_id: null},
{id: 20, role: "bot", content: "Root two", parent_message_id: null, retry_prompt_message_id: foreignMessage}
]
}]});
const chat = restored.chats[0];
assert.equal(chat.assistant_persona_id, null);
assert.equal(chat.source_chat_id, null);
assert.equal(chat.branched_from_message_id, null);
assert.equal(chat.messages[1].retry_prompt_message_id, null);
assert.ok(chat.messages.every(message => message.parent_message_id === null));
assert.deepEqual(repo.listActiveBranchMessages(chat.id).map(message => message.content), ["Root two"]);
assert.equal(restored.templates.find(template => template.name === "Detached").persona_id, null);
});
test("message references are remapped even when the parent is imported later", t => {
const {repo} = fixture(t);
const restored = restore(repo, {chats: [{title: "Forward reference", active_leaf_message_id: 20, messages: [
{id: 20, role: "bot", content: "Answer", parentMessageId: 10, retryPromptMessageId: 10},
{id: 10, role: "user", content: "Question", parentMessageId: null}
]}]});
const [answer, prompt] = restored.chats[0].messages;
assert.equal(answer.parent_message_id, prompt.id);
assert.equal(answer.retry_prompt_message_id, prompt.id);
assert.equal(restored.chats[0].active_leaf_message_id, answer.id);
});
test("optional generation settings preserve unset values and numeric zero", () => {
for (const value of [null, undefined, "", " ", 0, "0", 0.7]) {
const {workspace} = validateWorkspaceImport({chats: [{title: "Settings", temperature: value, context_length: value, response_length: value}]});
const chat = workspace.chats[0];
const expected = value === 0 || value === "0" ? 0 : value === 0.7 ? 0.7 : null;
assert.equal(chat.temperature, expected);
assert.equal(chat.context_length, expected === 0.7 ? null : expected);
assert.equal(chat.response_length, expected === 0.7 ? null : expected);
}
});
test("ambiguous IDs and cyclic message chains fail validation", () => {
for (const messages of [
[{id: 1}, {id: 1}],
[{id: 1, parent_message_id: 2}, {id: 2, parent_message_id: 1}]
]) {
const validation = validateWorkspaceImport({chats: [{messages: messages.map(message => ({role: "user", content: "Text", ...message}))}]});
assert.equal(validation.ok, false);
assert.match(validation.errors.join(" "), /duplicate message ID|cyclic message chain/);
}
});