237 lines
11 KiB
JavaScript
237 lines
11 KiB
JavaScript
import {chatSearchInput, msgInput, messagesDiv} from "./dom.js?v=20260909-account-controls";
|
|
import {get, post} from "./api.js?v=20260909-account-controls";
|
|
import {requestedChatId} from "./constants.js?v=20260909-account-controls";
|
|
|
|
export function createConversationController({
|
|
state,
|
|
renderChatList,
|
|
attachmentComposer,
|
|
resizeComposerInput,
|
|
isMobileLayout,
|
|
closeMobileSidebar,
|
|
setChatLoading,
|
|
setChatActivity,
|
|
updateWorkspaceCopy,
|
|
updateChatActionState,
|
|
setNotice,
|
|
populateGenerationSettings,
|
|
renderMessages,
|
|
updateJumpToLatest,
|
|
updateSendState,
|
|
loadSummary,
|
|
updateHistoryControls = () => {},
|
|
getPersonalityId = () => "general-assistant"
|
|
}) {
|
|
let opening = false;
|
|
function getChatById(id) { return state.chatSessions.find((chat) => chat.id === id); }
|
|
|
|
async function openCreatedChat(chat) {
|
|
if (!chat?.id) throw new Error("The server did not return the newly created chat");
|
|
if (chatSearchInput) {
|
|
chatSearchInput.value = "";
|
|
scheduleChatSearch();
|
|
}
|
|
const chatsResponse = await get("/chats");
|
|
if (chatsResponse.error) throw new Error(chatsResponse.error);
|
|
state.chatSessions = chatsResponse.chats || [];
|
|
if (!state.chatSessions.some((item) => item.id === chat.id)) {
|
|
throw new Error("The newly created chat was not persisted");
|
|
}
|
|
renderChatList();
|
|
const opened = await setActiveChat(chat.id);
|
|
if (opened?.error) throw new Error(opened.error);
|
|
}
|
|
|
|
async function setActiveChat(id, {preserveComposer = false, matchMessageId = null} = {}) {
|
|
const failed = response => { setNotice(response.error, "error"); return response; };
|
|
const openRequest = ++state.chatOpenRequest;
|
|
if (isMobileLayout()) closeMobileSidebar();
|
|
if (!opening) {
|
|
opening = true;
|
|
setChatLoading(true, "Opening chat...");
|
|
setChatActivity(true, {
|
|
eyebrow: "Opening chat", title: "Loading conversation",
|
|
detail: "Fetching messages and restoring the current scene."
|
|
});
|
|
}
|
|
try {
|
|
const historyUrl = `/chats/${id}/messages${matchMessageId ? `?around=${matchMessageId}` : ""}`;
|
|
let res = await get(historyUrl, {retries: 0});
|
|
if (openRequest !== state.chatOpenRequest) return;
|
|
if (res.error) return failed(res);
|
|
if (matchMessageId && !res.messages?.some(message => message.id === matchMessageId)) {
|
|
const activated = await post(`/chats/${id}/branches/${matchMessageId}/activate`, {includeDescendants: true});
|
|
if (openRequest !== state.chatOpenRequest) return;
|
|
if (activated.error) return failed(activated);
|
|
res = await get(historyUrl, {retries: 0});
|
|
if (openRequest !== state.chatOpenRequest) return;
|
|
if (res.error) return failed(res);
|
|
}
|
|
// Commit identity, content and drafts together, only for the latest successful load.
|
|
if (!preserveComposer && id !== state.activeChatId) {
|
|
if (state.activeChatId != null) {
|
|
state.chatDrafts.set(state.activeChatId, msgInput.value);
|
|
attachmentComposer.saveDraft(state.activeChatId);
|
|
msgInput.value = state.chatDrafts.get(id) || "";
|
|
attachmentComposer.restoreDraft(id);
|
|
resizeComposerInput();
|
|
} else {
|
|
if (msgInput.value || attachmentComposer.pending || attachmentComposer.attachments.length) {
|
|
state.chatDrafts.set("new", msgInput.value);
|
|
attachmentComposer.saveDraft(null);
|
|
}
|
|
msgInput.value = state.chatDrafts.get(id) || "";
|
|
attachmentComposer.restoreDraft(id);
|
|
resizeComposerInput();
|
|
}
|
|
}
|
|
const existing = getChatById(id);
|
|
if (res.chat && existing) Object.assign(existing, res.chat);
|
|
state.activeChatId = id;
|
|
attachmentComposer.adoptDraft?.(id);
|
|
if (preserveComposer) state.chatDrafts.delete("new");
|
|
state.chatDrafts.set(id, msgInput.value);
|
|
state.currentMessages = res.messages || [];
|
|
state.historyPage = res.pagination || null;
|
|
state.historyLoading = false;
|
|
updateHistoryControls();
|
|
history.replaceState(null, "", `/app/chats/${id}`);
|
|
state.messageRetryState = new Map();
|
|
updateWorkspaceCopy(); renderChatList(); updateChatActionState();
|
|
populateGenerationSettings(res.chat || existing);
|
|
renderMessages();
|
|
if (matchMessageId) requestAnimationFrame(() => {
|
|
if (openRequest !== state.chatOpenRequest) return;
|
|
const target = [...messagesDiv.querySelectorAll("[data-message-id]")]
|
|
.find(node => Number(node.dataset.messageId) === Number(matchMessageId));
|
|
if (target) { target.scrollIntoView({block: "center"}); updateJumpToLatest(); }
|
|
});
|
|
updateSendState();
|
|
return {ok: true};
|
|
} finally {
|
|
if (openRequest === state.chatOpenRequest) {
|
|
opening = false;
|
|
setChatLoading(false);
|
|
setChatActivity(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function loadOlderMessages() {
|
|
if (state.historyLoading || !state.historyPage?.hasMore || !state.activeChatId) return;
|
|
const chatId = state.activeChatId, requestId = state.chatOpenRequest, page = state.historyPage;
|
|
state.historyLoading = true;
|
|
updateHistoryControls();
|
|
try {
|
|
const result = await get(`/chats/${chatId}/messages?before=${page.before}&leaf=${page.leafId}`, {retries: 0});
|
|
if (chatId !== state.activeChatId || requestId !== state.chatOpenRequest) return;
|
|
if (result.error) { setNotice(result.error, "error"); return result; }
|
|
const oldHeight = messagesDiv.scrollHeight, oldTop = messagesDiv.scrollTop;
|
|
const existing = new Set(state.currentMessages.map(message => message.id));
|
|
state.currentMessages = [...result.messages.filter(message => !existing.has(message.id)), ...state.currentMessages];
|
|
state.historyPage = {...result.pagination, hasNewer: page.hasNewer};
|
|
renderMessages({preserveScroll: true});
|
|
messagesDiv.scrollTop = oldTop + messagesDiv.scrollHeight - oldHeight;
|
|
} finally {
|
|
if (state.historyPage === page || requestId === state.chatOpenRequest) {
|
|
state.historyLoading = false;
|
|
updateHistoryControls();
|
|
}
|
|
}
|
|
}
|
|
|
|
async function loadChatSessions() {
|
|
setChatLoading(true, "Loading chats...");
|
|
const res = await get("/chats");
|
|
if (res.error) {
|
|
setChatLoading(false);
|
|
return setNotice(res.error, "error");
|
|
}
|
|
state.chatSessions = res.chats || []; renderChatList();
|
|
if (state.activeChatId && getChatById(state.activeChatId)) {
|
|
updateWorkspaceCopy();
|
|
setChatLoading(false);
|
|
return;
|
|
}
|
|
if (location.pathname.endsWith("/new") && !state.activeChatId) { state.currentMessages = []; renderMessages(); updateWorkspaceCopy(); updateSendState(); setChatLoading(false); return; }
|
|
if (requestedChatId && !getChatById(requestedChatId) && !state.activeChatId) { setChatLoading(false); return setNotice("Conversation not found. Choose a chat from the sidebar or start a new one.", "error"); }
|
|
if (state.chatSessions.length) {
|
|
const preferredChatId = state.activeChatId && getChatById(state.activeChatId) ? state.activeChatId : (requestedChatId && getChatById(requestedChatId)) ? requestedChatId : state.chatSessions[0].id;
|
|
setChatLoading(false);
|
|
return setActiveChat(preferredChatId);
|
|
}
|
|
state.activeChatId = null;
|
|
state.currentMessages = [];
|
|
renderMessages();
|
|
updateWorkspaceCopy();
|
|
updateSendState();
|
|
setChatLoading(false);
|
|
return setNotice("Pick a starting action to begin.", "success");
|
|
}
|
|
|
|
async function searchChatSessions(query, requestId) {
|
|
const res = await get(`/chats/search?q=${encodeURIComponent(query)}`);
|
|
if (requestId !== state.chatSearchRequest || chatSearchInput.value.trim() !== query) return;
|
|
if (res.error) {
|
|
state.chatSearchError = "Unable to search chats.";
|
|
renderChatList();
|
|
setNotice(res.error, "error");
|
|
return;
|
|
}
|
|
state.chatSearchResults = res.chats || [];
|
|
renderChatList();
|
|
}
|
|
|
|
function scheduleChatSearch() {
|
|
clearTimeout(state.chatSearchTimer);
|
|
const requestId = ++state.chatSearchRequest;
|
|
const query = chatSearchInput.value.trim();
|
|
state.chatSearchResults = null;
|
|
state.chatSearchError = "";
|
|
if (!query) {
|
|
renderChatList();
|
|
return;
|
|
}
|
|
renderChatList();
|
|
state.chatSearchTimer = setTimeout(() => { void searchChatSessions(query, requestId); }, 300);
|
|
}
|
|
|
|
async function createNewChat({preserveComposer = false, signal} = {}) {
|
|
const previousChatId = state.activeChatId;
|
|
setChatLoading(true, "Creating chat...");
|
|
setChatActivity(true, {
|
|
eyebrow: "Creating chat", title: "Opening a new conversation",
|
|
detail: "Setting up a fresh chat so you can start sending messages."
|
|
});
|
|
try {
|
|
const res = await post("/chats", {title: "New chat", personalityId: getPersonalityId()}, {signal});
|
|
if (res.error || !res.chat) {
|
|
const error = res.error || "Unable to create chat.";
|
|
setNotice(error, "error");
|
|
return {error};
|
|
}
|
|
state.chatSessions.unshift(res.chat);
|
|
await loadSummary(); renderChatList();
|
|
if (!signal?.aborted && state.activeChatId === previousChatId) {
|
|
const opened = await setActiveChat(res.chat.id, {preserveComposer});
|
|
if (opened?.error) return opened;
|
|
msgInput.focus();
|
|
}
|
|
setNotice("New chat created.", "success");
|
|
return res.chat;
|
|
} finally {
|
|
setChatLoading(false); setChatActivity(false);
|
|
}
|
|
}
|
|
|
|
return {
|
|
getChatById,
|
|
openCreatedChat,
|
|
setActiveChat,
|
|
loadChatSessions,
|
|
scheduleChatSearch,
|
|
createNewChat,
|
|
loadOlderMessages
|
|
};
|
|
}
|