Signed-off-by: Daniel <845765@qq.com>
This commit is contained in:
Daniel
2026-06-03 11:36:24 +08:00
parent 3431a6afeb
commit 3ee395b3bf
30 changed files with 579 additions and 53 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "رفض",
"agentThinkingAnalyzing": "جاري تحليل طلبك...",
"agentThinkingProcessing": "جاري معالجة النتائج...",
"agentChat": "AI Agent",
"agentChat": "وكيل",
"agentNewSession": "جلسة جديدة",
"agentInputPlaceholder": "اكتب رسالة، Enter للإرسال...",
"agentSend": "إرسال",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Ablehnen",
"agentThinkingAnalyzing": "Anfrage wird analysiert...",
"agentThinkingProcessing": "Ergebnisse werden verarbeitet...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "Neue Sitzung",
"agentInputPlaceholder": "Nachricht eingeben, Enter zum Senden...",
"agentSend": "Senden",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Reject",
"agentThinkingAnalyzing": "Analyzing your request...",
"agentThinkingProcessing": "Processing results...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "New Session",
"agentInputPlaceholder": "Type a message, Enter to send...",
"agentSend": "Send",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Rechazar",
"agentThinkingAnalyzing": "Analizando tu solicitud...",
"agentThinkingProcessing": "Procesando resultados...",
"agentChat": "AI Agent",
"agentChat": "Agente",
"agentNewSession": "Nueva sesión",
"agentInputPlaceholder": "Escribe un mensaje, Enter para enviar...",
"agentSend": "Enviar",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Rejeter",
"agentThinkingAnalyzing": "Analyse de votre demande...",
"agentThinkingProcessing": "Traitement des résultats...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "Nouvelle session",
"agentInputPlaceholder": "Tapez un message, Entrée pour envoyer...",
"agentSend": "Envoyer",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "דחה",
"agentThinkingAnalyzing": "מנתח את הבקשה שלך...",
"agentThinkingProcessing": "מעבד תוצאות...",
"agentChat": "AI Agent",
"agentChat": "סוכן",
"agentNewSession": "הפעלה חדשה",
"agentInputPlaceholder": "הקלד הודעה, Enter לשליחה...",
"agentSend": "שלח",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "अस्वीकृत करें",
"agentThinkingAnalyzing": "आपके अनुरोध का विश्लेषण...",
"agentThinkingProcessing": "परिणाम संसाधित कर रहा है...",
"agentChat": "AI Agent",
"agentChat": "एजेंट",
"agentNewSession": "नया सत्र",
"agentInputPlaceholder": "संदेश लिखें, Enter भेजने के लिए...",
"agentSend": "भेजें",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Tolak",
"agentThinkingAnalyzing": "Menganalisis permintaan Anda...",
"agentThinkingProcessing": "Memproses hasil...",
"agentChat": "AI Agent",
"agentChat": "Agen",
"agentNewSession": "Sesi baru",
"agentInputPlaceholder": "Ketik pesan, Enter untuk mengirim...",
"agentSend": "Kirim",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Rifiuta",
"agentThinkingAnalyzing": "Analisi della richiesta...",
"agentThinkingProcessing": "Elaborazione risultati...",
"agentChat": "AI Agent",
"agentChat": "Agente",
"agentNewSession": "Nuova sessione",
"agentInputPlaceholder": "Digita un messaggio, Invio per inviare...",
"agentSend": "Invia",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "拒否",
"agentThinkingAnalyzing": "リクエストを分析中...",
"agentThinkingProcessing": "結果を処理中...",
"agentChat": "AI Agent",
"agentChat": "エージェント",
"agentNewSession": "新しいセッション",
"agentInputPlaceholder": "メッセージを入力、Enterで送信...",
"agentSend": "送信",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "거부",
"agentThinkingAnalyzing": "요청 분석 중...",
"agentThinkingProcessing": "결과 처리 중...",
"agentChat": "AI Agent",
"agentChat": "에이전트",
"agentNewSession": "새 세션",
"agentInputPlaceholder": "메시지를 입력하고 Enter로 전송...",
"agentSend": "보내기",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Afwijzen",
"agentThinkingAnalyzing": "Verzoek analyseren...",
"agentThinkingProcessing": "Resultaten verwerken...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "Nieuwe sessie",
"agentInputPlaceholder": "Typ een bericht, Enter om te verzenden...",
"agentSend": "Verzenden",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Odrzuć",
"agentThinkingAnalyzing": "Analizowanie żądania...",
"agentThinkingProcessing": "Przetwarzanie wyników...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "Nowa sesja",
"agentInputPlaceholder": "Wpisz wiadomość, Enter aby wysłać...",
"agentSend": "Wyślij",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Rejeitar",
"agentThinkingAnalyzing": "Analisando sua solicitação...",
"agentThinkingProcessing": "Processando resultados...",
"agentChat": "AI Agent",
"agentChat": "Agente",
"agentNewSession": "Nova sessão",
"agentInputPlaceholder": "Digite uma mensagem, Enter para enviar...",
"agentSend": "Enviar",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Отклонить",
"agentThinkingAnalyzing": "Анализ запроса...",
"agentThinkingProcessing": "Обработка результатов...",
"agentChat": "AI Agent",
"agentChat": "Агент",
"agentNewSession": "Новая сессия",
"agentInputPlaceholder": "Введите сообщение, Enter для отправки...",
"agentSend": "Отправить",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Odmietnuť",
"agentThinkingAnalyzing": "Analyzovanie požiadavky...",
"agentThinkingProcessing": "Spracovanie výsledkov...",
"agentChat": "AI Agent",
"agentChat": "Agent",
"agentNewSession": "Nová relácia",
"agentInputPlaceholder": "Napíšte správu, Enter na odoslanie...",
"agentSend": "Odoslať",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "ปฏิเสธ",
"agentThinkingAnalyzing": "กำลังวิเคราะห์คำขอ...",
"agentThinkingProcessing": "กำลังประมวลผล...",
"agentChat": "AI Agent",
"agentChat": "เอเจนต์",
"agentNewSession": "เซสชันใหม่",
"agentInputPlaceholder": "พิมพ์ข้อความ กด Enter เพื่อส่ง...",
"agentSend": "ส่ง",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Reddet",
"agentThinkingAnalyzing": "İsteğiniz analiz ediliyor...",
"agentThinkingProcessing": "Sonuçlar işleniyor...",
"agentChat": "AI Agent",
"agentChat": "Ajan",
"agentNewSession": "Yeni oturum",
"agentInputPlaceholder": "Mesaj yazın, Enter ile gönderin...",
"agentSend": "Gönder",
+1 -1
View File
@@ -4,7 +4,7 @@
"agentConfirmReject": "Відхилити",
"agentThinkingAnalyzing": "Аналіз запиту...",
"agentThinkingProcessing": "Обробка результатів...",
"agentChat": "AI Agent",
"agentChat": "Агент",
"agentNewSession": "Нова сесія",
"agentInputPlaceholder": "Введіть повідомлення, Enter для надсилання...",
"agentSend": "Надіслати",
+2 -2
View File
@@ -4,8 +4,8 @@
"agentConfirmReject": "拒絕",
"agentThinkingAnalyzing": "正在分析你的請求...",
"agentThinkingProcessing": "正在處理結果...",
"agentChat": "AI Agent",
"agentNewSession": "新對話",
"agentChat": "智能體",
"agentNewSession": "新會話",
"agentInputPlaceholder": "輸入訊息,Enter 送出...",
"agentSend": "送出",
"agentStop": "停止",
+2 -2
View File
@@ -4,8 +4,8 @@
"agentConfirmReject": "拒绝",
"agentThinkingAnalyzing": "正在分析你的请求...",
"agentThinkingProcessing": "正在处理结果...",
"agentChat": "AI Agent",
"agentNewSession": "新对话",
"agentChat": "智能体",
"agentNewSession": "新会话",
"agentInputPlaceholder": "输入消息,回车发送...",
"agentSend": "发送",
"agentStop": "停止",
@@ -6,6 +6,7 @@
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
padding: 8px 12px;
border-bottom: 1px solid var(--b3-border-color);
min-height: 36px;
@@ -324,3 +325,100 @@
gap: 8px;
margin-top: 6px;
}
.agent-chat__session-menu {
font-size: 14px;
padding: 2px 6px;
line-height: 1;
}
.agent-session-popup {
position: absolute;
top: 40px;
right: 8px;
z-index: 100;
width: 280px;
max-height: 300px;
overflow-y: auto;
background: var(--b3-theme-background);
border: 1px solid var(--b3-border-color);
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}
.agent-session-popup__list {
padding: 4px 0;
}
.agent-session-popup__item {
display: flex;
align-items: center;
padding: 8px 12px;
cursor: pointer;
border-bottom: 1px solid var(--b3-border-color);
}
.agent-session-popup__item:last-child {
border-bottom: none;
}
.agent-session-popup__item:hover {
background: var(--b3-theme-surface-light);
}
.agent-session-popup__item--active {
background: var(--b3-theme-primary-lightest);
}
.agent-session-popup__title {
flex: 1;
font-size: 13px;
color: var(--b3-theme-on-background);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-session-popup__actions {
display: flex;
gap: 8px;
flex-shrink: 0;
margin-left: 8px;
}
.agent-session-popup__rename,
.agent-session-popup__delete {
font-size: 13px;
cursor: pointer;
padding: 2px 4px;
border-radius: 4px;
color: var(--b3-theme-on-surface-light);
}
.agent-session-popup__rename:hover,
.agent-session-popup__delete:hover {
background: var(--b3-theme-surface-light);
color: var(--b3-theme-on-surface);
}
.agent-session-popup__delete:hover {
color: var(--b3-theme-error);
}
.agent-session-popup__rename-input {
flex: 1;
font-size: 13px;
padding: 2px 4px;
border: 1px solid var(--b3-theme-primary);
border-radius: 4px;
outline: none;
background: var(--b3-theme-background);
color: var(--b3-theme-on-background);
}
.agent-session-popup__empty {
padding: 16px;
text-align: center;
font-size: 13px;
color: var(--b3-theme-on-surface-light);
}
@@ -51,9 +51,37 @@
font-size: 13px;
color: var(--b3-theme-on-background);
cursor: pointer;
white-space: nowrap;
line-height: 1.4;
}
.agent-mention-menu__first {
display: flex;
align-items: center;
gap: 6px;
overflow: hidden;
}
.agent-mention-menu__icon {
width: 14px;
height: 14px;
flex-shrink: 0;
color: var(--b3-theme-on-surface-light);
}
.agent-mention-menu__text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-mention-menu__hpath {
font-size: 11px;
color: var(--b3-theme-on-surface-light);
margin-top: 2px;
margin-left: 20px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-mention-menu__item:hover,
+1 -1
View File
@@ -65,7 +65,7 @@ export const onGetConfig = (isStart: boolean, app: App) => {
if (section[i] && section[i].type === "agentChat") { found = true; break; }
}
if (!found) {
section.unshift({type: "agentChat", size: {width: 340, height: 0}, show: false, icon: "iconSparkles", title: "AI Agent"});
section.unshift({type: "agentChat", size: {width: 340, height: 0}, show: false, icon: "iconSparkles", hotkeyLangId: "agentChat"});
}
}
}
+1 -1
View File
@@ -725,7 +725,7 @@ export abstract class Constants {
size: {width: 320, height: 0},
show: false,
icon: "iconSparkles",
title: "AI Agent",
hotkeyLangId: "agentChat",
}, {
type: "graph",
size: {width: 320, height: 0},
@@ -1,8 +1,9 @@
import {Tab} from "../layout/Tab";
import {Model} from "../layout/Model";
import {App} from "../index";
import {fetchAgentSSE, ISSEResult} from "../util/agentSSE";
import {Tab} from "../Tab";
import {Model} from "../Model";
import {App} from "../../index";
import {fetchAgentSSE, ISSEResult} from "../../util/agentSSE";
import {mountComposer} from "./AgentComposer";
import {AgentSession, SessionStore} from "./SessionStore";
interface IAgentMessage {
role: "user" | "assistant";
@@ -17,6 +18,10 @@ export class AgentChat extends Model {
private stopBtn: HTMLElement;
private newSessionBtn: HTMLElement;
private titleElement: HTMLElement;
private sessionMenuBtn: HTMLElement;
private sessionPopup: HTMLElement | null = null;
private sessionId = "";
private sessionTitle = "AI Agent";
private messages: IAgentMessage[] = [];
private hasTitled = false;
private isStreaming = false;
@@ -41,6 +46,7 @@ export class AgentChat extends Model {
panel.innerHTML = '<div class="agent-chat fn__flex-column fn__flex-1">' +
'<div class="agent-chat__header">' +
'<span class="agent-chat__title">' + (L.agentChat || "AI Agent") + '</span>' +
'<button class="agent-chat__session-menu b3-button b3-button--small b3-button--text">&#9776;</button>' +
'<button class="agent-chat__new-session b3-button b3-button--small b3-button--outline">' + (L.agentNewSession || "New Session") + '</button>' +
'</div>' +
'<div class="agent-chat__messages fn__flex-1"></div>' +
@@ -59,22 +65,243 @@ export class AgentChat extends Model {
this.stopBtn = panel.querySelector(".agent-chat__stop") as HTMLElement;
this.newSessionBtn = panel.querySelector(".agent-chat__new-session") as HTMLElement;
this.titleElement = panel.querySelector(".agent-chat__title") as HTMLElement;
this.sessionMenuBtn = panel.querySelector(".agent-chat__session-menu") as HTMLElement;
var self = this;
this.composer = mountComposer(this.composerHost, function () { self.sendMessage(); });
this.initSessions();
}
private bindEvents() {
var self = this;
this.sendBtn.addEventListener("click", function () { self.sendMessage(); });
this.stopBtn.addEventListener("click", function () { self.stopGeneration(); });
this.newSessionBtn.addEventListener("click", function () { self.clearSession(); });
this.newSessionBtn.addEventListener("click", function () { self.createSession(); });
this.sessionMenuBtn.addEventListener("click", function (e: MouseEvent) {
e.stopPropagation();
self.toggleSessionMenu();
});
this.parent.panelElement.addEventListener("click", function () {
self.composer?.focus();
});
}
private async initSessions() {
await SessionStore.init();
var list = await SessionStore.list();
if (list.length > 0) {
list.sort(function (a, b) { return b.updatedAt - a.updatedAt; });
var last = list[0];
var session = await SessionStore.load(last.id);
if (session) {
this.sessionId = session.id;
this.sessionTitle = session.title;
this.messages = session.messages;
this.hasTitled = true;
this.titleElement.textContent = session.title;
for (var i = 0; i < session.messages.length; i++) {
var msg = session.messages[i];
if (msg.role === "user") {
this.appendUserMessage(msg.content);
} else if (msg.role === "assistant") {
this.appendPersistedAssistant(msg.content);
}
}
this.scrollToBottom();
return;
}
}
this.sessionId = SessionStore.newSessionId();
this.sessionTitle = "AI Agent";
this.messages = [];
}
private toggleSessionMenu() {
if (this.sessionPopup) {
this.closeSessionMenu();
return;
}
var self = this;
this.renderSessionList();
}
private closeSessionMenu() {
if (this.sessionPopup) {
this.sessionPopup.remove();
this.sessionPopup = null;
}
}
private async renderSessionList() {
var self = this;
this.closeSessionMenu();
var list = await SessionStore.list();
list.sort(function (a, b) { return b.updatedAt - a.updatedAt; });
this.sessionPopup = document.createElement("div");
this.sessionPopup.className = "agent-session-popup";
var html = '<div class="agent-session-popup__list">';
if (list.length === 0) {
html += '<div class="agent-session-popup__empty">' + (window.siyuan.languages.emptyContent || "No sessions") + '</div>';
} else {
for (var i = 0; i < list.length; i++) {
var s = list[i];
var isActive = s.id === this.sessionId;
html += '<div class="agent-session-popup__item' + (isActive ? ' agent-session-popup__item--active' : '') + '" data-id="' + s.id + '">' +
'<span class="agent-session-popup__title">' + this.escapeHtml(s.title || "AI Agent") + '</span>' +
'<span class="agent-session-popup__actions">' +
'<span class="agent-session-popup__rename" data-id="' + s.id + '">&#9998;</span>' +
'<span class="agent-session-popup__delete" data-id="' + s.id + '">&#10005;</span>' +
'</span>' +
'</div>';
}
}
html += '</div>';
this.sessionPopup.innerHTML = html;
this.sessionPopup.querySelectorAll(".agent-session-popup__item").forEach(function (item) {
item.addEventListener("click", function (e) {
var id = item.getAttribute("data-id") || "";
if (id && id !== self.sessionId) {
self.switchSession(id);
self.closeSessionMenu();
}
});
});
this.sessionPopup.querySelectorAll(".agent-session-popup__delete").forEach(function (btn) {
btn.addEventListener("click", function (e: MouseEvent) {
e.stopPropagation();
var id = btn.getAttribute("data-id") || "";
if (id) { self.deleteSession(id); }
});
});
this.sessionPopup.querySelectorAll(".agent-session-popup__rename").forEach(function (btn) {
btn.addEventListener("click", function (e: MouseEvent) {
e.stopPropagation();
var id = btn.getAttribute("data-id") || "";
if (id) {
var parent = btn.parentElement;
var row = parent ? parent.parentElement as HTMLElement : null;
if (row) { self.startRename(id, row); }
}
});
});
this.parent.panelElement.appendChild(this.sessionPopup);
var self2 = this;
this.sessionPopup.addEventListener("click", function (e: MouseEvent) {
e.stopPropagation();
});
setTimeout(function () {
document.addEventListener("click", function closeOut() {
self2.closeSessionMenu();
document.removeEventListener("click", closeOut);
});
}, 10);
}
private startRename(id: string, rowEl: HTMLElement) {
var self = this;
var titleEl = rowEl.querySelector(".agent-session-popup__title") as HTMLElement;
var oldTitle = titleEl.textContent || "";
var input = document.createElement("input");
input.type = "text";
input.value = oldTitle;
input.className = "agent-session-popup__rename-input";
titleEl.replaceWith(input);
input.focus();
input.select();
input.addEventListener("blur", function () { self.finishRename(id, input.value, input, titleEl); });
input.addEventListener("keydown", function (e: KeyboardEvent) {
if (e.key === "Enter") { input.blur(); }
if (e.key === "Escape") { input.value = oldTitle; input.blur(); }
});
}
private async finishRename(id: string, newTitle: string, input: HTMLInputElement, titleEl: HTMLElement) {
var title = newTitle.trim() || "AI Agent";
input.replaceWith(titleEl);
titleEl.textContent = title;
await SessionStore.rename(id, title);
if (id === this.sessionId) {
this.sessionTitle = title;
this.titleElement.textContent = title;
}
}
private async saveSession() {
if (this.messages.length === 0) { return; }
var session: AgentSession = {
id: this.sessionId,
title: this.sessionTitle,
messages: this.messages.slice(),
createdAt: Date.now(),
updatedAt: Date.now(),
};
await SessionStore.save(session);
}
private async switchSession(id: string) {
await this.saveSession();
var session = await SessionStore.load(id);
if (!session) { return; }
this.sessionId = session.id;
this.sessionTitle = session.title;
this.messages = session.messages;
this.hasTitled = true;
this.currentAIElement = null;
this.currentContent = "";
this.messagesContainer.innerHTML = "";
this.titleElement.textContent = session.title;
for (var i = 0; i < session.messages.length; i++) {
var msg = session.messages[i];
if (msg.role === "user") {
this.appendUserMessage(msg.content);
} else if (msg.role === "assistant") {
this.appendPersistedAssistant(msg.content);
}
}
this.scrollToBottom();
}
private appendPersistedAssistant(content: string) {
var el = document.createElement("div");
el.className = "agent-chat__msg agent-chat__msg--ai";
el.innerHTML = '<div class="agent-chat__bubble">' + (this.lute.MarkdownStr("", content) || this.escapeHtml(content)) + '</div>';
this.messagesContainer.appendChild(el);
}
private async createSession() {
await this.saveSession();
this.sessionId = SessionStore.newSessionId();
this.sessionTitle = "AI Agent";
this.messages = [];
this.hasTitled = false;
this.currentAIElement = null;
this.currentContent = "";
this.messagesContainer.innerHTML = "";
this.titleElement.textContent = "AI Agent";
if (this.composer) { this.composer.clear(); }
this.composer?.focus();
}
private async deleteSession(id: string) {
this.closeSessionMenu();
await SessionStore.remove(id);
if (id === this.sessionId) {
var list = await SessionStore.list();
if (list.length > 0) {
await this.switchSession(list[0].id);
} else {
await this.createSession();
}
}
}
private sendMessage() {
if (!this.composer) { return; }
var sendData = this.composer.getSendData();
@@ -290,6 +517,7 @@ export class AgentChat extends Model {
this.hasTitled = true;
this.generateTitle();
}
this.saveSession();
}
private generateTitle() {
@@ -300,8 +528,10 @@ export class AgentChat extends Model {
headers: {"Content-Type": "application/json"},
body: JSON.stringify({message: firstMsg}),
}).then(function (resp) { return resp.json(); }).then(function (data) {
if (data.code === 0 && data.data) {
if (data.code === 0 && data.data && data.data !== self.sessionTitle) {
self.sessionTitle = data.data;
self.titleElement.textContent = data.data;
self.saveSession();
}
});
}
@@ -320,6 +550,7 @@ export class AgentChat extends Model {
}
this.currentAIElement = null;
this.scrollToBottom();
this.saveSession();
}
private stopGeneration() {
@@ -413,17 +644,6 @@ export class AgentChat extends Model {
}
}
private clearSession() {
this.messages = [];
this.currentAIElement = null;
this.currentContent = "";
this.hasTitled = false;
this.messagesContainer.innerHTML = "";
this.titleElement.textContent = "AI Agent";
if (this.composer) { this.composer.clear(); }
this.composer?.focus();
}
private setStreaming(streaming: boolean) {
this.isStreaming = streaming;
this.sendBtn.classList.toggle("fn__none", streaming);
@@ -6,10 +6,13 @@ import HardBreak from "@tiptap/extension-hard-break";
import Mention from "@tiptap/extension-mention";
import {Placeholder} from "@tiptap/extension-placeholder";
import {History} from "@tiptap/extension-history";
import {getIconByType} from "../../editor/getIcon";
interface BlockHit {
id: string;
label: string;
icon: string;
hPath: string;
}
interface ComposerHandle {
@@ -20,7 +23,14 @@ interface ComposerHandle {
}
export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHandle {
const L = window.siyuan.languages;
var L = window.siyuan.languages;
var escapeHtmlHelper = function (text: string): string {
var div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
};
let suggestionMenu: HTMLElement | null = null;
let selectedIndex = 0;
let suggestionCommand: ((item: BlockHit) => void) | null = null;
@@ -55,7 +65,9 @@ export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHa
var row = document.createElement("div");
row.className = "agent-mention-menu__item";
row.setAttribute("data-index", i.toString());
row.textContent = item.label;
var iconSvg = item.icon ? '<svg class="agent-mention-menu__icon"><use xlink:href="#' + item.icon + '"></use></svg>' : '';
var hPathText = item.hPath ? '<div class="agent-mention-menu__hpath">' + escapeHtmlHelper(item.hPath) + '</div>' : '';
row.innerHTML = '<div class="agent-mention-menu__first">' + iconSvg + '<span class="agent-mention-menu__text">' + escapeHtmlHelper(item.label) + '</span></div>' + hPathText;
row.addEventListener("mousedown", function (hit: BlockHit) {
return function (e: MouseEvent) { e.preventDefault(); command(hit); };
}(item));
@@ -101,17 +113,24 @@ export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHa
char: "@",
items: async function ({query}): Promise<BlockHit[]> {
try {
var resp = await fetch("/api/filetree/searchDocs", {
var resp = await fetch("/api/search/searchRefBlock", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({k: query}),
body: JSON.stringify({k: query, id: "", rootID: "", beforeLen: 48, isDatabase: false, isSquareBrackets: true}),
});
var data = await resp.json();
var items = data?.data || [];
return items.slice(0, 10).map(function (b: Record<string, unknown>) {
var blocks = data?.data?.blocks || [];
return blocks.slice(0, 10).map(function (b: Record<string, unknown>) {
var id = String(b.id || "");
var raw = String(b.content || b.refText || b.name || id);
var plain = raw.replace(/<[^>]+>/g, "").trim() || id;
var type = String(b.type || "NodeParagraph");
var sub = b.subType ? String(b.subType) : "";
return {
id: String(b.path || ""),
label: String(b.hPath || b.path || ""),
id: id,
label: plain.slice(0, 80),
icon: getIconByType(type, sub),
hPath: String(b.hPath || ""),
};
});
} catch (e) {
+160
View File
@@ -0,0 +1,160 @@
import {fetchSyncPost} from "../../util/fetch";
const SESSIONS_DIR = "data/storage/ai/agent/sessions/";
const SESSIONS_INDEX = SESSIONS_DIR + "index.json";
interface SessionIndexItem {
id: string;
title: string;
createdAt: number;
updatedAt: number;
}
export interface AgentSession {
id: string;
title: string;
messages: Array<{role: string; content: string}>;
createdAt: number;
updatedAt: number;
}
function newSessionId(): string {
return (window as any).Lute ? (window as any).Lute.NewNodeID() : Date.now().toString(36);
}
async function readTextFile(path: string): Promise<string | null> {
try {
var r = await fetchSyncPost("/api/file/getFile", {path: path}) as any;
console.log("[SS] getFile full response:", JSON.stringify(r));
if (!r || r.code !== 0 || !r.data || r.data === null) {
return null;
}
return r.data;
} catch (e) {
console.log("[SS] readText error:", path, e);
return null;
}
}
async function readJsonFile(path: string): Promise<any | null> {
var text = await readTextFile(path);
if (!text) { console.log("[SS] readJson null, path:", path); return null; }
try { return JSON.parse(text); } catch (e) { console.log("[SS] readJson parse err:", path, e); return null; }
}
async function writeJsonFile(path: string, data: any): Promise<void> {
var content = JSON.stringify(data, null, 2);
var fileName = path.split("/").pop() || "file.json";
var file = new File([new Blob([content], {type: "application/json"})], fileName);
var formData = new FormData();
formData.append("path", path);
formData.append("file", file);
formData.append("isDir", "false");
await fetchSyncPost("/api/file/putFile", formData);
}
async function ensureDir(): Promise<void> {
var idx = await readJsonFile(SESSIONS_INDEX);
if (idx && Array.isArray(idx)) { return; }
try {
var r = await fetchSyncPost("/api/file/readDir", {path: SESSIONS_DIR}) as any;
if (r && r.code === 0) {
await rebuildIndex();
return;
}
} catch (e) {
// readDir 失败,继续尝试创建
}
await writeJsonFile(SESSIONS_INDEX, []);
}
async function rebuildIndex(): Promise<void> {
try {
var r = await fetchSyncPost("/api/file/readDir", {path: SESSIONS_DIR}) as any;
if (!r || r.code !== 0 || !r.data) {
await writeJsonFile(SESSIONS_INDEX, []);
return;
}
var entries = r.data as Array<{name: string; updated: number}>;
var list: SessionIndexItem[] = [];
for (var i = 0; i < entries.length; i++) {
var name = entries[i].name;
if (name === "index.json" || !name.endsWith(".json")) { continue; }
var id = name.replace(".json", "");
var session = await readJsonFile(SESSIONS_DIR + name);
if (session && session.id && session.messages) {
list.push({
id: id,
title: session.title || "AI Agent",
createdAt: session.createdAt || entries[i].updated || Date.now(),
updatedAt: session.updatedAt || entries[i].updated || Date.now(),
});
}
}
await writeJsonFile(SESSIONS_INDEX, list);
} catch (e) {
console.warn("[SessionStore] rebuildIndex failed:", e);
await writeJsonFile(SESSIONS_INDEX, []);
}
}
async function writeIndex(list: SessionIndexItem[]): Promise<void> {
await writeJsonFile(SESSIONS_INDEX, list);
}
export const SessionStore = {
async init(): Promise<void> {
await ensureDir();
var idx = await readJsonFile(SESSIONS_INDEX);
if (!idx || !Array.isArray(idx)) {
await rebuildIndex();
}
},
async list(): Promise<SessionIndexItem[]> {
var idx = await readJsonFile(SESSIONS_INDEX);
return Array.isArray(idx) ? idx : [];
},
async load(id: string): Promise<AgentSession | null> {
return await readJsonFile(SESSIONS_DIR + id + ".json");
},
async save(session: AgentSession): Promise<void> {
session.updatedAt = Date.now();
await writeJsonFile(SESSIONS_DIR + session.id + ".json", session);
var list = await this.list();
var found = false;
for (var i = 0; i < list.length; i++) {
if (list[i].id === session.id) {
list[i].title = session.title;
list[i].updatedAt = session.updatedAt;
found = true;
break;
}
}
if (!found) {
list.unshift({id: session.id, title: session.title, createdAt: session.createdAt, updatedAt: session.updatedAt});
}
await writeIndex(list);
},
async remove(id: string): Promise<void> {
await fetchSyncPost("/api/file/removeFile", {path: SESSIONS_DIR + id + ".json"});
var list = await this.list();
list = list.filter(function (item: any) { return item.id !== id; });
await writeIndex(list);
},
async rename(id: string, newTitle: string): Promise<void> {
var session = await this.load(id);
if (!session) { return; }
session.title = newTitle;
await this.save(session);
},
newSessionId: newSessionId,
};
+1 -1
View File
@@ -14,7 +14,7 @@ import {getDockByType, resizeTabs, setTabPosition} from "../tabUtil";
import {Inbox} from "./Inbox";
import {Protyle} from "../../protyle";
import {Backlink} from "./Backlink";
import {AgentChat} from "../../ai/AgentChat";
import {AgentChat} from "./AgentChat";
import {adjustDockPadding, resetFloatDockSize} from "./util";
import {hasClosestByAttribute, hasClosestByClassName} from "../../protyle/util/hasClosest";
import {App} from "../../index";
+2 -1
View File
@@ -232,7 +232,8 @@ const initInternalDock = (dockItem: Config.IUILayoutDockTab[]) => {
}
if (existSubItem.hotkeyLangId) {
existSubItem.title = window.siyuan.languages[existSubItem.hotkeyLangId];
existSubItem.hotkey = window.siyuan.config.keymap.general[existSubItem.hotkeyLangId].custom;
var km = window.siyuan.config.keymap.general[existSubItem.hotkeyLangId];
existSubItem.hotkey = km ? km.custom : "";
}
});
};