Skip to content

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

:sparkles: Support syncing custom AI editor actions across devices https://github.com/siyuan-note/siyuan/issues/9246

Daniele06fe71db911
diff --git a/app/src/ai/actions.ts b/app/src/ai/actions.ts
index 894711046c..456f8c6ed2 100644
--- a/app/src/ai/actions.ts
+++ b/app/src/ai/actions.ts
@@ -8,12 +8,17 @@ import {blockRender} from "../protyle/render/blockRender";
import {processRender} from "../protyle/util/processCode";
import {highlightRender} from "../protyle/render/highlightRender";
import {Constants} from "../constants";
-import {setStorageVal} from "../protyle/util/compatibility";
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../util/escape";
import {showMessage} from "../dialog/message";
import {Menu} from "../plugin/Menu";
import {upDownHint} from "../util/upDownHint";
+interface IAIEditorAction {
+ id: string;
+ name: string;
+ action: string;
+}
+
export const fillContent = (protyle: IProtyle, data: string, elements: Element[]) => {
if (!data) {
return;
@@ -26,7 +31,7 @@ export const fillContent = (protyle: IProtyle, data: string, elements: Element[]
highlightRender(protyle.wysiwyg.element);
};
-const editDialog = (customName: string, customMemo: string) => {
+const editDialog = (item: IAIEditorAction) => {
const dialog = new Dialog({
title: window.siyuan.languages.update,
content: `<div class="b3-dialog__content">
@@ -43,42 +48,33 @@ const editDialog = (customName: string, customMemo: string) => {
});
dialog.element.setAttribute("data-key", Constants.DIALOG_AIUPDATECUSTOMACTION);
const nameElement = dialog.element.querySelector("input");
- nameElement.value = customName;
+ nameElement.value = item.name;
const customElement = dialog.element.querySelector("textarea");
const btnsElement = dialog.element.querySelectorAll(".b3-button");
dialog.bindInput(customElement, () => {
(btnsElement[2] as HTMLButtonElement).click();
});
- customElement.value = customMemo;
+ customElement.value = item.action;
btnsElement[1].addEventListener("click", () => {
dialog.destroy();
});
btnsElement[2].addEventListener("click", () => {
- window.siyuan.storage[Constants.LOCAL_AI].find((subItem: {
- name: string,
- memo: string
- }) => {
- if (customName === subItem.name && customMemo === subItem.memo) {
- subItem.name = nameElement.value;
- subItem.memo = customElement.value;
- setStorageVal(Constants.LOCAL_AI, window.siyuan.storage[Constants.LOCAL_AI]);
- return true;
- }
+ if (!nameElement.value && !customElement.value) {
+ showMessage(window.siyuan.languages["_kernel"][142]);
+ return;
+ }
+ fetchPost("/api/ai/editor/saveAction", {
+ id: item.id,
+ name: nameElement.value,
+ action: customElement.value,
+ }, () => {
+ dialog.destroy();
});
- dialog.destroy();
});
btnsElement[0].addEventListener("click", () => {
- window.siyuan.storage[Constants.LOCAL_AI].find((subItem: {
- name: string,
- memo: string
- }, index: number) => {
- if (customName === subItem.name && customMemo === subItem.memo) {
- window.siyuan.storage[Constants.LOCAL_AI].splice(index, 1);
- setStorageVal(Constants.LOCAL_AI, window.siyuan.storage[Constants.LOCAL_AI]);
- return true;
- }
+ fetchPost("/api/ai/editor/removeAction", {id: item.id}, () => {
+ dialog.destroy();
});
- dialog.destroy();
});
nameElement.focus();
};
@@ -126,12 +122,12 @@ const customDialog = (protyle: IProtyle, ids: string[], elements: Element[]) =>
showMessage(window.siyuan.languages["_kernel"][142]);
return;
}
- window.siyuan.storage[Constants.LOCAL_AI].push({
+ fetchPost("/api/ai/editor/saveAction", {
name: nameElement.value,
- memo: customElement.value
+ action: customElement.value,
+ }, () => {
+ dialog.destroy();
});
- setStorageVal(Constants.LOCAL_AI, window.siyuan.storage[Constants.LOCAL_AI]);
- dialog.destroy();
});
nameElement.focus();
};
@@ -155,7 +151,7 @@ const filterAI = (element: HTMLElement, inputElement: HTMLInputElement) => {
element.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");
};
-export const AIActions = (elements: Element[], protyle: IProtyle) => {
+const openAIActions = (actions: IAIEditorAction[], elements: Element[], protyle: IProtyle) => {
window.siyuan.menus.menu.remove();
const ids: string[] = [];
elements.forEach(item => {
@@ -165,8 +161,8 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
focusByRange(protyle.toolbar.range);
});
let customHTML = "";
- window.siyuan.storage[Constants.LOCAL_AI].forEach((item: { name: string, memo: string }, index: number) => {
- customHTML += `<div data-action="${escapeAttr(item.memo || item.name)}" data-position="10west" data-index="${index}" class="b3-list-item b3-list-item--narrow ariaLabel" aria-label="${escapeAriaLabel(item.memo)}">
+ actions.forEach((item) => {
+ customHTML += `<div data-type="saved" data-id="${escapeAttr(item.id)}" data-position="10west" class="b3-list-item b3-list-item--narrow ariaLabel" aria-label="${escapeAriaLabel(item.action)}">
<span class="b3-list-item__text">${escapeHtml(item.name)}</span>
<span data-type="edit" class="b3-list-item__action"><svg><use xlink:href="#iconEdit"></use></svg></span>
</div>`;
@@ -214,6 +210,24 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
/// #endif
const listElement = element.querySelector(".b3-list");
const inputElement = element.querySelector("input");
+ const runAction = (itemElement: HTMLElement) => {
+ let action = itemElement.dataset.action;
+ if (itemElement.dataset.type === "saved") {
+ const item = actions.find((currentItem) => currentItem.id === itemElement.dataset.id);
+ action = item?.action || item?.name;
+ }
+ if (typeof action !== "string") {
+ return;
+ }
+ fetchPost("/api/ai/chatGPTWithAction", {ids, action}, (response) => {
+ fillContent(protyle, response.data, elements);
+ });
+ if (action === clearContext) {
+ showMessage(window.siyuan.languages.clearContextSucc);
+ } else {
+ menu.close();
+ }
+ };
inputElement.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.isComposing) {
return;
@@ -233,17 +247,7 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
customDialog(protyle, ids, elements);
menu.close();
} else {
- fetchPost("/api/ai/chatGPTWithAction", {
- ids,
- action: currentElement.dataset.action
- }, (response) => {
- fillContent(protyle, response.data, elements);
- });
- if (currentElement.dataset.action === clearContext) {
- showMessage(window.siyuan.languages.clearContextSucc);
- } else {
- menu.close();
- }
+ runAction(currentElement);
}
}
});
@@ -260,8 +264,10 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
let target = event.target as HTMLElement;
while (target && (target !== element)) {
if (target.classList.contains("b3-list-item__action")) {
- const subItem = window.siyuan.storage[Constants.LOCAL_AI][target.parentElement.dataset.index];
- editDialog(subItem.name, subItem.memo);
+ const subItem = actions.find((item) => item.id === target.parentElement.dataset.id);
+ if (subItem) {
+ editDialog(subItem);
+ }
menu.close();
event.stopPropagation();
event.preventDefault();
@@ -271,14 +277,7 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
customDialog(protyle, ids, elements);
menu.close();
} else {
- fetchPost("/api/ai/chatGPTWithAction", {ids, action: target.dataset.action}, (response) => {
- fillContent(protyle, response.data, elements);
- });
- if (target.dataset.action === clearContext) {
- showMessage(window.siyuan.languages.clearContextSucc);
- } else {
- menu.close();
- }
+ runAction(target);
}
event.stopPropagation();
event.preventDefault();
@@ -302,3 +301,16 @@ export const AIActions = (elements: Element[], protyle: IProtyle) => {
menu.element.querySelector("input").focus();
/// #endif
};
+
+let aiActionsRequestID = 0;
+
+export const AIActions = (elements: Element[], protyle: IProtyle) => {
+ window.siyuan.menus.menu.remove();
+ const requestID = ++aiActionsRequestID;
+ fetchPost("/api/ai/editor/lsActions", {}, (response) => {
+ if (requestID !== aiActionsRequestID || elements.length === 0 || !elements[elements.length - 1].isConnected) {
+ return;
+ }
+ openAIActions(Array.isArray(response.data) ? response.data : [], elements, protyle);
+ });
+};
diff --git a/app/src/constants.ts b/app/src/constants.ts
index c923f1194f..afdaf0c0a3 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -169,7 +169,6 @@ export abstract class Constants {
public static readonly LOCAL_BAZAAR = "local-bazaar";
public static readonly LOCAL_PDFTHEME = "local-pdftheme";
public static readonly LOCAL_LAYOUTS = "local-layouts";
- public static readonly LOCAL_AI = "local-ai";
public static readonly LOCAL_PLUGINTOPUNPIN = "local-plugintopunpin";
public static readonly LOCAL_FLASHCARD = "local-flashcard";
public static readonly LOCAL_FILEPOSITION = "local-fileposition";
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index 636a5c3f5c..f268beac50 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -677,7 +677,6 @@ export const getLocalStorage = (cb: () => void) => {
annoColor: "var(--b3-pdf-background1)"
};
defaultStorage[Constants.LOCAL_LAYOUTS] = []; // {name: "", layout:{}, time: number, filespaths: IFilesPath[]}
- defaultStorage[Constants.LOCAL_AI] = []; // {name: "", memo: ""}
defaultStorage[Constants.LOCAL_PLUGIN_DOCKS] = {}; // { pluginName: {dockId: IPluginDockTab}}
defaultStorage[Constants.LOCAL_PLUGINTOPUNPIN] = [];
defaultStorage[Constants.LOCAL_OUTLINE] = {
@@ -764,7 +763,7 @@ export const getLocalStorage = (cb: () => void) => {
[Constants.LOCAL_EXPORTIMG, Constants.LOCAL_SEARCHKEYS, Constants.LOCAL_PDFTHEME, Constants.LOCAL_BAZAAR,
Constants.LOCAL_EXPORTWORD, Constants.LOCAL_EXPORTPDF, Constants.LOCAL_DOCINFO, Constants.LOCAL_MOBILE_TABS,
Constants.LOCAL_FONTSTYLES,
- Constants.LOCAL_SEARCHDATA, Constants.LOCAL_ZOOM, Constants.LOCAL_LAYOUTS, Constants.LOCAL_AI,
+ Constants.LOCAL_SEARCHDATA, Constants.LOCAL_ZOOM, Constants.LOCAL_LAYOUTS,
Constants.LOCAL_PLUGINTOPUNPIN, Constants.LOCAL_SEARCHASSET, Constants.LOCAL_FLASHCARD,
Constants.LOCAL_DIALOGPOSITION, Constants.LOCAL_SEARCHUNREF, Constants.LOCAL_HISTORY,
Constants.LOCAL_OUTLINE, Constants.LOCAL_FILEPOSITION, Constants.LOCAL_FILESPATHS, Constants.LOCAL_IMAGES,
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index b681650995..ab2dd944df 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -94,6 +94,69 @@ func chatGPTWithAction(c *gin.Context) {
ret.Data = model.ChatGPTWithAction(ids, action)
}
+func lsAIEditorActions(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ actions, err := model.GetAIEditorActions()
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = actions
+}
+
+func saveAIEditorAction(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var id, name, action string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("id", &id, false, false),
+ util.BindJsonArg("name", &name, true, false),
+ util.BindJsonArg("action", &action, true, false),
+ ) {
+ return
+ }
+
+ saved, err := model.SaveAIEditorAction(&model.AIEditorAction{
+ ID: id,
+ Name: name,
+ Action: action,
+ })
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = saved
+}
+
+func removeAIEditorAction(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var id string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
+ return
+ }
+ if err := model.RemoveAIEditorAction(id); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
+}
+
// testModel 测试 AI 模型可用性。使用已保存的 Provider 或详情页草稿中的 baseURL/APIKey/超时,
// 校验指定模型是否可用。优先通过 ListModels 拉取可用模型清单精确匹配,
// 若该端点不可用则回退到极简 Chat Completion 验证连通性。
diff --git a/kernel/api/ai_editor_test.go b/kernel/api/ai_editor_test.go
new file mode 100644
index 0000000000..e201f18a09
--- /dev/null
+++ b/kernel/api/ai_editor_test.go
@@ -0,0 +1,99 @@
+// 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 api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAIEditorActionAPI(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ })
+
+ engine := gin.New()
+ engine.POST("/api/ai/editor/lsActions", lsAIEditorActions)
+ engine.POST("/api/ai/editor/saveAction", saveAIEditorAction)
+ engine.POST("/api/ai/editor/removeAction", removeAIEditorAction)
+
+ saveRecorder := httptest.NewRecorder()
+ saveRequest := httptest.NewRequest(http.MethodPost, "/api/ai/editor/saveAction",
+ strings.NewReader(`{"name":"Format","action":"Line 1\nLine 2"}`))
+ saveRequest.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(saveRecorder, saveRequest)
+
+ saveResponse := &struct {
+ Code int `json:"code"`
+ Data *model.AIEditorAction `json:"data"`
+ }{}
+ if err := json.Unmarshal(saveRecorder.Body.Bytes(), saveResponse); err != nil {
+ t.Fatal(err)
+ }
+ if saveResponse.Code != 0 || saveResponse.Data == nil || saveResponse.Data.ID == "" ||
+ saveResponse.Data.Action != "Line 1\nLine 2" {
+ t.Fatalf("unexpected save response: %s", saveRecorder.Body.String())
+ }
+
+ listRecorder := httptest.NewRecorder()
+ listRequest := httptest.NewRequest(http.MethodPost, "/api/ai/editor/lsActions", nil)
+ engine.ServeHTTP(listRecorder, listRequest)
+ listResponse := &struct {
+ Code int `json:"code"`
+ Data []*model.AIEditorAction `json:"data"`
+ }{}
+ if err := json.Unmarshal(listRecorder.Body.Bytes(), listResponse); err != nil {
+ t.Fatal(err)
+ }
+ if listResponse.Code != 0 || len(listResponse.Data) != 1 || listResponse.Data[0].ID != saveResponse.Data.ID {
+ t.Fatalf("unexpected list response: %s", listRecorder.Body.String())
+ }
+
+ removeRecorder := httptest.NewRecorder()
+ removeRequest := httptest.NewRequest(http.MethodPost, "/api/ai/editor/removeAction",
+ strings.NewReader(`{"id":"`+saveResponse.Data.ID+`"}`))
+ removeRequest.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(removeRecorder, removeRequest)
+ removeResponse := &struct {
+ Code int `json:"code"`
+ }{}
+ if err := json.Unmarshal(removeRecorder.Body.Bytes(), removeResponse); err != nil {
+ t.Fatal(err)
+ }
+ if removeResponse.Code != 0 {
+ t.Fatalf("unexpected remove response: %s", removeRecorder.Body.String())
+ }
+
+ actions, err := model.GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 0 {
+ t.Fatalf("action was not removed: %#v", actions)
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index e94f77f457..89dc10a767 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -603,6 +603,9 @@ 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/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)
ginServer.Handle("POST", "/api/ai/testModel", model.CheckAuth, model.CheckAdminRole, testModel)
ginServer.Handle("POST", "/api/ai/testEmbeddingModel", model.CheckAuth, model.CheckAdminRole, testEmbeddingModel)
ginServer.Handle("POST", "/api/ai/testRerankModel", model.CheckAuth, model.CheckAdminRole, testRerankModel)
diff --git a/kernel/model/ai_editor.go b/kernel/model/ai_editor.go
new file mode 100644
index 0000000000..a8b627af77
--- /dev/null
+++ b/kernel/model/ai_editor.go
@@ -0,0 +1,265 @@
+// 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 (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/88250/gulu"
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ aiEditorActionsVersion = 1
+ legacyAIEditorActionsStorageKey = "local-ai"
+)
+
+type AIEditorAction struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Action string `json:"action"`
+}
+
+type aiEditorActionsData struct {
+ Version int `json:"version"`
+ Actions []*AIEditorAction `json:"actions"`
+}
+
+type legacyAIEditorAction struct {
+ Name string `json:"name"`
+ Memo string `json:"memo"`
+}
+
+var aiEditorActionsLock sync.Mutex
+
+func GetAIEditorActions() (ret []*AIEditorAction, err error) {
+ waitForSyncingStorages()
+ aiEditorActionsLock.Lock()
+ defer aiEditorActionsLock.Unlock()
+
+ data, err := loadAIEditorActions()
+ if err != nil {
+ return nil, err
+ }
+ if err = migrateLegacyAIEditorActions(data, !util.ReadOnly); err != nil {
+ return nil, err
+ }
+ return data.Actions, nil
+}
+
+func SaveAIEditorAction(action *AIEditorAction) (ret *AIEditorAction, err error) {
+ if action == nil || (action.Name == "" && action.Action == "") {
+ return nil, errors.New("AI editor action must not be empty")
+ }
+ if action.ID != "" && !ast.IsNodeIDPattern(action.ID) {
+ return nil, errors.New("invalid AI editor action ID")
+ }
+
+ waitForSyncingStorages()
+ aiEditorActionsLock.Lock()
+ defer aiEditorActionsLock.Unlock()
+
+ data, err := loadAIEditorActions()
+ if err != nil {
+ return nil, err
+ }
+ if err = migrateLegacyAIEditorActions(data, true); err != nil {
+ return nil, err
+ }
+
+ ret = &AIEditorAction{
+ ID: action.ID,
+ Name: action.Name,
+ Action: action.Action,
+ }
+ if ret.ID == "" {
+ ret.ID = ast.NewNodeID()
+ data.Actions = append(data.Actions, ret)
+ } else {
+ updated := false
+ for i, item := range data.Actions {
+ if item.ID == ret.ID {
+ data.Actions[i] = ret
+ updated = true
+ break
+ }
+ }
+ if !updated {
+ return nil, errors.New("AI editor action not found")
+ }
+ }
+
+ if err = saveAIEditorActions(data); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+func RemoveAIEditorAction(id string) (err error) {
+ if !ast.IsNodeIDPattern(id) {
+ return errors.New("invalid AI editor action ID")
+ }
+
+ waitForSyncingStorages()
+ aiEditorActionsLock.Lock()
+ defer aiEditorActionsLock.Unlock()
+
+ data, err := loadAIEditorActions()
+ if err != nil {
+ return err
+ }
+ if err = migrateLegacyAIEditorActions(data, true); err != nil {
+ return err
+ }
+
+ for i, item := range data.Actions {
+ if item.ID == id {
+ data.Actions = append(data.Actions[:i], data.Actions[i+1:]...)
+ return saveAIEditorActions(data)
+ }
+ }
+ return nil
+}
+
+func aiEditorActionsPath() string {
+ return filepath.Join(util.DataDir, "storage", "ai", "editor", "actions.json")
+}
+
+func loadAIEditorActions() (ret *aiEditorActionsData, err error) {
+ ret = &aiEditorActionsData{
+ Version: aiEditorActionsVersion,
+ Actions: []*AIEditorAction{},
+ }
+ dataPath := aiEditorActionsPath()
+ if !filelock.IsExist(dataPath) {
+ return ret, nil
+ }
+
+ data, err := filelock.ReadFile(dataPath)
+ if err != nil {
+ return nil, fmt.Errorf("read AI editor actions failed: %w", err)
+ }
+ if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil {
+ return nil, fmt.Errorf("unmarshal AI editor actions failed: %w", err)
+ }
+ if ret.Version != aiEditorActionsVersion {
+ return nil, fmt.Errorf("unsupported AI editor actions version [%d]", ret.Version)
+ }
+ if ret.Actions == nil {
+ ret.Actions = []*AIEditorAction{}
+ }
+
+ ids := make(map[string]struct{}, len(ret.Actions))
+ for _, action := range ret.Actions {
+ if action == nil || !ast.IsNodeIDPattern(action.ID) || (action.Name == "" && action.Action == "") {
+ return nil, errors.New("invalid AI editor action data")
+ }
+ if _, ok := ids[action.ID]; ok {
+ return nil, fmt.Errorf("duplicate AI editor action ID [%s]", action.ID)
+ }
+ ids[action.ID] = struct{}{}
+ }
+ return ret, nil
+}
+
+func saveAIEditorActions(data *aiEditorActionsData) (err error) {
+ data.Version = aiEditorActionsVersion
+ if data.Actions == nil {
+ data.Actions = []*AIEditorAction{}
+ }
+
+ dirPath := filepath.Dir(aiEditorActionsPath())
+ if err = os.MkdirAll(dirPath, 0755); err != nil {
+ return fmt.Errorf("create AI editor actions directory failed: %w", err)
+ }
+ bytes, err := gulu.JSON.MarshalIndentJSON(data, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal AI editor actions failed: %w", err)
+ }
+ if err = filelock.WriteFile(aiEditorActionsPath(), bytes); err != nil {
+ return fmt.Errorf("write AI editor actions failed: %w", err)
+ }
+ return nil
+}
+
+func migrateLegacyAIEditorActions(data *aiEditorActionsData, persist bool) (err error) {
+ localStorage := GetLocalStorage()
+ legacyRaw, ok := localStorage[legacyAIEditorActionsStorageKey]
+ if !ok {
+ return nil
+ }
+
+ var legacyActions []*legacyAIEditorAction
+ if legacyJSON, isString := legacyRaw.(string); isString {
+ if err = gulu.JSON.UnmarshalJSON([]byte(legacyJSON), &legacyActions); err != nil {
+ return fmt.Errorf("unmarshal legacy AI editor actions failed: %w", err)
+ }
+ } else {
+ legacyJSON, marshalErr := gulu.JSON.MarshalJSON(legacyRaw)
+ if marshalErr != nil {
+ return fmt.Errorf("marshal legacy AI editor actions failed: %w", marshalErr)
+ }
+ if err = gulu.JSON.UnmarshalJSON(legacyJSON, &legacyActions); err != nil {
+ return fmt.Errorf("unmarshal legacy AI editor actions failed: %w", err)
+ }
+ }
+
+ type actionKey struct {
+ name string
+ action string
+ }
+ existing := make(map[actionKey]struct{}, len(data.Actions))
+ for _, action := range data.Actions {
+ existing[actionKey{name: action.Name, action: action.Action}] = struct{}{}
+ }
+
+ changed := false
+ for _, legacyAction := range legacyActions {
+ if legacyAction == nil || (legacyAction.Name == "" && legacyAction.Memo == "") {
+ continue
+ }
+ key := actionKey{name: legacyAction.Name, action: legacyAction.Memo}
+ if _, ok = existing[key]; ok {
+ continue
+ }
+ data.Actions = append(data.Actions, &AIEditorAction{
+ ID: ast.NewNodeID(),
+ Name: legacyAction.Name,
+ Action: legacyAction.Memo,
+ })
+ existing[key] = struct{}{}
+ changed = true
+ }
+ if !persist {
+ return nil
+ }
+ if changed {
+ if err = saveAIEditorActions(data); err != nil {
+ return err
+ }
+ }
+ if err = RemoveLocalStorageVals([]string{legacyAIEditorActionsStorageKey}); err != nil {
+ return fmt.Errorf("remove legacy AI editor actions failed: %w", err)
+ }
+ return nil
+}
diff --git a/kernel/model/ai_editor_test.go b/kernel/model/ai_editor_test.go
new file mode 100644
index 0000000000..6656e7d424
--- /dev/null
+++ b/kernel/model/ai_editor_test.go
@@ -0,0 +1,239 @@
+// 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 (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAIEditorActionsCRUD(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ })
+
+ actions, err := GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 0 {
+ t.Fatalf("unexpected initial actions: %#v", actions)
+ }
+
+ actionText := "First line\n\"quoted\" & <tag>\nLast line"
+ saved, err := SaveAIEditorAction(&AIEditorAction{Name: "Format", Action: actionText})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !ast.IsNodeIDPattern(saved.ID) {
+ t.Fatalf("invalid generated action ID: %q", saved.ID)
+ }
+
+ actions, err = GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 1 || actions[0].ID != saved.ID || actions[0].Action != actionText {
+ t.Fatalf("saved action changed: %#v", actions)
+ }
+
+ updatedText := "Updated\n\nAction"
+ updated, err := SaveAIEditorAction(&AIEditorAction{ID: saved.ID, Name: "Updated", Action: updatedText})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if updated.ID != saved.ID || updated.Action != updatedText {
+ t.Fatalf("unexpected updated action: %#v", updated)
+ }
+
+ nameOnly, err := SaveAIEditorAction(&AIEditorAction{Name: "Name only"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ actions, err = GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 2 || actions[0].ID != saved.ID || actions[1].ID != nameOnly.ID {
+ t.Fatalf("action order changed: %#v", actions)
+ }
+
+ if err = RemoveAIEditorAction(saved.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = RemoveAIEditorAction(saved.ID); err != nil {
+ t.Fatal(err)
+ }
+ actions, err = GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 1 || actions[0].ID != nameOnly.ID {
+ t.Fatalf("unexpected actions after removal: %#v", actions)
+ }
+}
+
+func TestMigrateLegacyAIEditorActions(t *testing.T) {
+ tests := []struct {
+ name string
+ legacyData any
+ }{
+ {
+ name: "array",
+ legacyData: []any{
+ map[string]any{"name": "Existing", "memo": "Existing action"},
+ map[string]any{"name": "Migrated", "memo": "Line 1\nLine 2"},
+ },
+ },
+ {
+ name: "JSON string",
+ legacyData: `[{"name":"Migrated","memo":"Line 1\nLine 2"}]`,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() {
+ util.DataDir = oldDataDir
+ }()
+
+ if test.name == "array" {
+ if _, err := SaveAIEditorAction(&AIEditorAction{Name: "Existing", Action: "Existing action"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := SetLocalStorage(map[string]any{legacyAIEditorActionsStorageKey: test.legacyData}); err != nil {
+ t.Fatal(err)
+ }
+
+ actions, err := GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantCount := 1
+ if test.name == "array" {
+ wantCount = 2
+ }
+ if len(actions) != wantCount {
+ t.Fatalf("unexpected migrated actions: %#v", actions)
+ }
+ migrated := actions[len(actions)-1]
+ if migrated.Name != "Migrated" || migrated.Action != "Line 1\nLine 2" {
+ t.Fatalf("legacy action changed during migration: %#v", migrated)
+ }
+ if _, ok := GetLocalStorage()[legacyAIEditorActionsStorageKey]; ok {
+ t.Fatal("legacy AI editor actions were not removed")
+ }
+ })
+ }
+}
+
+func TestAIEditorActionsInvalidDataIsNotOverwritten(t *testing.T) {
+ tests := []struct {
+ name string
+ data []byte
+ }{
+ {name: "invalid JSON", data: []byte(`{"version":`)},
+ {name: "future version", data: []byte(`{"version":2,"actions":[]}`)},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() {
+ util.DataDir = oldDataDir
+ }()
+
+ dataPath := aiEditorActionsPath()
+ if err := os.MkdirAll(filepath.Dir(dataPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dataPath, test.data, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := GetAIEditorActions(); err == nil {
+ t.Fatal("expected invalid data error")
+ }
+ if _, err := SaveAIEditorAction(&AIEditorAction{Name: "Must not be saved"}); err == nil {
+ t.Fatal("expected save to reject invalid data")
+ }
+ current, err := os.ReadFile(dataPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(current) != string(test.data) {
+ t.Fatalf("invalid data was overwritten: %s", current)
+ }
+ })
+ }
+}
+
+func TestAIEditorActionsInvalidLegacyDataIsRetained(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ })
+
+ if err := SetLocalStorage(map[string]any{legacyAIEditorActionsStorageKey: "{"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := GetAIEditorActions(); err == nil {
+ t.Fatal("expected invalid legacy data error")
+ }
+ if _, ok := GetLocalStorage()[legacyAIEditorActionsStorageKey]; !ok {
+ t.Fatal("invalid legacy AI editor actions were removed")
+ }
+}
+
+func TestAIEditorActionsReadOnlyMigration(t *testing.T) {
+ oldDataDir, oldReadOnly := util.DataDir, util.ReadOnly
+ util.DataDir, util.ReadOnly = t.TempDir(), true
+ t.Cleanup(func() {
+ util.DataDir, util.ReadOnly = oldDataDir, oldReadOnly
+ })
+
+ if err := SetLocalStorage(map[string]any{
+ legacyAIEditorActionsStorageKey: []any{
+ map[string]any{"name": "Read only", "memo": "Legacy action"},
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ actions, err := GetAIEditorActions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(actions) != 1 || actions[0].Name != "Read only" {
+ t.Fatalf("legacy action is unavailable in read-only mode: %#v", actions)
+ }
+ if _, err = os.Stat(aiEditorActionsPath()); !os.IsNotExist(err) {
+ t.Fatalf("read-only migration wrote the synchronized file: %v", err)
+ }
+ if _, ok := GetLocalStorage()[legacyAIEditorActionsStorageKey]; !ok {
+ t.Fatal("read-only migration removed legacy AI editor actions")
+ }
+}