Skip to content

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

:sparkles: Support tagged snapshot associations in file history https://github.com/siyuan-note/siyuan/issues/19916

Daniel5e869bf3c8ba
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index ddb7f50bb8..00db528c6e 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "اللقطات الموسومة المرتبطة",
+ "historySnapshotsError": "تعذّر تحميل اللقطات المرتبطة",
+ "historySnapshotMissing": "هذه اللقطة لم تعد متاحة",
"autoDirection": "اتجاه النص التلقائي",
"autoDirectionTip": "تحديد اتجاه الفقرات والعناوين تلقائيًا حسب أول حرف ذي اتجاه قوي، مع إعطاء الأولوية للاتجاه المحدد يدويًا",
"cardFullRowTip": "يشغل الحقل الأساسي صفًا كاملًا دائمًا؛ أوقف عرض أسماء الحقول لترتيب الحقول الأخرى بشكل مضغوط",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 9d61182461..d3e7325237 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Zugehörige markierte Schnappschüsse",
+ "historySnapshotsError": "Zugehörige Schnappschüsse konnten nicht geladen werden",
+ "historySnapshotMissing": "Dieser Schnappschuss ist nicht mehr verfügbar",
"autoDirection": "Automatische Textrichtung",
"autoDirectionTip": "Richtung von Absätzen und Überschriften anhand des ersten Zeichens mit starker Schreibrichtung automatisch bestimmen; manuelle Einstellungen haben Vorrang",
"cardFullRowTip": "Das Primärfeld belegt immer eine ganze Zeile; blende die Feldnamen aus, um andere Felder kompakt anzuordnen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 4280e80b51..ddda845f83 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Related tagged snapshots",
+ "historySnapshotsError": "Unable to load related snapshots",
+ "historySnapshotMissing": "This snapshot is no longer available",
"autoDirection": "Automatic text direction",
"autoDirectionTip": "Detect paragraph and heading direction from the first strong directional character; manual direction takes priority",
"cardFullRowTip": "The primary field always occupies a full row; hide field names to arrange other fields compactly",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 6fb1e1b353..af3225c76f 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Instantáneas etiquetadas relacionadas",
+ "historySnapshotsError": "No se pueden cargar las instantáneas relacionadas",
+ "historySnapshotMissing": "Esta instantánea ya no está disponible",
"autoDirection": "Dirección automática del texto",
"autoDirectionTip": "Detectar la dirección de párrafos y encabezados a partir del primer carácter direccional fuerte; la dirección manual tiene prioridad",
"cardFullRowTip": "El campo principal siempre ocupa una fila completa; oculta los nombres de los campos para distribuir los demás de forma compacta",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 813a076d3f..5d7466ed28 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Instantanés étiquetés associés",
+ "historySnapshotsError": "Impossible de charger les instantanés associés",
+ "historySnapshotMissing": "Cet instantané n’est plus disponible",
"autoDirection": "Direction automatique du texte",
"autoDirectionTip": "Détecter la direction des paragraphes et des titres à partir du premier caractère directionnel fort ; la direction manuelle est prioritaire",
"cardFullRowTip": "Le champ principal occupe toujours une ligne entière ; masquez les noms des champs pour disposer les autres de façon compacte",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index cdd55bb352..4fe89d30d1 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "תמונות מצב מתויגות קשורות",
+ "historySnapshotsError": "לא ניתן לטעון תמונות מצב קשורות",
+ "historySnapshotMissing": "תמונת מצב זו אינה זמינה עוד",
"autoDirection": "כיוון טקסט אוטומטי",
"autoDirectionTip": "זיהוי כיוון הפסקאות והכותרות לפי התו הראשון בעל כיווניות חזקה; כיוון שהוגדר ידנית מקבל עדיפות",
"cardFullRowTip": "השדה הראשי תמיד תופס שורה שלמה; יש להסתיר את שמות השדות כדי לסדר את שאר השדות בצפיפות",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 915e9f58d8..df635423be 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "संबंधित टैग किए गए स्नैपशॉट",
+ "historySnapshotsError": "संबंधित स्नैपशॉट लोड नहीं हो सके",
+ "historySnapshotMissing": "यह स्नैपशॉट अब उपलब्ध नहीं है",
"autoDirection": "स्वचालित पाठ दिशा",
"autoDirectionTip": "पहले प्रबल दिशात्मक वर्ण से अनुच्छेद और शीर्षक की दिशा पहचानें; मैन्युअल दिशा को प्राथमिकता दी जाती है",
"cardFullRowTip": "मुख्य फ़ील्ड हमेशा पूरी पंक्ति घेरता है; अन्य फ़ील्ड को सघन रूप से व्यवस्थित करने के लिए फ़ील्ड के नाम छिपाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index f0ad8b6088..e6b1f97443 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Snapshot bertanda terkait",
+ "historySnapshotsError": "Tidak dapat memuat snapshot terkait",
+ "historySnapshotMissing": "Snapshot ini sudah tidak tersedia",
"autoDirection": "Arah teks otomatis",
"autoDirectionTip": "Deteksi arah paragraf dan judul dari karakter pertama dengan arah kuat; arah yang diatur secara manual diutamakan",
"cardFullRowTip": "Kolom utama selalu menempati satu baris penuh; sembunyikan nama kolom untuk menata kolom lain secara ringkas",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index b7b5d07588..7e96cea769 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Istantanee contrassegnate correlate",
+ "historySnapshotsError": "Impossibile caricare le istantanee correlate",
+ "historySnapshotMissing": "Questa istantanea non è più disponibile",
"autoDirection": "Direzione automatica del testo",
"autoDirectionTip": "Rileva la direzione di paragrafi e titoli dal primo carattere direzionale forte; la direzione manuale ha la priorità",
"cardFullRowTip": "Il campo principale occupa sempre un'intera riga; nascondi i nomi dei campi per disporre gli altri in modo compatto",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index edd0e74fd8..35cd4aaa7a 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "関連するタグ付きスナップショット",
+ "historySnapshotsError": "関連するスナップショットを読み込めません",
+ "historySnapshotMissing": "このスナップショットは存在しません",
"autoDirection": "テキスト方向の自動判定",
"autoDirectionTip": "最初の強い方向性を持つ文字に基づいて段落と見出しの方向を自動判定し、手動で指定した方向を優先します",
"cardFullRowTip": "主キーフィールドは常に行全体を占有します。他のフィールドをコンパクトに配置するには、フィールド名の表示をオフにしてください",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 1ff73ebaf0..213559ba75 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "관련 태그 스냅샷",
+ "historySnapshotsError": "관련 스냅샷을 불러올 수 없습니다",
+ "historySnapshotMissing": "이 스냅샷은 더 이상 사용할 수 없습니다",
"autoDirection": "자동 텍스트 방향",
"autoDirectionTip": "첫 번째 강한 방향성 문자를 기준으로 문단과 제목의 방향을 감지하며, 수동으로 지정한 방향을 우선 적용",
"cardFullRowTip": "기본 필드는 항상 한 행 전체를 차지합니다. 다른 필드를 조밀하게 배치하려면 필드 이름을 숨기세요",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 43d90ff888..39e9d135fe 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Gerelateerde gemarkeerde momentopnamen",
+ "historySnapshotsError": "Gerelateerde momentopnamen kunnen niet worden geladen",
+ "historySnapshotMissing": "Deze momentopname is niet meer beschikbaar",
"autoDirection": "Automatische tekstrichting",
"autoDirectionTip": "Bepaal de richting van alinea’s en koppen op basis van het eerste teken met een sterke schrijfrichting; handmatige instellingen hebben voorrang",
"cardFullRowTip": "Het primaire veld neemt altijd een volledige rij in beslag; verberg veldnamen om andere velden compact te rangschikken",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 05f6f8f404..c7741a628e 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Powiązane oznaczone migawki",
+ "historySnapshotsError": "Nie można wczytać powiązanych migawek",
+ "historySnapshotMissing": "Ta migawka nie jest już dostępna",
"autoDirection": "Automatyczny kierunek tekstu",
"autoDirectionTip": "Wykrywaj kierunek akapitów i nagłówków na podstawie pierwszego znaku o silnej kierunkowości; kierunek ustawiony ręcznie ma pierwszeństwo",
"cardFullRowTip": "Pole główne zawsze zajmuje cały wiersz; ukryj nazwy pól, aby rozmieścić pozostałe pola w sposób zwarty",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index e0104e86e5..d5c1de6298 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Snapshots marcados relacionados",
+ "historySnapshotsError": "Não foi possível carregar os snapshots relacionados",
+ "historySnapshotMissing": "Este snapshot não está mais disponível",
"autoDirection": "Direção automática do texto",
"autoDirectionTip": "Detectar a direção de parágrafos e títulos pelo primeiro caractere direcional forte; a direção manual tem prioridade",
"cardFullRowTip": "O campo principal sempre ocupa uma linha inteira; oculte os nomes dos campos para organizar os demais de forma compacta",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 645cba00cb..fbb18dab14 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Связанные помеченные снимки",
+ "historySnapshotsError": "Не удалось загрузить связанные снимки",
+ "historySnapshotMissing": "Этот снимок больше недоступен",
"autoDirection": "Автоматическое направление текста",
"autoDirectionTip": "Определять направление абзацев и заголовков по первому символу с сильной направленностью; ручная настройка имеет приоритет",
"cardFullRowTip": "Основное поле всегда занимает всю строку; скройте названия полей, чтобы расположить остальные поля компактно",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index fc1570638a..6001806f3c 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Súvisiace označené snímky",
+ "historySnapshotsError": "Súvisiace snímky sa nepodarilo načítať",
+ "historySnapshotMissing": "Táto snímka už nie je dostupná",
"autoDirection": "Automatický smer textu",
"autoDirectionTip": "Určiť smer odsekov a nadpisov podľa prvého znaku so silnou smerovosťou; ručné nastavenie má prednosť",
"cardFullRowTip": "Primárne pole vždy zaberá celý riadok; skryte názvy polí, aby sa ostatné polia usporiadali kompaktne",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 078296695b..7cf7472993 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Повезани означени снимци",
+ "historySnapshotsError": "Није могуће учитати повезане снимке",
+ "historySnapshotMissing": "Овај снимак више није доступан",
"autoDirection": "Аутоматски смер текста",
"autoDirectionTip": "Одреди смер пасуса и наслова према првом знаку са јаком усмереношћу; ручно подешен смер има предност",
"cardFullRowTip": "Примарно поље увек заузима цео ред; сакријте називе поља да бисте остала поља распоредили компактно",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 3279f45735..8903b6db18 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "สแนปช็อตที่ติดแท็กที่เกี่ยวข้อง",
+ "historySnapshotsError": "ไม่สามารถโหลดสแนปช็อตที่เกี่ยวข้องได้",
+ "historySnapshotMissing": "สแนปช็อตนี้ไม่มีอยู่แล้ว",
"autoDirection": "ทิศทางข้อความอัตโนมัติ",
"autoDirectionTip": "ตรวจจับทิศทางของย่อหน้าและหัวเรื่องจากอักขระตัวแรกที่มีทิศทางชัดเจน โดยให้ความสำคัญกับทิศทางที่กำหนดด้วยตนเอง",
"cardFullRowTip": "ฟิลด์หลักจะใช้พื้นที่เต็มแถวเสมอ ซ่อนชื่อฟิลด์เพื่อจัดเรียงฟิลด์อื่นให้กระชับ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 7651e3858a..5a60fd4885 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "İlgili etiketli anlık görüntüler",
+ "historySnapshotsError": "İlgili anlık görüntüler yüklenemedi",
+ "historySnapshotMissing": "Bu anlık görüntü artık mevcut değil",
"autoDirection": "Otomatik metin yönü",
"autoDirectionTip": "Paragraf ve başlık yönünü güçlü yönlülüğe sahip ilk karakterden algıla; elle ayarlanan yön önceliklidir",
"cardFullRowTip": "Birincil alan her zaman tam bir satır kaplar; diğer alanları sıkışık yerleştirmek için alan adlarını gizleyin",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 8ea7acf29f..c6ae3daa8a 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "Пов’язані позначені знімки",
+ "historySnapshotsError": "Не вдалося завантажити пов’язані знімки",
+ "historySnapshotMissing": "Цей знімок більше недоступний",
"autoDirection": "Автоматичний напрямок тексту",
"autoDirectionTip": "Визначати напрямок абзаців і заголовків за першим символом із сильною спрямованістю; ручне налаштування має пріоритет",
"cardFullRowTip": "Основне поле завжди займає весь рядок; приховайте назви полів, щоб розташувати інші поля компактно",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 2d6b0f4ce5..e9dc3b6303 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "关联标记快照",
+ "historySnapshotsError": "无法加载关联快照",
+ "historySnapshotMissing": "该快照已不存在",
"autoDirection": "自动文本方向",
"autoDirectionTip": "根据首个具有强方向性的字符自动判定段落和标题的方向,手动设置的方向优先",
"cardFullRowTip": "主键字段始终独占整行;关闭「显示字段名称」后,其他字段才能紧凑排列",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 4c19617728..55b7a99cc9 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "historySnapshots": "關聯標記快照",
+ "historySnapshotsError": "無法載入關聯快照",
+ "historySnapshotMissing": "此快照已不存在",
"autoDirection": "自動文字方向",
"autoDirectionTip": "根據首個具有強方向性的字元自動判定段落和標題的方向,手動設定的方向優先",
"cardFullRowTip": "主鍵欄位始終獨佔整列;關閉「顯示欄位名稱」後,其他欄位才能緊湊排列",
diff --git a/app/src/assets/scss/business/_history.scss b/app/src/assets/scss/business/_history.scss
index d1c876bce6..d7661d3200 100644
--- a/app/src/assets/scss/business/_history.scss
+++ b/app/src/assets/scss/business/_history.scss
@@ -1,4 +1,94 @@
.history {
+ &__associations {
+ padding: 8px 16px;
+ flex-shrink: 0;
+
+ summary {
+ cursor: pointer;
+ }
+ }
+
+ &__association-list {
+ max-height: 30vh;
+ overflow: auto;
+ }
+
+ &__association {
+ padding: 8px 0;
+ }
+
+ &__association-heading {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 4px 12px;
+ }
+
+ &__association-link {
+ max-width: 100%;
+ min-width: 0;
+ }
+
+ &__association-memo {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ }
+
+ &__snapshot-detail,
+ &__snapshot-detail-content {
+ height: 100%;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ }
+
+ &__snapshot-detail-meta {
+ padding: 12px 16px;
+ max-height: 25vh;
+ overflow: auto;
+ overflow-wrap: anywhere;
+ flex-shrink: 0;
+ }
+
+ &__snapshot-detail-panels {
+ display: flex;
+ min-height: 0;
+ flex: 1;
+ }
+
+ &__snapshot-detail-files {
+ width: 35%;
+ min-width: 0;
+ overflow: auto;
+ }
+
+ &__snapshot-detail-preview {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+
+ > div {
+ flex: 1;
+ min-height: 0;
+ }
+ }
+
+ @media (max-width: 600px) {
+ &__snapshot-detail-panels {
+ flex-direction: column;
+ }
+
+ &__snapshot-detail-files {
+ width: auto;
+ max-height: 25vh;
+ flex-shrink: 0;
+ }
+ }
+
&__snapshots {
min-width: 0;
min-height: 0;
diff --git a/app/src/history/doc.ts b/app/src/history/doc.ts
index 51de74a025..b2c9856108 100644
--- a/app/src/history/doc.ts
+++ b/app/src/history/doc.ts
@@ -13,10 +13,10 @@ import {resizeSide} from "./resizeSide";
import {escapeHtml} from "../util/escape";
import {renderRepoFile, renderRepoFileList, rollbackRepoFile, saveRepoFile} from "./repoFile";
import {showDocVersionDiff, type IDocVersionRef} from "./docDiff";
+import {DocHistorySnapshots, getDocHistorySnapshots} from "./docSnapshots";
+import {forgetNotebookHistoryDialog, trackNotebookHistoryDialog} from "./notebookDialogs";
-let historyEditor: Protyle;
const repoHistoryEditors = new WeakMap<HTMLElement, Protyle>();
-let isLoading = false;
const genCurrentVersionItem = () => `<li class="b3-list-item history__current-version" data-type="currentVersionItem">
<span class="b3-list-item__text">${window.siyuan.languages.currentVer}</span>
@@ -27,6 +27,9 @@ const genCurrentVersionItem = () => `<li class="b3-list-item history__current-ve
</li>`;
const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
+ getDocHistorySnapshots(element)?.reset();
+ const request = (Number(element.dataset.historyRequest) || 0) + 1;
+ element.dataset.historyRequest = String(request);
const previousElement = element.querySelector('[data-type="docprevious"]');
const nextElement = element.querySelector('[data-type="docnext"]');
if (currentPage > 1) {
@@ -45,6 +48,9 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
op: opElement.value,
type: 3
}, (response) => {
+ if (!element.isConnected || element.dataset.historyRequest !== String(request)) {
+ return;
+ }
if (currentPage < response.data.pageCount) {
nextElement.removeAttribute("disabled");
} else {
@@ -70,7 +76,7 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
let logsHTML = genCurrentVersionItem();
histories.forEach((item: string) => {
logsHTML += `<li class="b3-list-item b3-list-item--hide-action" data-created="${item}">
- <span class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
+ <div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span><span data-history-tags="${item}"></span></div>
<span class="fn__space"></span>
<span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">
<svg><use xlink:href="#iconUndo"></use></svg>
@@ -82,6 +88,7 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
});
listElement.innerHTML = logsHTML;
element.dispatchEvent(new CustomEvent("versionListRendered"));
+ void getDocHistorySnapshots(element)?.load(histories, opElement.value);
});
};
@@ -153,6 +160,20 @@ export const openDocHistory = (options: {
notebookId: string,
pathString: string
}) => {
+ let historyEditor: Protyle;
+ let isLoading = false;
+ const getHistoryPath = (target: Element, op: string, id: string, cb: (item: {path: string, title: string}) => void) => {
+ isLoading = true;
+ const created = target.getAttribute("data-created");
+ historyEditor.protyle.options.history.created = created;
+ fetchPost("/api/history/getHistoryItems", {query: id, op, type: 3, created}, response => {
+ if (!target.isConnected || !historyEditor || !response.data.items.length) {
+ isLoading = false;
+ return;
+ }
+ cb(response.data.items[0]);
+ });
+ };
const currentVersion = {
type: "current" as const,
id: options.id,
@@ -234,12 +255,16 @@ export const openDocHistory = (options: {
height: isMobile() ? "100dvh" : "80vh",
containerClassName: "b3-dialog__container--theme",
destroyCallback() {
+ forgetNotebookHistoryDialog(dialog);
+ getDocHistorySnapshots(fileElement)?.destroy();
+ historyEditor?.destroy();
historyEditor = undefined;
repoHistoryEditors.get(repoElement)?.destroy();
repoHistoryEditors.delete(repoElement);
}
});
dialog.element.setAttribute("data-key", Constants.DIALOG_HISTORYDOC);
+ trackNotebookHistoryDialog(dialog, [options.notebookId]);
const versionKey = (version: IDocVersionRef) => `${version.type}:${version.id || version.path || ""}`;
const syncVersionSelection = () => {
@@ -280,6 +305,7 @@ export const openDocHistory = (options: {
};
const fileElement = dialog.element.querySelector('#docHistoryContainer [data-type="doc"]') as HTMLElement;
+ const historySnapshots = new DocHistorySnapshots(options.app, fileElement, options.id);
const repoElement = dialog.element.querySelector('#docHistoryContainer [data-type="repo"]') as HTMLElement;
fileElement.addEventListener("versionListRendered", syncVersionSelection);
repoElement.addEventListener("versionListRendered", syncVersionSelection);
@@ -401,6 +427,7 @@ export const openDocHistory = (options: {
event.preventDefault();
break;
} else if (target.classList.contains("b3-list-item") && type === "currentVersionItem") {
+ historySnapshots.select("");
toggleVersionSelection(currentVersion);
event.stopPropagation();
event.preventDefault();
@@ -429,11 +456,16 @@ export const openDocHistory = (options: {
break;
} else if (target.classList.contains("b3-list-item") &&
target.getAttribute("data-type") !== "searchFileItem" && !isLoading) {
+ historySnapshots.select(target.getAttribute("data-created"));
getHistoryPath(target, opElement.value, options.id, (item) => {
const dataPath = item.path;
fetchPost("/api/history/getDocHistoryContent", {
historyPath: dataPath,
}, (response) => {
+ if (!target.isConnected || !historyEditor) {
+ isLoading = false;
+ return;
+ }
if (response.data.isLargeDoc) {
mdElement.value = response.data.content;
mdElement.classList.remove("fn__none");
@@ -511,21 +543,3 @@ export const openDocHistory = (options: {
resizeSide(fileElement.querySelector(".history__resize"), fileElement.querySelector(".history__side"), "sideDocWidth");
resizeSide(repoElement.querySelector(".history__resize"), repoElement.querySelector(".history__side"), "sideDocWidth");
};
-
-const getHistoryPath = (target: Element, op: string, id: string, cb: (item: any) => void) => {
- isLoading = true;
- const path = target.getAttribute("data-path");
- if (path) {
- cb(path);
- }
- const created = target.getAttribute("data-created");
- historyEditor.protyle.options.history.created = created;
- fetchPost("/api/history/getHistoryItems", {
- query: id,
- op,
- type: 3,
- created
- }, (response) => {
- cb(response.data.items[0]);
- });
-};
diff --git a/app/src/history/docSnapshots.test.ts b/app/src/history/docSnapshots.test.ts
new file mode 100644
index 0000000000..b56194c177
--- /dev/null
+++ b/app/src/history/docSnapshots.test.ts
@@ -0,0 +1,89 @@
+import {it} from "node:test";
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {ScriptTarget, transpileModule} from "typescript";
+import {escapeAttr, escapeHtml} from "../util/escape";
+
+const setup = () => {
+ const source = readFileSync(join(__dirname, "docSnapshots.ts"), "utf8");
+ const code = source.slice(source.indexOf("const views =")).replace(/export /g, "");
+ const panel = {innerHTML: "", textContent: "", classList: {toggle() {}, add() {}}, setAttribute() {}, querySelector: (): HTMLElement | null => null};
+ const summary = {innerHTML: "", dataset: {historyTags: "1"}};
+ const listeners: Record<string, (event: unknown) => void> = {};
+ const element = {
+ isConnected: true,
+ querySelector: () => ({before() {}}),
+ querySelectorAll: () => [summary],
+ addEventListener: (name: string, cb: (event: unknown) => void) => { listeners[name] = cb; },
+ contains: () => true,
+ };
+ const pending: ((response: unknown) => void)[] = [];
+ const signals: AbortSignal[] = [];
+ const opened: unknown[] = [];
+ const dependencies = {
+ document: {createElement: () => panel},
+ window: {siyuan: {languages: {loading: "loading", historySnapshots: "snapshots", historySnapshotsError: "failed", retry: "retry"}}},
+ fetchSyncPost: (_url: string, _body: unknown, _headers: unknown, _process: boolean, signal: AbortSignal) => {
+ signals.push(signal);
+ return new Promise(resolve => pending.push(resolve));
+ },
+ openSnapshotDetail: (_app: unknown, snapshot: unknown) => opened.push(snapshot),
+ escapeAttr, escapeHtml, dayjs: () => ({format: () => "date"}),
+ };
+ const View = new Function(...Object.keys(dependencies), transpileModule(code, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText + "\nreturn DocHistorySnapshots;")(...Object.values(dependencies));
+ return {view: new View({}, element, "doc"), panel, summary, pending, signals, opened, listeners, element};
+};
+
+const snapshot = (id: string) => ({id, fileID: "file", tags: ["<tag>"], memo: "<script>alert(1)</script>\nline", created: 1});
+const response = (ids: string[]) => ({code: 0, data: {histories: [{created: "1", historyPath: "history/path", snapshots: ids.map(snapshot)}]}});
+
+it("keeps all matching snapshots, escapes notes and opens the clicked snapshot", async () => {
+ const {view, panel, summary, pending, opened, listeners} = setup();
+ const loading = view.load(["1"], "all");
+ view.select("1");
+ pending[0](response(["first", "second"]));
+ await loading;
+ assert.match(summary.innerHTML, /\+1/);
+ assert.match(panel.innerHTML, /snapshots \(2\)/);
+ assert.match(panel.innerHTML, /&lt;script>/);
+ assert.ok(!panel.innerHTML.includes("<script>"));
+ assert.match(panel.innerHTML, /data-history-snapshot="second"/);
+ let stopped = false;
+ listeners.click({target: {closest: () => ({hasAttribute: () => false, dataset: {historyCreated: "1", historySnapshot: "second"}})}, stopPropagation: () => { stopped = true; }});
+ assert.deepEqual(opened, [snapshot("second")]);
+ assert.ok(stopped);
+});
+
+it("discards an earlier page response and cancels work when the dialog closes", async () => {
+ const {view, pending, signals, summary} = setup();
+ const old = view.load(["1"], "all");
+ view.reset();
+ const current = view.load(["1"], "update");
+ pending[1](response(["current"]));
+ await current;
+ pending[0](response(["stale"]));
+ await old;
+ assert.match(summary.innerHTML, /current/);
+ assert.ok(!summary.innerHTML.includes("stale"));
+ assert.ok(signals[0].aborted);
+ view.destroy();
+ assert.ok(signals[1].aborted);
+});
+
+it("distinguishes failed queries from an empty successful match", async () => {
+ const {view, pending, panel, summary} = setup();
+ view.select("1");
+ const failed = view.load(["1"], "all");
+ pending[0]({code: -1, msg: "corrupt"});
+ await failed;
+ assert.match(panel.innerHTML, /failed/);
+ assert.match(summary.innerHTML, /data-history-retry/);
+ const retried = view.load(["1"], "all");
+ pending[1](response([]));
+ await retried;
+ assert.equal(summary.innerHTML, "");
+ assert.ok(!panel.innerHTML.includes("failed"));
+});
diff --git a/app/src/history/docSnapshots.ts b/app/src/history/docSnapshots.ts
new file mode 100644
index 0000000000..4cdbe0c55a
--- /dev/null
+++ b/app/src/history/docSnapshots.ts
@@ -0,0 +1,140 @@
+import type {App} from "../index";
+import type {DocHistorySnapshot, DocHistorySnapshotEntry} from "../types/api";
+import {fetchSyncPost} from "../util/fetch";
+import {escapeAttr, escapeHtml} from "../util/escape";
+import * as dayjs from "dayjs";
+import {openSnapshotDetail} from "./snapshotDetail";
+
+const views = new WeakMap<Element, DocHistorySnapshots>();
+
+export const getDocHistorySnapshots = (element: Element) => views.get(element);
+
+export class DocHistorySnapshots {
+ private entries = new Map<string, DocHistorySnapshotEntry>();
+ private request = 0;
+ private created: string[] = [];
+ private op = "all";
+ private selected = "";
+ private error = "";
+ private loading = false;
+ private abort?: AbortController;
+ private panel: HTMLElement;
+
+ constructor(private app: App, private element: HTMLElement, private id: string) {
+ views.set(element, this);
+ this.panel = document.createElement("section");
+ this.panel.className = "history__associations fn__none";
+ this.panel.setAttribute("aria-live", "polite");
+ const title = element.querySelector(".protyle-title__input");
+ title.before(this.panel);
+ element.addEventListener("click", event => {
+ const target = (event.target as Element).closest<HTMLElement>("[data-history-snapshot], [data-history-retry]");
+ if (!target || !element.contains(target)) {
+ return;
+ }
+ event.stopPropagation();
+ if (target.hasAttribute("data-history-retry")) {
+ void this.load(this.created, this.op);
+ return;
+ }
+ const entry = this.entries.get(target.dataset.historyCreated);
+ const snapshot = entry?.snapshots.find(item => item.id === target.dataset.historySnapshot);
+ if (snapshot) {
+ void openSnapshotDetail(this.app, snapshot, entry.historyPath.split("/").filter(Boolean)[2]);
+ }
+ });
+ }
+
+ reset() {
+ this.abort?.abort();
+ this.request++;
+ this.entries.clear();
+ this.selected = "";
+ this.error = "";
+ this.loading = false;
+ this.panel.innerHTML = "";
+ this.panel.classList.add("fn__none");
+ }
+
+ destroy() {
+ this.reset();
+ views.delete(this.element);
+ }
+
+ select(created: string) {
+ this.selected = created;
+ this.renderPanel();
+ }
+
+ async load(created: string[], op: string) {
+ this.abort?.abort();
+ this.abort = new AbortController();
+ const request = ++this.request;
+ this.created = created;
+ this.op = op;
+ this.error = "";
+ this.loading = true;
+ this.entries.clear();
+ this.renderPanel();
+ if (created.length === 0) {
+ this.loading = false;
+ this.renderPanel();
+ return;
+ }
+ try {
+ const response = await fetchSyncPost("/api/history/getDocHistorySnapshots", {
+ id: this.id, created, op
+ }, undefined, false, this.abort.signal);
+ if (request !== this.request || !this.element.isConnected) {
+ return;
+ }
+ if (response.code !== 0) {
+ throw new Error(response.msg);
+ }
+ response.data.histories.forEach(entry => this.entries.set(entry.created, entry));
+ } catch (error) {
+ if (request !== this.request || !this.element.isConnected) {
+ return;
+ }
+ this.error = error instanceof Error ? error.message : String(error);
+ }
+ this.loading = false;
+ this.element.querySelectorAll<HTMLElement>("[data-history-tags]").forEach(summary => {
+ const created = summary.dataset.historyTags;
+ const snapshots = this.entries.get(created)?.snapshots || [];
+ if (this.error) {
+ summary.innerHTML = `<button class="b3-button b3-button--text" data-history-retry title="${escapeAttr(escapeHtml(this.error))}">${window.siyuan.languages.historySnapshotsError}</button>`;
+ } else if (snapshots.length) {
+ const names = snapshots.flatMap(item => item.tags).join(" / ");
+ summary.innerHTML = `<button class="b3-button b3-button--text history__association-link" data-history-created="${escapeAttr(created)}" data-history-snapshot="${snapshots[0].id}" title="${escapeAttr(escapeHtml(names))}"><svg><use xlink:href="#iconTags"></use></svg><span class="fn__ellipsis">${escapeHtml(snapshots[0].tags.join(" / "))}</span>${snapshots.length > 1 ? `<span class="fn__space"></span><span>+${snapshots.length - 1}</span>` : ""}</button>`;
+ } else {
+ summary.innerHTML = "";
+ }
+ });
+ this.renderPanel();
+ }
+
+ private renderPanel() {
+ const snapshots = this.entries.get(this.selected)?.snapshots || [];
+ this.panel.classList.toggle("fn__none", !this.selected || (!this.loading && !this.error && !snapshots.length));
+ if (!this.selected) {
+ return;
+ }
+ const lang = window.siyuan.languages;
+ if (this.loading) {
+ this.panel.textContent = lang.loading;
+ } else if (this.error) {
+ this.panel.innerHTML = `<span class="ft__error">${lang.historySnapshotsError}</span><span class="fn__space"></span><button class="b3-button b3-button--outline" data-history-retry title="${escapeAttr(escapeHtml(this.error))}">${lang.retry}</button>`;
+ } else {
+ const open = this.panel.querySelector("details")?.open ?? true;
+ this.panel.innerHTML = `<details${open ? " open" : ""}><summary>${lang.historySnapshots} (${snapshots.length})</summary><div class="history__association-list">${snapshots.map(snapshot => this.renderSnapshot(snapshot)).join("")}</div></details>`;
+ }
+ }
+
+ private renderSnapshot(snapshot: DocHistorySnapshot) {
+ return `<div class="history__association">
+ <div class="history__association-heading"><button class="b3-button b3-button--text history__association-link" data-history-created="${escapeAttr(this.selected)}" data-history-snapshot="${snapshot.id}"><svg><use xlink:href="#iconTags"></use></svg><span class="fn__ellipsis">${escapeHtml(snapshot.tags.join(" / "))}</span></button><span class="ft__on-surface">${dayjs(snapshot.created).format("YYYY-MM-DD HH:mm:ss")}</span></div>
+ <div class="history__association-memo">${escapeHtml(snapshot.memo)}</div>
+</div>`;
+ }
+}
diff --git a/app/src/history/notebookDialogs.test.ts b/app/src/history/notebookDialogs.test.ts
new file mode 100644
index 0000000000..bda15f80fe
--- /dev/null
+++ b/app/src/history/notebookDialogs.test.ts
@@ -0,0 +1,22 @@
+import {it} from "node:test";
+import * as assert from "node:assert/strict";
+import type {Dialog} from "../dialog";
+import {closeNotebookHistoryDialogs, forgetNotebookHistoryDialog, trackNotebookHistoryDialog} from "./notebookDialogs";
+
+it("closes snapshot details before their history dialog when a notebook locks", () => {
+ const closed: string[] = [];
+ const makeDialog = (name: string) => ({destroy: () => { closed.push(name); }} as Dialog);
+ const history = makeDialog("history");
+ const detail = makeDialog("detail");
+ const other = makeDialog("other");
+ trackNotebookHistoryDialog(history, ["encrypted"]);
+ trackNotebookHistoryDialog(detail, ["encrypted", "another"]);
+ trackNotebookHistoryDialog(other, ["unrelated"]);
+ closeNotebookHistoryDialogs("encrypted");
+ assert.deepEqual(closed, ["detail", "history"]);
+ closeNotebookHistoryDialogs("another");
+ assert.equal(closed.length, 2);
+ forgetNotebookHistoryDialog(other);
+ closeNotebookHistoryDialogs("unrelated");
+ assert.equal(closed.length, 2);
+});
diff --git a/app/src/history/notebookDialogs.ts b/app/src/history/notebookDialogs.ts
new file mode 100644
index 0000000000..8ea2c0fe81
--- /dev/null
+++ b/app/src/history/notebookDialogs.ts
@@ -0,0 +1,21 @@
+import type {Dialog} from "../dialog";
+
+const dialogs = new Map<Dialog, Set<string>>();
+
+export const trackNotebookHistoryDialog = (dialog: Dialog, notebooks: string[]) => {
+ dialogs.set(dialog, new Set(notebooks));
+};
+
+export const forgetNotebookHistoryDialog = (dialog: Dialog) => {
+ dialogs.delete(dialog);
+};
+
+export const closeNotebookHistoryDialogs = (notebook: string) => {
+ // 从上层详情开始关闭,避免焦点返回已经销毁的下层对话框。
+ Array.from(dialogs.entries()).reverse().forEach(([dialog, notebooks]) => {
+ if (notebooks.has(notebook)) {
+ dialog.destroy();
+ dialogs.delete(dialog);
+ }
+ });
+};
diff --git a/app/src/history/snapshotDetail.ts b/app/src/history/snapshotDetail.ts
new file mode 100644
index 0000000000..ebf2579a82
--- /dev/null
+++ b/app/src/history/snapshotDetail.ts
@@ -0,0 +1,107 @@
+import type {App} from "../index";
+import type {DocHistorySnapshot} from "../types/api";
+import {Dialog} from "../dialog";
+import {Protyle} from "../protyle";
+import {fetchSyncPost} from "../util/fetch";
+import {escapeHtml} from "../util/escape";
+import {isMobile} from "../util/functions";
+import {renderRepoFile} from "./repoFile";
+import * as dayjs from "dayjs";
+import {forgetNotebookHistoryDialog, trackNotebookHistoryDialog} from "./notebookDialogs";
+
+export const openSnapshotDetail = async (app: App, reference: DocHistorySnapshot, notebook: string) => {
+ const lang = window.siyuan.languages;
+ let editor: Protyle;
+ const abort = new AbortController();
+ const dialog = new Dialog({
+ title: escapeHtml(reference.tags.join(" / ")),
+ content: `<div class="history__snapshot-detail"><div data-detail-status>${lang.loading}</div><div class="history__snapshot-detail-content fn__none"><div class="history__snapshot-detail-meta"></div><div class="history__snapshot-detail-panels"><ul class="b3-list b3-list--background history__snapshot-detail-files"></ul><div class="history__snapshot-detail-preview"></div></div></div></div>`,
+ width: isMobile() ? "100vw" : "85vw",
+ height: isMobile() ? "100dvh" : "80vh",
+ containerClassName: "b3-dialog__container--theme",
+ destroyCallback: () => {
+ forgetNotebookHistoryDialog(dialog);
+ abort.abort();
+ dialog.element.querySelector(".history__snapshot-detail-preview")?.removeAttribute("data-request-id");
+ editor?.destroy();
+ }
+ });
+ const notebooks = new Set([notebook]);
+ trackNotebookHistoryDialog(dialog, Array.from(notebooks));
+ const root = dialog.element;
+ const status = root.querySelector<HTMLElement>("[data-detail-status]");
+ const list = root.querySelector<HTMLElement>(".history__snapshot-detail-files");
+ const preview = root.querySelector<HTMLElement>(".history__snapshot-detail-preview");
+ const select = (row: HTMLElement) => {
+ if (row.dataset.notebook) {
+ notebooks.add(row.dataset.notebook);
+ trackNotebookHistoryDialog(dialog, Array.from(notebooks));
+ }
+ editor?.destroy();
+ editor = undefined;
+ list.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");
+ row.classList.add("b3-list-item--focus");
+ renderRepoFile(app, row, preview, value => { editor = value; });
+ };
+ list.addEventListener("click", event => {
+ const row = (event.target as Element).closest<HTMLElement>("[data-id]");
+ if (row && list.contains(row)) {
+ select(row);
+ }
+ });
+ list.addEventListener("keydown", event => {
+ if (event.key === "Enter" || event.key === " ") {
+ const row = (event.target as Element).closest<HTMLElement>("[data-id]");
+ if (row) {
+ event.preventDefault();
+ select(row);
+ }
+ }
+ });
+ try {
+ const response = await fetchSyncPost("/api/repo/getRepoSnapshots", {id: reference.id, page: 1, includeFiles: true}, undefined, false, abort.signal);
+ if (abort.signal.aborted || !root.isConnected) {
+ return;
+ }
+ if (response.code !== 0) {
+ throw new Error(response.msg);
+ }
+ const snapshot = response.data.snapshots.find(item => item.id === reference.id);
+ if (!snapshot) {
+ throw new Error(lang.historySnapshotMissing);
+ }
+ root.querySelector(".history__snapshot-detail-meta").innerHTML = `<div class="ft__on-surface">${dayjs(snapshot.created).format("YYYY-MM-DD HH:mm:ss")} <code>${escapeHtml(snapshot.id)}</code></div><div class="history__association-memo">${escapeHtml(snapshot.memo)}</div>`;
+ const fragment = document.createDocumentFragment();
+ let selected: HTMLElement;
+ snapshot.files.forEach(file => {
+ const row = document.createElement("li");
+ row.className = "b3-list-item";
+ row.tabIndex = 0;
+ row.setAttribute("role", "button");
+ row.dataset.id = file.id;
+ row.dataset.snapshot = snapshot.id;
+ row.dataset.notebook = file.path.split("/").filter(Boolean)[0];
+ row.title = file.path;
+ const text = document.createElement("span");
+ text.className = "b3-list-item__text";
+ text.textContent = file.path;
+ row.append(text);
+ fragment.append(row);
+ if (file.id === reference.fileID) {
+ selected = row;
+ }
+ });
+ list.replaceChildren(fragment);
+ status.classList.add("fn__none");
+ root.querySelector(".history__snapshot-detail-content").classList.remove("fn__none");
+ if (selected) {
+ select(selected);
+ selected.scrollIntoView({block: "nearest"});
+ }
+ } catch (error) {
+ if (!abort.signal.aborted && root.isConnected) {
+ status.textContent = error instanceof Error ? error.message : String(error);
+ status.classList.add("ft__error");
+ }
+ }
+};
diff --git a/app/src/index.ts b/app/src/index.ts
index 527d62e64c..0ae421e797 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -1,4 +1,5 @@
import {Constants} from "./constants";
+import {closeNotebookHistoryDialogs} from "./history/notebookDialogs";
import {systemConfig} from "./config/systemConfig";
import {openStandaloneDatabaseItemByURI} from "./protyle/render/av/openStandaloneDatabaseItem";
/// #if BROWSER
@@ -197,6 +198,7 @@ export class App {
break;
case "closeBox":
case "removeBox":
+ closeNotebookHistoryDialogs(data.data.box);
removeBlockPanelEditors({notebookId: data.data.box});
getAllTabs().forEach((tab) => {
if (tab.headElement) {
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index c1858eda4d..f850c75ec8 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -1,4 +1,5 @@
import {openMobileFileById} from "../editor";
+import {closeNotebookHistoryDialogs} from "../../history/notebookDialogs";
import {MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";
import {showMobileBars} from "./mobileBars";
import {
@@ -123,6 +124,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
break;
case "closeBox":
case "removeBox": {
+ closeNotebookHistoryDialogs(data.data.box);
removeMobileBacklinkContent({notebookId: data.data.box});
window.siyuan.mobile.tabs?.removeNotebook(data.data.box);
break;
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index eb6924f5a6..e2faa8522e 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -862,6 +862,14 @@ export type DocHistoryContentData = { "content": string; "id": string; "isLargeD
export type DocHistoryContentRequestInput = { "highlight"?: boolean | null; "historyPath": string; "k"?: string | null; };
+export type DocHistorySnapshot = { "created": number; "fileID": string; "id": string; "memo": string; "tags": Array<string> | null; };
+
+export type DocHistorySnapshotEntry = { "created": string; "historyPath": string; "snapshots": Array<DocHistorySnapshot | null> | null; };
+
+export type DocHistorySnapshotsData = { "histories": Array<DocHistorySnapshotEntry | null> | null; };
+
+export type DocHistorySnapshotsRequestInput = { "created": Array<string>; "id": string; "op"?: string; };
+
export type DocInfo = { "attrViews": Array<DocAttrView | null> | null; "ial": Record<string, string> | null; "icon": string; "id": string; "name": string; "refCount": number; "refIDs": Array<string> | null; "rootID": string; "subFileCount": number; };
export type DocOrdersRequestInput = { "id": string; };
@@ -1142,7 +1150,7 @@ export type GetRepoDocHistoryRequestInput = { "id": string; "page": number; };
export type GetRepoFileRequestInput = { "id": string; };
-export type GetRepoSnapshotsRequestInput = { "id"?: string; "page": number; };
+export type GetRepoSnapshotsRequestInput = { "id"?: string; "includeFiles"?: boolean; "page": number; };
export type GetSnippetRequestInput = { "enabled": number; "keyword"?: string | null; "type": string; };
@@ -4162,6 +4170,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": DocHistoryContentData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/history/getDocHistorySnapshots": {
+ request: DocHistorySnapshotsRequestInput;
+ response: { "code": 0; "data": DocHistorySnapshotsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/history/getHistoryItems": {
request: HistoryItemsRequestInput;
response: { "code": 0; "data": HistoryItemsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index 769f4b0326..680d1ea720 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -1,4 +1,5 @@
import {onWindowWorkspaceStorageChanged} from "./workspace";
+import {closeNotebookHistoryDialogs} from "../history/notebookDialogs";
import {Constants} from "../constants";
import {systemConfig} from "../config/systemConfig";
import {Menus} from "../menus";
@@ -154,6 +155,7 @@ class App {
break;
case "closeBox":
case "removeBox":
+ closeNotebookHistoryDialogs(data.data.box);
removeBlockPanelEditors({notebookId: data.data.box});
getAllTabs().forEach((tab) => {
if (tab.headElement) {
diff --git a/app/tests/historySnapshots.test.js b/app/tests/historySnapshots.test.js
new file mode 100644
index 0000000000..60b4def6ca
--- /dev/null
+++ b/app/tests/historySnapshots.test.js
@@ -0,0 +1,193 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const runCases = async (sources, css, mobile, dark) => {
+ const assert = require("node:assert/strict");
+ const path = require("node:path");
+ const tick = () => new Promise(resolve => setTimeout(resolve, 80));
+ document.body.innerHTML = "";
+ const style = document.createElement("style");
+ style.textContent = css;
+ document.head.replaceChildren(style);
+ document.documentElement.dataset.themeMode = dark ? "dark" : "light";
+ new Function(sources.icons)();
+ const menu = document.createElement("div");
+ window.siyuan = {languages: JSON.parse(sources.languages), dialogs: [], storage: {}, zIndex: 100,
+ menus: {menu: {element: menu, remove() {}}}};
+ const snapshots = [
+ {id: "a".repeat(40), fileID: "doc-file", tags: ["发布版本", "阶段归档"], memo: "功能验收完成\n保留此版本用于后续对照", created: 1790557200000},
+ {id: "b".repeat(40), fileID: "doc-file", tags: ["周五备份"], memo: "包含相同文档版本", created: 1790470800000},
+ ];
+ let responseMode = "success";
+ let pending;
+ let signal;
+ const files = [{id: "doc-file", path: "/notebook/project/document.sy"}, ...Array.from({length: 20}, (_, i) => ({id: "file-" + i, path: "/notebook/project/note-" + i + ".sy"}))];
+ let nextID = 0;
+ const stubs = {
+ "util/genID": {genUUID: () => String(++nextID)},
+ "util/zIndex": {isAbove: () => false},
+ "dialog/moveResize": {moveResize() {}},
+ "util/functions": {isMobile: () => mobile},
+ "protyle/util/compatibility": {isNotCtrl: () => true, saveExportFile() {}},
+ "protyle": {Protyle: class {}},
+ "constants": {Constants: {TIMEOUT_DBLCLICK: 0, TIMEOUT_OPENDIALOG: 0, SIYUAN_ASSETS_IMAGE: [], SIYUAN_ASSETS_AUDIO: [], SIYUAN_ASSETS_VIDEO: []}},
+ "asset/renderAssets": {renderAssetsPreview: () => ""},
+ "dialog/confirmDialog": {confirmDialog() {}},
+ "protyle/util/onGet": {disabledProtyle() {}, onGet() {}},
+ "util/pathName": {pathPosix: () => require("node:path").posix},
+ "util/hostCapabilities": {getHostCapabilities: () => ({importExport: true})},
+ "dayjs": require(path.join(sources.app, "node_modules/dayjs")),
+ "util/fetch": {
+ fetchSyncPost: async (url, body, _headers, _process, abortSignal) => {
+ if (url === "/api/history/getDocHistorySnapshots") {
+ return {code: 0, data: {histories: [{created: "1", historyPath: "/history/date/notebook/document.sy", snapshots}]}};
+ }
+ assert.equal(url, "/api/repo/getRepoSnapshots");
+ assert.equal(body.includeFiles, true);
+ signal = abortSignal;
+ if (responseMode === "pending") {
+ return new Promise(resolve => { pending = resolve; });
+ }
+ if (responseMode === "error") {
+ return {code: -1, msg: "read failure"};
+ }
+ return {code: 0, data: {snapshots: responseMode === "missing" ? [] : [{...snapshots.find(item => item.id === body.id), files}]}};
+ },
+ fetchPost: (url, body, callback) => {
+ assert.equal(url, "/api/repo/openRepoSnapshotFile");
+ callback({code: 0, data: {displayInText: true, content: "文档内容 " + body.id}});
+ },
+ },
+ };
+ const modules = {};
+ const load = name => {
+ if (stubs[name]) {return stubs[name];}
+ if (modules[name]) {return modules[name];}
+ const key = sources[name] ? name : name + "/index";
+ assert.ok(sources[key], "missing module " + key);
+ const exports = {};
+ modules[name] = exports;
+ new Function("require", "exports", sources[key])(specifier => load(specifier.startsWith(".") ? require("node:path").posix.normalize(require("node:path").posix.join(require("node:path").posix.dirname(key), specifier)) : specifier), exports);
+ return exports;
+ };
+ const {Dialog} = load("dialog");
+ const {DocHistorySnapshots} = load("history/docSnapshots");
+ const {closeNotebookHistoryDialogs} = load("history/notebookDialogs");
+ const history = new Dialog({title: "项目计划 - 文件历史", width: mobile ? "100vw" : "90vw", height: mobile ? "100dvh" : "80vh",
+ content: '<div class="history__repo fn__block" style="height:100%"><div class="fn__flex fn__flex-1 history__panel"><ul class="b3-list b3-list--background history__side" style="width:240px"><li class="b3-list-item b3-list-item--focus"><div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">2026-09-28 09:00:00</span><span data-history-tags="1"></span></div></li></ul><div class="fn__flex-1 fn__flex-column"><div class="protyle-title__input">项目计划</div><textarea class="history__text fn__flex-1" readonly>原文件历史预览</textarea></div></div></div>'});
+ const root = history.element.querySelector(".history__repo");
+ const view = new DocHistorySnapshots({}, root, "doc");
+ await view.load(["1"], "all");
+ view.select("1");
+ await tick();
+ const links = root.querySelectorAll(".history__association button");
+ assert.equal(links.length, 2);
+ assert.ok(root.scrollWidth <= root.clientWidth + 1, "history horizontal overflow");
+ await require("electron").ipcRenderer.invoke("history-snapshots-capture", `history-${mobile ? "mobile" : "desktop"}-${dark ? "dark" : "light"}`);
+ const original = root.innerHTML;
+ links[1].focus();
+ links[1].click();
+ await tick();
+ const detail = window.siyuan.dialogs.at(-1);
+ assert.equal(window.siyuan.dialogs.length, 2);
+ assert.match(detail.element.querySelector(".b3-dialog__header").textContent, /周五备份/);
+ assert.equal(detail.element.querySelectorAll(".history__snapshot-detail-files li").length, files.length);
+ assert.equal(detail.element.querySelector("textarea").value, "文档内容 doc-file");
+ assert.ok(detail.element.querySelector("textarea").readOnly);
+ for (const font of [16, 28]) {
+ detail.element.style.fontSize = font + "px";
+ await tick();
+ const panels = detail.element.querySelector(".history__snapshot-detail-panels");
+ const preview = detail.element.querySelector(".history__snapshot-detail-preview");
+ assert.ok(panels.scrollWidth <= panels.clientWidth + 1, "detail horizontal overflow");
+ assert.ok(preview.clientHeight > 80, "preview must remain visible");
+ assert.equal(getComputedStyle(panels).flexDirection, mobile ? "column" : "row");
+ }
+ detail.element.style.fontSize = "";
+ await require("electron").ipcRenderer.invoke("history-snapshots-capture", `${mobile ? "mobile" : "desktop"}-${dark ? "dark" : "light"}`);
+ detail.destroy();
+ await tick();
+ assert.equal(root.innerHTML, original);
+ assert.equal(document.activeElement, links[1]);
+ responseMode = "missing";
+ links[0].click();
+ await tick();
+ assert.equal(window.siyuan.dialogs.at(-1).element.querySelector("[data-detail-status]").textContent, window.siyuan.languages.historySnapshotMissing);
+ window.siyuan.dialogs.at(-1).destroy();
+ await tick();
+ responseMode = "error";
+ links[0].click();
+ await tick();
+ assert.equal(window.siyuan.dialogs.at(-1).element.querySelector("[data-detail-status]").textContent, "read failure");
+ window.siyuan.dialogs.at(-1).destroy();
+ await tick();
+ responseMode = "pending";
+ links[0].click();
+ await tick();
+ closeNotebookHistoryDialogs("notebook");
+ await tick();
+ assert.ok(signal.aborted);
+ pending({code: 0, data: {snapshots: [{...snapshots[0], files}]}});
+ await tick();
+ assert.equal(window.siyuan.dialogs.length, 1);
+ view.destroy();
+ history.destroy();
+ await tick();
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow, ipcMain} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true}});
+ let code = 0;
+ try {
+ ipcMain.handle("history-snapshots-capture", async (_event, name) => {
+ if (process.env.SIYUAN_HISTORY_CAPTURE_DIR) {
+ assert.match(name, /^(history-)?(mobile|desktop)-(dark|light)$/);
+ win.webContents.invalidate();
+ await new Promise(resolve => setTimeout(resolve, 350));
+ fs.writeFileSync(path.join(process.env.SIYUAN_HISTORY_CAPTURE_DIR, name + ".png"), (await win.webContents.capturePage()).toPNG());
+ }
+ });
+ const ts = require("typescript");
+ const sass = require("sass");
+ const sources = {app: path.resolve(__dirname, ".."), icons: fs.readFileSync(path.join(__dirname, "../appearance/icons/litheness/icon.js"), "utf8"), languages: fs.readFileSync(path.join(__dirname, "../appearance/langs/zh-CN.json"), "utf8")};
+ for (const name of ["dialog/index", "util/escape", "history/docSnapshots", "history/snapshotDetail", "history/notebookDialogs", "history/repoFile"]) {
+ sources[name] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText;
+ }
+ for (const mobile of [false, true]) {
+ const styles = sass.compile(path.join(__dirname, `../src/assets/scss/${mobile ? "mobile" : "base"}.scss`), {logger: sass.Logger.silent}).css;
+ for (const dark of [false, true]) {
+ win.setContentSize(mobile ? 390 : 1280, 800);
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ const theme = fs.readFileSync(path.join(__dirname, `../appearance/themes/${dark ? "midnight" : "daylight"}/theme.css`), "utf8");
+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(theme + styles)}, ${mobile}, ${dark})`);
+ }
+ }
+ } catch (error) {
+ console.error(error);
+ code = 1;
+ } finally {
+ win.destroy();
+ app.exit(code);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("history snapshot details preserve selection, display files and handle missing snapshots, locks and responsive themes", async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-history-snapshots-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 90000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/kernel/api/contract_history_snapshots_test.go b/kernel/api/contract_history_snapshots_test.go
new file mode 100644
index 0000000000..e200e1af74
--- /dev/null
+++ b/kernel/api/contract_history_snapshots_test.go
@@ -0,0 +1,139 @@
+//go:build fts5
+
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/dejavu"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractDocHistorySnapshots(t *testing.T) {
+ const helper = "SIYUAN_TEST_HISTORY_SNAPSHOTS"
+ if os.Getenv(helper) != "1" {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractDocHistorySnapshots$", "-test.v")
+ cmd.Env = append(os.Environ(), helper+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("history snapshot contract failed: %v\n%s", err, output)
+ }
+ return
+ }
+ root, lockedBoxID := setupArchiveWorkspace(t)
+ util.TempDir = filepath.Join(root, "temp")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.RepoDir = filepath.Join(root, "repo")
+ util.HistoryDBPath = filepath.Join(root, "history.db")
+ util.DBPath = filepath.Join(root, "siyuan.db")
+ util.AssetContentDBPath = filepath.Join(root, "assets.db")
+ util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")
+ model.Conf = model.NewAppConf()
+ model.Conf.Repo = conf.NewRepo()
+ model.Conf.Repo.Key = bytes.Repeat([]byte{1}, 32)
+ model.Conf.Sync = conf.NewSync()
+ model.Conf.System = conf.NewSystem()
+ model.Conf.Editor = conf.NewEditor()
+ model.Conf.Export = conf.NewExport()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ const id = "20260928100000-abcdefg"
+ const box = "20260928100000-normal1"
+ const created = "1790560800"
+ data := []byte(`{"ID":"` + id + `","Spec":"2","Type":"NodeDocument","Properties":{"id":"` + id + `","title":"History"},"Children":[]}`)
+ historyPath := "2026-09-28-100000-update/" + box + "/" + id + ".sy"
+ for _, p := range []string{filepath.Join(util.HistoryDir, historyPath), filepath.Join(util.DataDir, box, id+".sy")} {
+ if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ sql.IndexHistoriesQueue([]*sql.History{
+ {ID: id, Type: model.HistoryTypeDoc, Op: "update", Title: "History", Path: historyPath, Created: created},
+ {ID: "20260928100000-locked1", Type: model.HistoryTypeDoc, Op: "update", Title: "Locked", Path: "2026-09-28-100000-update/" + lockedBoxID + "/20260928100000-locked1.sy", Created: created},
+ })
+ sql.FlushHistoryQueue()
+ repo, err := dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, "test", "test", "test", model.Conf.Repo.Key, nil, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ index, err := repo.Index("memo\nline", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = repo.AddTag(index.ID, "release"); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ const endpoint = "/api/history/getDocHistorySnapshots"
+ engine.POST(endpoint, getDocHistorySnapshots)
+ engine.POST("/api/repo/getRepoSnapshots", getRepoSnapshots)
+ for _, include := range []bool{false, true} {
+ body, _ := json.Marshal(map[string]interface{}{"id": index.ID, "page": 1, "includeFiles": include})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/repo/getRepoSnapshots", bytes.NewReader(body)))
+ requireAPIContract(t, "POST", "/api/repo/getRepoSnapshots", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data apicontract.RepoSnapshotsData `json:"data"`
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || len(response.Data.Snapshots) != 1 {
+ t.Fatalf("snapshot detail: %s, %v", recorder.Body.String(), err)
+ }
+ if (len(response.Data.Snapshots[0].Files) > 0) != include {
+ t.Fatalf("unexpected file metadata: %s", recorder.Body.String())
+ }
+ }
+ for _, test := range []struct {
+ body string
+ code int
+ }{
+ {`{"id":"` + id + `","created":["` + created + `"]}`, 0},
+ {`{"id":"` + id + `","created":["` + created + `"],"op":"update"}`, 0},
+ {`{"id":"20260928100000-locked1","created":["` + created + `"]}`, -1},
+ {`{"id":"` + id + `","created":["0"]}`, -1},
+ {`{"id":"` + id + `","created":[]}`, -1},
+ {`{"id":"` + id + `","created":["` + created + `"],"op":"invalid"}`, -1},
+ {`{"id":"` + id + `","created":[null]}`, -1},
+ {`{}`, -1},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", endpoint, strings.NewReader(test.body)))
+ requireAPIContract(t, "POST", endpoint, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data apicontract.DocHistorySnapshotsData `json:"data"`
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != test.code {
+ t.Fatalf("unexpected response: %s: %s, %v", test.body, recorder.Body.String(), err)
+ }
+ if test.code == 0 {
+ if len(response.Data.Histories) != 1 || len(response.Data.Histories[0].Snapshots) != 1 {
+ t.Fatalf("missing association: %s", recorder.Body.String())
+ }
+ snapshot := response.Data.Histories[0].Snapshots[0]
+ if snapshot.ID != index.ID || snapshot.Memo != "memo\nline" || len(snapshot.Tags) != 1 || snapshot.Tags[0] != "release" {
+ t.Fatalf("metadata lost: %+v", snapshot)
+ }
+ }
+ }
+}
diff --git a/kernel/api/history_snapshots.go b/kernel/api/history_snapshots.go
new file mode 100644
index 0000000000..9f376b0130
--- /dev/null
+++ b/kernel/api/history_snapshots.go
@@ -0,0 +1,46 @@
+package api
+
+import (
+ "path/filepath"
+ "sort"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var getDocHistorySnapshots = contractHandler(apicontract.GetDocHistorySnapshots, func(c *gin.Context, request apicontract.DocHistorySnapshotsRequest) apicontract.Response[apicontract.DocHistorySnapshotsData] {
+ histories, err := model.ResolveDocHistorySnapshots(request.ID, request.Created, request.Op)
+ if err != nil {
+ return apicontract.Failure[apicontract.DocHistorySnapshotsData](-1, err.Error())
+ }
+ boxes := map[string]bool{}
+ for _, history := range histories {
+ boxes[model.ExtractBoxIDFromHistoryPath(filepath.Join(util.WorkspaceDir, history.HistoryPath))] = true
+ }
+ ids := make([]string, 0, len(boxes))
+ for id := range boxes {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ for _, id := range ids {
+ if err = holdEncryptedBoxRequest(c, id); err != nil {
+ return apicontract.Failure[apicontract.DocHistorySnapshotsData](-1, model.Conf.Language(314))
+ }
+ }
+ if err = model.GetDocHistorySnapshots(c.Request.Context(), request.ID, histories); err != nil {
+ return apicontract.Failure[apicontract.DocHistorySnapshotsData](-1, err.Error())
+ }
+ data := apicontract.DocHistorySnapshotsData{Histories: make([]*apicontract.DocHistorySnapshotEntry, 0, len(histories))}
+ for _, history := range histories {
+ entry := &apicontract.DocHistorySnapshotEntry{Created: history.Created, HistoryPath: history.HistoryPath, Snapshots: []*apicontract.DocHistorySnapshot{}}
+ for _, snapshot := range history.Snapshots {
+ entry.Snapshots = append(entry.Snapshots, &apicontract.DocHistorySnapshot{
+ ID: snapshot.ID, FileID: snapshot.FileID, Tags: snapshot.Tags, Memo: snapshot.Memo, Created: snapshot.Created,
+ })
+ }
+ data.Histories = append(data.Histories, entry)
+ }
+ return apicontract.Success(data)
+})
diff --git a/kernel/api/repo.go b/kernel/api/repo.go
index e1433c10fc..025ba897aa 100644
--- a/kernel/api/repo.go
+++ b/kernel/api/repo.go
@@ -167,8 +167,8 @@ var getRepoSnapshots = contractHandler(apicontract.GetRepoSnapshots, func(c *gin
var snapshots []*model.Snapshot
var pageCount, totalCount int
var err error
- if request.ID != "" {
- snapshots, pageCount, totalCount, err = model.SearchRepoSnapshot(request.ID)
+ if request.ID != "" || request.IncludeFiles {
+ snapshots, pageCount, totalCount, err = model.SearchRepoSnapshot(request.ID, request.IncludeFiles)
} else {
snapshots, pageCount, totalCount, err = model.GetRepoSnapshots(int(request.Page))
}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 8d0bc8dcd7..906c81082c 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -228,6 +228,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/history/rollbackNotebookHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackNotebookHistory)
ginServer.Handle("POST", "/api/history/rollbackAssetsHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackAssetsHistory)
ginServer.Handle("POST", "/api/history/getDocHistoryContent", model.CheckAuth, model.CheckAdminRole, getDocHistoryContent)
+ ginServer.Handle("POST", "/api/history/getDocHistorySnapshots", model.CheckAuth, model.CheckAdminRole, getDocHistorySnapshots)
ginServer.Handle("POST", "/api/history/diffDocVersions", model.CheckAuth, model.CheckAdminRole, diffDocVersions)
ginServer.Handle("POST", "/api/history/rollbackDocHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackDocHistory)
ginServer.Handle("POST", "/api/history/clearWorkspaceHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, clearWorkspaceHistory)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index b134fb489c..443aeac165 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -601,6 +601,8 @@ var GetNotebookHistory = define[EmptyRequest, NotebookHistoryData]("getNotebookH
var GetDocHistoryContent = define[DocHistoryContentRequest, DocHistoryContentData]("getDocHistoryContent", "/api/history/getDocHistoryContent", JSONBody, ResponseOptions{}, "POST")
+var GetDocHistorySnapshots = define[DocHistorySnapshotsRequest, DocHistorySnapshotsData]("getDocHistorySnapshots", "/api/history/getDocHistorySnapshots", JSONBody, ResponseOptions{}, "POST")
+
var CreateDocHistory = define[CreateDocHistoryRequest, Null]("createDocHistory", "/api/history/createDocHistory", JSONBody, ResponseOptions{}, "POST")
var CreateAssetHistory = define[CreateAssetHistoryRequest, Null]("createAssetHistory", "/api/history/createAssetHistory", JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/history_snapshots.go b/kernel/apicontract/history_snapshots.go
new file mode 100644
index 0000000000..10e2e04869
--- /dev/null
+++ b/kernel/apicontract/history_snapshots.go
@@ -0,0 +1,30 @@
+package apicontract
+
+// DocHistorySnapshotsRequest 批量查询同一文档当前页文件历史关联的本地标记快照。
+// created 为 searchHistory 返回的时间戳,最多 32 项;op 默认为 all。
+// 只关联认证解密后完整 .sy 数据相同的文件,不表示资源、数据库或引用内容相同。
+// 没有仓库密钥时返回空关联;路径缺失、格式错误、认证失败及仓库损坏返回错误。
+// 加密笔记本必须解锁,请求租约保持到响应结束;不下载云端快照,不保存内容摘要。
+type DocHistorySnapshotsRequest struct {
+ ID string `json:"id" api:"trim"`
+ Created []string `json:"created"`
+ Op string `json:"op" api:"optional"`
+}
+
+type DocHistorySnapshot struct {
+ ID string `json:"id"`
+ FileID string `json:"fileID"`
+ Tags []string `json:"tags"`
+ Memo string `json:"memo"`
+ Created int64 `json:"created"`
+}
+
+type DocHistorySnapshotEntry struct {
+ Created string `json:"created"`
+ HistoryPath string `json:"historyPath"`
+ Snapshots []*DocHistorySnapshot `json:"snapshots"`
+}
+
+type DocHistorySnapshotsData struct {
+ Histories []*DocHistorySnapshotEntry `json:"histories"`
+}
diff --git a/kernel/apicontract/history_test.go b/kernel/apicontract/history_test.go
index 1903578d78..cd69a534d9 100644
--- a/kernel/apicontract/history_test.go
+++ b/kernel/apicontract/history_test.go
@@ -5,6 +5,18 @@ import (
"testing"
)
+func TestDocHistorySnapshotsContract(t *testing.T) {
+ request, err := GetDocHistorySnapshots.Decode(strings.NewReader(`{"id":" 20260928100000-abcdefg ","created":["123"]}`))
+ if err != nil || request.ID != "20260928100000-abcdefg" || request.Op != "" || len(request.Created) != 1 {
+ t.Fatalf("unexpected request: %+v %v", request, err)
+ }
+ for _, body := range []string{`{}`, `{"id":"doc","created":null}`, `{"id":"doc","created":[null]}`, `{"id":"doc","created":[1]}`, `{"id":"doc","created":[],"op":false}`} {
+ if _, err = GetDocHistorySnapshots.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("invalid request accepted: %s", body)
+ }
+ }
+}
+
func TestHistoryItemsRequestCompatibility(t *testing.T) {
request, err := GetHistoryItems.Decode(strings.NewReader(`{"created":" time ","query":" query ","notebook":null,"op":" op ","type":1.9}`))
if err != nil || request.Created != "time" || request.Query != " query " || request.Notebook != "" || request.Op != " op " || request.Type == nil || *request.Type != 1.9 {
diff --git a/kernel/apicontract/repo.go b/kernel/apicontract/repo.go
index a89d7535f5..85ea824a15 100644
--- a/kernel/apicontract/repo.go
+++ b/kernel/apicontract/repo.go
@@ -63,6 +63,8 @@ type GetRepoSnapshotsRequest struct {
// 前缀匹配多个快照时全部返回,按创建时间降序排列。
// 省略或留空时保留分页列表;未找到返回空列表,格式错误及仓库读取失败返回错误。
ID string `json:"id" api:"optional"`
+ // IncludeFiles 默认为 false;为 true 时 ID 必须完整,返回该快照的文件元数据,不读取文件正文。
+ IncludeFiles bool `json:"includeFiles" api:"optional"`
}
type SearchRepoFileRequest struct {
Keyword string `json:"keyword" api:"trim"`
@@ -328,6 +330,14 @@ func init() {
return request, err
}
request.ID = strings.TrimSpace(request.ID)
+ if raw, exists := fields["includeFiles"]; exists {
+ if string(raw) == "null" {
+ return request, errors.New("includeFiles must be a boolean")
+ }
+ if err = json.Unmarshal(raw, &request.IncludeFiles); err != nil {
+ return request, err
+ }
+ }
return request, nil
}
SearchRepoFile.decodeRequest = func(reader io.Reader) (request SearchRepoFileRequest, err error) {
diff --git a/kernel/apicontract/repo_test.go b/kernel/apicontract/repo_test.go
index 46235766da..c7a8e3331b 100644
--- a/kernel/apicontract/repo_test.go
+++ b/kernel/apicontract/repo_test.go
@@ -7,6 +7,18 @@ import (
)
func TestRepoSnapshotIDContract(t *testing.T) {
+ for _, enabled := range []bool{false, true} {
+ body, _ := json.Marshal(map[string]interface{}{"page": 1, "includeFiles": enabled})
+ request, err := GetRepoSnapshots.Decode(strings.NewReader(string(body)))
+ if err != nil || request.IncludeFiles != enabled {
+ t.Fatalf("includeFiles: %+v %v", request, err)
+ }
+ }
+ for _, value := range []string{"null", `"true"`, "1", "[]"} {
+ if _, err := GetRepoSnapshots.Decode(strings.NewReader(`{"page":1,"includeFiles":` + value + `}`)); err == nil {
+ t.Fatalf("invalid includeFiles accepted: %s", value)
+ }
+ }
for _, body := range []string{`{"page":1}`, `{"page":1,"id":""}`, `{"page":1,"id":null}`} {
request, err := GetRepoSnapshots.Decode(strings.NewReader(body))
if err != nil || request.ID != "" {
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 0af80d8a09..aff04f0451 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -21530,6 +21530,132 @@
],
"additionalProperties": false
},
+ "DocHistorySnapshot": {
+ "type": "object",
+ "properties": {
+ "created": {
+ "type": "integer"
+ },
+ "fileID": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "memo": {
+ "type": "string"
+ },
+ "tags": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "created",
+ "fileID",
+ "id",
+ "memo",
+ "tags"
+ ],
+ "additionalProperties": false
+ },
+ "DocHistorySnapshotEntry": {
+ "type": "object",
+ "properties": {
+ "created": {
+ "type": "string"
+ },
+ "historyPath": {
+ "type": "string"
+ },
+ "snapshots": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DocHistorySnapshot"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "created",
+ "historyPath",
+ "snapshots"
+ ],
+ "additionalProperties": false
+ },
+ "DocHistorySnapshotsData": {
+ "type": "object",
+ "properties": {
+ "histories": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DocHistorySnapshotEntry"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "histories"
+ ],
+ "additionalProperties": false
+ },
+ "DocHistorySnapshotsRequestInput": {
+ "type": "object",
+ "properties": {
+ "created": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "id": {
+ "type": "string"
+ },
+ "op": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "created",
+ "id"
+ ],
+ "additionalProperties": false
+ },
"DocInfo": {
"type": "object",
"properties": {
@@ -26494,6 +26620,9 @@
"id": {
"type": "string"
},
+ "includeFiles": {
+ "type": "boolean"
+ },
"page": {
"type": "number"
}
@@ -137438,6 +137567,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/history/getDocHistorySnapshots",
+ "handler": "getDocHistorySnapshots",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/DocHistorySnapshotsRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/DocHistorySnapshotsData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/history/getHistoryItems",
diff --git a/kernel/model/history_snapshots.go b/kernel/model/history_snapshots.go
new file mode 100644
index 0000000000..5fec6fa457
--- /dev/null
+++ b/kernel/model/history_snapshots.go
@@ -0,0 +1,216 @@
+package model
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/dejavu/entity"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+type DocHistorySnapshot struct {
+ ID string
+ FileID string
+ Tags []string
+ Memo string
+ Created int64
+}
+
+type DocHistorySnapshotEntry struct {
+ Created string
+ HistoryPath string
+ Snapshots []*DocHistorySnapshot
+}
+
+// ResolveDocHistorySnapshots 与文件历史预览使用相同的查询和首条记录。
+func ResolveDocHistorySnapshots(id string, created []string, op string) ([]*DocHistorySnapshotEntry, error) {
+ if !ast.IsNodeIDPattern(id) || len(created) == 0 || len(created) > fileHistoryPageSize {
+ return nil, errors.New("invalid document history snapshot query")
+ }
+ if op == "" {
+ op = "all"
+ }
+ validOp := op == "all"
+ for _, item := range validOps {
+ validOp = validOp || item == op
+ }
+ if !validOp {
+ return nil, errors.New("invalid history operation")
+ }
+ ret := make([]*DocHistorySnapshotEntry, 0, len(created))
+ for _, timestamp := range created {
+ if _, err := strconv.ParseInt(timestamp, 10, 64); err != nil {
+ return nil, errors.New("invalid history timestamp")
+ }
+ items := FullTextSearchHistoryItems(timestamp, id, "%", op, HistoryTypeDocID)
+ if len(items) == 0 {
+ return nil, errors.New("document history no longer exists")
+ }
+ ret = append(ret, &DocHistorySnapshotEntry{Created: timestamp, HistoryPath: items[0].Path, Snapshots: []*DocHistorySnapshot{}})
+ }
+ return ret, nil
+}
+
+// GetDocHistorySnapshots 按页匹配本地标记快照,仅在本次请求内复用文件摘要。
+// 调用方须持有所有历史所属加密笔记本的请求租约,覆盖响应序列化。
+func GetDocHistorySnapshots(ctx context.Context, id string, histories []*DocHistorySnapshotEntry) error {
+ type matchKey struct {
+ boxID string
+ hash [sha256.Size]byte
+ }
+ matches := map[matchKey][]*DocHistorySnapshotEntry{}
+ allowedBoxes := map[string]bool{}
+ for _, history := range histories {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ version, err := loadHistoryDocVersion(history.HistoryPath)
+ if err != nil {
+ return err
+ }
+ hash, err := docHistorySnapshotDigest(version.raw, id)
+ clear(version.raw)
+ if err != nil {
+ return err
+ }
+ boxID := ""
+ if IsEncryptedBox(version.boxID) {
+ boxID = version.boxID
+ }
+ allowedBoxes[boxID] = true
+ key := matchKey{boxID, hash}
+ matches[key] = append(matches[key], history)
+ }
+ if len(Conf.Repo.Key) == 0 {
+ return nil
+ }
+ repo, err := newRepository()
+ if err != nil {
+ return err
+ }
+ // 只读取标记引用与索引,避免为每个标记重复展开整个快照的文件列表。
+ tags, err := os.ReadDir(filepath.Join(repo.Path, "refs", "tags"))
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ indexes := map[string]*entity.Index{}
+ indexTags := map[string][]string{}
+ for _, tag := range tags {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if tag.IsDir() {
+ continue
+ }
+ indexID, readErr := repo.GetTag(tag.Name())
+ if readErr != nil {
+ return readErr
+ }
+ if _, readErr = hex.DecodeString(indexID); len(indexID) != 40 || readErr != nil {
+ return errors.New("invalid tagged snapshot ID")
+ }
+ if indexes[indexID] == nil {
+ index, readErr := repo.GetIndex(indexID)
+ if readErr != nil {
+ return readErr
+ }
+ if index.ID != indexID || !index.VerifyAESKey(Conf.Repo.Key) {
+ return errors.New("invalid tagged snapshot index")
+ }
+ indexes[indexID] = index
+ }
+ indexTags[indexID] = append(indexTags[indexID], tag.Name())
+ }
+ fileMatches := map[string][]*DocHistorySnapshotEntry{}
+ for indexID, index := range indexes {
+ seen := map[*DocHistorySnapshotEntry]bool{}
+ for _, fileID := range index.Files {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ matched, checked := fileMatches[fileID]
+ if !checked {
+ fileMatches[fileID] = nil
+ file, readErr := repo.GetFile(fileID)
+ if readErr != nil {
+ return readErr
+ }
+ if path.Base(file.Path) != id+".sy" {
+ continue
+ }
+ boxID := strings.Split(strings.TrimPrefix(file.Path, "/"), "/")[0]
+ if !IsEncryptedBox(boxID) {
+ boxID = ""
+ }
+ if !allowedBoxes[boxID] {
+ continue
+ }
+ data, readErr := repo.OpenFile(file)
+ if readErr != nil {
+ return readErr
+ }
+ data, readErr = decryptRepoDataIfNeeded(data, file.Path)
+ if readErr != nil {
+ return readErr
+ }
+ hash, readErr := docHistorySnapshotDigest(data, id)
+ clear(data)
+ if readErr != nil {
+ return readErr
+ }
+ matched = matches[matchKey{boxID, hash}]
+ fileMatches[fileID] = matched
+ }
+ for _, history := range matched {
+ if seen[history] {
+ continue
+ }
+ seen[history] = true
+ history.Snapshots = append(history.Snapshots, &DocHistorySnapshot{
+ ID: indexID, FileID: fileID, Tags: indexTags[indexID], Memo: index.Memo, Created: index.Created,
+ })
+ }
+ }
+ }
+ for _, history := range histories {
+ sort.Slice(history.Snapshots, func(i, j int) bool {
+ a, b := history.Snapshots[i], history.Snapshots[j]
+ if a.Created == b.Created {
+ return a.ID < b.ID
+ }
+ return a.Created > b.Created
+ })
+ }
+ return nil
+}
+
+func docHistorySnapshotDigest(data []byte, id string) ([sha256.Size]byte, error) {
+ if err := treenode.CheckSpecJSON(data); err != nil {
+ return [sha256.Size]byte{}, err
+ }
+ var root struct {
+ ID string
+ Type string
+ }
+ if err := json.Unmarshal(data, &root); err != nil {
+ return [sha256.Size]byte{}, err
+ }
+ if root.ID != id || root.Type != "NodeDocument" {
+ return [sha256.Size]byte{}, fmt.Errorf("history snapshot document ID does not match [%s]", id)
+ }
+ return sha256.Sum256(data), nil
+}
diff --git a/kernel/model/history_snapshots_test.go b/kernel/model/history_snapshots_test.go
new file mode 100644
index 0000000000..bd02188d50
--- /dev/null
+++ b/kernel/model/history_snapshots_test.go
@@ -0,0 +1,190 @@
+package model
+
+import (
+ "bytes"
+ "context"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+)
+
+const historySnapshotDocID = "20260928100000-histdoc"
+const historySnapshotBoxID = "20260928100000-histbox"
+
+func historySnapshotData(title string) []byte {
+ return []byte(`{"ID":"` + historySnapshotDocID + `","Spec":"2","Type":"NodeDocument","Properties":{"id":"` + historySnapshotDocID + `","title":"` + title + `"},"Children":[]}`)
+}
+
+func writeHistorySnapshotTestFile(t *testing.T, file string, data []byte) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(file, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func historySnapshotTestEntry(t *testing.T, data []byte) *DocHistorySnapshotEntry {
+ t.Helper()
+ rel := filepath.Join("history", "2026-09-28-100000-update", historySnapshotBoxID, historySnapshotDocID+".sy")
+ writeHistorySnapshotTestFile(t, filepath.Join(util.WorkspaceDir, rel), data)
+ return &DocHistorySnapshotEntry{Created: "1790560800", HistoryPath: filepath.ToSlash(rel), Snapshots: []*DocHistorySnapshot{}}
+}
+
+func TestDocHistorySnapshotsMatching(t *testing.T) {
+ _, repo, _ := prepareAssetDownloadRepoTest(t)
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ data := historySnapshotData("original")
+ docPath := filepath.Join(util.DataDir, historySnapshotBoxID, historySnapshotDocID+".sy")
+ writeHistorySnapshotTestFile(t, docPath, data)
+ first, err := repo.Index("first memo", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first.Created = 1000
+ if err = repo.PutIndex(first); err != nil {
+ t.Fatal(err)
+ }
+ for _, tag := range []string{"first", "alias"} {
+ if err = repo.AddTag(first.ID, tag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeHistorySnapshotTestFile(t, filepath.Join(util.DataDir, "unrelated.txt"), []byte("second"))
+ second, err := repo.Index("second\nline", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second.Created = 2000
+ if err = repo.PutIndex(second); err != nil {
+ t.Fatal(err)
+ }
+ if err = repo.AddTag(second.ID, "second"); err != nil {
+ t.Fatal(err)
+ }
+ query := func(data []byte) *DocHistorySnapshotEntry {
+ t.Helper()
+ entry := historySnapshotTestEntry(t, data)
+ if err := GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err != nil {
+ t.Fatal(err)
+ }
+ return entry
+ }
+ entry := query(data)
+ if len(entry.Snapshots) != 2 || entry.Snapshots[0].ID != second.ID || entry.Snapshots[1].ID != first.ID ||
+ strings.Join(entry.Snapshots[1].Tags, ",") != "alias,first" || entry.Snapshots[0].Memo != "second\nline" ||
+ entry.Snapshots[0].FileID == "" {
+ t.Fatalf("unexpected snapshot associations: %+v", entry.Snapshots)
+ }
+ if len(query(historySnapshotData("different")).Snapshots) != 0 {
+ t.Fatal("different document data matched")
+ }
+ if err = repo.SetSnapshotMemo(first.ID, "edited"); err != nil {
+ t.Fatal(err)
+ }
+ if err = repo.RemoveTag("second"); err != nil {
+ t.Fatal(err)
+ }
+ entry = query(data)
+ if len(entry.Snapshots) != 1 || entry.Snapshots[0].Memo != "edited" {
+ t.Fatal("tag deletion or memo edit was hidden by stale associations")
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err = GetDocHistorySnapshots(ctx, historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err != context.Canceled {
+ t.Fatalf("cancellation ignored: %v", err)
+ }
+ corrupt := []byte("invalid-index-reference")
+ tagPath := filepath.Join(util.RepoDir, "refs", "tags", "broken")
+ writeHistorySnapshotTestFile(t, tagPath, corrupt)
+ if err = GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err == nil {
+ t.Fatal("corrupt tag was treated as no match")
+ }
+ if actual, err := os.ReadFile(tagPath); err != nil || !bytes.Equal(actual, corrupt) {
+ t.Fatal("corrupt tag was modified")
+ }
+}
+
+func TestDocHistorySnapshotsEncrypted(t *testing.T) {
+ prepareAssetDownloadRepoTest(t)
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ defer prepareEncryptedBoxLifecycleTest(t, historySnapshotBoxID)()
+ setEncryptedBoxState(historySnapshotBoxID, EncryptedBoxStateUnlocked)
+ dek, err := GetDEKIfUnlocked(historySnapshotBoxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rel := "/" + historySnapshotDocID + ".sy"
+ plain := historySnapshotData("secret")
+ historyData, err := EncryptFile(historySnapshotBoxID, rel, dek, plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ snapshotData, err := EncryptFile(historySnapshotBoxID, rel, dek, plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Equal(historyData, snapshotData) {
+ t.Fatal("test requires different ciphertext for identical plaintext")
+ }
+ writeHistorySnapshotTestFile(t, filepath.Join(util.DataDir, historySnapshotBoxID, rel), snapshotData)
+ repo, err := newRepository()
+ if err != nil {
+ t.Fatal(err)
+ }
+ index, err := repo.Index("encrypted", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = repo.AddTag(index.ID, "encrypted"); err != nil {
+ t.Fatal(err)
+ }
+ entry := historySnapshotTestEntry(t, historyData)
+ if err = GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err != nil || len(entry.Snapshots) != 1 {
+ t.Fatalf("authenticated match failed: %v %+v", err, entry.Snapshots)
+ }
+ bad := bytes.Clone(historyData)
+ bad[len(bad)-1] ^= 1
+ entry = historySnapshotTestEntry(t, bad)
+ if err = GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err == nil {
+ t.Fatal("unauthenticated history matched")
+ }
+ entry = historySnapshotTestEntry(t, historyData)
+ setEncryptedBoxState(historySnapshotBoxID, EncryptedBoxStateLocked)
+ cachedDEKsLock.Lock()
+ clear(cachedDEKs[historySnapshotBoxID])
+ delete(cachedDEKs, historySnapshotBoxID)
+ cachedDEKsLock.Unlock()
+ if err = GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err == nil {
+ t.Fatal("locked history matched")
+ }
+}
+
+func TestDocHistorySnapshotDigest(t *testing.T) {
+ for _, data := range [][]byte{[]byte("broken"), []byte(`{"Spec":"999"}`), bytes.ReplaceAll(historySnapshotData("same"), []byte(historySnapshotDocID), []byte("20260928100000-otherid"))} {
+ if _, err := docHistorySnapshotDigest(data, historySnapshotDocID); err == nil {
+ t.Fatalf("invalid source accepted: %s", data)
+ }
+ }
+ for _, query := range []struct {
+ id, op string
+ created []string
+ }{
+ {"invalid", "all", []string{"1"}},
+ {historySnapshotDocID, "all", nil},
+ {historySnapshotDocID, "all", make([]string, 33)},
+ {historySnapshotDocID, "' OR 1=1", []string{"1"}},
+ {historySnapshotDocID, "all", []string{"bad"}},
+ } {
+ if _, err := ResolveDocHistorySnapshots(query.id, query.created, query.op); err == nil {
+ t.Fatal("invalid query accepted")
+ }
+ }
+}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index bcb6a6b9d6..da0109165e 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -989,12 +989,15 @@ type TypeCount struct {
}
// SearchRepoSnapshot 按完整 ID 或至少 7 位前缀读取本地快照,复用列表的元数据和下载状态计算。
-func SearchRepoSnapshot(id string) (ret []*Snapshot, pageCount, totalCount int, err error) {
+func SearchRepoSnapshot(id string, includeFiles bool) (ret []*Snapshot, pageCount, totalCount int, err error) {
ret = []*Snapshot{}
id = strings.ToLower(strings.TrimSpace(id))
if len(id) < 7 || len(id) > sha1.Size*2 || strings.Trim(id, "0123456789abcdef") != "" {
return ret, 0, 0, errors.New("invalid snapshot ID")
}
+ if includeFiles && len(id) != sha1.Size*2 {
+ return ret, 0, 0, errors.New("complete snapshot ID is required to include files")
+ }
if len(Conf.Repo.Key) == 0 {
return ret, 0, 0, errors.New(Conf.Language(26))
}
@@ -1045,7 +1048,7 @@ func SearchRepoSnapshot(id string) (ret []*Snapshot, pageCount, totalCount int,
return ret, 0, 0, nil
}
sort.SliceStable(logs, func(i, j int) bool { return logs[i].Created > logs[j].Created })
- ret = buildSnapshots(logs)
+ ret = buildSnapshots(logs, includeFiles)
return ret, 1, len(ret), nil
}
@@ -1073,14 +1076,14 @@ func GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err
return
}
- ret = buildSnapshots(logs)
+ ret = buildSnapshots(logs, false)
if 1 > len(ret) {
ret = []*Snapshot{}
}
return
}
-func buildSnapshots(logs []*dejavu.Log) (ret []*Snapshot) {
+func buildSnapshots(logs []*dejavu.Log, includeFiles bool) (ret []*Snapshot) {
chunkAvailability := map[string]bool{}
for _, l := range logs {
typesCount := statTypesByPath(l.Files)
@@ -1091,7 +1094,9 @@ func buildSnapshots(logs []*dejavu.Log) (ret []*Snapshot) {
break
}
}
- l.Files = nil // 置空,否则返回前端数据量太大
+ if !includeFiles {
+ l.Files = nil // 列表仅返回概要,避免传输所有快照的文件列表。
+ }
ret = append(ret, &Snapshot{
Log: l,
TypesCount: typesCount,
@@ -1765,7 +1770,7 @@ func GetTagSnapshots() (ret []*Snapshot, err error) {
if err != nil {
return
}
- ret = buildSnapshots(logs)
+ ret = buildSnapshots(logs, false)
if 1 > len(ret) {
ret = []*Snapshot{}
}
diff --git a/kernel/model/repository_snapshot_test.go b/kernel/model/repository_snapshot_test.go
index fcbf0603dc..3954cba517 100644
--- a/kernel/model/repository_snapshot_test.go
+++ b/kernel/model/repository_snapshot_test.go
@@ -22,8 +22,14 @@ func TestSearchRepoSnapshot(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ if found, _, _, err := SearchRepoSnapshot(index.ID, true); err != nil || len(found) != 1 || len(found[0].Files) != len(index.Files) {
+ t.Fatalf("snapshot file metadata missing: %v %v", found, err)
+ }
+ if _, _, _, err := SearchRepoSnapshot(index.ID[:7], true); err == nil {
+ t.Fatal("file listing accepted an ambiguous snapshot prefix")
+ }
for _, id := range []string{index.ID, index.ID[:7], index.ID[:15], " \n" + strings.ToUpper(index.ID[:7]) + "\t", " \n" + strings.ToUpper(index.ID) + "\t"} {
- found, pages, total, searchErr := SearchRepoSnapshot(id)
+ found, pages, total, searchErr := SearchRepoSnapshot(id, false)
if searchErr != nil || len(found) != 1 || pages != 1 || total != 1 {
t.Fatalf("search %q: %v %d %d %v", id, found, pages, total, searchErr)
}
@@ -40,11 +46,11 @@ func TestSearchRepoSnapshot(t *testing.T) {
}
}
missing := strings.Repeat("0", 40)
- if found, pages, total, err := SearchRepoSnapshot(missing); err != nil || len(found) != 0 || pages != 0 || total != 0 {
+ if found, pages, total, err := SearchRepoSnapshot(missing, false); err != nil || len(found) != 0 || pages != 0 || total != 0 {
t.Fatalf("missing snapshot: %v %d %d %v", found, pages, total, err)
}
for _, id := range []string{"", "short", "abcdef", "abcdefg", "../../outside", strings.Repeat("z", 40), strings.Repeat("a", 41)} {
- if _, _, _, err := SearchRepoSnapshot(id); err == nil {
+ if _, _, _, err := SearchRepoSnapshot(id, false); err == nil {
t.Fatalf("invalid ID accepted: %q", id)
}
}
@@ -58,7 +64,7 @@ func TestSearchRepoSnapshot(t *testing.T) {
if err = store.PutIndex(&other); err != nil {
t.Fatal(err)
}
- if found, pages, total, searchErr := SearchRepoSnapshot(index.ID[:7]); searchErr != nil || pages != 1 || total != 2 ||
+ if found, pages, total, searchErr := SearchRepoSnapshot(index.ID[:7], false); searchErr != nil || pages != 1 || total != 2 ||
len(found) != 2 || found[0].ID != other.ID || found[1].ID != index.ID {
t.Fatalf("shared prefix: %v %d %d %v", found, pages, total, searchErr)
}
@@ -71,10 +77,10 @@ func TestSearchRepoSnapshot(t *testing.T) {
if err = os.WriteFile(file, corrupt, 0644); err != nil {
t.Fatal(err)
}
- if _, _, _, err = SearchRepoSnapshot(corruptID); err == nil {
+ if _, _, _, err = SearchRepoSnapshot(corruptID, false); err == nil {
t.Fatal("corrupt snapshot returned as missing")
}
- if _, _, _, err = SearchRepoSnapshot(corruptID[:7]); err == nil {
+ if _, _, _, err = SearchRepoSnapshot(corruptID[:7], false); err == nil {
t.Fatal("corrupt snapshot prefix returned as missing")
}
if unchanged, err := os.ReadFile(file); err != nil || !bytes.Equal(unchanged, corrupt) {