"use strict"; const { readableImageSql } = require("../AgentWorker/attachments"); const { reviewProjection, REVIEW_SOURCE_REF_PREFIX } = require("../AgentWorker/action-proposal"); const { safeTruncateUtf16 } = require("../utils/safe-truncate"); const CHAT_HISTORY_PAGE_ROWS = 50; const CHAT_HISTORY_PAGE_BYTES = 12 * 1024 * 1024; const GENERATED_CHAT_TITLE_LENGTH = 80; function deriveAiAgentChatTitle(prompt, fallback = "ADPanel Agent") { const clean = String(prompt || fallback || "ADPanel Agent").trim().replace(/\s+/g, " "); if (!clean) return "ADPanel Agent"; return clean.length > GENERATED_CHAT_TITLE_LENGTH ? `${safeTruncateUtf16(clean, GENERATED_CHAT_TITLE_LENGTH - 3)}...` : clean; } async function readFirstAgentChatTitle(db, row, prompt) { const [chat] = await db.query(`SELECT chat.title FROM ai_chats chat JOIN ai_messages submission ON submission.id = ? AND submission.chat_id = chat.id AND submission.role = 'user' WHERE chat.id = ? AND chat.created_by = ? AND NOT EXISTS ( SELECT 1 FROM ai_messages earlier WHERE earlier.chat_id = chat.id AND earlier.role = 'user' AND earlier.id < submission.id )`, [row.submission_message_id, row.chat_id, row.user_id]); const title = chat?.title; return title === "New Chat" || title === deriveAiAgentChatTitle(prompt) ? title : null; } function isValidServerAgentChatCursor(value) { return typeof value === "string" && /^[1-9]\d{0,19}$/.test(value) && BigInt(value) <= 18446744073709551615n; } async function readOwnedServerAgentChat(db, chatId, ownerId, source) { const [chat] = await db.query(`SELECT chat.*, job.status AS latest_job_status, job.error AS latest_job_error, CASE WHEN job.status IN ('queued','running') THEN CAST(job.id AS CHAR) END AS active_job_id, CASE WHEN job.submission_message_id IS NULL AND job.source_ref LIKE '${REVIEW_SOURCE_REF_PREFIX}%' THEN 1 ELSE 0 END AS active_job_is_review, ${reviewProjection}, (SELECT CAST(MAX(message.id) AS CHAR) FROM ai_messages message WHERE message.chat_id = chat.id) AS latest_message_id FROM ai_chats chat LEFT JOIN ai_agent_jobs job ON job.id = (SELECT recent.id FROM ai_agent_jobs recent WHERE recent.chat_id = chat.id AND recent.user_id = chat.created_by AND recent.source = ? ORDER BY recent.id DESC LIMIT 1) WHERE chat.id = ? AND chat.created_by = ?`, [source, chatId, ownerId]); return chat; } async function readServerAgentChatPage(db, chatId, beforeId) { const values = beforeId === undefined ? [chatId] : [chatId, beforeId]; const cursorClause = beforeId === undefined ? "" : " AND id < CAST(? AS UNSIGNED)"; // adpanel:agent-history-budget - never fetch whole attachment bodies to decide which messages fit. const candidates = await db.query(`SELECT CAST(id AS CHAR) AS cursor_id, role, created_at, OCTET_LENGTH(content) + COALESCE(OCTET_LENGTH(agent_actions), 0) + COALESCE(OCTET_LENGTH(${readableImageSql}), 0) + COALESCE(OCTET_LENGTH(thinking_content), 0) + COALESCE(OCTET_LENGTH(model), 0) AS stored_bytes FROM ai_messages WHERE chat_id = ?${cursorClause} ORDER BY id DESC LIMIT ${CHAT_HISTORY_PAGE_ROWS + 1}`, values); let size = 0; const ids = []; for (const row of candidates.slice(0, CHAT_HISTORY_PAGE_ROWS)) { size += Number(row.stored_bytes); if (size > CHAT_HISTORY_PAGE_BYTES) break; ids.push(row.cursor_id); } if (ids.length) { const messages = await db.query(`SELECT id, role, content, agent_actions, ${readableImageSql} AS image_data, thinking_time_ms, thinking_content, model, created_at FROM ai_messages WHERE chat_id = ? AND id IN (${ids.map(() => "CAST(? AS UNSIGNED)").join(", ")}) ORDER BY id ASC`, [chatId, ...ids]); return { messages, nextBeforeId: candidates.length > ids.length ? ids.at(-1) : null }; } const oversized = candidates[0]; if (!oversized) return { messages: [], nextBeforeId: null }; return { messages: [{ id: oversized.cursor_id, role: oversized.role, created_at: oversized.created_at, content: "[Message exceeds the transcript size limit]" }], nextBeforeId: candidates.length > 1 ? oversized.cursor_id : null, }; } async function ensureServerAgentChatOwnerSchema(db) { try { await db.query("ALTER TABLE ai_chats ADD COLUMN created_by BIGINT UNSIGNED NULL"); } catch (error) { if (error.code !== "ER_DUP_FIELDNAME") throw error; } try { await db.query("CREATE INDEX idx_ai_chats_owner_updated ON ai_chats (created_by, updated_at)"); } catch (error) { if (error.code !== "ER_DUP_KEYNAME") throw error; } } async function ensureServerAgentChatActionSchema(db) { try { await db.query("ALTER TABLE ai_messages ADD COLUMN agent_actions MEDIUMTEXT NULL"); } catch (error) { if (error.code !== "ER_DUP_FIELDNAME") throw error; } } async function backfillServerAgentChatOwners(db) { // adpanel:agent-chat-owner - a current email match cannot prove historical ownership. return db.query(`UPDATE ai_chats AS chat JOIN ( SELECT chat_id, MIN(user_id) AS owner_id FROM ai_agent_jobs GROUP BY chat_id HAVING MIN(user_id) = MAX(user_id) ) AS evidence ON evidence.chat_id = chat.id JOIN users AS owner ON owner.id = evidence.owner_id SET chat.created_by = evidence.owner_id, chat.updated_at = chat.updated_at WHERE chat.created_by IS NULL`); } async function createServerAgentChat(db, user, title, connection = null) { const ownerId = Number(user?.id); if (!Number.isSafeInteger(ownerId) || ownerId <= 0) throw new TypeError("Invalid Agent chat owner"); const sql = "INSERT INTO ai_chats (created_by, user_email, title) VALUES (?, ?, ?)"; const values = [ownerId, String(user.email || "").trim().toLowerCase(), title]; const result = connection ? (await connection.execute(sql, values))[0] : await db.query(sql, values); return result.insertId; } async function deleteAccountServerAgentChats(connection, accountId) { await connection.execute("DELETE FROM ai_messages WHERE chat_id IN (SELECT id FROM ai_chats WHERE created_by = ?)", [accountId]); await connection.execute("DELETE FROM ai_chats WHERE created_by = ?", [accountId]); } module.exports = { ensureServerAgentChatOwnerSchema, ensureServerAgentChatActionSchema, backfillServerAgentChatOwners, createServerAgentChat, deleteAccountServerAgentChats, isValidServerAgentChatCursor, readOwnedServerAgentChat, readServerAgentChatPage, deriveAiAgentChatTitle, readFirstAgentChatTitle, GENERATED_CHAT_TITLE_LENGTH };