Skip to content

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

:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797

Danielaee98a8941ed
diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scss
index 2f02a5cf71..8679e19b8a 100644
--- a/app/src/assets/scss/business/_agentChat.scss
+++ b/app/src/assets/scss/business/_agentChat.scss
@@ -594,13 +594,22 @@
position: fixed;
z-index: 9999;
width: 280px;
- max-height: 300px;
+ max-height: 360px;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+
+ .b3-menu__items {
+ flex: 1;
+ min-height: 0;
+ }
}
.agent-session-popup__search {
width: calc(100% - 16px);
margin: 0 8px 4px;
box-sizing: border-box;
+ flex-shrink: 0;
}
.agent-session-popup__actions {
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index 914aceeea1..6b67e45229 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -43,6 +43,10 @@ export class AgentChat extends Model {
private abortController: AbortController | null = null;
private isRenderingSessionList = false;
private sessionListItems: SessionIndexItem[] = [];
+ private sessionListTotal = 0;
+ private sessionListPage = 0;
+ private isLoadingMore = false;
+ private searchTimer: number | null = null;
private currentSearchKeyword = "";
private currentThinkingText = "";
private currentThinkingReasoning = "";
@@ -241,14 +245,19 @@ export class AgentChat extends Model {
this.sessionPopup = null;
this.currentSearchKeyword = "";
this.sessionListItems = [];
+ this.sessionListTotal = 0;
+ this.sessionListPage = 0;
+ if (this.searchTimer !== null) { clearTimeout(this.searchTimer); this.searchTimer = null; }
}
private async renderSessionList() {
this.isRenderingSessionList = true;
this.closeSessionMenu();
try {
- this.sessionListItems = await SessionStore.list();
- this.sessionListItems.sort((a, b) => b.createdAt - a.createdAt);
+ const result = await SessionStore.list({page: 1, pageSize: 30});
+ this.sessionListItems = result.sessions;
+ this.sessionListTotal = result.total;
+ this.sessionListPage = 1;
this.sessionPopup = document.createElement("div");
this.sessionPopup.className = "agent-session-popup b3-menu";
@@ -261,8 +270,7 @@ export class AgentChat extends Model {
this.sessionPopup.innerHTML = html;
const itemsContainer = this.sessionPopup.querySelector(".b3-menu__items") as HTMLElement;
- this.rebuildSessionItems(itemsContainer);
-
+ this.renderSessionItems(itemsContainer, result.sessions, false);
const searchInput = this.sessionPopup.querySelector(".agent-session-popup__search") as HTMLInputElement;
searchInput.addEventListener("input", () => {
this.filterSessionList(searchInput.value, itemsContainer);
@@ -271,6 +279,14 @@ export class AgentChat extends Model {
e.stopPropagation();
});
+ itemsContainer.addEventListener("scroll", () => {
+ if (this.isLoadingMore) { return; }
+ if (this.sessionListItems.length >= this.sessionListTotal) { return; }
+ if (itemsContainer.scrollHeight - itemsContainer.scrollTop - itemsContainer.clientHeight <= 30) {
+ this.loadMoreSessions(itemsContainer);
+ }
+ });
+
this.parent.panelElement.appendChild(this.sessionPopup);
const btnRect = this.sessionMenuBtn.getBoundingClientRect();
@@ -291,14 +307,13 @@ export class AgentChat extends Model {
}
}
- private rebuildSessionItems(container: HTMLElement) {
- const list = this.sessionListItems;
+ private renderSessionItems(container: HTMLElement, items: SessionIndexItem[], append: boolean) {
let html = "";
- if (list.length === 0) {
+ if (items.length === 0 && !append) {
html += '<div class="b3-menu__item"><span class="b3-menu__label" style="text-align:center;color:var(--b3-theme-on-surface-light)">' + (window.siyuan.languages.emptyContent || "No sessions") + "</span></div>";
} else {
- for (let i = 0; i < list.length; i++) {
- const s = list[i];
+ for (let i = 0; i < items.length; i++) {
+ const s = items[i];
const isActive = s.id === this.sessionId;
html += '<div class="b3-menu__item' + (isActive ? " b3-menu__item--current" : "") + '" data-id="' + s.id + '">' +
'<span class="b3-menu__label ariaLabel" data-position="east" aria-label="' + this.escapeHtml(s.title || this.defaultTitle) + '">' + this.escapeHtml(s.title || this.defaultTitle) + "</span>" +
@@ -309,65 +324,79 @@ export class AgentChat extends Model {
"</div>";
}
}
- container.innerHTML = html;
+ if (append) {
+ container.insertAdjacentHTML("beforeend", html);
+ } else {
+ container.innerHTML = html;
+ }
this.bindSessionItemEvents(container);
}
private bindSessionItemEvents(container: HTMLElement) {
- container.querySelectorAll(".b3-menu__item").forEach((item) => {
- item.addEventListener("click", () => {
- const id = item.getAttribute("data-id") || "";
- if (id && id !== this.sessionId) {
- this.closeSessionMenu();
- this.switchSession(id);
- }
- });
- });
- container.querySelectorAll(".agent-session-popup__delete").forEach((btn) => {
- btn.addEventListener("click", (e: MouseEvent) => {
+ if (container.dataset.eventsBound) { return; }
+ container.dataset.eventsBound = "1";
+
+ container.addEventListener("click", (e: MouseEvent) => {
+ const target = e.target as HTMLElement;
+
+ const deleteBtn = target.closest(".agent-session-popup__delete");
+ if (deleteBtn) {
e.stopPropagation();
- const id = btn.getAttribute("data-id") || "";
+ const id = deleteBtn.getAttribute("data-id") || "";
if (id) { this.deleteSession(id); }
- });
- });
- container.querySelectorAll(".agent-session-popup__rename").forEach((btn) => {
- btn.addEventListener("click", (e: MouseEvent) => {
+ return;
+ }
+
+ const renameBtn = target.closest(".agent-session-popup__rename");
+ if (renameBtn) {
e.stopPropagation();
- const id = btn.getAttribute("data-id") || "";
+ const id = renameBtn.getAttribute("data-id") || "";
if (id) {
- const parent = btn.parentElement;
+ const parent = renameBtn.parentElement;
const row = parent ? parent.parentElement as HTMLElement : null;
if (row) { this.startRename(id, row); }
}
- });
+ return;
+ }
+
+ const item = target.closest(".b3-menu__item");
+ if (item) {
+ const id = (item as HTMLElement).getAttribute("data-id") || "";
+ if (id && id !== this.sessionId) {
+ this.closeSessionMenu();
+ this.switchSession(id);
+ }
+ }
});
}
+ private async loadMoreSessions(container: HTMLElement) {
+ if (this.isLoadingMore) { return; }
+ this.isLoadingMore = true;
+ try {
+ const result = await SessionStore.list({page: this.sessionListPage + 1, pageSize: 30, keyword: this.currentSearchKeyword});
+ this.sessionListPage = result.page;
+ this.sessionListItems = this.sessionListItems.concat(result.sessions);
+ this.sessionListTotal = result.total;
+ this.renderSessionItems(container, result.sessions, true);
+ } finally {
+ this.isLoadingMore = false;
+ }
+ }
+
private filterSessionList(keyword: string, container: HTMLElement) {
this.currentSearchKeyword = keyword.trim();
- if (!this.currentSearchKeyword) {
- this.rebuildSessionItems(container);
- return;
- }
- const kw = this.currentSearchKeyword.toLowerCase();
- let hasVisible = false;
- const items = container.querySelectorAll(".b3-menu__item[data-id]");
- for (let i = 0; i < items.length; i++) {
- const item = items[i] as HTMLElement;
- const id = item.getAttribute("data-id") || "";
- const session = this.sessionListItems.find((s) => s.id === id);
- const title = (session ? session.title : "") || this.defaultTitle;
- if (title.toLowerCase().indexOf(kw) >= 0) {
- item.style.display = "";
- hasVisible = true;
- } else {
- item.style.display = "none";
- }
- }
- if (!hasVisible) {
- container.innerHTML = '<div class="b3-menu__item"><span class="b3-menu__label" style="text-align:center;color:var(--b3-theme-on-surface-light)">' + (window.siyuan.languages.emptyContent || "No sessions") + "</span></div>";
- }
- this.highlightCurrentSession();
+ if (this.searchTimer !== null) { clearTimeout(this.searchTimer); }
+ this.searchTimer = window.setTimeout(async () => {
+ const result = await SessionStore.list({page: 1, pageSize: 30, keyword: this.currentSearchKeyword});
+ this.sessionListItems = result.sessions;
+ this.sessionListTotal = result.total;
+ this.sessionListPage = 1;
+ this.searchTimer = null;
+ this.renderSessionItems(container, result.sessions, false);
+ container.scrollTop = 0;
+ this.highlightCurrentSession();
+ }, 300);
}
private startRename(id: string, rowEl: HTMLElement) {
@@ -537,7 +566,8 @@ export class AgentChat extends Model {
this.sessionListItems = this.sessionListItems.filter((item) => item.id !== id);
const wasCurrent = id === this.sessionId;
if (wasCurrent) {
- const list = await SessionStore.list();
+ const result = await SessionStore.list({page: 1, pageSize: 1});
+ const list = result.sessions;
this.sessionListItems = list;
this.entries = [];
if (list.length > 0) {
@@ -551,12 +581,11 @@ export class AgentChat extends Model {
const itemsContainer = this.sessionPopup?.querySelector(".b3-menu__items") as HTMLElement;
if (itemsContainer) {
- if (this.currentSearchKeyword) {
- this.filterSessionList(this.currentSearchKeyword, itemsContainer);
- } else {
- this.rebuildSessionItems(itemsContainer);
- }
- }
+ const result = await SessionStore.list({page: 1, pageSize: 30, keyword: this.currentSearchKeyword});
+ this.sessionListItems = result.sessions;
+ this.sessionListTotal = result.total;
+ this.sessionListPage = 1;
+ this.renderSessionItems(itemsContainer, result.sessions, false); }
}
private highlightCurrentSession() {
diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts
index d81888feaa..aafebc6a26 100644
--- a/app/src/layout/dock/SessionStore.ts
+++ b/app/src/layout/dock/SessionStore.ts
@@ -1,15 +1,21 @@
import {fetchSyncPost} from "../../util/fetch";
-const SESSIONS_DIR = "data/storage/ai/agent/sessions/";
+const API = "/api/ai/agent";
export interface SessionIndexItem {
id: string;
title: string;
- model?: string;
createdAt: number;
updatedAt: number;
}
+export interface SessionListResult {
+ sessions: SessionIndexItem[];
+ total: number;
+ page: number;
+ pageSize: number;
+}
+
export interface AgentSession {
id: string;
title: string;
@@ -35,78 +41,34 @@ function newSessionId(): string {
return (window as any).Lute ? (window as any).Lute.NewNodeID() : Date.now().toString(36);
}
-async function readJsonFile(path: string): Promise<any | null> {
- try {
- const r = await fetchSyncPost("/api/file/getFile", {path: path}) as any;
- if (!r) { return null; }
- return r;
- } catch (e) {
- return null;
- }
-}
-
-async function writeJsonFile(path: string, data: any): Promise<void> {
- const content = JSON.stringify(data, null, "\t");
- const fileName = path.split("/").pop() || "file.json";
- const file = new File([new Blob([content], {type: "application/json"})], fileName);
- const formData = new FormData();
- formData.append("path", path);
- formData.append("file", file);
- formData.append("isDir", "false");
- await fetchSyncPost("/api/file/putFile", formData);
-}
-
-async function readDir(path: string): Promise<Array<{name: string; isDir: boolean; updated: number}> | null> {
- try {
- const r = await fetchSyncPost("/api/file/readDir", {path}) as any;
- if (r && r.code === 0 && r.data) { return r.data; }
- } catch (e) { /* readDir failed, directory may not exist */ }
- return null;
-}
-
-function getSessionFilePath(id: string): string {
- return SESSIONS_DIR + id + "/session.json";
-}
-
export const SessionStore = {
async init(): Promise<SessionIndexItem[]> {
- return await this.list();
+ const result = await this.list({page: 1, pageSize: 1});
+ return result.sessions;
},
- async list(): Promise<SessionIndexItem[]> {
- const entries = await readDir(SESSIONS_DIR);
- if (!entries) { return []; }
-
- const list: SessionIndexItem[] = [];
- for (let i = 0; i < entries.length; i++) {
- const entry = entries[i];
- if (!entry.isDir) { continue; }
- const session = await readJsonFile(getSessionFilePath(entry.name));
- if (session && session.id) {
- list.push({
- id: session.id,
- title: session.title || "AI Agent",
- model: session.model || "",
- createdAt: session.createdAt || entry.updated || Date.now(),
- updatedAt: session.updatedAt || entry.updated || Date.now(),
- });
- }
- }
- list.sort((a, b) => b.updatedAt - a.updatedAt);
- return list;
+ async list(opts?: {page?: number, pageSize?: number, keyword?: string}): Promise<SessionListResult> {
+ const resp = await fetchSyncPost(API + "/lsSessions", {
+ page: opts?.page || 1,
+ pageSize: opts?.pageSize || 30,
+ keyword: opts?.keyword || "",
+ }) as {code: number, data: SessionListResult};
+ if (resp && resp.code === 0) { return resp.data; }
+ return {sessions: [], total: 0, page: 1, pageSize: opts?.pageSize || 30};
},
async load(id: string): Promise<AgentSession | null> {
- return await readJsonFile(getSessionFilePath(id));
+ const resp = await fetchSyncPost(API + "/getSession", {id}) as {code: number, data: AgentSession};
+ return (resp && resp.code === 0) ? resp.data : null;
},
async save(session: AgentSession): Promise<void> {
session.updatedAt = Date.now();
- await writeJsonFile(getSessionFilePath(session.id), session);
+ await fetchSyncPost(API + "/saveSession", session);
},
async remove(id: string): Promise<void> {
- await fetchSyncPost("/api/file/removeFile", {path: SESSIONS_DIR + id + "/"});
+ await fetchSyncPost(API + "/removeSession", {id});
},
async rename(id: string, newTitle: string): Promise<void> {
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index f9ff8a5576..2f28305d63 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -696,6 +696,7 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
return
}
_ = filelock.WriteFile(path, data)
+ UpdateSessionIndex(sessionID, cp.Title, cp.CreatedAt, cp.UpdatedAt)
}
func createStreamWithRetry(ctx context.Context, client *openai.Client, req openai.ChatCompletionRequest, maxRetries int, ch chan<- AgentEvent) (*openai.ChatCompletionStream, error) {
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
new file mode 100644
index 0000000000..66da60c774
--- /dev/null
+++ b/kernel/agent/session.go
@@ -0,0 +1,333 @@
+// SiYuan - Refactor your thinking
+// 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 agent
+
+import (
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var indexMu sync.Mutex
+
+func sessionsIndexPath() string {
+ return filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", "index.json")
+}
+
+func sessionsDir() string {
+ return filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions")
+}
+
+type SessionIndexItem struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
+
+type SessionListResult struct {
+ Sessions []*SessionIndexItem `json:"sessions"`
+ Total int `json:"total"`
+ Page int `json:"page"`
+ PageSize int `json:"pageSize"`
+}
+
+type sessionMeta struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
+
+func loadSessionIndex() map[string]*SessionIndexItem {
+ data, err := os.ReadFile(sessionsIndexPath())
+ if err != nil {
+ return nil
+ }
+ var index map[string]*SessionIndexItem
+ if gulu.JSON.UnmarshalJSON(data, &index) != nil {
+ return nil
+ }
+ return index
+}
+
+func saveSessionIndex(index map[string]*SessionIndexItem) {
+ data, err := gulu.JSON.MarshalIndentJSON(index, "", "\t")
+ if err != nil {
+ return
+ }
+ _ = os.MkdirAll(filepath.Dir(sessionsIndexPath()), 0755)
+ _ = filelock.WriteFile(sessionsIndexPath(), data)
+}
+
+func rebuildSessionIndex() map[string]*SessionIndexItem {
+ entries, err := os.ReadDir(sessionsDir())
+ if err != nil {
+ return nil
+ }
+ index := map[string]*SessionIndexItem{}
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ id := entry.Name()
+ sessionPath := filepath.Join(sessionsDir(), id, "session.json")
+ sessionData, err := os.ReadFile(sessionPath)
+ if err != nil {
+ continue
+ }
+ var meta sessionMeta
+ if gulu.JSON.UnmarshalJSON(sessionData, &meta) != nil || meta.ID == "" {
+ continue
+ }
+ title := meta.Title
+ if title == "" {
+ title = "AI Agent"
+ }
+ index[id] = &SessionIndexItem{
+ ID: meta.ID,
+ Title: title,
+ CreatedAt: meta.CreatedAt,
+ UpdatedAt: meta.UpdatedAt,
+ }
+ }
+ saveSessionIndex(index)
+ return index
+}
+
+func UpdateSessionIndex(id, title string, createdAt, updatedAt int64) {
+ if id == "" {
+ return
+ }
+ indexMu.Lock()
+ defer indexMu.Unlock()
+
+ index := loadSessionIndex()
+ if index == nil {
+ index = map[string]*SessionIndexItem{}
+ }
+ if title == "" {
+ title = "AI Agent"
+ }
+ index[id] = &SessionIndexItem{
+ ID: id,
+ Title: title,
+ CreatedAt: createdAt,
+ UpdatedAt: updatedAt,
+ }
+ saveSessionIndex(index)
+}
+
+func ListSessions(page, pageSize int, keyword string) *SessionListResult {
+ if page <= 0 {
+ page = 1
+ }
+ if pageSize <= 0 {
+ pageSize = 30
+ }
+
+ indexMu.Lock()
+ index := loadSessionIndex()
+ if index == nil || len(index) == 0 {
+ index = rebuildSessionIndex()
+ }
+
+ if index != nil {
+ entries, err := os.ReadDir(sessionsDir())
+ if err == nil {
+ dirMap := map[string]bool{}
+ for _, entry := range entries {
+ if entry.IsDir() {
+ dirMap[entry.Name()] = true
+ }
+ }
+
+ needsSave := false
+
+ for id := range index {
+ if !dirMap[id] {
+ delete(index, id)
+ needsSave = true
+ }
+ }
+
+ for id := range dirMap {
+ if _, ok := index[id]; !ok {
+ sessionPath := filepath.Join(sessionsDir(), id, "session.json")
+ sessionData, err := os.ReadFile(sessionPath)
+ if err == nil {
+ var meta sessionMeta
+ if gulu.JSON.UnmarshalJSON(sessionData, &meta) == nil && meta.ID != "" {
+ title := meta.Title
+ if title == "" {
+ title = "AI Agent"
+ }
+ index[id] = &SessionIndexItem{
+ ID: meta.ID,
+ Title: title,
+ CreatedAt: meta.CreatedAt,
+ UpdatedAt: meta.UpdatedAt,
+ }
+ needsSave = true
+ }
+ }
+ }
+ }
+
+ if needsSave {
+ saveSessionIndex(index)
+ }
+ }
+ }
+ indexMu.Unlock()
+
+ if index == nil {
+ return &SessionListResult{
+ Sessions: []*SessionIndexItem{},
+ Total: 0,
+ Page: page,
+ PageSize: pageSize,
+ }
+ }
+
+ items := make([]*SessionIndexItem, 0, len(index))
+ for _, item := range index {
+ if keyword != "" {
+ kw := strings.ToLower(keyword)
+ title := strings.ToLower(item.Title)
+ if !strings.Contains(title, kw) {
+ continue
+ }
+ }
+ items = append(items, item)
+ }
+
+ sort.Slice(items, func(i, j int) bool {
+ return items[i].CreatedAt > items[j].CreatedAt
+ })
+
+ total := len(items)
+
+ start := (page - 1) * pageSize
+ if start >= total {
+ return &SessionListResult{
+ Sessions: []*SessionIndexItem{},
+ Total: total,
+ Page: page,
+ PageSize: pageSize,
+ }
+ }
+ end := start + pageSize
+ if end > total {
+ end = total
+ }
+
+ return &SessionListResult{
+ Sessions: items[start:end],
+ Total: total,
+ Page: page,
+ PageSize: pageSize,
+ }
+}
+
+func GetSession(id string) (map[string]interface{}, error) {
+ if id == "" {
+ return nil, nil
+ }
+ sessionPath := filepath.Join(sessionsDir(), id, "session.json")
+ data, err := os.ReadFile(sessionPath)
+ if err != nil {
+ return nil, err
+ }
+ var session map[string]interface{}
+ if err := gulu.JSON.UnmarshalJSON(data, &session); err != nil {
+ return nil, err
+ }
+ return session, nil
+}
+
+func SaveSession(data []byte) error {
+ var meta sessionMeta
+ if err := gulu.JSON.UnmarshalJSON(data, &meta); err != nil || meta.ID == "" {
+ return nil
+ }
+
+ dir := filepath.Join(sessionsDir(), meta.ID)
+ _ = os.MkdirAll(dir, 0755)
+ path := filepath.Join(dir, "session.json")
+
+ existing, err := os.ReadFile(path)
+ if err == nil && len(existing) > 0 {
+ var existingData map[string]interface{}
+ var newData map[string]interface{}
+ if gulu.JSON.UnmarshalJSON(existing, &existingData) == nil &&
+ gulu.JSON.UnmarshalJSON(data, &newData) == nil {
+ for k, v := range existingData {
+ if _, ok := newData[k]; !ok {
+ newData[k] = v
+ }
+ }
+ merged, err := gulu.JSON.MarshalIndentJSON(newData, "", "\t")
+ if err == nil {
+ data = merged
+ }
+ }
+ } else {
+ var newData map[string]interface{}
+ if gulu.JSON.UnmarshalJSON(data, &newData) == nil {
+ indented, err := gulu.JSON.MarshalIndentJSON(newData, "", "\t")
+ if err == nil {
+ data = indented
+ }
+ }
+ }
+
+ _ = filelock.WriteFile(path, data)
+
+ title := meta.Title
+ if title == "" {
+ title = "AI Agent"
+ }
+ UpdateSessionIndex(meta.ID, title, meta.CreatedAt, meta.UpdatedAt)
+
+ return nil
+}
+
+func DeleteSession(id string) error {
+ if id == "" {
+ return nil
+ }
+
+ dir := filepath.Join(sessionsDir(), id)
+ _ = os.RemoveAll(dir)
+
+ indexMu.Lock()
+ index := loadSessionIndex()
+ if index != nil {
+ delete(index, id)
+ saveSessionIndex(index)
+ }
+ indexMu.Unlock()
+
+ return nil
+}
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 050a57fae4..0cd1ea7524 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -20,6 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/http"
"sync"
"time"
@@ -202,6 +203,90 @@ func agentChatTitle(c *gin.Context) {
c.JSON(http.StatusOK, ret)
}
+type agentSessionsReq struct {
+ Page int `json:"page"`
+ PageSize int `json:"pageSize"`
+ Keyword string `json:"keyword"`
+}
+
+func lsSessions(c *gin.Context) {
+ req := &agentSessionsReq{}
+ if err := c.ShouldBindJSON(req); err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "invalid request: " + err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ result := agent.ListSessions(req.Page, req.PageSize, req.Keyword)
+ ret := gulu.Ret.NewResult()
+ ret.Data = result
+ c.JSON(http.StatusOK, ret)
+}
+
+type agentSessionGetReq struct {
+ ID string `json:"id"`
+}
+
+func getSession(c *gin.Context) {
+ req := &agentSessionGetReq{}
+ if err := c.ShouldBindJSON(req); err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "invalid request: " + err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ session, err := agent.GetSession(req.ID)
+ if err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ ret := gulu.Ret.NewResult()
+ ret.Data = session
+ c.JSON(http.StatusOK, ret)
+}
+
+type agentSessionDeleteReq struct {
+ ID string `json:"id"`
+}
+
+func removeSession(c *gin.Context) {
+ req := &agentSessionDeleteReq{}
+ if err := c.ShouldBindJSON(req); err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "invalid request: " + err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ _ = agent.DeleteSession(req.ID)
+ ret := gulu.Ret.NewResult()
+ c.JSON(http.StatusOK, ret)
+}
+
+func saveSession(c *gin.Context) {
+ body, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "failed to read body: " + err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ _ = agent.SaveSession(body)
+ ret := gulu.Ret.NewResult()
+ c.JSON(http.StatusOK, ret)
+}
+
func writeSSE(c *gin.Context, event agent.AgentEvent) error {
switch event.Type {
case "content":
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 0961c97d8d..f12fc2ae1e 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -528,6 +528,10 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/agent/confirm", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatConfirm)
ginServer.Handle("POST", "/api/ai/agent/question", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatQuestion)
ginServer.Handle("POST", "/api/ai/agent/title", model.CheckAuth, model.CheckAdminRole, agentChatTitle)
+ ginServer.Handle("POST", "/api/ai/agent/lsSessions", model.CheckAuth, model.CheckAdminRole, lsSessions)
+ ginServer.Handle("POST", "/api/ai/agent/getSession", model.CheckAuth, model.CheckAdminRole, getSession)
+ ginServer.Handle("POST", "/api/ai/agent/saveSession", model.CheckAuth, model.CheckAdminRole, saveSession)
+ ginServer.Handle("POST", "/api/ai/agent/removeSession", model.CheckAuth, model.CheckAdminRole, removeSession)
ginServer.Handle("POST", "/api/petal/loadPetals", model.CheckAuth, loadPetals)
ginServer.Handle("POST", "/api/petal/setPetalEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalEnabled)