Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,225 @@
|
||||
"use strict";
|
||||
|
||||
const { AsyncLocalStorage } = require("node:async_hooks");
|
||||
|
||||
function accountChanged() {
|
||||
const error = new Error("The assistant account changed. Sign in again before continuing.");
|
||||
error.code = "ASSISTANT_ACCOUNT_CHANGED";
|
||||
return error;
|
||||
}
|
||||
|
||||
// adpanel:assistant-history-owner - email reuse never transfers conversations;
|
||||
// legacy rows without a provable account ID stay unassigned and unreadable.
|
||||
function createDashboardAssistantHistory({ db, findUserByEmail, title = "ADPanel Assistant" } = {}) {
|
||||
const owners = new AsyncLocalStorage();
|
||||
let initPromise = null;
|
||||
const emailKey = (email) => String(email || "").trim().toLowerCase();
|
||||
const owner = () => {
|
||||
const current = owners.getStore();
|
||||
if (!current) throw accountChanged();
|
||||
return current;
|
||||
};
|
||||
|
||||
async function runForUser(email, operation, expectedId) {
|
||||
const current = owners.getStore();
|
||||
if (current) {
|
||||
if (emailKey(email) !== current.email || (expectedId != null && Number(expectedId) !== current.id)) throw accountChanged();
|
||||
return operation();
|
||||
}
|
||||
const user = await findUserByEmail(emailKey(email));
|
||||
const id = Number(user?.id);
|
||||
if (!Number.isSafeInteger(id) || id <= 0 || user.suspended ||
|
||||
(expectedId != null && Number(expectedId) !== id)) throw accountChanged();
|
||||
return owners.run(Object.freeze({ id, email: emailKey(user.email) }), operation);
|
||||
}
|
||||
|
||||
async function ensureTables() {
|
||||
if (initPromise) return initPromise;
|
||||
initPromise = (async () => {
|
||||
await db.query(`CREATE TABLE IF NOT EXISTS dashboard_assistant_chats (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
user_id BIGINT UNSIGNED NULL,
|
||||
user_email VARCHAR(255) NOT NULL,
|
||||
title VARCHAR(255) NOT NULL DEFAULT 'ADPanel Assistant',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_dashboard_assistant_chats_user (user_email),
|
||||
KEY idx_dashboard_assistant_chats_owner (user_id, updated_at),
|
||||
KEY idx_dashboard_assistant_chats_updated (updated_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
|
||||
for (const [sql, duplicateCode] of [
|
||||
["ALTER TABLE dashboard_assistant_chats ADD COLUMN user_id BIGINT UNSIGNED NULL AFTER id", "ER_DUP_FIELDNAME"],
|
||||
["ALTER TABLE dashboard_assistant_chats ADD KEY idx_dashboard_assistant_chats_owner (user_id, updated_at)", "ER_DUP_KEYNAME"]
|
||||
]) {
|
||||
try { await db.query(sql); } catch (error) { if (error.code !== duplicateCode) throw error; }
|
||||
}
|
||||
await db.query(`CREATE TABLE IF NOT EXISTS dashboard_assistant_messages (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
chat_id BIGINT UNSIGNED NOT NULL,
|
||||
role ENUM('user', 'assistant', 'system') NOT NULL,
|
||||
content LONGTEXT NOT NULL,
|
||||
model VARCHAR(255) NULL,
|
||||
thinking_time_ms INT UNSIGNED NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_dashboard_assistant_messages_chat (chat_id),
|
||||
KEY idx_dashboard_assistant_messages_created (created_at),
|
||||
CONSTRAINT fk_dashboard_assistant_messages_chat FOREIGN KEY (chat_id)
|
||||
REFERENCES dashboard_assistant_chats(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
|
||||
})().catch((error) => { initPromise = null; throw error; });
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
async function withLiveOwner(operation) {
|
||||
const current = owner();
|
||||
await ensureTables();
|
||||
const connection = await db.pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
const [users] = await connection.execute("SELECT id, email, suspended FROM users WHERE id = ? AND LOWER(email) = LOWER(?) FOR UPDATE", [current.id, current.email]);
|
||||
if (!users[0] || Number(users[0].suspended) !== 0 || emailKey(users[0].email) !== current.email) throw accountChanged();
|
||||
const result = await operation(connection, current);
|
||||
await connection.commit();
|
||||
return result;
|
||||
} catch (error) {
|
||||
try { await connection.rollback(); } catch (_) { }
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
const chatSql = `SELECT c.id, c.title, c.created_at, c.updated_at
|
||||
FROM dashboard_assistant_chats c JOIN users u ON u.id = c.user_id
|
||||
WHERE c.user_id = ? AND u.suspended = 0`;
|
||||
|
||||
async function getChatById(email, chatId) {
|
||||
await ensureTables();
|
||||
const id = Number(chatId);
|
||||
if (!Number.isSafeInteger(id) || id <= 0) return null;
|
||||
return (await db.query(`${chatSql} AND c.id = ? LIMIT 1`, [owner().id, id]))[0] || null;
|
||||
}
|
||||
|
||||
async function createFreshChat(email) {
|
||||
return withLiveOwner(async (connection, current) => {
|
||||
const [result] = await connection.execute("INSERT INTO dashboard_assistant_chats (user_id, user_email, title) VALUES (?, ?, ?)", [current.id, current.email, title]);
|
||||
const [rows] = await connection.execute("SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? LIMIT 1", [result.insertId, current.id]);
|
||||
return rows[0];
|
||||
});
|
||||
}
|
||||
|
||||
async function getPrimaryChat(email) {
|
||||
await ensureTables();
|
||||
const rows = await db.query(`${chatSql} ORDER BY c.updated_at DESC, c.id DESC LIMIT 1`, [owner().id]);
|
||||
return rows[0] || createFreshChat(email);
|
||||
}
|
||||
|
||||
async function resetChat(email) {
|
||||
return withLiveOwner(async (connection, current) => {
|
||||
const [empty] = await connection.execute(`SELECT c.id FROM dashboard_assistant_chats c
|
||||
WHERE c.user_id = ? AND NOT EXISTS (
|
||||
SELECT 1 FROM dashboard_assistant_messages m WHERE m.chat_id = c.id)
|
||||
ORDER BY c.updated_at DESC, c.id DESC LIMIT 1 FOR UPDATE`, [current.id]);
|
||||
let chatId = empty[0]?.id;
|
||||
if (chatId) {
|
||||
await connection.execute("UPDATE dashboard_assistant_chats SET updated_at = NOW() WHERE id = ? AND user_id = ?", [chatId, current.id]);
|
||||
await connection.execute(`DELETE FROM dashboard_assistant_chats WHERE user_id = ? AND id <> ?
|
||||
AND NOT EXISTS (SELECT 1 FROM dashboard_assistant_messages m WHERE m.chat_id = dashboard_assistant_chats.id)`, [current.id, chatId]);
|
||||
} else {
|
||||
const [result] = await connection.execute("INSERT INTO dashboard_assistant_chats (user_id, user_email, title) VALUES (?, ?, ?)", [current.id, current.email, title]);
|
||||
chatId = result.insertId;
|
||||
}
|
||||
const [rows] = await connection.execute("SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? LIMIT 1", [chatId, current.id]);
|
||||
return rows[0];
|
||||
});
|
||||
}
|
||||
|
||||
async function getChatMessages(chatId, limit = 60) {
|
||||
await ensureTables();
|
||||
const safeLimit = Math.max(1, Math.min(200, parseInt(limit, 10) || 60));
|
||||
const select = `SELECT m.id, m.role, m.content, m.model, m.thinking_time_ms, m.created_at
|
||||
FROM dashboard_assistant_messages m JOIN dashboard_assistant_chats c ON c.id = m.chat_id
|
||||
JOIN users u ON u.id = c.user_id WHERE m.chat_id = ? AND c.user_id = ? AND u.suspended = 0`;
|
||||
const rows = await db.query(`${select} ORDER BY m.id DESC LIMIT ${safeLimit}`, [chatId, owner().id]);
|
||||
const windowRows = (rows || []).slice().sort((left, right) => Number(left.id) - Number(right.id));
|
||||
if (!windowRows.length) return [];
|
||||
const windowIds = windowRows.map((row) => Number(row.id));
|
||||
const systemRows = await db.query(`${select} AND m.role = 'system' AND m.id NOT IN (${windowIds.map(() => "?").join(", ")})
|
||||
ORDER BY m.created_at ASC, m.id ASC LIMIT ${safeLimit}`, [chatId, owner().id, ...windowIds]);
|
||||
return [...(systemRows || []), ...windowRows].sort((left, right) => Number(left.id) - Number(right.id));
|
||||
}
|
||||
|
||||
async function getChatMessageCount(chatId) {
|
||||
await ensureTables();
|
||||
const rows = await db.query(`SELECT COUNT(*) AS total FROM dashboard_assistant_messages m
|
||||
JOIN dashboard_assistant_chats c ON c.id = m.chat_id JOIN users u ON u.id = c.user_id
|
||||
WHERE m.chat_id = ? AND c.user_id = ? AND u.suspended = 0 AND m.role IN ('user', 'assistant')`, [chatId, owner().id]);
|
||||
return Number(rows[0]?.total || 0);
|
||||
}
|
||||
|
||||
async function addMessage(chatId, { role, content, model = null, thinkingTimeMs = null }) {
|
||||
return withLiveOwner(async (connection, current) => {
|
||||
const [chats] = await connection.execute("SELECT id FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? FOR UPDATE", [chatId, current.id]);
|
||||
if (!chats[0]) throw accountChanged();
|
||||
await connection.execute("INSERT INTO dashboard_assistant_messages (chat_id, role, content, model, thinking_time_ms) VALUES (?, ?, ?, ?, ?)", [chatId, role, String(content || ""), model, thinkingTimeMs]);
|
||||
await connection.execute("UPDATE dashboard_assistant_chats SET updated_at = NOW() WHERE id = ? AND user_id = ?", [chatId, current.id]);
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteChat(email, chatId) {
|
||||
return withLiveOwner(async (connection, current) => {
|
||||
await connection.execute("DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE id = ? AND user_id = ?)", [chatId, current.id]);
|
||||
await connection.execute("DELETE FROM dashboard_assistant_chats WHERE id = ? AND user_id = ?", [chatId, current.id]);
|
||||
});
|
||||
}
|
||||
|
||||
async function maybeUpdateChatTitle(chatId, userMessage) {
|
||||
return withLiveOwner(async (connection, current) => {
|
||||
const [rows] = await connection.execute("SELECT title FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? FOR UPDATE", [chatId, current.id]);
|
||||
if (!rows[0]) throw accountChanged();
|
||||
if (rows[0].title && rows[0].title !== title) return;
|
||||
await connection.execute("UPDATE dashboard_assistant_chats SET title = ? WHERE id = ? AND user_id = ?", [String(userMessage || "").trim().slice(0, 80) || title, chatId, current.id]);
|
||||
});
|
||||
}
|
||||
|
||||
return { runForUser, ensureTables, getPrimaryChat, createFreshChat, resetChat, getChatById, getChatMessages, getChatMessageCount, addMessage, deleteChat, maybeUpdateChatTitle };
|
||||
}
|
||||
|
||||
async function deleteAccountAssistantHistory(connection, userId, email) {
|
||||
// adpanel:assistant-history-delete - the caller holds the user row lock;
|
||||
// history writes take that same lock and cannot outlive the account.
|
||||
let predicate = "user_id = ? OR (user_id IS NULL AND user_email = ?)";
|
||||
let params = [userId, email];
|
||||
try {
|
||||
await connection.execute(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} FOR UPDATE`, params);
|
||||
} catch (error) {
|
||||
if (error.code === "ER_NO_SUCH_TABLE") return;
|
||||
if (error.code !== "ER_BAD_FIELD_ERROR" || !String(error.message).includes("user_id")) throw error;
|
||||
predicate = "user_email = ?";
|
||||
params = [email];
|
||||
await connection.execute(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} FOR UPDATE`, params);
|
||||
}
|
||||
try {
|
||||
await connection.execute(`DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE ${predicate})`, params);
|
||||
} catch (error) { if (error.code !== "ER_NO_SUCH_TABLE") throw error; }
|
||||
await connection.execute(`DELETE FROM dashboard_assistant_chats WHERE ${predicate}`, params);
|
||||
}
|
||||
|
||||
async function cleanupOrphanAssistantHistory(db) {
|
||||
let predicate = "(user_id IS NOT NULL AND user_id NOT IN (SELECT id FROM users)) OR (user_id IS NULL AND user_email NOT IN (SELECT email FROM users))";
|
||||
try {
|
||||
await db.query(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} LIMIT 1`);
|
||||
} catch (error) {
|
||||
if (error.code === "ER_NO_SUCH_TABLE") return;
|
||||
if (error.code !== "ER_BAD_FIELD_ERROR" || !String(error.message).includes("user_id")) throw error;
|
||||
predicate = "user_email NOT IN (SELECT email FROM users)";
|
||||
}
|
||||
try {
|
||||
await db.query(`DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE ${predicate})`);
|
||||
} catch (error) { if (error.code !== "ER_NO_SUCH_TABLE") throw error; }
|
||||
await db.query(`DELETE FROM dashboard_assistant_chats WHERE ${predicate}`);
|
||||
}
|
||||
|
||||
module.exports = { createDashboardAssistantHistory, deleteAccountAssistantHistory, cleanupOrphanAssistantHistory };
|
||||
Reference in new issue
Block a user