Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Improve AI editing with streaming selection actions https://github.com/siyuan-note/siyuan/issues/10540

Daniel8ed3948345ec
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index f6c534390e..a2549b24b4 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "تجاهل",
+ "aiInsertAtCursor": "إدراج عند المؤشر",
+ "aiInsertAtOriginal": "إدراج في الموضع الأصلي",
+ "aiSourceChanged": "تم تغيير المحتوى المصدر",
+ "aiStopped": "تم الإيقاف",
+ "aiReplaceCurrentTask": "هل تريد إيقاف مهمة تحرير الذكاء الاصطناعي الحالية وبدء مهمة جديدة؟",
"orderedListStart": "رقم البداية",
"continueListNumbering": "متابعة ترقيم القائمة",
"msgFormatPainterTip": "إشعارات تنشيط نسخ التنسيق والخروج منه",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 999e063e81..986d82b44d 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Verwerfen",
+ "aiInsertAtCursor": "An der Einfügemarke einfügen",
+ "aiInsertAtOriginal": "An der ursprünglichen Position einfügen",
+ "aiSourceChanged": "Quellinhalt wurde geändert",
+ "aiStopped": "Angehalten",
+ "aiReplaceCurrentTask": "Aktuelle KI-Bearbeitungsaufgabe anhalten und eine neue starten?",
"orderedListStart": "Startnummer",
"continueListNumbering": "Listennummerierung fortsetzen",
"msgFormatPainterTip": "Benachrichtigungen beim Aktivieren und Beenden der Formatübertragung",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index ce8c623096..f80e731358 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Discard",
+ "aiInsertAtCursor": "Insert at cursor",
+ "aiInsertAtOriginal": "Insert at original position",
+ "aiSourceChanged": "Source content changed",
+ "aiStopped": "Stopped",
+ "aiReplaceCurrentTask": "Stop the current AI editing task and start a new one?",
"orderedListStart": "Starting number",
"continueListNumbering": "Continue list numbering",
"msgFormatPainterTip": "Format Painter activation and exit notifications",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index e346656e86..5830c7edd4 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Descartar",
+ "aiInsertAtCursor": "Insertar en el cursor",
+ "aiInsertAtOriginal": "Insertar en la posición original",
+ "aiSourceChanged": "El contenido de origen cambió",
+ "aiStopped": "Detenido",
+ "aiReplaceCurrentTask": "¿Detener la tarea actual de edición con IA e iniciar una nueva?",
"orderedListStart": "Número inicial",
"continueListNumbering": "Continuar numeración de la lista",
"msgFormatPainterTip": "Notificaciones al activar y desactivar Copiar formato",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 092195ea39..f08c6480c6 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Ignorer",
+ "aiInsertAtCursor": "Insérer au curseur",
+ "aiInsertAtOriginal": "Insérer à la position d’origine",
+ "aiSourceChanged": "Le contenu source a été modifié",
+ "aiStopped": "Arrêté",
+ "aiReplaceCurrentTask": "Arrêter la tâche d’édition par IA actuelle et en démarrer une nouvelle ?",
"orderedListStart": "Numéro de départ",
"continueListNumbering": "Continuer la numérotation de la liste",
"msgFormatPainterTip": "Notifications d’activation et de désactivation de la reproduction de mise en forme",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 86a5fc3705..efb1605eb7 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "ביטול",
+ "aiInsertAtCursor": "הוספה במיקום הסמן",
+ "aiInsertAtOriginal": "הוספה במיקום המקורי",
+ "aiSourceChanged": "תוכן המקור השתנה",
+ "aiStopped": "נעצר",
+ "aiReplaceCurrentTask": "לעצור את משימת עריכת הבינה המלאכותית הנוכחית ולהתחיל משימה חדשה?",
"orderedListStart": "מספר התחלתי",
"continueListNumbering": "המשך מספור הרשימה",
"msgFormatPainterTip": "התראות על הפעלה ויציאה ממברשת העיצוב",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 0559b90187..a4eb421952 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "त्यागें",
+ "aiInsertAtCursor": "कर्सर पर डालें",
+ "aiInsertAtOriginal": "मूल स्थान पर डालें",
+ "aiSourceChanged": "स्रोत सामग्री बदल गई है",
+ "aiStopped": "रोक दिया गया",
+ "aiReplaceCurrentTask": "वर्तमान AI संपादन कार्य रोककर नया कार्य शुरू करें?",
"orderedListStart": "प्रारंभिक संख्या",
"continueListNumbering": "सूची क्रमांकन जारी रखें",
"msgFormatPainterTip": "फ़ॉर्मैट पेंटर चालू करने और बाहर निकलने की सूचनाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 7fa554db72..2167ff2501 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Buang",
+ "aiInsertAtCursor": "Sisipkan di kursor",
+ "aiInsertAtOriginal": "Sisipkan di posisi semula",
+ "aiSourceChanged": "Konten sumber telah berubah",
+ "aiStopped": "Dihentikan",
+ "aiReplaceCurrentTask": "Hentikan tugas penyuntingan AI saat ini dan mulai tugas baru?",
"orderedListStart": "Nomor awal",
"continueListNumbering": "Lanjutkan penomoran daftar",
"msgFormatPainterTip": "Notifikasi aktivasi dan keluar penyalinan format",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 726016644b..b94c796ab5 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Scarta",
+ "aiInsertAtCursor": "Inserisci al cursore",
+ "aiInsertAtOriginal": "Inserisci nella posizione originale",
+ "aiSourceChanged": "Il contenuto di origine è cambiato",
+ "aiStopped": "Interrotto",
+ "aiReplaceCurrentTask": "Interrompere l’attività di modifica IA corrente e avviarne una nuova?",
"orderedListStart": "Numero iniziale",
"continueListNumbering": "Continua la numerazione dell'elenco",
"msgFormatPainterTip": "Notifiche di attivazione e uscita di Copia formato",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index c3e0829b60..954f7f1cf9 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "破棄",
+ "aiInsertAtCursor": "現在のカーソル位置に挿入",
+ "aiInsertAtOriginal": "元の位置に挿入",
+ "aiSourceChanged": "元の内容が変更されました",
+ "aiStopped": "停止しました",
+ "aiReplaceCurrentTask": "現在の AI 編集タスクを停止して新しいタスクを開始しますか?",
"orderedListStart": "開始番号",
"continueListNumbering": "リストの番号を継続",
"msgFormatPainterTip": "書式のコピーの有効化と終了の通知",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 19fb105df6..6b79eabf38 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "버리기",
+ "aiInsertAtCursor": "현재 커서 위치에 삽입",
+ "aiInsertAtOriginal": "원래 위치에 삽입",
+ "aiSourceChanged": "원본 내용이 변경됨",
+ "aiStopped": "중지됨",
+ "aiReplaceCurrentTask": "현재 AI 편집 작업을 중지하고 새 작업을 시작할까요?",
"orderedListStart": "시작 번호",
"continueListNumbering": "목록 번호 계속",
"msgFormatPainterTip": "서식 복사 활성화 및 종료 알림",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 0695af2f90..7dda8ae433 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Verwerpen",
+ "aiInsertAtCursor": "Invoegen bij cursor",
+ "aiInsertAtOriginal": "Invoegen op oorspronkelijke positie",
+ "aiSourceChanged": "Broninhoud is gewijzigd",
+ "aiStopped": "Gestopt",
+ "aiReplaceCurrentTask": "De huidige AI-bewerking stoppen en een nieuwe starten?",
"orderedListStart": "Startnummer",
"continueListNumbering": "Lijstnummering voortzetten",
"msgFormatPainterTip": "Meldingen bij activeren en afsluiten van Opmaak kopiëren",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index da727afdcc..b3c1888204 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Odrzuć",
+ "aiInsertAtCursor": "Wstaw przy kursorze",
+ "aiInsertAtOriginal": "Wstaw w pierwotnym miejscu",
+ "aiSourceChanged": "Treść źródłowa została zmieniona",
+ "aiStopped": "Zatrzymano",
+ "aiReplaceCurrentTask": "Zatrzymać bieżące zadanie edycji AI i rozpocząć nowe?",
"orderedListStart": "Numer początkowy",
"continueListNumbering": "Kontynuuj numerację listy",
"msgFormatPainterTip": "Powiadomienia o włączeniu i wyłączeniu Malarza formatów",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 3b5f2f2607..6c4f6b6cc1 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Descartar",
+ "aiInsertAtCursor": "Inserir no cursor",
+ "aiInsertAtOriginal": "Inserir na posição original",
+ "aiSourceChanged": "O conteúdo de origem foi alterado",
+ "aiStopped": "Interrompido",
+ "aiReplaceCurrentTask": "Interromper a tarefa atual de edição com IA e iniciar uma nova?",
"orderedListStart": "Número inicial",
"continueListNumbering": "Continuar numeração da lista",
"msgFormatPainterTip": "Notificações ao ativar e sair do Pincel de formatação",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index eaea4a4c12..086a107e12 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Отбросить",
+ "aiInsertAtCursor": "Вставить в позицию курсора",
+ "aiInsertAtOriginal": "Вставить в исходную позицию",
+ "aiSourceChanged": "Исходное содержимое изменено",
+ "aiStopped": "Остановлено",
+ "aiReplaceCurrentTask": "Остановить текущую задачу редактирования ИИ и начать новую?",
"orderedListStart": "Начальный номер",
"continueListNumbering": "Продолжить нумерацию списка",
"msgFormatPainterTip": "Уведомления о включении и отключении формата по образцу",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 94a83942a5..1a1b50d7c5 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Zahodiť",
+ "aiInsertAtCursor": "Vložiť na pozíciu kurzora",
+ "aiInsertAtOriginal": "Vložiť na pôvodné miesto",
+ "aiSourceChanged": "Zdrojový obsah bol zmenený",
+ "aiStopped": "Zastavené",
+ "aiReplaceCurrentTask": "Zastaviť aktuálnu úlohu úprav pomocou AI a spustiť novú?",
"orderedListStart": "Počiatočné číslo",
"continueListNumbering": "Pokračovať v číslovaní zoznamu",
"msgFormatPainterTip": "Upozornenia na aktiváciu a ukončenie kopírovania formátu",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index d8d1c365b2..0d035339fc 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "ละทิ้ง",
+ "aiInsertAtCursor": "แทรกที่เคอร์เซอร์",
+ "aiInsertAtOriginal": "แทรกที่ตำแหน่งเดิม",
+ "aiSourceChanged": "เนื้อหาต้นฉบับมีการเปลี่ยนแปลง",
+ "aiStopped": "หยุดแล้ว",
+ "aiReplaceCurrentTask": "หยุดงานแก้ไขด้วย AI ปัจจุบันและเริ่มงานใหม่หรือไม่?",
"orderedListStart": "หมายเลขเริ่มต้น",
"continueListNumbering": "ดำเนินการลำดับเลขรายการต่อ",
"msgFormatPainterTip": "การแจ้งเตือนเมื่อเปิดและออกจากการคัดลอกรูปแบบ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 11a0ad8694..05acfa10c8 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "At",
+ "aiInsertAtCursor": "İmleç konumuna ekle",
+ "aiInsertAtOriginal": "Özgün konuma ekle",
+ "aiSourceChanged": "Kaynak içerik değişti",
+ "aiStopped": "Durduruldu",
+ "aiReplaceCurrentTask": "Geçerli AI düzenleme görevini durdurup yeni bir görev başlatmak ister misiniz?",
"orderedListStart": "Başlangıç numarası",
"continueListNumbering": "Liste numaralandırmasına devam et",
"msgFormatPainterTip": "Biçim Boyacısını etkinleştirme ve kapatma bildirimleri",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 8eeec795ea..8732482bc9 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "Відкинути",
+ "aiInsertAtCursor": "Вставити в позицію курсора",
+ "aiInsertAtOriginal": "Вставити у вихідну позицію",
+ "aiSourceChanged": "Вихідний вміст змінено",
+ "aiStopped": "Зупинено",
+ "aiReplaceCurrentTask": "Зупинити поточне завдання редагування ШІ та почати нове?",
"orderedListStart": "Початковий номер",
"continueListNumbering": "Продовжити нумерацію списку",
"msgFormatPainterTip": "Сповіщення про ввімкнення та вимкнення формату за зразком",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index bb7fb570be..e0035c7846 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "丢弃",
+ "aiInsertAtCursor": "在当前光标处插入",
+ "aiInsertAtOriginal": "在原位置插入",
+ "aiSourceChanged": "原内容已更改",
+ "aiStopped": "已停止",
+ "aiReplaceCurrentTask": "停止当前智能编辑任务并开始新任务?",
"orderedListStart": "起始编号",
"continueListNumbering": "继续编号",
"msgFormatPainterTip": "格式刷启用和退出提示",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index f2769d7574..0603f45c81 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,10 @@
{
+ "aiDiscard": "捨棄",
+ "aiInsertAtCursor": "在目前游標處插入",
+ "aiInsertAtOriginal": "在原位置插入",
+ "aiSourceChanged": "原內容已變更",
+ "aiStopped": "已停止",
+ "aiReplaceCurrentTask": "停止目前智慧編輯任務並開始新任務?",
"orderedListStart": "起始編號",
"continueListNumbering": "繼續編號",
"msgFormatPainterTip": "格式刷啟用與退出提示",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
index df9864564d..6a45e3470b 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
@@ -6,7 +6,7 @@
"id": "20230304000547-ibldj1z",
"title": "Artificial Intelligence",
"type": "doc",
- "updated": "20260804233000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260804170002-24z0hpx",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -75,7 +75,7 @@
},
"Properties": {
"id": "20260804170004-9yg5i8j",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -204,7 +204,7 @@
},
"Properties": {
"id": "20260804170009-l87zz79",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -212,7 +212,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804170010-wxcjvxu",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -226,16 +226,16 @@
},
{
"Type": "NodeText",
- "Data": " to open the dialog, or use "
+ "Data": " to open the writing dialog. For AI editing, select text and choose "
},
{
"Type": "NodeTextMark",
"TextMarkType": "kbd",
- "TextMarkTextContent": "Artificial Intelligence"
+ "TextMarkTextContent": "AI Edit"
},
{
"Type": "NodeText",
- "Data": " in the block menu for more actions"
+ "Data": " in the selection toolbar, or choose it from the block menu. The result streams into a panel where you can replace or insert it, copy it, retry, stop, or discard it. Replacement is available only for a supported selection within one block. Cross-block selections, complex sources, and sources changed while generating can still use insertion."
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
index 13070a9a68..b864a8d9eb 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
@@ -6,7 +6,7 @@
"id": "20230303235619-ex5l63e",
"title": "人工智能",
"type": "doc",
- "updated": "20260804233000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260804170002-f53lzwu",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -75,7 +75,7 @@
},
"Properties": {
"id": "20260804170004-q7ds60m",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -212,7 +212,7 @@
},
"Properties": {
"id": "20260804170009-gz98pxs",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -220,7 +220,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804170010-nnv0eos",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -234,16 +234,16 @@
},
{
"Type": "NodeText",
- "Data": " 唤起对话框,或者通过块标菜单中的 "
+ "Data": " 唤起编写对话框。进行 AI 编辑时,划选文本后使用划选工具栏中的 "
},
{
"Type": "NodeTextMark",
"TextMarkType": "kbd",
- "TextMarkTextContent": "人工智能"
+ "TextMarkTextContent": "智能编辑"
},
{
"Type": "NodeText",
- "Data": " 执行更多操作"
+ "Data": ",或从块标菜单中选择智能编辑。结果将流式显示在面板中,可替换、插入、复制、重试、停止或丢弃。仅支持替换单块内的普通划选;跨块划选、复杂来源或生成期间发生变化的来源仍可使用插入。"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
index 065a7fe215..75d96bbbc3 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
@@ -6,7 +6,7 @@
"id": "20230304000829-9jwu3po",
"title": "人工智能",
"type": "doc",
- "updated": "20260804233000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260804170002-ffdgp2j",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -75,7 +75,7 @@
},
"Properties": {
"id": "20260804170004-xvmu96u",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -212,7 +212,7 @@
},
"Properties": {
"id": "20260804170009-5fzfiio",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -220,7 +220,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804170010-dvzeba4",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -234,16 +234,16 @@
},
{
"Type": "NodeText",
- "Data": " 喚起對話框,或者透過區塊標選單中的 "
+ "Data": " 喚起編寫對話框。進行 AI 編輯時,劃選文字後使用劃選工具列中的 "
},
{
"Type": "NodeTextMark",
"TextMarkType": "kbd",
- "TextMarkTextContent": "人工智能"
+ "TextMarkTextContent": "智慧編輯"
},
{
"Type": "NodeText",
- "Data": " 執行更多操作"
+ "Data": ",或從區塊標選單中選擇智慧編輯。結果會串流顯示在面板中,可取代、插入、複製、重試、停止或捨棄。僅支援取代單一區塊內的一般劃選;跨區塊劃選、複雜來源或產生期間發生變化的來源仍可使用插入。"
}
]
}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
index 849d06a6b6..71e079eac3 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
@@ -6,7 +6,7 @@
"id": "20240530101000-ei5t6tt",
"title": "人工知能",
"type": "doc",
- "updated": "20260804233000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260804170002-b4z0hyu",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -75,7 +75,7 @@
},
"Properties": {
"id": "20260804170004-pwxfq0o",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -204,7 +204,7 @@
},
"Properties": {
"id": "20260804170009-bubnkd1",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -212,7 +212,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804170010-5uzk823",
- "updated": "20260804180000"
+ "updated": "20260813120000"
},
"Children": [
{
@@ -222,16 +222,16 @@
},
{
"Type": "NodeText",
- "Data": " でダイアログを開くか、ブロックメニューの "
+ "Data": " でライティングダイアログを開きます。AI 編集では、テキストを選択して選択ツールバーの "
},
{
"Type": "NodeTextMark",
"TextMarkType": "kbd",
- "TextMarkTextContent": "AI を呼び出す"
+ "TextMarkTextContent": "AI Edit"
},
{
"Type": "NodeText",
- "Data": " からその他の操作を実行します"
+ "Data": " を使うか、ブロックメニューから AI Edit を選びます。結果はパネルにストリーミング表示され、置換、挿入、コピー、再試行、停止、破棄ができます。置換できるのは、単一ブロック内の対応した選択範囲だけです。ブロックをまたぐ選択範囲、複雑な元データ、生成中に変更された元データには、引き続き挿入を使用できます。"
}
]
}
diff --git a/app/src/ai/actions.ts b/app/src/ai/actions.ts
index 456f8c6ed2..0d56b1cc40 100644
--- a/app/src/ai/actions.ts
+++ b/app/src/ai/actions.ts
@@ -1,17 +1,13 @@
import {fetchPost} from "../util/fetch";
-import {focusByRange, setLastNodeRange} from "../protyle/util/selection";
-import {insertHTML} from "../protyle/util/insertHTML";
+import {focusByRange} from "../protyle/util/selection";
import {Dialog} from "../dialog";
import {isMobile} from "../util/functions";
-import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";
-import {blockRender} from "../protyle/render/blockRender";
-import {processRender} from "../protyle/util/processCode";
-import {highlightRender} from "../protyle/render/highlightRender";
import {Constants} from "../constants";
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../util/escape";
import {showMessage} from "../dialog/message";
import {Menu} from "../plugin/Menu";
import {upDownHint} from "../util/upDownHint";
+import {clearAIEditorHistory, startAIEditorAction} from "./editor";
interface IAIEditorAction {
id: string;
@@ -19,18 +15,6 @@ interface IAIEditorAction {
action: string;
}
-export const fillContent = (protyle: IProtyle, data: string, elements: Element[]) => {
- if (!data) {
- return;
- }
- setLastNodeRange(getContenteditableElement(elements[elements.length - 1]), protyle.toolbar.range);
- protyle.toolbar.range.collapse(true);
- insertHTML(protyle.lute.SpinBlockDOM(data), protyle, true, true);
- blockRender(protyle, protyle.wysiwyg.element);
- processRender(protyle.wysiwyg.element);
- highlightRender(protyle.wysiwyg.element);
-};
-
const editDialog = (item: IAIEditorAction) => {
const dialog = new Dialog({
title: window.siyuan.languages.update,
@@ -79,7 +63,7 @@ const editDialog = (item: IAIEditorAction) => {
nameElement.focus();
};
-const customDialog = (protyle: IProtyle, ids: string[], elements: Element[]) => {
+const customDialog = (protyle: IProtyle, elements: HTMLElement[], range?: Range) => {
const dialog = new Dialog({
title: window.siyuan.languages.aiCustomAction,
content: `<div class="b3-dialog__content">
@@ -109,13 +93,8 @@ const customDialog = (protyle: IProtyle, ids: string[], elements: Element[]) =>
showMessage(window.siyuan.languages["_kernel"][142]);
return;
}
- fetchPost("/api/ai/chatGPTWithAction", {
- ids,
- action: customElement.value,
- }, (response) => {
- dialog.destroy();
- fillContent(protyle, response.data, elements);
- });
+ dialog.destroy();
+ startAIEditorAction(protyle, elements, range, customElement.value);
});
btnsElement[2].addEventListener("click", () => {
if (!nameElement.value && !customElement.value) {
@@ -151,14 +130,12 @@ const filterAI = (element: HTMLElement, inputElement: HTMLInputElement) => {
element.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");
};
-const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle: IProtyle) => {
+const openAIActions = (actions: IAIEditorAction[], elements: HTMLElement[], protyle: IProtyle, range?: Range) => {
window.siyuan.menus.menu.remove();
- const ids: string[] = [];
- elements.forEach(item => {
- ids.push(item.getAttribute("data-node-id"));
- });
const menu = new Menu(Constants.MENU_AI, () => {
- focusByRange(protyle.toolbar.range);
+ if (protyle.toolbar.range) {
+ focusByRange(protyle.toolbar.range);
+ }
});
let customHTML = "";
actions.forEach((item) => {
@@ -219,13 +196,12 @@ const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle:
if (typeof action !== "string") {
return;
}
- fetchPost("/api/ai/chatGPTWithAction", {ids, action}, (response) => {
- fillContent(protyle, response.data, elements);
- });
if (action === clearContext) {
+ clearAIEditorHistory(protyle);
showMessage(window.siyuan.languages.clearContextSucc);
} else {
menu.close();
+ startAIEditorAction(protyle, elements, range, action);
}
};
inputElement.addEventListener("keydown", (event: KeyboardEvent) => {
@@ -244,7 +220,7 @@ const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle:
return;
}
if (currentElement.dataset.type === "custom") {
- customDialog(protyle, ids, elements);
+ customDialog(protyle, elements, range);
menu.close();
} else {
runAction(currentElement);
@@ -274,7 +250,7 @@ const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle:
break;
} else if (target.classList.contains("b3-list-item")) {
if (target.dataset.type === "custom") {
- customDialog(protyle, ids, elements);
+ customDialog(protyle, elements, range);
menu.close();
} else {
runAction(target);
@@ -292,7 +268,8 @@ const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle:
/// #if MOBILE
menu.fullscreen();
/// #else
- const rect = elements[elements.length - 1].getBoundingClientRect();
+ const rect = elements[elements.length - 1]?.getBoundingClientRect() || range?.getBoundingClientRect() ||
+ protyle.element.getBoundingClientRect();
menu.open({
x: rect.left,
y: rect.bottom,
@@ -304,13 +281,21 @@ const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle:
let aiActionsRequestID = 0;
-export const AIActions = (elements: Element[], protyle: IProtyle) => {
+export const AIActions = (elements: Element[], protyle: IProtyle, range?: Range) => {
window.siyuan.menus.menu.remove();
+ const sourceElements = elements.filter((item): item is HTMLElement => item instanceof HTMLElement);
+ const sourceRange = range?.cloneRange();
+ if (sourceRange) {
+ protyle.toolbar.range = sourceRange;
+ }
const requestID = ++aiActionsRequestID;
fetchPost("/api/ai/editor/lsActions", {}, (response) => {
- if (requestID !== aiActionsRequestID || elements.length === 0 || !elements[elements.length - 1].isConnected) {
+ if (requestID !== aiActionsRequestID ||
+ (sourceElements.length > 0 && !sourceElements[sourceElements.length - 1].isConnected) ||
+ (sourceRange && (!protyle.wysiwyg.element.contains(sourceRange.startContainer) ||
+ !protyle.wysiwyg.element.contains(sourceRange.endContainer)))) {
return;
}
- openAIActions(Array.isArray(response.data) ? response.data : [], elements, protyle);
+ openAIActions(Array.isArray(response.data) ? response.data : [], sourceElements, protyle, sourceRange);
});
};
diff --git a/app/src/ai/chat.ts b/app/src/ai/chat.ts
index d20fed0bc6..4f530bb2e8 100644
--- a/app/src/ai/chat.ts
+++ b/app/src/ai/chat.ts
@@ -1,9 +1,9 @@
import {Dialog} from "../dialog";
import {isMobile} from "../util/functions";
-import {fetchPost} from "../util/fetch";
-import {fillContent} from "./actions";
+import {clearAIEditorHistory, startAIWriting} from "./editor";
+import {showMessage} from "../dialog/message";
-export const AIChat = (protyle: IProtyle, element: Element) => {
+export const AIChat = (protyle: IProtyle, element: HTMLElement) => {
const dialog = new Dialog({
title: "✨ " + window.siyuan.languages.aiWriting,
content: `<div class="b3-dialog__content fn__flex"><textarea class="b3-text-field fn__flex-1" style="resize:none"></textarea></div>
@@ -23,19 +23,17 @@ export const AIChat = (protyle: IProtyle, element: Element) => {
dialog.destroy();
});
btnsElement[1].addEventListener("click", () => {
- let inputValue = inputElement.value;
- fetchPost("/api/ai/chatGPT", {
- msg: inputValue,
- }, (response) => {
- dialog.destroy();
- let respContent = "";
- if (response.data && "" !== response.data) {
- respContent = "\n\n" + response.data;
- }
- if (inputValue === "Clear context") {
- inputValue = "";
- }
- fillContent(protyle, `${inputValue}${respContent}`, [element]);
- });
+ const inputValue = inputElement.value;
+ if (!inputValue.trim()) {
+ showMessage(window.siyuan.languages["_kernel"][142]);
+ return;
+ }
+ dialog.destroy();
+ if (inputValue === "Clear context") {
+ clearAIEditorHistory(protyle);
+ showMessage(window.siyuan.languages.clearContextSucc);
+ return;
+ }
+ startAIWriting(protyle, element, inputValue);
});
};
diff --git a/app/src/ai/editor.ts b/app/src/ai/editor.ts
new file mode 100644
index 0000000000..4ed5eb1f31
--- /dev/null
+++ b/app/src/ai/editor.ts
@@ -0,0 +1,649 @@
+import {fetchAIEditorSSE, IAIEditorMessage, TAIEditorSSEEvent} from "./editorSSE";
+import {genUUID} from "../util/genID";
+import {
+ focusByOffset,
+ getBlockRanges,
+ getEditorRange,
+ getSelectionOffset,
+ setLastNodeRange
+} from "../protyle/util/selection";
+import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";
+import {hasClosestByAttribute, hasClosestByTag, isInEmbedBlock} from "../protyle/util/hasClosest";
+import {insertHTML} from "../protyle/util/insertHTML";
+import {blockRender} from "../protyle/render/blockRender";
+import {processRender} from "../protyle/util/processCode";
+import {highlightRender} from "../protyle/render/highlightRender";
+import {copyPlainText} from "../protyle/util/compatibility";
+import {showMessage} from "../dialog/message";
+import {confirmDialog} from "../dialog/confirmDialog";
+import {escapeHtml} from "../util/escape";
+import {isMobile} from "../util/functions";
+import {Constants} from "../constants";
+
+type TAIEditorSourceKind = "selection" | "blocks" | "writing";
+type TAIEditorTaskStatus = "streaming" | "done" | "stopped" | "error";
+
+interface IAIEditorSourcePart {
+ id: string;
+ start: number;
+ end: number;
+ signature: string;
+}
+
+interface IAIEditorSource {
+ kind: TAIEditorSourceKind;
+ parts: IAIEditorSourcePart[];
+ ids: string[];
+ input: string;
+ action: string;
+ replaceSupported: boolean;
+ insertSupported: boolean;
+}
+
+interface IAIEditorTask {
+ id: string;
+ protyle: IProtyle;
+ source: IAIEditorSource;
+ status: TAIEditorTaskStatus;
+ content: string;
+ notice: string;
+ panel: HTMLElement;
+ body: HTMLElement;
+ statusElement: HTMLElement;
+ stopButton: HTMLButtonElement;
+ actionsElement: HTMLElement;
+ abortController: AbortController;
+ mutationObserver?: MutationObserver;
+ resizeObserver?: ResizeObserver;
+ historySnapshot: IAIEditorMessage[];
+ historyCommitted: boolean;
+ renderFrame?: number;
+ updatePosition: () => void;
+}
+
+interface IAIEditorState {
+ task?: IAIEditorTask;
+ history: IAIEditorMessage[];
+}
+
+const states = new WeakMap<IProtyle, IAIEditorState>();
+const replaceableTypes = new Set(["NodeParagraph", "NodeHeading", "NodeCodeBlock"]);
+
+const getState = (protyle: IProtyle) => {
+ let state = states.get(protyle);
+ if (!state) {
+ state = {history: []};
+ states.set(protyle, state);
+ }
+ return state;
+};
+
+const normalizeSourceElement = (element: HTMLElement) => {
+ const clone = element.cloneNode(true) as HTMLElement;
+ clone.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--hl");
+ clone.removeAttribute(Constants.ATTRIBUTE_EDITING);
+ clone.querySelectorAll(".protyle-wysiwyg--select, .protyle-wysiwyg--hl").forEach(item => {
+ item.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--hl");
+ });
+ clone.querySelectorAll(`[${Constants.ATTRIBUTE_EDITING}]`).forEach(item => {
+ item.removeAttribute(Constants.ATTRIBUTE_EDITING);
+ });
+ return clone.outerHTML;
+};
+
+const findSourceElement = (protyle: IProtyle, id: string) => {
+ return Array.from(protyle.wysiwyg.element.querySelectorAll<HTMLElement>(`[data-node-id="${id}"]`)).find(item =>
+ !isInEmbedBlock(item));
+};
+
+const getSourceConflict = (task: IAIEditorTask) => {
+ let missing = false;
+ let changed = false;
+ const orderedElements: HTMLElement[] = [];
+ const seen = new Set<string>();
+ task.source.parts.forEach(part => {
+ if (seen.has(part.id)) {
+ return;
+ }
+ seen.add(part.id);
+ const element = findSourceElement(task.protyle, part.id);
+ if (!element) {
+ missing = true;
+ return;
+ }
+ orderedElements.push(element);
+ if (normalizeSourceElement(element) !== part.signature) {
+ changed = true;
+ }
+ });
+ for (let i = 1; i < orderedElements.length; i++) {
+ if (!(orderedElements[i - 1].compareDocumentPosition(orderedElements[i]) & Node.DOCUMENT_POSITION_FOLLOWING)) {
+ changed = true;
+ break;
+ }
+ }
+ return {missing, changed};
+};
+
+const sourcePartText = (protyle: IProtyle, range: Range) => {
+ const text = range.toString().replace(new RegExp(Constants.ZWSP, "g"), "");
+ const fragment = range.cloneContents();
+ if (!fragment.querySelector('.img, [data-type~="inline-math"], [data-type~="a"], [data-type~="block-ref"]')) {
+ return text;
+ }
+ const element = document.createElement("div");
+ element.append(fragment);
+ return protyle.lute.BlockDOM2StdMd(element.innerHTML).trimEnd() || text;
+};
+
+const buildSelectionSource = (protyle: IProtyle, range: Range, action: string): IAIEditorSource | undefined => {
+ const blockRanges = getBlockRanges(protyle.wysiwyg.element, range);
+ if (blockRanges.length === 0) {
+ return;
+ }
+ const parts = blockRanges.map(item => ({
+ id: item.blockElement.getAttribute("data-node-id") || "",
+ start: item.start,
+ end: item.end,
+ signature: normalizeSourceElement(item.blockElement),
+ }));
+ const replaceSupported = !protyle.disabled && blockRanges.length === 1 && blockRanges.every(item =>
+ replaceableTypes.has(item.blockElement.getAttribute("data-type")) && !isInEmbedBlock(item.blockElement));
+ return {
+ kind: "selection",
+ parts,
+ ids: [],
+ input: blockRanges.map(item => sourcePartText(protyle, item.range)).filter(Boolean).join("\n\n"),
+ action,
+ replaceSupported,
+ insertSupported: !protyle.disabled,
+ };
+};
+
+const getFullBlockPart = (element: HTMLElement): IAIEditorSourcePart | undefined => {
+ const editableElement = getContenteditableElement(element);
+ if (!editableElement) {
+ return {
+ id: element.getAttribute("data-node-id") || "",
+ start: 0,
+ end: 0,
+ signature: normalizeSourceElement(element),
+ };
+ }
+ const range = document.createRange();
+ range.selectNodeContents(editableElement);
+ const position = getSelectionOffset(editableElement, undefined, range);
+ return {
+ id: element.getAttribute("data-node-id") || "",
+ start: position.start,
+ end: position.end,
+ signature: normalizeSourceElement(element),
+ };
+};
+
+const buildBlockSource = (protyle: IProtyle, elements: HTMLElement[], action: string): IAIEditorSource | undefined => {
+ const sourceElements = elements.filter(item => item?.isConnected && item.hasAttribute("data-node-id"));
+ const parts = sourceElements.map(getFullBlockPart).filter((item): item is IAIEditorSourcePart => Boolean(item));
+ if (parts.length === 0) {
+ return;
+ }
+ const replaceSupported = !protyle.disabled && sourceElements.length === 1 &&
+ parts.length === sourceElements.length && sourceElements.every(item =>
+ replaceableTypes.has(item.getAttribute("data-type")) && !isInEmbedBlock(item));
+ return {
+ kind: "blocks",
+ parts,
+ ids: sourceElements.map(item => item.getAttribute("data-node-id") || ""),
+ input: "",
+ action,
+ replaceSupported,
+ insertSupported: !protyle.disabled,
+ };
+};
+
+const buildWritingSource = (protyle: IProtyle, element: HTMLElement, input: string): IAIEditorSource | undefined => {
+ const editableElement = getContenteditableElement(element);
+ if (!editableElement) {
+ return;
+ }
+ const range = document.createRange();
+ setLastNodeRange(editableElement, range);
+ range.collapse(true);
+ const position = getSelectionOffset(editableElement, undefined, range);
+ return {
+ kind: "writing",
+ parts: [{
+ id: element.getAttribute("data-node-id") || "",
+ start: position.start,
+ end: position.end,
+ signature: normalizeSourceElement(element),
+ }],
+ ids: [],
+ input,
+ action: "",
+ replaceSupported: false,
+ insertSupported: !protyle.disabled,
+ };
+};
+
+const rebuildSourceRange = (task: IAIEditorTask) => {
+ const firstPart = task.source.parts[0];
+ const lastPart = task.source.parts[task.source.parts.length - 1];
+ const firstElement = findSourceElement(task.protyle, firstPart.id);
+ const lastElement = findSourceElement(task.protyle, lastPart.id);
+ if (!firstElement || !lastElement) {
+ return;
+ }
+ if (firstElement === lastElement) {
+ return focusByOffset(firstElement, firstPart.start, lastPart.end, false) as Range;
+ }
+ const startRange = focusByOffset(firstElement, firstPart.start, firstPart.start, false) as Range;
+ const endRange = focusByOffset(lastElement, lastPart.end, lastPart.end, false) as Range;
+ if (!startRange || !endRange) {
+ return;
+ }
+ const range = document.createRange();
+ range.setStart(startRange.startContainer, startRange.startOffset);
+ range.setEnd(endRange.endContainer, endRange.endOffset);
+ return range;
+};
+
+const getInsertRange = (task: IAIEditorTask) => {
+ if (task.source.kind === "writing") {
+ return rebuildSourceRange(task);
+ }
+ const lastPart = task.source.parts[task.source.parts.length - 1];
+ const lastElement = findSourceElement(task.protyle, lastPart.id);
+ if (!lastElement) {
+ return;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(lastElement);
+ range.collapse(false);
+ return range;
+};
+
+const getInsertHTML = (task: IAIEditorTask, range: Range, asReplacement: boolean) => {
+ const inCode = hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock") ||
+ hasClosestByTag(range.startContainer, "CODE");
+ const content = task.source.kind === "writing" ? `${task.source.input}\n\n${task.content}` : task.content;
+ return {
+ html: inCode ? content : task.protyle.lute.Md2BlockDOM(content),
+ isBlock: !inCode && !asReplacement,
+ };
+};
+
+const renderInsertedContent = (protyle: IProtyle) => {
+ blockRender(protyle, protyle.wysiwyg.element);
+ processRender(protyle.wysiwyg.element);
+ highlightRender(protyle.wysiwyg.element);
+};
+
+const cleanupTask = (task: IAIEditorTask) => {
+ task.abortController.abort();
+ if (task.renderFrame) {
+ cancelAnimationFrame(task.renderFrame);
+ }
+ task.mutationObserver?.disconnect();
+ task.resizeObserver?.disconnect();
+ task.protyle.contentElement.removeEventListener("scroll", task.updatePosition);
+ window.removeEventListener("resize", task.updatePosition);
+ task.panel.remove();
+ const state = getState(task.protyle);
+ if (state.task === task) {
+ state.task = undefined;
+ }
+};
+
+const applyTaskResult = (task: IAIEditorTask, action: "replace" | "source" | "cursor") => {
+ if (!task.content) {
+ return;
+ }
+ const conflict = getSourceConflict(task);
+ let range: Range;
+ if (action === "replace") {
+ if (!task.source.replaceSupported || conflict.missing || conflict.changed) {
+ return;
+ }
+ range = rebuildSourceRange(task);
+ } else if (action === "source") {
+ if (!task.source.insertSupported || conflict.missing ||
+ (task.source.kind === "writing" && conflict.changed)) {
+ return;
+ }
+ range = getInsertRange(task);
+ } else {
+ if (!task.source.insertSupported) {
+ return;
+ }
+ range = task.protyle.toolbar.range;
+ if (!range || !task.protyle.wysiwyg.element.contains(range.startContainer)) {
+ range = getEditorRange(task.protyle.wysiwyg.element);
+ }
+ range = range?.cloneRange();
+ range?.collapse(false);
+ }
+ if (!range || !task.protyle.wysiwyg.element.contains(range.startContainer)) {
+ showMessage(window.siyuan.languages.aiSourceChanged, 5000, "error");
+ return;
+ }
+ task.protyle.toolbar.range = range;
+ const insertion = getInsertHTML(task, range, action === "replace");
+ insertHTML(insertion.html, task.protyle, insertion.isBlock, true);
+ renderInsertedContent(task.protyle);
+ cleanupTask(task);
+};
+
+const renderTaskPreview = (task: IAIEditorTask, rich = false) => {
+ if (task.renderFrame) {
+ cancelAnimationFrame(task.renderFrame);
+ task.renderFrame = undefined;
+ }
+ if (!rich) {
+ task.body.classList.add("ai-editor-panel__body--streaming");
+ task.body.textContent = task.content;
+ return;
+ }
+ task.body.classList.remove("ai-editor-panel__body--streaming");
+ task.body.innerHTML = task.protyle.lute.Md2BlockDOM(task.content);
+ blockRender(task.protyle, task.body);
+ processRender(task.body);
+ highlightRender(task.body);
+ task.body.querySelectorAll("[contenteditable]").forEach(item => item.setAttribute("contenteditable", "false"));
+};
+
+const scheduleTaskPreview = (task: IAIEditorTask) => {
+ if (task.renderFrame) {
+ return;
+ }
+ task.renderFrame = requestAnimationFrame(() => {
+ task.renderFrame = undefined;
+ renderTaskPreview(task);
+ task.updatePosition();
+ });
+};
+
+const updateTaskActions = (task: IAIEditorTask) => {
+ const conflict = getSourceConflict(task);
+ const replaceButton = task.actionsElement.querySelector<HTMLButtonElement>('[data-action="replace"]');
+ const sourceButton = task.actionsElement.querySelector<HTMLButtonElement>('[data-action="source"]');
+ const cursorButton = task.actionsElement.querySelector<HTMLButtonElement>('[data-action="cursor"]');
+ if (replaceButton) {
+ replaceButton.disabled = !task.content || conflict.missing || conflict.changed || !task.source.replaceSupported;
+ }
+ if (sourceButton) {
+ sourceButton.disabled = !task.content || !task.source.insertSupported || conflict.missing ||
+ (task.source.kind === "writing" && conflict.changed);
+ }
+ if (cursorButton) {
+ cursorButton.disabled = !task.content || !task.source.insertSupported;
+ }
+ task.actionsElement.querySelectorAll<HTMLButtonElement>("button").forEach(item => {
+ if (item.dataset.action !== "retry" && item.dataset.action !== "discard" && !task.content) {
+ item.disabled = true;
+ }
+ });
+ if (conflict.missing || conflict.changed) {
+ task.statusElement.textContent = window.siyuan.languages.aiSourceChanged;
+ } else if (task.status === "streaming") {
+ task.statusElement.textContent = window.siyuan.languages.loading;
+ } else if (task.notice) {
+ task.statusElement.textContent = task.notice;
+ } else if (task.status === "stopped") {
+ task.statusElement.textContent = window.siyuan.languages.aiStopped;
+ } else if (task.status === "done") {
+ task.statusElement.textContent = "";
+ }
+};
+
+const finishTask = (task: IAIEditorTask) => {
+ if (task.status !== "streaming") {
+ return;
+ }
+ task.status = "done";
+ task.stopButton.classList.add("fn__none");
+ task.actionsElement.classList.remove("fn__none");
+ renderTaskPreview(task, true);
+ if (task.source.kind === "writing" && !task.historyCommitted && task.content) {
+ const state = getState(task.protyle);
+ state.history.push({role: "user", content: task.source.input}, {role: "assistant", content: task.content});
+ task.historyCommitted = true;
+ }
+ updateTaskActions(task);
+ task.updatePosition();
+};
+
+const stopTask = (task: IAIEditorTask) => {
+ if (task.status !== "streaming") {
+ return;
+ }
+ task.abortController.abort();
+ task.status = "stopped";
+ task.stopButton.classList.add("fn__none");
+ task.actionsElement.classList.remove("fn__none");
+ renderTaskPreview(task, true);
+ updateTaskActions(task);
+};
+
+const handleTaskEvent = (task: IAIEditorTask, event: TAIEditorSSEEvent) => {
+ if (event.type === "content") {
+ task.content += event.token;
+ scheduleTaskPreview(task);
+ } else if (event.type === "truncated") {
+ task.notice = event.message;
+ } else if (event.type === "error") {
+ task.status = "error";
+ task.notice = event.message;
+ task.stopButton.classList.add("fn__none");
+ task.actionsElement.classList.remove("fn__none");
+ renderTaskPreview(task, true);
+ updateTaskActions(task);
+ } else if (event.type === "done") {
+ finishTask(task);
+ }
+};
+
+const startTaskStream = (task: IAIEditorTask) => {
+ const abortController = new AbortController();
+ task.abortController = abortController;
+ task.status = "streaming";
+ task.content = "";
+ task.notice = "";
+ task.body.textContent = "";
+ task.statusElement.textContent = window.siyuan.languages.loading;
+ task.stopButton.classList.remove("fn__none");
+ task.actionsElement.classList.add("fn__none");
+ fetchAIEditorSSE({
+ taskID: task.id,
+ ids: task.source.ids,
+ input: task.source.input,
+ action: task.source.action,
+ history: task.source.kind === "writing" ? task.historySnapshot : [],
+ }, event => {
+ if (task.abortController === abortController) {
+ handleTaskEvent(task, event);
+ }
+ }, abortController.signal).catch(error => {
+ if (abortController.signal.aborted || task.abortController !== abortController ||
+ getState(task.protyle).task !== task) {
+ return;
+ }
+ task.status = "error";
+ task.notice = error instanceof Error ? error.message : String(error);
+ task.stopButton.classList.add("fn__none");
+ task.actionsElement.classList.remove("fn__none");
+ renderTaskPreview(task, true);
+ updateTaskActions(task);
+ });
+};
+
+const retryTask = (task: IAIEditorTask) => {
+ if (task.historyCommitted) {
+ const state = getState(task.protyle);
+ state.history.splice(Math.max(0, state.history.length - 2), 2);
+ task.historyCommitted = false;
+ }
+ task.abortController.abort();
+ startTaskStream(task);
+};
+
+const createTaskButton = (action: string, label: string, primary = false) => {
+ const button = document.createElement("button");
+ button.className = `b3-button${primary ? " b3-button--text" : " b3-button--outline"}`;
+ button.dataset.action = action;
+ button.textContent = label;
+ return button;
+};
+
+const createTask = (protyle: IProtyle, source: IAIEditorSource) => {
+ const panel = document.createElement("div");
+ panel.className = `ai-editor-panel${isMobile() ? " ai-editor-panel--mobile" : ""}`;
+ panel.setAttribute("contenteditable", "false");
+ panel.style.zIndex = (++window.siyuan.zIndex).toString();
+ panel.innerHTML = `<div class="ai-editor-panel__header">
+ <span class="fn__flex-1">${escapeHtml(window.siyuan.languages.aiEdit)}</span>
+ <span class="ai-editor-panel__status"></span>
+ <button class="b3-button b3-button--outline ai-editor-panel__stop">${escapeHtml(window.siyuan.languages.agentStop)}</button>
+</div>
+<div class="ai-editor-panel__body protyle-wysiwyg" data-readonly="true"></div>
+<div class="ai-editor-panel__actions fn__none"></div>`;
+ const actionsElement = panel.querySelector(".ai-editor-panel__actions") as HTMLElement;
+ if (source.replaceSupported) {
+ actionsElement.append(createTaskButton("replace", window.siyuan.languages.replace, true));
+ }
+ actionsElement.append(createTaskButton("source", source.kind === "writing" ?
+ window.siyuan.languages.aiInsertAtOriginal : window.siyuan.languages.insertAfter, !source.replaceSupported));
+ actionsElement.append(createTaskButton("cursor", window.siyuan.languages.aiInsertAtCursor));
+ actionsElement.append(createTaskButton("copy", window.siyuan.languages.copy));
+ actionsElement.append(createTaskButton("retry", window.siyuan.languages.retry));
+ actionsElement.append(createTaskButton("discard", window.siyuan.languages.aiDiscard));
+
+ const task: IAIEditorTask = {
+ id: genUUID(),
+ protyle,
+ source,
+ status: "streaming",
+ content: "",
+ notice: "",
+ panel,
+ body: panel.querySelector(".ai-editor-panel__body") as HTMLElement,
+ statusElement: panel.querySelector(".ai-editor-panel__status") as HTMLElement,
+ stopButton: panel.querySelector(".ai-editor-panel__stop") as HTMLButtonElement,
+ actionsElement,
+ abortController: new AbortController(),
+ historySnapshot: getState(protyle).history.map(item => ({...item})),
+ historyCommitted: false,
+ updatePosition: () => undefined,
+ };
+ task.updatePosition = () => {
+ if (!task.panel.isConnected || task.panel.classList.contains("ai-editor-panel--mobile")) {
+ return;
+ }
+ const anchorPart = task.source.parts[task.source.parts.length - 1];
+ const anchorElement = findSourceElement(protyle, anchorPart.id);
+ const protyleRect = protyle.element.getBoundingClientRect();
+ const panelRect = panel.getBoundingClientRect();
+ if (!anchorElement) {
+ panel.style.left = `${Math.max(8, protyle.element.clientWidth - panelRect.width - 16)}px`;
+ panel.style.top = `${Math.max(8, protyle.element.clientHeight - panelRect.height - 16)}px`;
+ return;
+ }
+ const anchorRect = anchorElement.getBoundingClientRect();
+ const left = Math.min(Math.max(8, anchorRect.left - protyleRect.left),
+ Math.max(8, protyle.element.clientWidth - panelRect.width - 16));
+ let top = anchorRect.bottom - protyleRect.top + 4;
+ if (top + panelRect.height > protyle.element.clientHeight - 8) {
+ top = Math.max(8, anchorRect.top - protyleRect.top - panelRect.height - 4);
+ }
+ panel.style.left = `${left}px`;
+ panel.style.top = `${top}px`;
+ };
+ task.stopButton.addEventListener("click", () => stopTask(task));
+ actionsElement.addEventListener("click", event => {
+ const button = (event.target as HTMLElement).closest<HTMLButtonElement>("button[data-action]");
+ if (!button || button.disabled) {
+ return;
+ }
+ switch (button.dataset.action) {
+ case "replace":
+ applyTaskResult(task, "replace");
+ break;
+ case "source":
+ applyTaskResult(task, "source");
+ break;
+ case "cursor":
+ applyTaskResult(task, "cursor");
+ break;
+ case "copy":
+ copyPlainText(task.content);
+ showMessage(window.siyuan.languages.copied, 2000);
+ break;
+ case "retry":
+ retryTask(task);
+ break;
+ case "discard":
+ cleanupTask(task);
+ break;
+ }
+ });
+ protyle.element.append(panel);
+ task.mutationObserver = new MutationObserver(() => updateTaskActions(task));
+ task.mutationObserver.observe(protyle.wysiwyg.element, {
+ attributes: true,
+ characterData: true,
+ childList: true,
+ subtree: true,
+ });
+ task.resizeObserver = new ResizeObserver(task.updatePosition);
+ task.resizeObserver.observe(panel);
+ protyle.contentElement.addEventListener("scroll", task.updatePosition);
+ window.addEventListener("resize", task.updatePosition);
+ requestAnimationFrame(task.updatePosition);
+ return task;
+};
+
+const beginTask = (protyle: IProtyle, source: IAIEditorSource) => {
+ const state = getState(protyle);
+ const start = () => {
+ if (state.task) {
+ cleanupTask(state.task);
+ }
+ const task = createTask(protyle, source);
+ state.task = task;
+ startTaskStream(task);
+ };
+ if (!state.task) {
+ start();
+ return;
+ }
+ confirmDialog(window.siyuan.languages.aiEdit, window.siyuan.languages.aiReplaceCurrentTask, start);
+};
+
+export const startAIEditorAction = (protyle: IProtyle, elements: HTMLElement[], range: Range | undefined,
+ action: string) => {
+ const source = range && !range.collapsed && protyle.wysiwyg.element.contains(range.startContainer) ?
+ buildSelectionSource(protyle, range, action) : buildBlockSource(protyle, elements, action);
+ if (!source || (!source.input && source.ids.length === 0)) {
+ return;
+ }
+ beginTask(protyle, source);
+};
+
+export const startAIWriting = (protyle: IProtyle, element: HTMLElement, input: string) => {
+ const source = buildWritingSource(protyle, element, input);
+ if (source) {
+ beginTask(protyle, source);
+ }
+};
+
+export const clearAIEditorHistory = (protyle: IProtyle) => {
+ getState(protyle).history = [];
+};
+
+export const destroyAIEditor = (protyle: IProtyle) => {
+ const state = states.get(protyle);
+ if (state?.task) {
+ cleanupTask(state.task);
+ }
+ states.delete(protyle);
+};
diff --git a/app/src/ai/editorSSE.test.ts b/app/src/ai/editorSSE.test.ts
new file mode 100644
index 0000000000..7ae7ad95c9
--- /dev/null
+++ b/app/src/ai/editorSSE.test.ts
@@ -0,0 +1,25 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {createAIEditorSSEParserState, parseAIEditorSSE} from "./editorSSE";
+
+test("parses fragmented AI editor SSE events", () => {
+ const state = createAIEditorSSEParserState();
+ assert.deepEqual(parseAIEditorSSE(state, "event:content\ndata:{\"tok"), []);
+ assert.deepEqual(parseAIEditorSSE(state, "en\":\"hel\"}\n\nevent:done\n"), [{
+ type: "content",
+ token: "hel",
+ }]);
+ assert.deepEqual(parseAIEditorSSE(state, "data:{\"finishReason\":\"stop\"}\n\n"), [{
+ type: "done",
+ finishReason: "stop",
+ }]);
+});
+
+test("skips malformed AI editor SSE events", () => {
+ const state = createAIEditorSSEParserState();
+ assert.deepEqual(parseAIEditorSSE(state,
+ "event:content\ndata:not-json\n\nevent:content\ndata:{\"token\":\"ok\"}\n\n"), [{
+ type: "content",
+ token: "ok",
+ }]);
+});
diff --git a/app/src/ai/editorSSE.ts b/app/src/ai/editorSSE.ts
new file mode 100644
index 0000000000..f0f794a917
--- /dev/null
+++ b/app/src/ai/editorSSE.ts
@@ -0,0 +1,131 @@
+export interface IAIEditorMessage {
+ role: "user" | "assistant";
+ content: string;
+}
+
+export interface IAIEditorChatRequest {
+ taskID: string;
+ ids?: string[];
+ input?: string;
+ action?: string;
+ history?: IAIEditorMessage[];
+}
+
+export type TAIEditorSSEEvent = {
+ type: "start";
+ taskID: string;
+} | {
+ type: "content";
+ token: string;
+} | {
+ type: "truncated";
+ message: string;
+} | {
+ type: "error";
+ message: string;
+} | {
+ type: "done";
+ finishReason: string;
+};
+
+interface IAIEditorSSEParserState {
+ buffer: string;
+ event: string;
+}
+
+export const createAIEditorSSEParserState = (): IAIEditorSSEParserState => ({buffer: "", event: ""});
+
+const buildEvent = (event: string, data: Record<string, unknown>): TAIEditorSSEEvent | undefined => {
+ switch (event) {
+ case "start":
+ return {type: "start", taskID: String(data.taskID || "")};
+ case "content":
+ return {type: "content", token: String(data.token || "")};
+ case "truncated":
+ return {type: "truncated", message: String(data.message || "")};
+ case "error":
+ return {type: "error", message: String(data.message || "")};
+ case "done":
+ return {type: "done", finishReason: String(data.finishReason || "")};
+ }
+};
+
+export const parseAIEditorSSE = (state: IAIEditorSSEParserState, chunk: string, flush = false) => {
+ const events: TAIEditorSSEEvent[] = [];
+ state.buffer += chunk;
+ const lines = state.buffer.split("\n");
+ state.buffer = flush ? "" : lines.pop() || "";
+ for (let line of lines) {
+ if (line.endsWith("\r")) {
+ line = line.slice(0, -1);
+ }
+ if (line.startsWith("event:")) {
+ state.event = line.slice(6).trim();
+ continue;
+ }
+ if (!line.startsWith("data:") || !state.event) {
+ continue;
+ }
+ try {
+ const event = buildEvent(state.event, JSON.parse(line.slice(5).trim()));
+ if (event) {
+ events.push(event);
+ }
+ } catch (e) {
+ // 忽略格式错误的单条事件,后续完整事件仍可继续处理。
+ }
+ state.event = "";
+ }
+ if (flush && state.buffer) {
+ state.buffer = "";
+ }
+ return events;
+};
+
+export const fetchAIEditorSSE = async (
+ request: IAIEditorChatRequest,
+ onEvent: (event: TAIEditorSSEEvent) => void,
+ signal: AbortSignal,
+) => {
+ const response = await fetch("/api/ai/editor/chat", {
+ method: "POST",
+ headers: {"Content-Type": "application/json"},
+ body: JSON.stringify(request),
+ signal,
+ });
+ const contentType = response.headers.get("Content-Type") || "";
+ if (!response.ok || !contentType.includes("text/event-stream")) {
+ let message = window.siyuan.languages._kernel[28];
+ try {
+ const data = await response.json();
+ message = data?.msg || data?.message || message;
+ } catch (e) {
+ // 响应不是 JSON 时使用统一错误文案。
+ }
+ throw new Error(message);
+ }
+ const reader = response.body?.getReader();
+ if (!reader) {
+ throw new Error(window.siyuan.languages._kernel[28]);
+ }
+ const decoder = new TextDecoder();
+ const parserState = createAIEditorSSEParserState();
+ let terminalReceived = false;
+ while (true) {
+ const result = await reader.read();
+ if (result.done) {
+ break;
+ }
+ parseAIEditorSSE(parserState, decoder.decode(result.value, {stream: true})).forEach(event => {
+ terminalReceived = terminalReceived || event.type === "done" || event.type === "error";
+ onEvent(event);
+ });
+ }
+ parseAIEditorSSE(parserState, decoder.decode(), true).forEach(event => {
+ terminalReceived = terminalReceived || event.type === "done" || event.type === "error";
+ onEvent(event);
+ });
+ if (!terminalReceived && !signal.aborted) {
+ throw new Error(window.siyuan.languages._kernel[28]);
+ }
+};
diff --git a/app/src/assets/scss/base.scss b/app/src/assets/scss/base.scss
index ace90db08a..67cf2974e0 100644
--- a/app/src/assets/scss/base.scss
+++ b/app/src/assets/scss/base.scss
@@ -34,6 +34,7 @@
@use "business/av" as *;
@use "business/emojis" as *;
@use "business/ai_agent" as *;
+@use "business/ai_editor" as *;
@use "business/onboarding" as *;
@use "component/svg" as *;
@use "main/main" as *;
diff --git a/app/src/assets/scss/business/_ai_editor.scss b/app/src/assets/scss/business/_ai_editor.scss
new file mode 100644
index 0000000000..914cc68156
--- /dev/null
+++ b/app/src/assets/scss/business/_ai_editor.scss
@@ -0,0 +1,68 @@
+.ai-editor-panel {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ box-sizing: border-box;
+ width: min(520px, calc(100% - 32px));
+ max-height: min(480px, 60%);
+ overflow: hidden;
+ background: var(--b3-theme-background);
+ border: 1px solid var(--b3-theme-surface-lighter);
+ border-radius: var(--b3-border-radius-b);
+ box-shadow: var(--b3-dialog-shadow);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 32px;
+ padding: 4px 8px 4px 12px;
+ border-bottom: 1px solid var(--b3-border-color);
+ color: var(--b3-theme-on-background);
+ font-size: 13px;
+ }
+
+ &__status {
+ overflow: hidden;
+ color: var(--b3-theme-on-surface-light);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__body.protyle-wysiwyg {
+ min-height: 72px;
+ padding: 12px 16px;
+ overflow: auto;
+ color: var(--b3-theme-on-background);
+ font-size: var(--b3-font-size);
+ line-height: 1.6;
+ user-select: text;
+ word-break: break-word;
+ }
+
+ &__body--streaming {
+ white-space: pre-wrap;
+ }
+
+ &__actions {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 8px;
+ border-top: 1px solid var(--b3-border-color);
+ }
+
+ &--mobile {
+ top: auto !important;
+ right: max(8px, env(safe-area-inset-right));
+ bottom: max(8px, env(safe-area-inset-bottom));
+ left: max(8px, env(safe-area-inset-left)) !important;
+ width: auto;
+ max-height: 55%;
+
+ .ai-editor-panel__actions .b3-button {
+ min-height: 36px;
+ }
+ }
+}
diff --git a/app/src/assets/scss/mobile.scss b/app/src/assets/scss/mobile.scss
index 5b7b663c39..ac9df98b82 100644
--- a/app/src/assets/scss/mobile.scss
+++ b/app/src/assets/scss/mobile.scss
@@ -32,6 +32,7 @@
@use "business/emojis" as *;
@use "business/onboarding" as *;
@use "business/ai_agent" as *;
+@use "business/ai_editor" as *;
@use "component/svg" as *;
@use "main/mobile" as *;
@use "util/responsive" as *;
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 44f0de0e67..40ac9c0774 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -135,6 +135,7 @@ export class Toolbar {
protyle.options.toolbar = toolbarKeyToMenu(isMobile() ? [
"block-ref",
"a",
+ "ai",
"|",
"text",
"strong",
@@ -149,6 +150,7 @@ export class Toolbar {
] : [
"block-ref",
"a",
+ "ai",
"|",
"text",
"strong",
diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.ts
index 3dd821ab28..9c9cc00e55 100644
--- a/app/src/protyle/toolbar/util.ts
+++ b/app/src/protyle/toolbar/util.ts
@@ -4,6 +4,7 @@ import {focusByRange, focusByWbr} from "../util/selection";
import {writeText} from "../util/compatibility";
import {isArrayEqual} from "../../util/functions";
import {hasSameTextStyle} from "./Font";
+import {AIActions} from "../../ai/actions";
export const previewTemplate = (pathString: string, element: Element, parentId: string) => {
if (!pathString) {
@@ -144,6 +145,19 @@ export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {
lang: "link",
icon: "iconLink",
tipPosition: "n",
+ }, {
+ name: "ai",
+ hotkey: window.siyuan.config.keymap.editor.general.ai.custom,
+ lang: "aiEdit",
+ icon: "iconSparkles",
+ tipPosition: "n",
+ click(protyle) {
+ const editor = protyle.protyle;
+ const range = editor.toolbar.range?.cloneRange();
+ if (range && !range.collapsed) {
+ AIActions([], editor, range);
+ }
+ },
}, {
name: "strong",
lang: "bold",
diff --git a/app/src/protyle/util/Options.ts b/app/src/protyle/util/Options.ts
index 8d832def87..5eeb56c811 100644
--- a/app/src/protyle/util/Options.ts
+++ b/app/src/protyle/util/Options.ts
@@ -93,6 +93,7 @@ export class Options {
toolbar: isMobile() ? [
"block-ref",
"a",
+ "ai",
"|",
"text",
"strong",
@@ -107,6 +108,7 @@ export class Options {
] : [
"block-ref",
"a",
+ "ai",
"|",
"text",
"strong",
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index 1652844b22..710b165fdf 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -1,11 +1,13 @@
import {hideElements} from "../ui/hideElements";
import {isSupportCSSHL} from "../render/searchMarkRender";
+import {destroyAIEditor} from "../../ai/editor";
export const destroy = (protyle: IProtyle) => {
if (!protyle) {
return;
}
hideElements(["util"], protyle);
+ destroyAIEditor(protyle);
protyle.hint?.destroy();
protyle.preview?.destroy();
if (isSupportCSSHL()) {
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 655bb4cf47..22007740cd 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -2265,11 +2265,16 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.ai.custom, event)) {
event.preventDefault();
event.stopPropagation();
- let selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
- if (selectsElement.length === 0) {
- selectsElement = [nodeElement];
+ if (!range.collapsed && protyle.wysiwyg.element.contains(range.startContainer) &&
+ protyle.wysiwyg.element.contains(range.endContainer)) {
+ AIActions([], protyle, range.cloneRange());
+ } else {
+ let selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
+ if (selectsElement.length === 0) {
+ selectsElement = [nodeElement];
+ }
+ AIActions(selectsElement, protyle);
}
- AIActions(selectsElement, protyle);
return;
}
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index ab2dd944df..1068316cc8 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -30,6 +30,14 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+type aiEditorChatReq struct {
+ TaskID string `json:"taskID"`
+ IDs []string `json:"ids"`
+ Input string `json:"input"`
+ Action string `json:"action"`
+ History []model.AIEditorMessage `json:"history"`
+}
+
func resolveAIProvider(arg map[string]any) (*conf.Provider, error) {
if providerConfig, ok := arg["providerConfig"]; ok && providerConfig != nil {
data, err := gulu.JSON.MarshalJSON(providerConfig)
@@ -94,6 +102,85 @@ func chatGPTWithAction(c *gin.Context) {
ret.Data = model.ChatGPTWithAction(ids, action)
}
+func aiEditorChat(c *gin.Context) {
+ if !model.Conf.AI.HasAnyProvider() {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(193)
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ req := &aiEditorChatReq{}
+ if err := c.ShouldBindJSON(req); nil != err {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "invalid request: " + err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+ stream, err := model.NewAIEditorChatStream(c.Request.Context(), req.IDs, req.Input, req.Action, req.History)
+ if nil != err {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+ defer stream.Close()
+
+ flusher, ok := c.Writer.(http.Flusher)
+ if !ok {
+ return
+ }
+ c.Header("Content-Type", "text/event-stream")
+ c.Header("Cache-Control", "no-cache")
+ c.Header("Connection", "keep-alive")
+ c.Header("X-Accel-Buffering", "no")
+ if err = writeSSEEvent(c, "start", map[string]string{"taskID": req.TaskID}); nil != err {
+ return
+ }
+ flusher.Flush()
+
+ finishReason := "stop"
+ for {
+ response, recvErr := stream.Recv()
+ if nil != recvErr {
+ if model.IsAIEditorStreamDone(recvErr) {
+ writeSSEEvent(c, "done", map[string]string{"finishReason": finishReason})
+ flusher.Flush()
+ return
+ }
+ if nil != c.Request.Context().Err() {
+ return
+ }
+ logging.LogErrorf("receive AI editor stream failed: %s", recvErr)
+ writeSSEError(c, recvErr.Error())
+ flusher.Flush()
+ return
+ }
+ for _, choice := range response.Choices {
+ if "" != choice.Delta.Content {
+ if err = writeSSEEvent(c, "content", map[string]string{"token": choice.Delta.Content}); nil != err {
+ return
+ }
+ flusher.Flush()
+ }
+ if "" == choice.FinishReason {
+ continue
+ }
+ finishReason = string(choice.FinishReason)
+ if "length" == finishReason {
+ writeSSEEvent(c, "truncated", map[string]string{"message": model.Conf.Language(297)})
+ flusher.Flush()
+ }
+ writeSSEEvent(c, "done", map[string]string{"finishReason": finishReason})
+ flusher.Flush()
+ return
+ }
+ }
+}
+
func lsAIEditorActions(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 5313d29c37..37df79b010 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -604,6 +604,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/chatGPT", model.CheckAuth, model.CheckAdminRole, chatGPT)
ginServer.Handle("POST", "/api/ai/chatGPTWithAction", model.CheckAuth, model.CheckAdminRole, chatGPTWithAction)
+ ginServer.Handle("POST", "/api/ai/editor/chat", model.CheckAuth, model.CheckAdminRole, aiEditorChat)
ginServer.Handle("POST", "/api/ai/editor/lsActions", model.CheckAuth, model.CheckAdminRole, lsAIEditorActions)
ginServer.Handle("POST", "/api/ai/editor/saveAction", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, saveAIEditorAction)
ginServer.Handle("POST", "/api/ai/editor/removeAction", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeAIEditorAction)
diff --git a/kernel/model/ai.go b/kernel/model/ai.go
index 594feea256..1761c7fcea 100644
--- a/kernel/model/ai.go
+++ b/kernel/model/ai.go
@@ -18,8 +18,11 @@ package model
import (
"bytes"
+ "context"
"errors"
+ "io"
"strings"
+ "time"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
@@ -71,10 +74,7 @@ func chatGPT(msg string, cloud bool) (ret string) {
}
func chatGPTWithAction(msg string, action string, cloud bool) (ret string) {
- action = strings.TrimSpace(action)
- if "" != action {
- msg = action + ":\n\n" + msg
- }
+ msg = BuildAIEditorPrompt(msg, action)
ret, _, err := chatGPTComplete(msg, nil, cloud)
if err != nil {
return
@@ -82,6 +82,138 @@ func chatGPTWithAction(msg string, action string, cloud bool) (ret string) {
return
}
+// BuildAIEditorPrompt 将编辑器输入填充到操作模板中。没有占位符时保持现有的操作前缀格式。
+func BuildAIEditorPrompt(input, action string) string {
+ action = strings.TrimSpace(action)
+ if "" == action {
+ return input
+ }
+ if strings.Contains(action, "{{input}}") {
+ return strings.ReplaceAll(action, "{{input}}", input)
+ }
+ return action + ":\n\n" + input
+}
+
+type AIEditorMessage struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+}
+
+type AIEditorChatStream struct {
+ stream *openai.ChatCompletionStream
+ cancel context.CancelFunc
+ idleTimeout time.Duration
+}
+
+func (stream *AIEditorChatStream) Recv() (response openai.ChatCompletionStreamResponse, err error) {
+ timer, timerDone := startAIEditorCancelTimer(stream.idleTimeout, stream.cancel)
+ response, err = stream.stream.Recv()
+ if stopAIEditorCancelTimer(timer, timerDone) {
+ err = errors.New("AI editor stream idle timeout")
+ }
+ return
+}
+
+func (stream *AIEditorChatStream) Close() {
+ stream.cancel()
+ stream.stream.Close()
+}
+
+// NewAIEditorChatStream 创建绑定到编辑器请求生命周期的模型流。
+func NewAIEditorChatStream(ctx context.Context, ids []string, input, action string, history []AIEditorMessage) (*AIEditorChatStream, error) {
+ if !Conf.AI.HasAnyProvider() {
+ return nil, errors.New("no AI provider configured")
+ }
+
+ prov, m := Conf.AI.GetEditingModel()
+ if nil == prov || nil == m {
+ return nil, errors.New("no AI editing model configured")
+ }
+ editing := Conf.AI.Editing
+ if nil == editing {
+ return nil, errors.New("no AI editing config")
+ }
+
+ if "" == input && 0 < len(ids) {
+ input = getBlocksContent(ids)
+ }
+ prompt := BuildAIEditorPrompt(input, action)
+ if "" == strings.TrimSpace(prompt) {
+ return nil, errors.New("AI editor input is empty")
+ }
+
+ if editing.MaxHistoryMessages < len(history) {
+ history = history[len(history)-editing.MaxHistoryMessages:]
+ }
+ messages := make([]openai.ChatCompletionMessage, 0, len(history)+1)
+ for _, item := range history {
+ role := strings.TrimSpace(item.Role)
+ content := strings.TrimSpace(item.Content)
+ if "" == content || (openai.ChatMessageRoleUser != role && openai.ChatMessageRoleAssistant != role) {
+ continue
+ }
+ messages = append(messages, openai.ChatCompletionMessage{Role: role, Content: content})
+ }
+ messages = append(messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: prompt})
+
+ req := openai.ChatCompletionRequest{
+ Model: m.Name,
+ MaxCompletionTokens: editing.MaxCompletionTokens,
+ Temperature: float32(editing.Temperature),
+ Messages: messages,
+ Stream: true,
+ }
+ streamCtx, cancel := context.WithCancel(ctx)
+ requestTimeout := time.Duration(prov.RequestTimeout) * time.Second
+ requestTimer, requestTimerDone := startAIEditorCancelTimer(requestTimeout, cancel)
+ client := util.NewOpenAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name)
+ completionStream, err := client.CreateChatCompletionStream(streamCtx, req)
+ requestTimedOut := stopAIEditorCancelTimer(requestTimer, requestTimerDone)
+ if requestTimedOut {
+ err = errors.New("AI editor request timeout")
+ }
+ if nil != err {
+ cancel()
+ return nil, err
+ }
+ if nil == completionStream {
+ cancel()
+ return nil, errors.New("AI editor model returned nil stream")
+ }
+ return &AIEditorChatStream{
+ stream: completionStream,
+ cancel: cancel,
+ idleTimeout: 120 * time.Second,
+ }, nil
+}
+
+func startAIEditorCancelTimer(timeout time.Duration, cancel context.CancelFunc) (*time.Timer, <-chan struct{}) {
+ if 0 >= timeout {
+ return nil, nil
+ }
+ done := make(chan struct{})
+ timer := time.AfterFunc(timeout, func() {
+ cancel()
+ close(done)
+ })
+ return timer, done
+}
+
+func stopAIEditorCancelTimer(timer *time.Timer, done <-chan struct{}) bool {
+ if nil == timer {
+ return false
+ }
+ if timer.Stop() {
+ return false
+ }
+ <-done
+ return true
+}
+
+func IsAIEditorStreamDone(err error) bool {
+ return errors.Is(err, io.EOF)
+}
+
func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string, retContextMsgs []string, err error) {
util.PushEndlessProgress("Requesting...")
defer util.ClearPushProgress(100)
diff --git a/kernel/model/ai_prompt_test.go b/kernel/model/ai_prompt_test.go
new file mode 100644
index 0000000000..e874b3354e
--- /dev/null
+++ b/kernel/model/ai_prompt_test.go
@@ -0,0 +1,53 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import "testing"
+
+func TestBuildAIEditorPrompt(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ action string
+ want string
+ }{
+ {
+ name: "input only",
+ input: "Selected text",
+ want: "Selected text",
+ },
+ {
+ name: "compatible prefix",
+ input: "Selected text",
+ action: "Translate",
+ want: "Translate:\n\nSelected text",
+ },
+ {
+ name: "replace every placeholder",
+ input: "Selected text",
+ action: "Before {{input}} and after {{input}}",
+ want: "Before Selected text and after Selected text",
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := BuildAIEditorPrompt(test.input, test.action); got != test.want {
+ t.Fatalf("unexpected prompt: %q", got)
+ }
+ })
+ }
+}