Skip to content

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

:sparkles: Improve Agent session permission controls https://github.com/siyuan-note/siyuan/issues/18553

Daniel15b34175bd5a
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index be23c8abb9..02486c6ad1 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "الإذن",
+ "agentPermissionConfirm": "يتطلب تأكيدًا",
+ "agentPermissionAllowSession": "السماح تلقائيًا",
"oidcVerificationFailed": "فشل التحقق من إعداد OIDC",
"oidcVerificationSuccess": "تم التحقق من إعداد OIDC وحفظه",
"oidcVerificationTip": "أكمل تسجيل الدخول إلى OIDC في نافذة المتصفح المفتوحة؛ سيظل الإعداد الحالي فعالًا حتى ينجح التحقق",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7790120c87..ea4201f7fe 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Berechtigung",
+ "agentPermissionConfirm": "Bestätigung erforderlich",
+ "agentPermissionAllowSession": "Automatisch erlauben",
"oidcVerificationFailed": "Überprüfung der OIDC-Konfiguration fehlgeschlagen",
"oidcVerificationSuccess": "OIDC-Konfiguration überprüft und gespeichert",
"oidcVerificationTip": "Schließen Sie die OIDC-Anmeldung im geöffneten Browserfenster ab; die aktuelle Konfiguration bleibt bis zur erfolgreichen Überprüfung aktiv",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 9938464ac7..96dd6e2ed9 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Permission",
+ "agentPermissionConfirm": "Require confirmation",
+ "agentPermissionAllowSession": "Automatically allow",
"oidcVerificationFailed": "OIDC configuration verification failed",
"oidcVerificationSuccess": "OIDC configuration verified and saved",
"oidcVerificationTip": "Complete OIDC login in the opened browser window; the current configuration remains active until verification succeeds",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 15ed6975db..8a7cb38972 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Permiso",
+ "agentPermissionConfirm": "Requerir confirmación",
+ "agentPermissionAllowSession": "Permitir automáticamente",
"oidcVerificationFailed": "La verificación de la configuración OIDC falló",
"oidcVerificationSuccess": "Configuración OIDC verificada y guardada",
"oidcVerificationTip": "Complete el inicio de sesión OIDC en la ventana del navegador abierta; la configuración actual seguirá activa hasta que la verificación se complete correctamente",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index b8840431e7..cd8d8f8d39 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Autorisation",
+ "agentPermissionConfirm": "Demander confirmation",
+ "agentPermissionAllowSession": "Autoriser automatiquement",
"oidcVerificationFailed": "Échec de la vérification de la configuration OIDC",
"oidcVerificationSuccess": "Configuration OIDC vérifiée et enregistrée",
"oidcVerificationTip": "Terminez la connexion OIDC dans la fenêtre de navigateur ouverte ; la configuration actuelle reste active jusqu’à la réussite de la vérification",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index ad94f0c42c..85d23b3314 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "הרשאה",
+ "agentPermissionConfirm": "דרוש אישור",
+ "agentPermissionAllowSession": "אפשר אוטומטית",
"oidcVerificationFailed": "אימות תצורת OIDC נכשל",
"oidcVerificationSuccess": "תצורת OIDC אומתה ונשמרה",
"oidcVerificationTip": "השלם את ההתחברות ל-OIDC בחלון הדפדפן שנפתח; התצורה הנוכחית תישאר פעילה עד שהאימות יצליח",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index e78208bcce..fa0853f8bd 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "अनुमति",
+ "agentPermissionConfirm": "पुष्टि आवश्यक",
+ "agentPermissionAllowSession": "स्वचालित रूप से अनुमति दें",
"oidcVerificationFailed": "OIDC कॉन्फ़िगरेशन सत्यापन विफल रहा",
"oidcVerificationSuccess": "OIDC कॉन्फ़िगरेशन सत्यापित और सहेजा गया",
"oidcVerificationTip": "खुली ब्राउज़र विंडो में OIDC लॉगिन पूरा करें; सत्यापन सफल होने तक वर्तमान कॉन्फ़िगरेशन सक्रिय रहेगा",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 5fbc7237e0..1bd5680965 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Izin",
+ "agentPermissionConfirm": "Perlu konfirmasi",
+ "agentPermissionAllowSession": "Izinkan otomatis",
"oidcVerificationFailed": "Verifikasi konfigurasi OIDC gagal",
"oidcVerificationSuccess": "Konfigurasi OIDC telah diverifikasi dan disimpan",
"oidcVerificationTip": "Selesaikan login OIDC di jendela browser yang terbuka; konfigurasi saat ini tetap aktif hingga verifikasi berhasil",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 8963b5d511..388d4d2d4a 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Autorizzazione",
+ "agentPermissionConfirm": "Richiedi conferma",
+ "agentPermissionAllowSession": "Consenti automaticamente",
"oidcVerificationFailed": "Verifica della configurazione OIDC non riuscita",
"oidcVerificationSuccess": "Configurazione OIDC verificata e salvata",
"oidcVerificationTip": "Completa l'accesso OIDC nella finestra del browser aperta; la configurazione attuale rimane attiva fino al completamento della verifica",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index d66f8e9014..bc1307944c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "権限",
+ "agentPermissionConfirm": "確認が必要",
+ "agentPermissionAllowSession": "自動許可",
"oidcVerificationFailed": "OIDC 設定の検証に失敗しました",
"oidcVerificationSuccess": "OIDC 設定を検証して保存しました",
"oidcVerificationTip": "開いたブラウザーウィンドウで OIDC ログインを完了してください。検証が成功するまで現在の設定が有効なまま維持されます",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 7acc998f0f..585eee9445 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "권한",
+ "agentPermissionConfirm": "확인 필요",
+ "agentPermissionAllowSession": "자동 허용",
"oidcVerificationFailed": "OIDC 구성 확인에 실패했습니다",
"oidcVerificationSuccess": "OIDC 구성을 확인하고 저장했습니다",
"oidcVerificationTip": "열린 브라우저 창에서 OIDC 로그인을 완료하세요. 확인에 성공할 때까지 현재 구성이 계속 적용됩니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index a0622d879e..49f390c86e 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Toestemming",
+ "agentPermissionConfirm": "Bevestiging vereisen",
+ "agentPermissionAllowSession": "Automatisch toestaan",
"oidcVerificationFailed": "Verificatie van de OIDC-configuratie is mislukt",
"oidcVerificationSuccess": "OIDC-configuratie geverifieerd en opgeslagen",
"oidcVerificationTip": "Voltooi de OIDC-aanmelding in het geopende browservenster; de huidige configuratie blijft actief totdat de verificatie slaagt",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 812de6e76f..55123ae520 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Uprawnienia",
+ "agentPermissionConfirm": "Wymagaj potwierdzenia",
+ "agentPermissionAllowSession": "Zezwalaj automatycznie",
"oidcVerificationFailed": "Weryfikacja konfiguracji OIDC nie powiodła się",
"oidcVerificationSuccess": "Konfiguracja OIDC została zweryfikowana i zapisana",
"oidcVerificationTip": "Dokończ logowanie OIDC w otwartym oknie przeglądarki; bieżąca konfiguracja pozostanie aktywna do czasu pomyślnej weryfikacji",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7e6f525613..e558085cc0 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Permissão",
+ "agentPermissionConfirm": "Exigir confirmação",
+ "agentPermissionAllowSession": "Permitir automaticamente",
"oidcVerificationFailed": "Falha na verificação da configuração OIDC",
"oidcVerificationSuccess": "Configuração OIDC verificada e salva",
"oidcVerificationTip": "Conclua o login OIDC na janela do navegador aberta; a configuração atual permanecerá ativa até que a verificação seja concluída com sucesso",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index cbb60a584c..569a35a1a4 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Разрешения",
+ "agentPermissionConfirm": "Требовать подтверждение",
+ "agentPermissionAllowSession": "Разрешать автоматически",
"oidcVerificationFailed": "Не удалось проверить конфигурацию OIDC",
"oidcVerificationSuccess": "Конфигурация OIDC проверена и сохранена",
"oidcVerificationTip": "Завершите вход OIDC в открывшемся окне браузера; текущая конфигурация останется активной до успешного завершения проверки",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 9127caa544..fc4a665141 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Povolenie",
+ "agentPermissionConfirm": "Vyžadovať potvrdenie",
+ "agentPermissionAllowSession": "Povoliť automaticky",
"oidcVerificationFailed": "Overenie konfigurácie OIDC zlyhalo",
"oidcVerificationSuccess": "Konfigurácia OIDC bola overená a uložená",
"oidcVerificationTip": "Dokončite prihlásenie OIDC v otvorenom okne prehliadača; aktuálna konfigurácia zostane aktívna, kým overenie nebude úspešné",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 7cdb0e3291..ebe24b5947 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "สิทธิ์",
+ "agentPermissionConfirm": "ต้องยืนยัน",
+ "agentPermissionAllowSession": "อนุญาตอัตโนมัติ",
"oidcVerificationFailed": "การตรวจสอบการกำหนดค่า OIDC ล้มเหลว",
"oidcVerificationSuccess": "ตรวจสอบและบันทึกการกำหนดค่า OIDC แล้ว",
"oidcVerificationTip": "ลงชื่อเข้าใช้ OIDC ให้เสร็จสิ้นในหน้าต่างเบราว์เซอร์ที่เปิดอยู่ การกำหนดค่าปัจจุบันจะยังคงมีผลจนกว่าการตรวจสอบจะสำเร็จ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 2398c5e727..96e51a51ce 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "İzin",
+ "agentPermissionConfirm": "Onay iste",
+ "agentPermissionAllowSession": "Otomatik olarak izin ver",
"oidcVerificationFailed": "OIDC yapılandırması doğrulanamadı",
"oidcVerificationSuccess": "OIDC yapılandırması doğrulandı ve kaydedildi",
"oidcVerificationTip": "Açılan tarayıcı penceresinde OIDC oturum açma işlemini tamamlayın; doğrulama başarılı olana kadar mevcut yapılandırma etkin kalır",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 13a1fc6612..7f75ac6d82 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "Дозвіл",
+ "agentPermissionConfirm": "Вимагати підтвердження",
+ "agentPermissionAllowSession": "Дозволяти автоматично",
"oidcVerificationFailed": "Не вдалося перевірити конфігурацію OIDC",
"oidcVerificationSuccess": "Конфігурацію OIDC перевірено та збережено",
"oidcVerificationTip": "Завершіть вхід OIDC у відкритому вікні браузера; поточна конфігурація залишатиметься активною до успішного завершення перевірки",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index f356c5f099..e8a1c49be6 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "权限",
+ "agentPermissionConfirm": "需确认",
+ "agentPermissionAllowSession": "自动允许",
"oidcVerificationFailed": "OIDC 配置验证失败",
"oidcVerificationSuccess": "OIDC 配置验证成功并已保存",
"oidcVerificationTip": "请在打开的浏览器窗口中完成 OIDC 登录;验证成功前当前配置将继续生效",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 96f55ee2ff..d5d3602913 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "agentPermission": "權限",
+ "agentPermissionConfirm": "需確認",
+ "agentPermissionAllowSession": "自動允許",
"oidcVerificationFailed": "OIDC 設定驗證失敗",
"oidcVerificationSuccess": "OIDC 設定驗證成功並已儲存",
"oidcVerificationTip": "請在開啟的瀏覽器視窗中完成 OIDC 登入;驗證成功前目前設定將繼續生效",
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scss
index df7538e595..6e9e691e95 100644
--- a/app/src/assets/scss/business/_ai_agent.scss
+++ b/app/src/assets/scss/business/_ai_agent.scss
@@ -697,6 +697,26 @@
}
}
+.agent-chat__permission {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 26px 4px 8px;
+ white-space: nowrap;
+ flex-shrink: 0;
+
+ &-icon {
+ height: 14px;
+ width: 14px;
+ color: var(--b3-theme-on-surface);
+ }
+
+ &-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+}
+
// 思考强度:使用菜单按钮,避免底部原生 select 向视口外展开。
.agent-chat__reasoning-effort {
display: inline-flex;
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 90e82c8de6..b8caa26e90 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -7,7 +7,7 @@ import {disabledWYSIWYG} from "../../../protyle/util/disabledWYSIWYG";
import {getAllEditor} from "../../getAll";
import "./frontendActions";
import {listActions, lookupAction} from "./frontendActions";
-import {AgentSession, SessionStore} from "./SessionStore";
+import {AgentPermissionMode, AgentSession, SessionStore} from "./SessionStore";
import {AgentSessionPanel} from "./AgentSessionPanel";
import {updateHotkeyAfterTip} from "../../../protyle/util/compatibility";
import {getAgentLute} from "../../../protyle/render/setLute";
@@ -172,6 +172,8 @@ export class AgentChat extends Model {
// 推理努力度(iconBrain + 菜单),仅实例记忆,刷新后回到默认。
private reasoningEffortButton: HTMLButtonElement;
private selectedReasoningEffort = "";
+ private permissionButton: HTMLButtonElement;
+ private permissionMode: AgentPermissionMode = "confirm";
private userScrolledUp = false;
private programmaticScroll = false;
private stickResizeObserver: ResizeObserver | null = null;
@@ -301,6 +303,9 @@ export class AgentChat extends Model {
'<div class="agent-chat__composer-host"></div>' +
'<div class="agent-chat__buttons">' +
'<div class="agent-chat__button-options">' +
+ '<button class="b3-select b3-select--noborder agent-chat__permission ariaLabel" data-menu="true" data-position="n" type="button">' +
+ '<svg class="agent-chat__permission-icon"><use xlink:href="#iconHand"></use></svg>' +
+ '<span class="agent-chat__permission-label"></span></button>' +
'<span class="fn__flex-1"></span>' +
'<span class="agent-chat__tokens fn__none b3-button b3-button--icon b3-button--cancel" aria-label="' + (L.tokenUsage || "Context Usage") + '">' +
'<svg viewBox="0 0 24 24">' +
@@ -331,6 +336,8 @@ export class AgentChat extends Model {
this.tokenDisplayEl = panel.querySelector(".agent-chat__tokens") as HTMLElement;
this.modelSelect = panel.querySelector('[data-type="groupedModelPicker"]') as HTMLButtonElement;
this.reasoningEffortButton = panel.querySelector(".agent-chat__reasoning-effort") as HTMLButtonElement;
+ this.permissionButton = panel.querySelector(".agent-chat__permission") as HTMLButtonElement;
+ this.initPermissionMenu();
this.initReasoningEffortMenu();
this.scrollBottomBtn = panel.querySelector(".agent-chat__scroll-bottom") as HTMLElement;
this.messagesContainer.addEventListener("scroll", () => {
@@ -518,6 +525,75 @@ export class AgentChat extends Model {
return this.selectedModel;
}
+ // 会话权限菜单显示后端当前状态,并允许在当前轮次中即时切换后续操作的确认策略。
+ private permissionLabel(mode = this.permissionMode) {
+ const L = window.siyuan.languages;
+ return mode === "allowSession" ?
+ (L.agentPermissionAllowSession || "Automatically allow") :
+ (L.agentPermissionConfirm || "Require confirmation");
+ }
+
+ private applyPermissionMode(mode: AgentPermissionMode) {
+ this.permissionMode = mode;
+ const label = this.permissionLabel();
+ const labelElement = this.permissionButton.querySelector(".agent-chat__permission-label");
+ if (labelElement) {
+ labelElement.textContent = label;
+ }
+ const L = window.siyuan.languages;
+ this.permissionButton.setAttribute("aria-label", mode === "allowSession" ?
+ (L.agentConfirmAlwaysDesc || label) : `${L.agentPermission || "Permission"} ${label}`);
+ }
+
+ private async changePermissionMode(mode: AgentPermissionMode) {
+ if (mode === this.permissionMode) {
+ return;
+ }
+ const sessionID = this.sessionId;
+ if (this.entries.length === 0) {
+ this.applyPermissionMode(mode);
+ return;
+ }
+ this.permissionButton.disabled = true;
+ try {
+ const persistedMode = await SessionStore.setPermission(sessionID, mode);
+ if (this.sessionId === sessionID) {
+ this.applyPermissionMode(persistedMode);
+ }
+ } catch (e) {
+ console.error("update agent session permission failed:", e);
+ showMessage(window.siyuan.languages._kernel[28], 3000, "error");
+ } finally {
+ if (this.sessionId === sessionID) {
+ this.permissionButton.disabled = false;
+ }
+ }
+ }
+
+ private initPermissionMenu() {
+ this.applyPermissionMode(this.permissionMode);
+ this.permissionButton.addEventListener("click", (event: MouseEvent) => {
+ event.stopPropagation();
+ const menu = new Menu("agent-chat-permission");
+ if (menu.isOpen) {
+ return;
+ }
+ (["confirm", "allowSession"] as AgentPermissionMode[]).forEach(mode => {
+ menu.addItem({
+ iconHTML: "",
+ label: escapeHtml(this.permissionLabel(mode)),
+ current: mode === this.permissionMode,
+ click: () => {
+ void this.changePermissionMode(mode);
+ },
+ });
+ });
+ const rect = this.permissionButton.getBoundingClientRect();
+ menu.element.style.minWidth = `${Math.max(rect.width, 160)}px`;
+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width});
+ });
+ }
+
// 初始化思考强度菜单:提供各供应商使用的标准档位,选择结果仅在当前实例中生效。
private initReasoningEffortMenu() {
const options = getAgentReasoningEffortOptions(window.siyuan.languages);
@@ -818,6 +894,7 @@ export class AgentChat extends Model {
this.sessionTitle = this.defaultTitle;
this.pendingSessionTitle = null;
this.entries = [];
+ this.applyPermissionMode("confirm");
this.showWelcome();
this.scrollToBottom(true);
}
@@ -843,6 +920,7 @@ export class AgentChat extends Model {
updatedAt: Date.now(),
messageHistory: this.composer?.getHistory() || [],
model: this.getSelectedModel(),
+ permissionMode: this.permissionMode,
};
if (turnID) {
session.commitTurnID = turnID;
@@ -876,6 +954,7 @@ export class AgentChat extends Model {
// 只包含已完成历史和交互卡片,不会把半截 assistant 文本当成最终结果。
// - streamEnd:后端 eventCh 关闭(流结束),只解除占位锁定;已提交内容由 saveSession 的 update
// 同步,未提交内容由后端紧随其后的恢复 update 同步。
+ // - permission:只刷新当前会话权限,不重绘正在流式生成的消息。
// - delete:当前会话被删除则清空视图。
private onWsMessage(data: IWebSocketData) {
if (!data || data.cmd !== "agentSessionChanged") {
@@ -891,6 +970,14 @@ export class AgentChat extends Model {
if (payload.sessionID !== this.sessionId) {
return;
}
+ if (payload.action === "permission") {
+ void SessionStore.load(payload.sessionID).then(session => {
+ if (session && this.sessionId === payload.sessionID) {
+ this.applyPermissionMode(session.permissionMode || "confirm");
+ }
+ });
+ return;
+ }
// 发起者自身流式中忽略(它走 SSE 自渲染)。
if (this.isStreaming) {
return;
@@ -1097,6 +1184,7 @@ export class AgentChat extends Model {
if (session.model) {
this.applySessionModelIfValid(session.model);
}
+ this.applyPermissionMode(session.permissionMode || "confirm");
this.titleElement.textContent = this.sessionTitle;
this.updateTokenDisplay();
}
@@ -1129,6 +1217,7 @@ export class AgentChat extends Model {
this.sessionCreatedAt = Date.now();
this.sessionTitle = this.defaultTitle;
this.pendingSessionTitle = null;
+ this.applyPermissionMode("confirm");
this.pendingRecoverySessionIDs.delete(deletedSessionID);
this.recoveryCommitTurnIDs.delete(deletedSessionID);
this.hasTitled = false;
@@ -1195,6 +1284,7 @@ export class AgentChat extends Model {
if (session.model) {
this.applySessionModelIfValid(session.model);
}
+ this.applyPermissionMode(session.permissionMode || "confirm");
if (this.tokenDisplayEl) {
this.updateTokenDisplay();
}
@@ -1506,6 +1596,7 @@ export class AgentChat extends Model {
this.sessionTitle = this.defaultTitle;
this.pendingSessionTitle = null;
this.entries = [];
+ this.applyPermissionMode("confirm");
this.hasTitled = false;
this.currentAIElement = null;
this.currentContent = "";
@@ -1894,6 +1985,9 @@ export class AgentChat extends Model {
this.setToolCallRunning(event.name, false);
this.appendConfirm(event.name, event.arguments, event.confirmID, event.effects);
break;
+ case "permission":
+ this.applyPermissionMode(event.permissionMode);
+ break;
case "tool_result":
{
const toolCall = this.currentToolCalls.find((item) => item.name === event.name && item.result === undefined);
@@ -3245,6 +3339,9 @@ export class AgentChat extends Model {
if (entry) {
entry.status = always ? "always" : (approved ? "approved" : "rejected");
}
+ if (always) {
+ this.applyPermissionMode("allowSession");
+ }
try {
await this.saveSession();
} catch (e) {
diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.ts
index d2872b0d63..e327beac3e 100644
--- a/app/src/layout/dock/agent/SessionStore.ts
+++ b/app/src/layout/dock/agent/SessionStore.ts
@@ -6,6 +6,8 @@ const sessionRevisions = new Map<string, number>();
const sessionRuntimeRevisions = new Map<string, number>();
const sessionSaveQueues = new Map<string, Promise<SessionSaveResult>>();
+export type AgentPermissionMode = "confirm" | "allowSession";
+
interface SessionSaveResult {
revision: number;
session?: AgentSession;
@@ -48,6 +50,7 @@ export interface AgentSession {
title: string;
titled?: boolean;
model?: string;
+ permissionMode?: AgentPermissionMode;
messages?: Array<{role: string; content: string; toolCalls?: Array<{name: string; arguments?: Record<string, unknown>; result?: string}>}>;
entries?: Array<{
id?: string;
@@ -207,6 +210,18 @@ export const SessionStore = {
await this.save(session);
},
+ async setPermission(id: string, permissionMode: AgentPermissionMode): Promise<AgentPermissionMode> {
+ await waitForPendingSave(id);
+ const resp = await fetchSyncPost(API + "/setPermission", {
+ sessionID: id,
+ permissionMode,
+ }, APP_HEADER) as {code: number; msg?: string; data?: {permissionMode?: AgentPermissionMode}};
+ if (!resp || resp.code !== 0) {
+ throw new Error(resp?.msg || "Failed to update agent session permission");
+ }
+ return resp.data?.permissionMode || permissionMode;
+ },
+
getRevision(id: string): number {
return sessionRevisions.get(id) ?? 0;
},
diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.ts
index a47ecba829..07db88605c 100644
--- a/app/src/layout/dock/agent/agentSSE.ts
+++ b/app/src/layout/dock/agent/agentSSE.ts
@@ -59,6 +59,9 @@ export type ISSEResult = {
} | {
type: "snapshot";
snapshotID: string;
+} | {
+ type: "permission";
+ permissionMode: "confirm" | "allowSession";
} | {
type: "frontend_tool_call";
callID: string;
@@ -272,6 +275,11 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResul
arguments: (data.arguments || {}) as Record<string, unknown>,
confirmID: data.confirmID as string,
};
+ case "permission":
+ return {
+ type: "permission",
+ permissionMode: data.permissionMode as "confirm" | "allowSession",
+ };
case "tool_result":
return {
type: "tool_result",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index f77259d1bc..256967628a 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -128,6 +128,11 @@ type confirmResult struct {
always bool
}
+type confirmWaiter struct {
+ sessionID string
+ ch chan confirmResult
+}
+
type doomLoopTracker struct {
prevSig string
prevName string
@@ -199,21 +204,27 @@ func buildDoomSignature(name, action string, args map[string]any) string {
}
var confirmChannelsMu sync.Mutex
-var confirmChannels = make(map[string]chan confirmResult)
+var confirmChannels = make(map[string]*confirmWaiter)
-func ConfirmSession(id string, approved bool, always bool) bool {
+func ConfirmSession(id string, approved bool, always bool) (bool, error) {
confirmChannelsMu.Lock()
defer confirmChannelsMu.Unlock()
- ch, ok := confirmChannels[id]
+ always = approved && always
+ waiter, ok := confirmChannels[id]
if !ok {
- return false
+ return false, nil
+ }
+ if always {
+ if err := SetSessionPermissionMode(waiter.sessionID, AgentPermissionAllowSession); err != nil {
+ return false, err
+ }
}
select {
- case ch <- confirmResult{approved: approved, always: always}:
+ case waiter.ch <- confirmResult{approved: approved, always: always}:
delete(confirmChannels, id)
- return true
+ return true, nil
default:
- return false
+ return false, nil
}
}
@@ -309,6 +320,7 @@ type AgentEvent struct {
RetryMax int
SnapshotID string
TurnID string
+ PermissionMode string
Effects mcptools.ToolEffects
}
@@ -464,6 +476,13 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
return
default:
}
+ permissionController, err := registerSessionPermissionController(sessionID)
+ if err != nil {
+ logging.LogErrorf("load agent session permission failed: %s", err)
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(28)})
+ return
+ }
+ defer unregisterSessionPermissionController(sessionID, permissionController)
rawUserMessage := userMessage
// 变量(非敏感)在用户消息注入对话时解析,让 LLM 看到实际值;密钥不进上下文。
@@ -476,7 +495,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
var sessionEntries []SessionEntry
var compaction *runtimeCompaction
var totalPrompt, totalCompletion, lastPromptTokens, lastCachedTokens int
- alwaysAllow := map[string]bool{}
var doomLoop doomLoopTracker
var snapshotIDs []string
snapshotCreated := false // 整个 AgentChat 过程最多打一次自动快照,避免多轮工具调用时每轮都打
@@ -486,14 +504,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
var runtime *agentRuntime
if loadedRuntime, err := loadRuntimeState(sessionID); err == nil {
runtime = loadedRuntime
- if runtime != nil && runtime.AlwaysAllow {
- alwaysAllow["*"] = true
- }
}
if cp := loadCheckpoint(sessionID); cp != nil {
- if cp.AlwaysAllow {
- alwaysAllow["*"] = true
- }
if len(cp.Entries) > 0 {
sessionEntries = append([]SessionEntry(nil), cp.Entries...)
contextEntries := cp.Entries
@@ -597,7 +609,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
return
default:
}
- if err := beginRuntimeTurn(sessionID, turn, alwaysAllow["*"]); err != nil {
+ if err := beginRuntimeTurn(sessionID, turn); err != nil {
logging.LogErrorf("begin agent runtime failed: %s", err)
sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(28)})
return
@@ -627,7 +639,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
turn.LastPromptTokens = lastPromptTokens
turn.CachedTokens = lastCachedTokens
turn.ContextLimit = contextLimit
- if err := saveRuntimeTurn(sessionID, turn, alwaysAllow["*"]); err != nil {
+ if err := saveRuntimeTurn(sessionID, turn); err != nil {
logging.LogErrorf("save agent runtime failed: %s", err)
return false
} else if state != "running" {
@@ -994,11 +1006,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
})
_, _, toolInputErr := validateToolCallInput(ctx, tc.Function.Name, args)
- if toolInputErr == nil && needsConfirm(tc.Function.Name, action, alwaysAllow) {
+ if toolInputErr == nil && !permissionController.allowSession.Load() &&
+ needsConfirm(tc.Function.Name, action, nil) {
confirmID := fmt.Sprintf("%s_%s_%d", turn.TurnID, tc.ID, i)
ch2 := make(chan confirmResult, 1)
confirmChannelsMu.Lock()
- confirmChannels[confirmID] = ch2
+ confirmChannels[confirmID] = &confirmWaiter{sessionID: sessionID, ch: ch2}
confirmChannelsMu.Unlock()
effects, _ := mcptools.GetTool(tc.Function.Name).EffectsFor(action)
sendCriticalEvent(ctx, ch, AgentEvent{
@@ -1072,7 +1085,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
}
if result.always {
- alwaysAllow["*"] = true
+ sendCriticalEvent(ctx, ch, AgentEvent{
+ Type: AgentEventPermission, PermissionMode: AgentPermissionAllowSession,
+ })
}
// 确认卡片会结束当前思考状态,工具执行前重新通知前端显示“思考中”。
sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: "processing"})
@@ -1485,7 +1500,7 @@ func finishQuestionWait(questionID string, ch chan QuestionAnswer) (QuestionAnsw
func finishConfirmWait(confirmID string, ch chan confirmResult) (confirmResult, bool) {
confirmChannelsMu.Lock()
registered, exists := confirmChannels[confirmID]
- pending := exists && registered == ch
+ pending := exists && registered.ch == ch
if pending {
delete(confirmChannels, confirmID)
}
diff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.go
index 473fc44b3e..552cfcdb16 100644
--- a/kernel/agent/compaction_test.go
+++ b/kernel/agent/compaction_test.go
@@ -209,7 +209,7 @@ func TestRuntimeCompactionPersistsBesideActiveTurn(t *testing.T) {
State: "running",
UpdatedAt: time.Now().UnixMilli(),
}
- if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := beginRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
compaction, err := newRuntimeCompaction(entries, 3, "Persisted summary")
diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.go
index b5156e44b4..344e9a10ab 100644
--- a/kernel/agent/runtime.go
+++ b/kernel/agent/runtime.go
@@ -20,6 +20,8 @@ import (
"fmt"
"os"
"path/filepath"
+ "sync"
+ "sync/atomic"
"time"
"github.com/88250/gulu"
@@ -27,17 +29,122 @@ import (
)
const (
- toolNotExecutedResult = "Tool was not executed because the turn was interrupted."
- toolUnknownResult = "Tool execution was interrupted; the result is unknown. Do not retry automatically."
+ toolNotExecutedResult = "Tool was not executed because the turn was interrupted."
+ toolUnknownResult = "Tool execution was interrupted; the result is unknown. Do not retry automatically."
+ AgentPermissionConfirm = "confirm"
+ AgentPermissionAllowSession = "allowSession"
+ AgentEventPermission = "permission"
)
type agentRuntime struct {
- SchemaVersion int `json:"schemaVersion"`
- Revision int64 `json:"revision"`
- SessionID string `json:"sessionID"`
- AlwaysAllow bool `json:"alwaysAllow,omitempty"`
- ActiveTurn *agentRuntimeTurn `json:"activeTurn,omitempty"`
- Compaction *runtimeCompaction `json:"compaction,omitempty"`
+ SchemaVersion int `json:"schemaVersion"`
+ Revision int64 `json:"revision"`
+ SessionID string `json:"sessionID"`
+ PermissionMode string `json:"permissionMode,omitempty"`
+ AlwaysAllow bool `json:"alwaysAllow,omitempty"`
+ ActiveTurn *agentRuntimeTurn `json:"activeTurn,omitempty"`
+ Compaction *runtimeCompaction `json:"compaction,omitempty"`
+}
+
+type sessionPermissionController struct {
+ allowSession atomic.Bool
+}
+
+var sessionPermissionControllers sync.Map
+
+func validAgentPermissionMode(mode string) bool {
+ return mode == AgentPermissionConfirm || mode == AgentPermissionAllowSession
+}
+
+func resolveSessionPermissionModeLocked(sessionID string, session map[string]any) (string, error) {
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return "", err
+ }
+ if runtime.PermissionMode != "" {
+ if !validAgentPermissionMode(runtime.PermissionMode) {
+ return "", fmt.Errorf("invalid agent permission mode")
+ }
+ return runtime.PermissionMode, nil
+ }
+ if runtime.AlwaysAllow {
+ return AgentPermissionAllowSession, nil
+ }
+ if session == nil {
+ data, readErr := os.ReadFile(filepath.Join(sessionsDir(), sessionID, "session.json"))
+ if readErr != nil {
+ return "", readErr
+ }
+ session = map[string]any{}
+ if unmarshalErr := gulu.JSON.UnmarshalJSON(data, &session); unmarshalErr != nil {
+ return "", unmarshalErr
+ }
+ }
+ if permissionMode, _ := session["permissionMode"].(string); permissionMode != "" {
+ if !validAgentPermissionMode(permissionMode) {
+ return "", fmt.Errorf("invalid agent permission mode")
+ }
+ return permissionMode, nil
+ }
+ if alwaysAllow, _ := session["alwaysAllow"].(bool); alwaysAllow {
+ return AgentPermissionAllowSession, nil
+ }
+ return AgentPermissionConfirm, nil
+}
+
+func registerSessionPermissionController(sessionID string) (*sessionPermissionController, error) {
+ controller := &sessionPermissionController{}
+ if sessionID == "" {
+ return controller, nil
+ }
+ if !isValidSessionID(sessionID) {
+ return nil, fmt.Errorf("invalid session id")
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ mode, err := resolveSessionPermissionModeLocked(sessionID, nil)
+ if err != nil {
+ return nil, err
+ }
+ controller.allowSession.Store(mode == AgentPermissionAllowSession)
+ sessionPermissionControllers.Store(sessionID, controller)
+ return controller, nil
+}
+
+func unregisterSessionPermissionController(sessionID string, controller *sessionPermissionController) {
+ if sessionID == "" || controller == nil {
+ return
+ }
+ sessionPermissionControllers.CompareAndDelete(sessionID, controller)
+}
+
+func SetSessionPermissionMode(sessionID, mode string) error {
+ if sessionID == "" || !isValidSessionID(sessionID) {
+ return fmt.Errorf("invalid session id")
+ }
+ if !validAgentPermissionMode(mode) {
+ return fmt.Errorf("invalid agent permission mode")
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ if _, err := os.Stat(filepath.Join(sessionsDir(), sessionID, "session.json")); err != nil {
+ return err
+ }
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return err
+ }
+ runtime.PermissionMode = mode
+ runtime.AlwaysAllow = false
+ if err = writeRuntimeLocked(sessionID, runtime); err != nil {
+ return err
+ }
+ if value, ok := sessionPermissionControllers.Load(sessionID); ok {
+ value.(*sessionPermissionController).allowSession.Store(mode == AgentPermissionAllowSession)
+ }
+ return nil
}
type agentRuntimeTurn struct {
@@ -134,7 +241,7 @@ func writeRuntimeLocked(sessionID string, runtime *agentRuntime) error {
return filelock.WriteFile(runtimePath(sessionID), data)
}
-func beginRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool) error {
+func beginRuntimeTurn(sessionID string, turn *agentRuntimeTurn) error {
if sessionID == "" || turn == nil {
return nil
}
@@ -175,7 +282,6 @@ func beginRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool
if findRuntimeUserAnchor(session, turn.UserEntryID) < 0 {
return fmt.Errorf("agent runtime user entry not found")
}
- runtime.AlwaysAllow = runtime.AlwaysAllow || alwaysAllow
runtime.ActiveTurn = turn
return writeRuntimeLocked(sessionID, runtime)
}
@@ -192,7 +298,7 @@ func isTurnCommittedLocked(sessionID, turnID string) (bool, error) {
return meta.LastCommittedTurnID == turnID, nil
}
-func saveRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool) error {
+func saveRuntimeTurn(sessionID string, turn *agentRuntimeTurn) error {
if sessionID == "" || turn == nil {
return nil
}
@@ -216,7 +322,6 @@ func saveRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool)
if runtime.ActiveTurn != nil && runtime.ActiveTurn.TurnID != turn.TurnID {
return fmt.Errorf("agent runtime turn changed")
}
- runtime.AlwaysAllow = runtime.AlwaysAllow || alwaysAllow
turn.UpdatedAt = time.Now().UnixMilli()
runtime.ActiveTurn = turn
return writeRuntimeLocked(sessionID, runtime)
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
index 28c67f3c33..2df6a7e601 100644
--- a/kernel/agent/session.go
+++ b/kernel/agent/session.go
@@ -303,6 +303,11 @@ func GetSessionState(id string, includeRuntime bool) (map[string]any, error) {
return nil, err
}
}
+ permissionMode, err := resolveSessionPermissionModeLocked(id, session)
+ if err != nil {
+ return nil, err
+ }
+ session["permissionMode"] = permissionMode
return session, nil
}
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
index 1bdc469ad0..d7106c37a3 100644
--- a/kernel/agent/session_test.go
+++ b/kernel/agent/session_test.go
@@ -27,6 +27,7 @@ func useTestDataDir(t *testing.T) {
t.Cleanup(func() {
util.DataDir = original
sessionLocks.Delete(testSessionID)
+ sessionPermissionControllers.Delete(testSessionID)
})
}
@@ -115,6 +116,109 @@ func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
}
}
+func TestSessionPermissionCanBeRevoked(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "alwaysAllow": true,
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+ session, err := GetSession(testSessionID)
+ if err != nil || session["permissionMode"] != AgentPermissionAllowSession {
+ t.Fatalf("legacy session permission was not restored: session=%#v, err=%v", session, err)
+ }
+ controller, err := registerSessionPermissionController(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer unregisterSessionPermissionController(testSessionID, controller)
+ if !controller.allowSession.Load() {
+ t.Fatal("legacy session permission was not registered")
+ }
+ if err = SetSessionPermissionMode(testSessionID, AgentPermissionConfirm); err != nil {
+ t.Fatal(err)
+ }
+ if controller.allowSession.Load() {
+ t.Fatal("active session permission was not revoked")
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120001-permiss",
+ Mode: "append",
+ UserEntryID: "user-1",
+ BaseRevision: 1,
+ State: "running",
+ }
+ if err = beginRuntimeTurn(testSessionID, turn); err != nil {
+ t.Fatal(err)
+ }
+ if err = saveRuntimeTurn(testSessionID, turn); err != nil {
+ t.Fatal(err)
+ }
+ session, err = GetSession(testSessionID)
+ if err != nil || session["permissionMode"] != AgentPermissionConfirm {
+ t.Fatalf("runtime checkpoint restored revoked permission: session=%#v, err=%v", session, err)
+ }
+ if err = SetSessionPermissionMode(testSessionID, AgentPermissionAllowSession); err != nil {
+ t.Fatal(err)
+ }
+ if !controller.allowSession.Load() {
+ t.Fatal("active session permission was not enabled")
+ }
+ if err = SetSessionPermissionMode(testSessionID, "invalid"); err == nil {
+ t.Fatal("invalid session permission mode was accepted")
+ }
+}
+
+func TestConfirmSessionPersistsAlwaysAllowBeforeAccepting(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+ controller, err := registerSessionPermissionController(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer unregisterSessionPermissionController(testSessionID, controller)
+ const confirmID = "test-permission-confirm"
+ ch := make(chan confirmResult, 1)
+ confirmChannelsMu.Lock()
+ confirmChannels[confirmID] = &confirmWaiter{sessionID: testSessionID, ch: ch}
+ confirmChannelsMu.Unlock()
+ t.Cleanup(func() {
+ confirmChannelsMu.Lock()
+ delete(confirmChannels, confirmID)
+ confirmChannelsMu.Unlock()
+ })
+ accepted, err := ConfirmSession(confirmID, true, true)
+ if err != nil || !accepted {
+ t.Fatalf("session confirmation was not accepted: accepted=%v, err=%v", accepted, err)
+ }
+ if !controller.allowSession.Load() {
+ t.Fatal("session permission was not enabled before confirmation returned")
+ }
+ session, err := GetSession(testSessionID)
+ if err != nil || session["permissionMode"] != AgentPermissionAllowSession {
+ t.Fatalf("session permission was not persisted: session=%#v, err=%v", session, err)
+ }
+ result := <-ch
+ if !result.approved || !result.always {
+ t.Fatalf("unexpected confirmation result: %#v", result)
+ }
+}
+
func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
useTestDataDir(t)
base := map[string]any{
@@ -153,10 +257,10 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
}},
}},
}
- if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := beginRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
- if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := saveRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
uncommitted, err := HasUncommittedTurn(testSessionID)
@@ -221,7 +325,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
t.Fatalf("running runtime turn was committed: revision=%d, err=%v", revision, err)
}
turn.State = "interrupted"
- if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := saveRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
recovered, err = GetSession(testSessionID)
@@ -281,7 +385,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
if uncommitted, err := HasUncommittedTurn(testSessionID); err != nil || uncommitted {
t.Fatalf("committed runtime turn remained active: uncommitted=%v, err=%v", uncommitted, err)
}
- if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := saveRuntimeTurn(testSessionID, turn); err != nil {
t.Fatalf("late runtime save should be ignored after commit: %v", err)
}
committed, err = GetSession(testSessionID)
@@ -295,7 +399,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
if err := DeleteSession(testSessionID); err != nil {
t.Fatal(err)
}
- if err := saveRuntimeTurn(testSessionID, turn, false); err == nil {
+ if err := saveRuntimeTurn(testSessionID, turn); err == nil {
t.Fatal("late runtime save recreated a deleted session")
}
if _, err := os.Stat(filepath.Join(sessionsDir(), testSessionID)); !os.IsNotExist(err) {
@@ -344,11 +448,11 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
turn.UserBlockHTML = new(editedBlockHTML)
turn.UserReferences = &emptyReferences
turn.UserEditorContext = &EditorContext{ActiveDocID: "new-doc"}
- if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := beginRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
turn.State = "interrupted"
- if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := saveRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
@@ -470,7 +574,7 @@ func TestBeginRuntimeTurnRejectsStaleRevision(t *testing.T) {
BaseRevision: 0,
State: "running",
}
- if err := beginRuntimeTurn(testSessionID, turn, false); !errors.Is(err, ErrSessionConflict) {
+ if err := beginRuntimeTurn(testSessionID, turn); !errors.Is(err, ErrSessionConflict) {
t.Fatalf("expected stale runtime revision to be rejected: %v", err)
}
if _, err := os.Stat(runtimePath(testSessionID)); !os.IsNotExist(err) {
@@ -498,7 +602,7 @@ func TestFinalizeOrphanedTurnMakesRuntimeRecoverable(t *testing.T) {
State: "running",
DraftContent: "partial response",
}
- if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ if err := beginRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
runtimeBefore, err := loadRuntimeState(testSessionID)
@@ -540,10 +644,10 @@ func TestFinalizeOrphanedTurnMakesRuntimeRecoverable(t *testing.T) {
func TestRuntimeRejectsInvalidSessionID(t *testing.T) {
useTestDataDir(t)
turn := &agentRuntimeTurn{TurnID: "20260715120004-abcdefg", State: "running"}
- if err := beginRuntimeTurn("..", turn, false); err == nil {
+ if err := beginRuntimeTurn("..", turn); err == nil {
t.Fatal("invalid runtime session id was accepted")
}
- if err := saveRuntimeTurn("..", turn, false); err == nil {
+ if err := saveRuntimeTurn("..", turn); err == nil {
t.Fatal("invalid runtime checkpoint session id was accepted")
}
}
@@ -566,7 +670,7 @@ func TestGetSessionRejectsRuntimeWithoutUserAnchor(t *testing.T) {
BaseRevision: 1,
State: "running",
}
- if err := beginRuntimeTurn(testSessionID, turn, false); err == nil {
+ if err := beginRuntimeTurn(testSessionID, turn); err == nil {
t.Fatal("runtime without a user anchor was started")
}
turn.State = "interrupted"
diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.go
index 09486321b2..b06d2af62f 100644
--- a/kernel/agent/tools_test.go
+++ b/kernel/agent/tools_test.go
@@ -314,7 +314,7 @@ func TestConfirmSessionAcceptsResponseOnce(t *testing.T) {
const confirmID = "test-confirm"
ch := make(chan confirmResult, 1)
confirmChannelsMu.Lock()
- confirmChannels[confirmID] = ch
+ confirmChannels[confirmID] = &confirmWaiter{sessionID: testSessionID, ch: ch}
confirmChannelsMu.Unlock()
t.Cleanup(func() {
confirmChannelsMu.Lock()
@@ -322,10 +322,11 @@ func TestConfirmSessionAcceptsResponseOnce(t *testing.T) {
confirmChannelsMu.Unlock()
})
- if !ConfirmSession(confirmID, true, false) {
+ accepted, err := ConfirmSession(confirmID, true, false)
+ if err != nil || !accepted {
t.Fatal("registered confirmation was rejected")
}
- if ConfirmSession(confirmID, false, false) {
+ if accepted, err = ConfirmSession(confirmID, false, false); err != nil || accepted {
t.Fatal("duplicate confirmation was accepted")
}
result, accepted := finishConfirmWait(confirmID, ch)
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 578c9cc036..6f983cdb67 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -206,8 +206,8 @@ func newAgentSessionDeadline(timeoutSeconds int) (*time.Timer, <-chan time.Time)
func recordRunningEvent(sessionID string, running *runningSession, event agent.AgentEvent) {
sessionsMu.Lock()
- defer sessionsMu.Unlock()
if runningSessions[sessionID] != running {
+ sessionsMu.Unlock()
return
}
if event.Type == "turn" {
@@ -216,6 +216,10 @@ func recordRunningEvent(sessionID string, running *runningSession, event agent.A
if event.Type == "done" || event.Type == "error" {
running.terminal = true
}
+ sessionsMu.Unlock()
+ if event.Type == agent.AgentEventPermission {
+ broadcastAgentSessionChanged(running.app, sessionID, "permission")
+ }
}
func finishRunningSession(sessionID string, running *runningSession) {
@@ -253,7 +257,14 @@ func agentChatConfirm(c *gin.Context) {
return
}
ret := gulu.Ret.NewResult()
- if !agent.ConfirmSession(req.ConfirmID, req.Approved, req.Always) {
+ accepted, err := agent.ConfirmSession(req.ConfirmID, req.Approved, req.Always)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+ if !accepted {
ret.Code = -1
ret.Msg = "agent confirmation expired"
c.JSON(http.StatusConflict, ret)
@@ -262,6 +273,32 @@ func agentChatConfirm(c *gin.Context) {
c.JSON(http.StatusOK, ret)
}
+type agentPermissionReq struct {
+ SessionID string `json:"sessionID"`
+ PermissionMode string `json:"permissionMode"`
+}
+
+func setAgentSessionPermission(c *gin.Context) {
+ req := &agentPermissionReq{}
+ 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
+ }
+ ret := gulu.Ret.NewResult()
+ if err := agent.SetSessionPermissionMode(req.SessionID, req.PermissionMode); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+ ret.Data = map[string]string{"permissionMode": req.PermissionMode}
+ c.JSON(http.StatusOK, ret)
+ broadcastAgentSessionChanged(c.GetHeader("X-SiYuan-App-ID"), req.SessionID, "permission")
+}
+
type agentQuestionReq struct {
QuestionID string `json:"questionID"`
Answers []string `json:"answers"`
@@ -610,7 +647,8 @@ func saveSession(c *gin.Context) {
}
// broadcastAgentSessionChanged 向除发起者 app 外、所有打开了 agentChat dock 的实例推送会话变更通知。
-// action: streamStart / streamEnd / update / delete。排除发起者 app(它已通过 SSE 自渲染或本地持有最新状态)。
+// action: streamStart / streamEnd / update / permission / delete。
+// 排除发起者 app,它已通过 SSE 自渲染或在本地持有最新状态。
func broadcastAgentSessionChanged(app, sessionID, action string) {
if "" == app || "" == sessionID {
return
@@ -643,6 +681,10 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {
"confirmID": event.ConfirmID,
"effects": event.Effects,
})
+ case agent.AgentEventPermission:
+ return writeSSEEvent(c, agent.AgentEventPermission, map[string]string{
+ "permissionMode": event.PermissionMode,
+ })
case "tool_call":
return writeSSEEvent(c, "tool_call", map[string]any{
"name": event.Name,
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 6eb9706f7c..b4225dd065 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -610,6 +610,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/retryFailedEmbedding", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, retryFailedEmbedding)
ginServer.Handle("POST", "/api/ai/agent/chat", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChat)
ginServer.Handle("POST", "/api/ai/agent/confirm", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatConfirm)
+ ginServer.Handle("POST", "/api/ai/agent/setPermission", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAgentSessionPermission)
ginServer.Handle("POST", "/api/ai/agent/question", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatQuestion)
ginServer.Handle("POST", "/api/ai/agent/frontendToolResult", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatFrontendResult)
ginServer.Handle("POST", "/api/ai/agent/title", model.CheckAuth, model.CheckAdminRole, agentChatTitle)