Skip to content

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

:sparkles: Support persistent agent session pinning https://github.com/siyuan-note/siyuan/issues/20699

Danielf9ba1fc3326e
diff --git a/app/src/layout/dock/agent/AgentChat.sessions.test.ts b/app/src/layout/dock/agent/AgentChat.sessions.test.ts
index 836314ccfb..1c61eadf98 100644
--- a/app/src/layout/dock/agent/AgentChat.sessions.test.ts
+++ b/app/src/layout/dock/agent/AgentChat.sessions.test.ts
@@ -79,6 +79,19 @@ const session = (overrides: Partial<AgentSession> = {}): AgentSession => ({
...overrides,
});
+test("session pin notifications refresh the list without disturbing conversations or drafts", () => {
+ const {chat} = createChat(async () => { throw new Error("pinning must not reload the conversation"); });
+ let refreshes = 0;
+ chat.sessionPanel = {refresh: () => { refreshes++; }};
+ chat.reloadFromDisk = () => { throw new Error("pinning must not redraw the conversation"); };
+ for (const streaming of [false, true]) {
+ chat.isStreaming = streaming;
+ chat.onWsMessage({cmd: "agentSessionChanged", data: {sessionID: "second", action: "pin"}});
+ chat.onWsMessage({cmd: "agentSessionChanged", data: {sessionID: "first", action: "pin"}});
+ }
+ assert.equal(refreshes, 4);
+});
+
test("a background turn ending during a session switch releases the stale mirror lock after recovery", async () => {
let loads = 0;
let commits = 0;
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index c30ee3748e..ba0d621262 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -1457,6 +1457,7 @@ export class AgentChat extends Model {
// - streamEnd:后端 eventCh 关闭(流结束),只解除占位锁定;已提交内容由 saveSession 的 update
// 同步,未提交内容由后端紧随其后的恢复 update 同步。
// - permission:只刷新当前会话权限,不重绘正在流式生成的消息。
+ // - pin:只刷新列表,不影响当前对话或输入草稿。
// - delete:当前会话被删除则清空视图。
private onWsMessage(data: IWebSocketData) {
if (!data || data.cmd !== "agentSessionChanged") {
diff --git a/app/src/layout/dock/agent/AgentSessionPanel.dom.test.ts b/app/src/layout/dock/agent/AgentSessionPanel.dom.test.ts
new file mode 100644
index 0000000000..46082f0772
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentSessionPanel.dom.test.ts
@@ -0,0 +1,138 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const tick = () => new Promise(resolve => setTimeout(resolve, 0));
+ const errors: string[] = [];
+ const requests: {id: string, pinned: boolean}[] = [];
+ const rows = [{id: "old", title: "Older session", createdAt: 1, pinnedAt: 0},
+ {id: "active", title: "Current session", createdAt: 2, pinnedAt: 0}];
+ let rejectPin = false;
+ let release: () => void;
+ let pending: Promise<void> | undefined;
+ const store = {
+ list: async () => ({sessions: rows.slice().sort((a, b) => b.pinnedAt - a.pinnedAt || b.createdAt - a.createdAt)
+ .map(row => ({...row})), total: rows.length, page: 1}),
+ setPinned: async (id: string, pinned: boolean) => {
+ requests.push({id, pinned});
+ await pending;
+ if (rejectPin) {
+ throw new Error("Pin failed");
+ }
+ rows.find(row => row.id === id).pinnedAt = pinned ? 100 : 0;
+ },
+ };
+ const module = {exports: {} as {AgentSessionPanel: new (...args: unknown[]) => {
+ render: () => Promise<void>, destroy: () => void,
+ }}};
+ const noop = () => {};
+ const dependencies: Record<string, unknown> = {
+ "./SessionStore": {SessionStore: store},
+ "../../../util/escape": {escapeHtml: (value: string) => value},
+ "../../../util/setPosition": {setPosition: noop},
+ "../../../protyle/util/hasClosest": {hasClosestByClassName: (element: Element, name: string) => element.closest("." + name)},
+ "../../../protyle/util/compatibility": {isInMobileApp: () => false, isPhablet: () => false},
+ "../../../util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: false})},
+ "../../../menus/menuMouseScroll": {bindMenuMouseScroll: noop},
+ "../../../dialog/message": {showMessage: (message: string) => errors.push(message)},
+ };
+ new Function("require", "module", "exports", source)((id: string) => dependencies[id] || {}, module, module.exports);
+ Object.assign(window, {siyuan: {zIndex: 10, languages: {
+ pinDoc: "Pin", unpinDoc: "Unpin", rename: "Rename", more: "More", delete: "Delete",
+ }}});
+ const trigger = document.createElement("button");
+ document.body.append(trigger);
+ let switched = 0;
+ for (const mobile of [false, true]) {
+ rows[0].pinnedAt = 0;
+ requests.length = 0;
+ const panel = new module.exports.AgentSessionPanel(trigger, document.body, () => "active", () => "Untitled",
+ {onSwitch: async () => { switched++; }}, mobile);
+ await panel.render();
+ const row = () => document.querySelector<HTMLElement>('.agent-session-popup .b3-list-item[data-id="old"]');
+ const pin = () => {
+ row().querySelector<HTMLElement>(".agent-session-more").click();
+ return row().querySelector<HTMLButtonElement>('[data-action="pin"]');
+ };
+ check.equal(pin().textContent, "Pin");
+ pending = new Promise(resolve => { release = resolve; });
+ const button = row().querySelector<HTMLButtonElement>('[data-action="pin"]');
+ button.click();
+ button.click();
+ check.equal(requests.length, 1, "repeated clicks cannot queue duplicate pin requests");
+ check.equal(button.disabled, true);
+ release();
+ pending = undefined;
+ await tick();
+ check.equal(document.querySelector(".agent-session-popup .b3-list-item").getAttribute("data-id"), "old");
+ check.ok(row().querySelector('.b3-list-item__graphic use[href="#iconPin"], .b3-list-item__graphic use'));
+ check.equal(pin().textContent, "Unpin");
+ check.equal(switched, 0, "pinning does not activate the target session");
+ panel.destroy();
+ await panel.render();
+ check.equal(pin().textContent, "Unpin", "reopening restores the persisted pin state");
+ rejectPin = true;
+ row().querySelector<HTMLButtonElement>('[data-action="pin"]').click();
+ await tick();
+ check.equal(errors.at(-1), "Pin failed");
+ check.equal(rows[0].pinnedAt, 100, "a failed request preserves the previous pin");
+ rejectPin = false;
+ pin().click();
+ await tick();
+ check.equal(rows[0].pinnedAt, 0);
+ check.equal(document.querySelector(".agent-session-popup .b3-list-item").getAttribute("data-id"), "active");
+ check.deepEqual(requests.map(request => request.pinned), [true, false, false]);
+ check.equal(switched, 0);
+ panel.destroy();
+ }
+ trigger.remove();
+ return "Session pin UI cases passed";
+};
+
+test("desktop and mobile session menus persist pins without switching chats", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+}, async () => {
+ const source = transpileModule(readFileSync(path.join(__dirname, "AgentSessionPanel.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+ }).outputText;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-session-pins-test-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {
+ nodeIntegration: true, contextIsolation: false, offscreen: true, backgroundThrottling: false,
+ }});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
+ browserCases.toString() + ")(" + JSON.stringify(source) + ").catch(error => { throw new Error(error.stack); })")}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 25000, windowsHide: true});
+ assert.match(result.stdout, /Session pin UI cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));
+ assert.ok(path.basename(temporary).startsWith("siyuan-session-pins-test-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/layout/dock/agent/AgentSessionPanel.ts b/app/src/layout/dock/agent/AgentSessionPanel.ts
index 8c7c0fde1b..f6a3e04566 100644
--- a/app/src/layout/dock/agent/AgentSessionPanel.ts
+++ b/app/src/layout/dock/agent/AgentSessionPanel.ts
@@ -12,6 +12,7 @@ import {useShell} from "../../../util/pathName";
import {getHostCapabilities} from "../../../util/hostCapabilities";
import {isInMobileApp, isPhablet} from "../../../protyle/util/compatibility";
import {bindMenuMouseScroll} from "../../../menus/menuMouseScroll";
+import {showMessage} from "../../../dialog/message";
export class AgentSessionPanel {
private popup: HTMLElement | null = null;
@@ -230,12 +231,15 @@ export class AgentSessionPanel {
html += '<div class="b3-list-item' + (this.mobile ? "" : " b3-list-item--hide-action") +
(isActive ? " b3-list-item--focus" : "") + '" data-id="' + s.id + '">' +
statusHTML +
+ (s.pinnedAt ? '<svg class="b3-list-item__graphic ariaLabel" aria-label="' + escapeHtml(L.pinDoc) + '"><use xlink:href="#iconPin"></use></svg>' : "") +
'<span class="b3-list-item__text ariaLabel" data-position="parentW" aria-label="' + escapeHtml(title) + '">' + escapeHtml(title) + "</span>" +
'<span class="b3-list-item__action b3-tooltips b3-tooltips__nw" data-id="' + s.id + '" aria-label="' + window.siyuan.languages.rename + '"><svg><use xlink:href="#iconEdit"></use></svg></span>' +
'<span class="b3-list-item__action b3-tooltips b3-tooltips__nw agent-session-more" data-id="' + s.id + '" aria-label="' + (L.more || "More") + '">' +
'<svg><use xlink:href="#iconMore"></use></svg>' +
'<div class="b3-menu__submenu">' +
'<div class="b3-menu__items">' +
+ '<button class="b3-menu__item" data-action="pin"><svg class="b3-menu__icon"><use xlink:href="#' + (s.pinnedAt ? "iconUnpin" : "iconPin") +
+ '"></use></svg><span class="b3-menu__label">' + escapeHtml(s.pinnedAt ? L.unpinDoc : L.pinDoc) + "</span></button>" +
(isDesktop && getHostCapabilities().localFileSystem ? '<button class="b3-menu__item" data-action="folder"><svg class="b3-menu__icon"><use xlink:href="#iconFolder"></use></svg><span class="b3-menu__label">' + escapeHtml(L.showInFolder) + "</span></button>" : "") +
'<button class="b3-menu__item b3-menu__item--warning" data-action="delete"><svg class="b3-menu__icon"><use xlink:href="#iconTrashcan"></use></svg><span class="b3-menu__label">' + escapeHtml(L.delete) + "</span></button>" +
"</div>" +
@@ -274,7 +278,7 @@ export class AgentSessionPanel {
const actionBtn = hasClosestByClassName(target, "b3-list-item__action");
if (actionBtn) {
- // "更多"按钮:弹出文件夹(桌面端)和删除操作。
+ // "更多"按钮:置顶、文件夹(桌面端)和删除操作。
if (actionBtn.classList.contains("agent-session-more")) {
e.stopPropagation();
const id = (actionBtn as HTMLElement).getAttribute("data-id") || "";
@@ -472,6 +476,18 @@ export class AgentSessionPanel {
if (!btn) { return; }
e.stopPropagation();
const action = btn.getAttribute("data-action");
+ if (action === "pin") {
+ if ((btn as HTMLButtonElement).disabled) {
+ return;
+ }
+ (btn as HTMLButtonElement).disabled = true;
+ const pinned = !this.items.find(item => item.id === id)?.pinnedAt;
+ void SessionStore.setPinned(id, pinned).then(() => this.refresh()).catch(error => {
+ showMessage(error.message);
+ }).finally(() => {
+ (btn as HTMLButtonElement).disabled = false;
+ });
+ }
if (action === "delete") {
this.callbacks.onDelete(id).then(() => {
this.refresh();
diff --git a/app/src/layout/dock/agent/SessionStore.test.ts b/app/src/layout/dock/agent/SessionStore.test.ts
new file mode 100644
index 0000000000..762f302b59
--- /dev/null
+++ b/app/src/layout/dock/agent/SessionStore.test.ts
@@ -0,0 +1,46 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/layout/dock/agent/SessionStore.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+}).outputText;
+
+test("pinning waits for a new session to be saved and uses the independent metadata endpoint", async () => {
+ let resolveSave: (result: unknown) => void;
+ let pinFailure = false;
+ const calls: {url: string, body: Record<string, unknown>}[] = [];
+ const exports = {} as {SessionStore: typeof import("./SessionStore").SessionStore};
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({
+ Constants: {SIYUAN_APPID: "test-app"},
+ fetchSyncPost: (url: string, body: Record<string, unknown>, headers: Record<string, string>) => {
+ calls.push({url, body});
+ assert.equal(headers["X-SiYuan-App-ID"], "test-app");
+ if (url.endsWith("/saveSession")) {
+ return new Promise(resolve => { resolveSave = resolve; });
+ }
+ assert.equal(url, "/api/ai/agent/setPinned");
+ return Promise.resolve(pinFailure ? {code: -1, msg: "Pin rejected"} :
+ {code: 0, data: {pinnedAt: body.pinned ? 123 : 0}});
+ },
+ }),
+ });
+ const store = exports.SessionStore;
+ const save = store.save({id: "session", title: "New", createdAt: 1, updatedAt: 1});
+ const pin = store.setPinned("session", true);
+ assert.equal(calls.length, 1);
+ resolveSave({code: 0, data: {revision: 1}});
+ await save;
+ assert.equal(await pin, 123);
+ assert.equal(calls.length, 2);
+ assert.equal(calls[1].body.id, "session");
+ assert.equal(calls[1].body.pinned, true);
+ assert.equal(store.getRevision("session"), 1, "pinning leaves conversation revisions alone");
+ assert.equal(await store.setPinned("session", false), 0);
+ pinFailure = true;
+ await assert.rejects(store.setPinned("session", true), /Pin rejected/);
+});
diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.ts
index 47aa09ab15..26324be61a 100644
--- a/app/src/layout/dock/agent/SessionStore.ts
+++ b/app/src/layout/dock/agent/SessionStore.ts
@@ -24,7 +24,7 @@ async function waitForPendingSave(id: string) {
}
}
-// 标识发起者 app,后端 saveSession/removeSession 据此排除自身、向其他实例广播会话变更。
+// 标识发起者 app,后端据此排除自身、向其他实例广播会话变更。
const APP_HEADER = {
"Content-Type": "application/json",
"X-SiYuan-App-ID": Constants.SIYUAN_APPID,
@@ -36,6 +36,7 @@ export interface SessionIndexItem {
title: string;
createdAt: number;
updatedAt: number;
+ pinnedAt?: number;
agentRunning?: boolean;
}
@@ -49,6 +50,7 @@ export interface SessionListResult {
export interface AgentSession {
id: string;
title: string;
+ pinnedAt?: number;
titled?: boolean;
model?: string;
permissionMode?: AgentPermissionMode;
@@ -222,6 +224,15 @@ export const SessionStore = {
await this.save(session);
},
+ async setPinned(id: string, pinned: boolean): Promise<number> {
+ await waitForPendingSave(id);
+ const resp = await fetchSyncPost("/api/ai/agent/setPinned", {id, pinned}, APP_HEADER);
+ if (!resp || resp.code !== 0 || !resp.data) {
+ throw new Error(resp?.msg || "Failed to update agent session pin");
+ }
+ return resp.data.pinnedAt;
+ },
+
async setPermission(id: string, permissionMode: AgentPermissionMode): Promise<AgentPermissionMode> {
await waitForPendingSave(id);
const resp = await fetchSyncPost(API + "/setPermission", {
diff --git a/app/src/menus/menuLayout.dom.test.ts b/app/src/menus/menuLayout.dom.test.ts
index bea802d02c..98fedae1ff 100644
--- a/app/src/menus/menuLayout.dom.test.ts
+++ b/app/src/menus/menuLayout.dom.test.ts
@@ -71,6 +71,7 @@ const browserCases = async (sources: Record<string, string>, css: string) => {
"layout/dock/agent/path": {},
"util/pathName": {},
"util/upDownHint": {},
+ "dialog/message": {},
"util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: false})},
"asset/pdf/internal_evt.js": {internalOpt: {}},
"asset/pdf/pdf_viewer.js": {PagesCountLimit: {FORCE_SCROLL_MODE_PAGE: 10000}},
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index fcb158e590..1ff757570b 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -170,20 +170,24 @@ export type AISessionExtensionAISessionEntryStep = ({ "content"?: string | null;
export type AISessionExtensionAISessionEntryStepInput = ({ "content"?: string | null; "reasoning"?: string | null; "reasoningContent"?: string | null; "roundID"?: string | null; "toolCallIDs"?: Array<string> | null; "toolNames"?: Array<string> | null; } & { [key: string]: JSONValue });
-export type AISessionExtensionAISessionFields = ({ "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionExtensionAISessionEntry> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AISessionExtensionAIAgentMessage> | null; "model"?: string | null; "permissionMode"?: string | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; } & { [key: string]: JSONValue });
+export type AISessionExtensionAISessionFields = ({ "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionExtensionAISessionEntry> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AISessionExtensionAIAgentMessage> | null; "model"?: string | null; "permissionMode"?: string | null; "pinnedAt"?: number | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; } & { [key: string]: JSONValue });
-export type AISessionExtensionAISessionFieldsInput = ({ "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionExtensionAISessionEntryInput> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AISessionExtensionAIAgentMessageInput> | null; "model"?: string | null; "permissionMode"?: string | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; } & { [key: string]: JSONValue });
+export type AISessionExtensionAISessionFieldsInput = ({ "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionExtensionAISessionEntryInput> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AISessionExtensionAIAgentMessageInput> | null; "model"?: string | null; "permissionMode"?: string | null; "pinnedAt"?: number | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; } & { [key: string]: JSONValue });
-export type AISessionFields = { "agentRunning"?: boolean; "alwaysAllow"?: boolean; "commitTurnID"?: string; "completionTokens"?: number; "contextCachedTokens"?: number; "contextLimit"?: number; "contextTokenBreakdown"?: Record<string, number>; "contextTokens"?: number; "createdAt"?: number; "entries"?: Array<AISessionEntry>; "expectedRevision"?: number; "id": string; "lastCommittedTurnID"?: string; "messageHistory"?: Array<string>; "messages"?: Array<AIAgentMessage>; "model"?: string; "permissionMode"?: string; "promptTokens"?: number; "recoveryRevision"?: number; "recoveryState"?: string; "recoveryTurnID"?: string; "revision"?: number; "snapshots"?: Array<string>; "title"?: string; "titled"?: boolean; "totalDuration"?: number; "updatedAt"?: number; };
+export type AISessionFields = { "agentRunning"?: boolean; "alwaysAllow"?: boolean; "commitTurnID"?: string; "completionTokens"?: number; "contextCachedTokens"?: number; "contextLimit"?: number; "contextTokenBreakdown"?: Record<string, number>; "contextTokens"?: number; "createdAt"?: number; "entries"?: Array<AISessionEntry>; "expectedRevision"?: number; "id": string; "lastCommittedTurnID"?: string; "messageHistory"?: Array<string>; "messages"?: Array<AIAgentMessage>; "model"?: string; "permissionMode"?: string; "pinnedAt"?: number; "promptTokens"?: number; "recoveryRevision"?: number; "recoveryState"?: string; "recoveryTurnID"?: string; "revision"?: number; "snapshots"?: Array<string>; "title"?: string; "titled"?: boolean; "totalDuration"?: number; "updatedAt"?: number; };
-export type AISessionFieldsInput = { "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionEntryInput> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AIAgentMessageInput> | null; "model"?: string | null; "permissionMode"?: string | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; };
+export type AISessionFieldsInput = { "agentRunning"?: boolean | null; "alwaysAllow"?: boolean | null; "commitTurnID"?: string | null; "completionTokens"?: number | null; "contextCachedTokens"?: number | null; "contextLimit"?: number | null; "contextTokenBreakdown"?: Record<string, number> | null; "contextTokens"?: number | null; "createdAt"?: number | null; "entries"?: Array<AISessionEntryInput> | null; "expectedRevision"?: number | null; "id": string; "lastCommittedTurnID"?: string | null; "messageHistory"?: Array<string> | null; "messages"?: Array<AIAgentMessageInput> | null; "model"?: string | null; "permissionMode"?: string | null; "pinnedAt"?: number | null; "promptTokens"?: number | null; "recoveryRevision"?: number | null; "recoveryState"?: string | null; "recoveryTurnID"?: string | null; "revision"?: number | null; "snapshots"?: Array<string> | null; "title"?: string | null; "titled"?: boolean | null; "totalDuration"?: number | null; "updatedAt"?: number | null; };
export type AISessionIDRequestInput = { "id"?: string | null; };
-export type AISessionIndex = { "agentRunning"?: boolean; "createdAt": number; "id": string; "title": string; "updatedAt": number; };
+export type AISessionIndex = { "agentRunning"?: boolean; "createdAt": number; "id": string; "pinnedAt"?: number; "title": string; "updatedAt": number; };
export type AISessionList = { "page": number; "pageSize": number; "sessions": Array<AISessionIndex | null> | null; "total": number; };
+export type AISessionPinnedData = { "pinnedAt": number; };
+
+export type AISessionPinnedRequestInput = { "id": string; "pinned": boolean; };
+
export type AISessionSaveData = { "revision": number; "session"?: AISessionExtensionAISessionFields; };
export type AISessionsRequestInput = { "keyword"?: string | null; "page"?: number | null; "pageSize"?: number | null; };
@@ -2892,6 +2896,11 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * Filter by title, then paginate sessions with pinned entries first, ordered by pinnedAt descending.
+ * Unpinned sessions retain createdAt descending order; equal timestamps use descending session IDs.
+ * Missing pinnedAt in older sessions means unpinned. Pinning survives index reconstruction.
+ */
"/api/ai/agent/lsSessions": {
request: AISessionsRequestInput;
response: { "code": 0; "data": AISessionList; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -2950,6 +2959,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * Save conversation content with revision checks. The stored pinnedAt is preserved regardless of the
+ * submitted snapshot; clients must use setPinned to update list pinning independently of active turns.
+ */
"/api/ai/agent/saveSession": {
request: AISessionExtensionAISessionFieldsInput;
response: { "code": 0; "data": AISessionSaveData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "revision"?: never; "session"?: never; }) | null | (AISessionSaveData & { "closeTimeout"?: never; }); "msg": string; };
@@ -2984,6 +2997,19 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * Persist pinning for an existing session. Requires administrator write access.
+ * pinned is a required boolean. Repeated pin requests preserve the original millisecond timestamp;
+ * unpinning returns pinnedAt=0. Missing or corrupt sessions fail without replacing their data.
+ * Pinning does not change conversation revisions, timestamps or active turns; stale saveSession requests cannot overwrite it.
+ */
+ "/api/ai/agent/setPinned": {
+ request: AISessionPinnedRequestInput;
+ response: { "code": 0; "data": AISessionPinnedData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
+ authorization?: readonly ["authenticated","admin","writable"];
+ };
"/api/ai/agent/title": {
request: AITitleRequestInput;
response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
index 2c78314b11..612f3fa93d 100644
--- a/kernel/agent/session.go
+++ b/kernel/agent/session.go
@@ -25,6 +25,7 @@ import (
"sort"
"strings"
"sync"
+ "time"
"github.com/88250/gulu"
"github.com/88250/lute/ast"
@@ -52,6 +53,7 @@ type SessionIndexItem struct {
Title string `json:"title"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
+ PinnedAt int64 `json:"pinnedAt,omitempty"`
AgentRunning bool `json:"agentRunning,omitempty"`
}
@@ -67,6 +69,7 @@ type sessionMeta struct {
Title string `json:"title"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
+ PinnedAt int64 `json:"pinnedAt,omitempty"`
Revision int64 `json:"revision"`
ExpectedRevision *int64 `json:"expectedRevision,omitempty"`
CommitTurnID string `json:"commitTurnID,omitempty"`
@@ -136,13 +139,14 @@ func rebuildSessionIndex() map[string]*SessionIndexItem {
Title: title,
CreatedAt: meta.CreatedAt,
UpdatedAt: meta.UpdatedAt,
+ PinnedAt: meta.PinnedAt,
}
}
saveSessionIndex(index)
return index
}
-func UpdateSessionIndex(id, title string, createdAt, updatedAt int64) {
+func UpdateSessionIndex(id, title string, createdAt, updatedAt, pinnedAt int64) {
if id == "" {
return
}
@@ -161,6 +165,7 @@ func UpdateSessionIndex(id, title string, createdAt, updatedAt int64) {
Title: title,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
+ PinnedAt: pinnedAt,
}
saveSessionIndex(index)
}
@@ -174,12 +179,12 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
}
indexMu.Lock()
+ defer indexMu.Unlock()
index := loadSessionIndex()
if len(index) == 0 {
index = rebuildSessionIndex()
}
if index == nil {
- indexMu.Unlock()
return &SessionListResult{
Sessions: []*SessionIndexItem{},
Total: 0,
@@ -189,7 +194,6 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
}
snapshot := make(map[string]*SessionIndexItem, len(index))
maps.Copy(snapshot, index)
- indexMu.Unlock()
entries, err := os.ReadDir(sessionsDir())
if err == nil {
@@ -225,6 +229,7 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
Title: title,
CreatedAt: meta.CreatedAt,
UpdatedAt: meta.UpdatedAt,
+ PinnedAt: meta.PinnedAt,
}
needsSave = true
}
@@ -233,9 +238,7 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
}
if needsSave {
- indexMu.Lock()
saveSessionIndex(snapshot)
- indexMu.Unlock()
}
}
@@ -254,6 +257,12 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
}
sort.Slice(items, func(i, j int) bool {
+ if items[i].PinnedAt != items[j].PinnedAt {
+ return items[i].PinnedAt > items[j].PinnedAt
+ }
+ if items[i].CreatedAt == items[j].CreatedAt {
+ return items[i].ID > items[j].ID
+ }
return items[i].CreatedAt > items[j].CreatedAt
})
@@ -336,6 +345,8 @@ func SaveSessionState(data []byte) (int64, map[string]any, error) {
delete(newData, "agentRunning")
delete(newData, "lastCommittedTurnID")
delete(newData, "pluginWorkflow")
+ // 置顶属于独立的列表元数据,旧客户端快照不能覆盖 setPinned 写入的状态。
+ delete(newData, "pinnedAt")
commitTurnID := meta.CommitTurnID
if commitTurnID == "" {
commitTurnID = meta.RecoveryTurnID
@@ -432,11 +443,49 @@ func SaveSessionState(data []byte) (int64, map[string]any, error) {
if value := numberToInt64(newData["updatedAt"]); value > 0 {
updatedAt = value
}
- UpdateSessionIndex(meta.ID, title, createdAt, updatedAt)
+ UpdateSessionIndex(meta.ID, title, createdAt, updatedAt, numberToInt64(newData["pinnedAt"]))
return newRevision, newData, nil
}
+func SetSessionPinned(id string, pinned bool) (int64, error) {
+ if !isValidSessionID(id) {
+ return 0, fmt.Errorf("invalid session id")
+ }
+ lock := sessionLock(id)
+ lock.Lock()
+ defer lock.Unlock()
+
+ path := filepath.Join(sessionsDir(), id, "session.json")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return 0, err
+ }
+ var session map[string]any
+ if err = gulu.JSON.UnmarshalJSON(data, &session); err != nil || session["id"] != id {
+ return 0, fmt.Errorf("invalid session data")
+ }
+ pinnedAt := numberToInt64(session["pinnedAt"])
+ if pinned {
+ if pinnedAt <= 0 {
+ pinnedAt = time.Now().UnixMilli()
+ }
+ } else {
+ pinnedAt = 0
+ }
+ session["pinnedAt"] = pinnedAt
+ data, err = gulu.JSON.MarshalIndentJSON(session, "", "\t")
+ if err != nil {
+ return 0, err
+ }
+ if err = filelock.WriteFile(path, data); err != nil {
+ return 0, err
+ }
+ title, _ := session["title"].(string)
+ UpdateSessionIndex(id, title, numberToInt64(session["createdAt"]), numberToInt64(session["updatedAt"]), pinnedAt)
+ return pinnedAt, nil
+}
+
func DeleteSession(id string) error {
if id == "" || !isValidSessionID(id) {
return fmt.Errorf("invalid session id")
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
index 43392b8886..4400088e3b 100644
--- a/kernel/agent/session_test.go
+++ b/kernel/agent/session_test.go
@@ -13,6 +13,8 @@ import (
"maps"
"os"
"path/filepath"
+ "reflect"
+ "sync"
"testing"
"time"
@@ -42,6 +44,126 @@ func marshalSession(t *testing.T, value any) []byte {
return data
}
+func TestSessionPinPersistenceAndOrdering(t *testing.T) {
+ useTestDataDir(t)
+ ids := []string{"20261020120000-aaaaaaa", "20261020120000-bbbbbbb", "20261020120000-ccccccc"}
+ for i, id := range ids {
+ _, _, err := SaveSessionState(marshalSession(t, map[string]any{
+ "id": id, "title": "Session " + id, "createdAt": i + 1, "updatedAt": i + 10,
+ "future": map[string]any{"keep": true}, "entries": []any{map[string]any{"type": "user", "content": "keep"}},
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ checkOrder := func(want []string) {
+ t.Helper()
+ got := []string{}
+ for page := 1; page <= len(want); page++ {
+ result := ListSessions(page, 1, "Session")
+ if result.Total != len(want) || len(result.Sessions) != 1 {
+ t.Fatalf("pagination: %+v", result)
+ }
+ got = append(got, result.Sessions[0].ID)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("order: %v != %v", got, want)
+ }
+ }
+ checkOrder([]string{ids[2], ids[1], ids[0]})
+ first, err := SetSessionPinned(ids[0], true)
+ if err != nil || first <= 0 {
+ t.Fatalf("pin: %d %v", first, err)
+ }
+ again, err := SetSessionPinned(ids[0], true)
+ if err != nil || again != first {
+ t.Fatalf("repeated pin changed timestamp: %d %v", again, err)
+ }
+ // Both timestamps may be equal; the stable ID tie-breaker gives the same expected order.
+ if _, err = SetSessionPinned(ids[1], true); err != nil {
+ t.Fatal(err)
+ }
+ checkOrder([]string{ids[1], ids[0], ids[2]})
+ if err = os.Remove(sessionsIndexPath()); err != nil {
+ t.Fatal(err)
+ }
+ checkOrder([]string{ids[1], ids[0], ids[2]})
+ before, err := GetSession(ids[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if numberToInt64(before["revision"]) != 1 || numberToInt64(before["updatedAt"]) != 10 || before["future"] == nil {
+ t.Fatalf("pin changed conversation metadata: %#v", before)
+ }
+ // A client loaded before pinning must not clear it, even when it supplies a stale value explicitly.
+ before["pinnedAt"] = int64(0)
+ before["expectedRevision"] = int64(1)
+ revision, saved, err := SaveSessionState(marshalSession(t, before))
+ if err != nil || revision != 2 || numberToInt64(saved["pinnedAt"]) != first {
+ t.Fatalf("stale save overwrote pin: %#v %v", saved, err)
+ }
+ if unpinned, err := SetSessionPinned(ids[0], false); err != nil || unpinned != 0 {
+ t.Fatalf("unpin: %d %v", unpinned, err)
+ }
+ saved["expectedRevision"] = revision
+ saved["pinnedAt"] = first
+ _, saved, err = SaveSessionState(marshalSession(t, saved))
+ if err != nil || numberToInt64(saved["pinnedAt"]) != 0 {
+ t.Fatalf("stale save restored pin: %#v %v", saved, err)
+ }
+ checkOrder([]string{ids[1], ids[2], ids[0]})
+ if err = DeleteSession(ids[1]); err != nil {
+ t.Fatal(err)
+ }
+ checkOrder([]string{ids[2], ids[0]})
+}
+
+func TestSessionPinRejectsInvalidDataAndSurvivesConcurrentIndexReads(t *testing.T) {
+ useTestDataDir(t)
+ for _, id := range []string{"", "../outside", testSessionID} {
+ if _, err := SetSessionPinned(id, true); err == nil {
+ t.Fatalf("invalid or missing session accepted: %q", id)
+ }
+ }
+ sessionPath := filepath.Join(sessionsDir(), testSessionID, "session.json")
+ if err := os.MkdirAll(filepath.Dir(sessionPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ for _, value := range []string{"{", "null", `{"id":"different"}`} {
+ if err := os.WriteFile(sessionPath, []byte(value), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetSessionPinned(testSessionID, true); err == nil {
+ t.Fatal("corrupt session accepted")
+ }
+ data, _ := os.ReadFile(sessionPath)
+ if string(data) != value {
+ t.Fatal("corrupt source overwritten")
+ }
+ }
+ if err := os.Remove(sessionPath); err != nil {
+ t.Fatal(err)
+ }
+ _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "createdAt": 1}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var jobs sync.WaitGroup
+ for i := 0; i < 12; i++ {
+ jobs.Go(func() { ListSessions(1, 30, "") })
+ jobs.Go(func() {
+ if _, pinErr := SetSessionPinned(testSessionID, true); pinErr != nil {
+ t.Error(pinErr)
+ }
+ })
+ }
+ jobs.Wait()
+ result := ListSessions(1, 30, "")
+ if len(result.Sessions) != 1 || result.Sessions[0].PinnedAt <= 0 {
+ t.Fatalf("index lost pin: %+v", result)
+ }
+}
+
func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
useTestDataDir(t)
base := map[string]any{
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 6be8b46b69..0fe15b2ac2 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -267,6 +267,18 @@ func agentChatConfirmContract(c *gin.Context, req apicontract.AIConfirmRequest)
var setAgentSessionPermission = contractHandler(apicontract.AIAgentSetPermission, setAgentSessionPermissionContract)
+var setAgentSessionPinned = contractHandler(apicontract.AISetSessionPinned, setAgentSessionPinnedContract)
+
+func setAgentSessionPinnedContract(c *gin.Context, req apicontract.AISessionPinnedRequest) apicontract.Response[apicontract.AISessionPinnedData] {
+ pinnedAt, err := agent.SetSessionPinned(req.ID, req.Pinned)
+ if err != nil {
+ return apicontract.Failure[apicontract.AISessionPinnedData](-1, err.Error())
+ }
+ return apicontract.WithAfterWrite(apicontract.Success(apicontract.AISessionPinnedData{PinnedAt: pinnedAt}), func() {
+ broadcastAgentSessionChanged(c.GetHeader("X-SiYuan-App-ID"), req.ID, "pin")
+ })
+}
+
func setAgentSessionPermissionContract(c *gin.Context, req apicontract.AIPermissionRequest) apicontract.Response[apicontract.AIPermissionData] {
ret := gulu.Ret.NewResult()
if err := agent.SetSessionPermissionMode(req.SessionID, req.PermissionMode); err != nil {
diff --git a/kernel/api/contract_agent_pinned_test.go b/kernel/api/contract_agent_pinned_test.go
new file mode 100644
index 0000000000..0414f1dbe3
--- /dev/null
+++ b/kernel/api/contract_agent_pinned_test.go
@@ -0,0 +1,87 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/agent"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractAISessionPinned(t *testing.T) {
+ aiContractConfiguration(t)
+ const id = "20261020120000-abcdefg"
+ if _, _, err := agent.SaveSessionState([]byte(`{"id":"` + id + `","title":"Pinned","createdAt":1}`)); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.POST("/api/ai/agent/setPinned", setAgentSessionPinned)
+ engine.POST("/api/ai/agent/lsSessions", lsSessions)
+ call := func(path, body string, code int) json.RawMessage {
+ t.Helper()
+ path = "/api/ai/agent/" + path
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))
+ requireAPIContract(t, "POST", path, recorder)
+ var result struct {
+ Code int
+ Data json.RawMessage
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.Code != code {
+ t.Fatalf("%s: %s %v", body, recorder.Body.String(), err)
+ }
+ return result.Data
+ }
+ var pin apicontract.AISessionPinnedData
+ if err := json.Unmarshal(call("setPinned", `{"id":"`+id+`","pinned":true}`, 0), &pin); err != nil || pin.PinnedAt <= 0 {
+ t.Fatalf("pin: %+v %v", pin, err)
+ }
+ var list apicontract.AISessionList
+ if err := json.Unmarshal(call("lsSessions", `{}`, 0), &list); err != nil || len(list.Sessions) != 1 || list.Sessions[0].PinnedAt != pin.PinnedAt {
+ t.Fatalf("list: %+v %v", list, err)
+ }
+ for _, body := range []string{
+ `{}`, `{"id":"` + id + `"}`, `{"id":"` + id + `","pinned":null}`,
+ `{"id":"` + id + `","pinned":1}`, `{"id":"` + id + `","pinned":"true"}`,
+ `{"id":null,"pinned":true}`, `{"id":"../outside","pinned":true}`,
+ `{"id":"20261020120000-missing","pinned":true}`,
+ } {
+ call("setPinned", body, -1)
+ }
+ if err := json.Unmarshal(call("setPinned", `{"id":"`+id+`","pinned":false}`, 0), &pin); err != nil || pin.PinnedAt != 0 {
+ t.Fatalf("unpin: %+v %v", pin, err)
+ }
+}
+
+func TestAPIContractAISessionPinnedAuthorization(t *testing.T) {
+ aiContractConfiguration(t)
+ previous := util.ReadOnly
+ t.Cleanup(func() { util.ReadOnly = previous })
+ for _, test := range []struct {
+ role model.Role
+ readonly bool
+ status int
+ }{
+ {model.RoleReader, false, http.StatusForbidden},
+ {model.RoleEditor, false, http.StatusForbidden},
+ {model.RoleAdministrator, true, http.StatusOK},
+ } {
+ util.ReadOnly = test.readonly
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, test.role); c.Next() })
+ ServeAPI(engine)
+ request := httptest.NewRequest("POST", "/api/ai/agent/setPinned", nil)
+ request.Body = aiUnreadBody{t: t}
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if recorder.Code != test.status || (test.readonly && !strings.Contains(recorder.Body.String(), `"code":-1`)) {
+ t.Fatalf("admission: %d %s", recorder.Code, recorder.Body.String())
+ }
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index bc7f244686..f632b51940 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -195,6 +195,7 @@ func registerAiRoutes(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/agent/chat", contractRouteHandlers(apicontract.AIAgentChat, agentChat)...)
ginServer.Handle("POST", "/api/ai/agent/confirm", contractRouteHandlers(apicontract.AIAgentConfirm, agentChatConfirm)...)
ginServer.Handle("POST", "/api/ai/agent/setPermission", contractRouteHandlers(apicontract.AIAgentSetPermission, setAgentSessionPermission)...)
+ ginServer.Handle("POST", "/api/ai/agent/setPinned", contractRouteHandlers(apicontract.AISetSessionPinned, setAgentSessionPinned)...)
ginServer.Handle("POST", "/api/ai/agent/question", contractRouteHandlers(apicontract.AIAgentQuestion, agentChatQuestion)...)
ginServer.Handle("POST", "/api/ai/agent/browserCapabilityResult", contractRouteHandlers(apicontract.AIAgentBrowserCapabilityResult, agentChatBrowserCapabilityResult)...)
ginServer.Handle("POST", "/api/ai/lsCapabilities", contractRouteHandlers(apicontract.AIListCapabilities, lsCapabilities)...)
diff --git a/kernel/apicontract/ai.go b/kernel/apicontract/ai.go
index 49b3756a58..f0776ff04f 100644
--- a/kernel/apicontract/ai.go
+++ b/kernel/apicontract/ai.go
@@ -47,6 +47,15 @@ type AISessionIDRequest struct {
ID string `json:"id" api:"optional,nullable"`
}
+type AISessionPinnedRequest struct {
+ ID string `json:"id"`
+ Pinned bool `json:"pinned"`
+}
+
+type AISessionPinnedData struct {
+ PinnedAt int64 `json:"pinnedAt"`
+}
+
type AISkillNameRequest struct {
Name string `json:"name" api:"optional,nullable"`
// Source 省略时保持工作空间和用户技能解析;显式内置来源拒绝由普通 HTTP 读取或修改。
@@ -133,6 +142,7 @@ type AISessionIndex struct {
Title string `json:"title"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
+ PinnedAt int64 `json:"pinnedAt,omitempty"`
AgentRunning bool `json:"agentRunning,omitempty"`
}
diff --git a/kernel/apicontract/ai_agent.go b/kernel/apicontract/ai_agent.go
index 6cc1396e22..16da742e82 100644
--- a/kernel/apicontract/ai_agent.go
+++ b/kernel/apicontract/ai_agent.go
@@ -144,14 +144,16 @@ type AISessionFields struct {
MessageHistory []string `json:"messageHistory,omitempty" api:"optional,nullable"`
CreatedAt int64 `json:"createdAt,omitempty" api:"optional,nullable"`
UpdatedAt int64 `json:"updatedAt,omitempty" api:"optional,nullable"`
- Revision int64 `json:"revision,omitempty" api:"optional,nullable"`
- ExpectedRevision *int64 `json:"expectedRevision,omitempty" api:"optional,nullable"`
- CommitTurnID string `json:"commitTurnID,omitempty" api:"optional,nullable"`
- LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty" api:"optional,nullable"`
- RecoveryTurnID string `json:"recoveryTurnID,omitempty" api:"optional,nullable"`
- RecoveryState string `json:"recoveryState,omitempty" api:"optional,nullable"`
- RecoveryRevision int64 `json:"recoveryRevision,omitempty" api:"optional,nullable"`
- AgentRunning bool `json:"agentRunning,omitempty" api:"optional,nullable"`
+ // PinnedAt is server-managed list metadata. Use setPinned to change it; saveSession preserves the stored value.
+ PinnedAt int64 `json:"pinnedAt,omitempty" api:"optional,nullable"`
+ Revision int64 `json:"revision,omitempty" api:"optional,nullable"`
+ ExpectedRevision *int64 `json:"expectedRevision,omitempty" api:"optional,nullable"`
+ CommitTurnID string `json:"commitTurnID,omitempty" api:"optional,nullable"`
+ LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty" api:"optional,nullable"`
+ RecoveryTurnID string `json:"recoveryTurnID,omitempty" api:"optional,nullable"`
+ RecoveryState string `json:"recoveryState,omitempty" api:"optional,nullable"`
+ RecoveryRevision int64 `json:"recoveryRevision,omitempty" api:"optional,nullable"`
+ AgentRunning bool `json:"agentRunning,omitempty" api:"optional,nullable"`
}
type AISessionSaveData struct {
Revision int64 `json:"revision"`
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 9051ad0bfd..31730dd6cb 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1386,10 +1386,20 @@ var AIReindexEmbedding = define[EmptyRequest, Null]("reindexEmbedding", "/api/ai
var AIRetryFailedEmbedding = define[EmptyRequest, Null]("retryFailedEmbedding", "/api/ai/retryFailedEmbedding", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
var AIAgentConfirm = define[AIConfirmRequest, Null]("agentChatConfirm", "/api/ai/agent/confirm", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
var AIAgentSetPermission = define[AIPermissionRequest, AIPermissionData]("setAgentSessionPermission", "/api/ai/agent/setPermission", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")
+
+// Persist pinning for an existing session. Requires administrator write access.
+// pinned is a required boolean. Repeated pin requests preserve the original millisecond timestamp;
+// unpinning returns pinnedAt=0. Missing or corrupt sessions fail without replacing their data.
+// Pinning does not change conversation revisions, timestamps or active turns; stale saveSession requests cannot overwrite it.
+var AISetSessionPinned = define[AISessionPinnedRequest, AISessionPinnedData]("setAgentSessionPinned", "/api/ai/agent/setPinned", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var AIAgentQuestion = define[AIQuestionRequest, Null]("agentChatQuestion", "/api/ai/agent/question", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
var AIAgentBrowserCapabilityResult = define[AIBrowserCapabilityResultRequest, Null]("agentChatBrowserCapabilityResult", "/api/ai/agent/browserCapabilityResult", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
var AIListCapabilities = define[EmptyRequest, []AICapabilityManifest]("lsCapabilities", "/api/ai/lsCapabilities", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var AIAgentTitle = define[AITitleRequest, string]("agentChatTitle", "/api/ai/agent/title", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")
+
+// Filter by title, then paginate sessions with pinned entries first, ordered by pinnedAt descending.
+// Unpinned sessions retain createdAt descending order; equal timestamps use descending session IDs.
+// Missing pinnedAt in older sessions means unpinned. Pinning survives index reconstruction.
var AIListSessions = define[AISessionsRequest, AISessionList]("lsSessions", "/api/ai/agent/lsSessions", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")
var AIRemoveSession = define[AISessionIDRequest, Null]("removeSession", "/api/ai/agent/removeSession", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409, 500}}, "POST")
var AIListSkills = define[EmptyRequest, []AISkillInfo]("lsSkills", "/api/ai/agent/lsSkills", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
@@ -1419,6 +1429,9 @@ var AIEditorChat = define[AIEditorChatRequest, Null]("aiEditorChat", "/api/ai/ed
var AIAgentChat = define[AIAgentChatRequest, Null]("agentChat", "/api/ai/agent/chat", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, aiAgentSSEOptions(), "POST")
var AIMCPOAuthCallback = define[EmptyRequest, BinaryContent]("mcpOAuthCallback", "/api/ai/mcp/oauth/callback/:flowID", PublicAccess, NoBody, HTTPContentOptions(HTTPContentVariant{Status: 200, ContentType: "text/html"}, HTTPContentVariant{Status: 400, ContentType: "text/html"}, HTTPContentVariant{Status: 403, ContentType: "text/plain"}), "GET")
var AIGetSession = define[AISessionIDRequest, *AISession]("getSession", "/api/ai/agent/getSession", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{500}}, "POST")
+
+// Save conversation content with revision checks. The stored pinnedAt is preserved regardless of the
+// submitted snapshot; clients must use setPinned to update list pinning independently of active turns.
var AISaveSession = define[AISession, AISessionSaveData]("saveSession", "/api/ai/agent/saveSession", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true, AdditionalErrorStatuses: []int{400, 409, 500}}, "POST")
// URL、TLS 和 Cookie 诊断对象包含标准库的原始 JSON。
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 352ef5db1b..b6a7dc3b13 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -4405,6 +4405,16 @@
}
]
},
+ "pinnedAt": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"promptTokens": {
"anyOf": [
{
@@ -4694,6 +4704,16 @@
}
]
},
+ "pinnedAt": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"promptTokens": {
"anyOf": [
{
@@ -4871,6 +4891,9 @@
"permissionMode": {
"type": "string"
},
+ "pinnedAt": {
+ "type": "integer"
+ },
"promptTokens": {
"type": "integer"
},
@@ -5088,6 +5111,16 @@
}
]
},
+ "pinnedAt": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"promptTokens": {
"anyOf": [
{
@@ -5225,6 +5258,9 @@
"id": {
"type": "string"
},
+ "pinnedAt": {
+ "type": "integer"
+ },
"title": {
"type": "string"
},
@@ -5281,6 +5317,34 @@
],
"additionalProperties": false
},
+ "AISessionPinnedData": {
+ "type": "object",
+ "properties": {
+ "pinnedAt": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "pinnedAt"
+ ],
+ "additionalProperties": false
+ },
+ "AISessionPinnedRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "pinned": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "id",
+ "pinned"
+ ],
+ "additionalProperties": false
+ },
"AISessionSaveData": {
"type": "object",
"properties": {
@@ -123077,6 +123141,86 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/ai/agent/setPinned",
+ "handler": "setAgentSessionPinned",
+ "authorization": [
+ "authenticated",
+ "admin",
+ "writable"
+ ],
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AISessionPinnedRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/AISessionPinnedData"
+ },
+ "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/ai/agent/title",