Skip to content

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

:sparkles: Support agents on mobile https://github.com/siyuan-note/siyuan/issues/17797

Daniel77c97d6a4d49
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scss
index a87fdcba4b..49a7f3e81c 100644
--- a/app/src/assets/scss/business/_ai_agent.scss
+++ b/app/src/assets/scss/business/_ai_agent.scss
@@ -1076,3 +1076,91 @@
max-height: 120px;
overflow-y: auto;
}
+
+#model.model--agent {
+ > .toolbar {
+ display: none;
+ }
+
+ #modelMain {
+ min-height: 0;
+ overflow: hidden;
+ }
+}
+
+.sy__agentChat--mobile {
+ position: relative;
+ height: 100%;
+ min-height: 0;
+ background: var(--b3-theme-background);
+
+ .block__icons {
+ min-height: 48px;
+ padding-left: max(8px, env(safe-area-inset-left));
+ padding-right: max(4px, env(safe-area-inset-right));
+ border-bottom: .5px solid var(--b3-theme-background-light);
+ }
+
+ .block__icon {
+ min-width: 40px;
+ min-height: 40px;
+ }
+
+ .agent-chat__messages {
+ padding: 12px max(12px, env(safe-area-inset-right)) 12px max(12px, env(safe-area-inset-left));
+ scrollbar-gutter: auto;
+ }
+
+ .agent-chat__msg-actions {
+ opacity: 1;
+ }
+
+ .agent-chat__body .protyle-icons {
+ opacity: .86;
+ }
+
+ .agent-chat__nav-rail {
+ display: none;
+ }
+
+ .agent-chat__input-area {
+ margin: 0 max(8px, env(safe-area-inset-right)) max(8px, env(safe-area-inset-bottom)) max(8px, env(safe-area-inset-left));
+ }
+
+ .agent-chat__composer-host {
+ max-height: min(120px, 30vh);
+ }
+
+ .agent-chat__button-options {
+ gap: 4px;
+ }
+
+ .agent-chat__confirm-actions,
+ .agent-chat__question-submit {
+ flex-wrap: wrap;
+
+ .b3-button {
+ min-height: 40px;
+ }
+ }
+
+ .agent-session-popup--mobile {
+ position: absolute;
+ inset: 0;
+ z-index: 20;
+ background: var(--b3-theme-background);
+
+ .agent-session-popup__search {
+ margin: 8px;
+ min-height: 36px;
+ }
+
+ .b3-list-item {
+ min-height: 44px;
+ }
+ }
+}
+
+.agent-menu-status--warning {
+ color: var(--b3-theme-error);
+}
diff --git a/app/src/assets/scss/mobile.scss b/app/src/assets/scss/mobile.scss
index 6045e3617f..5b7b663c39 100644
--- a/app/src/assets/scss/mobile.scss
+++ b/app/src/assets/scss/mobile.scss
@@ -31,6 +31,7 @@
@use "business/search" as *;
@use "business/emojis" as *;
@use "business/onboarding" as *;
+@use "business/ai_agent" as *;
@use "component/svg" as *;
@use "main/mobile" as *;
@use "util/responsive" as *;
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 304a94abba..2c1903cd82 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -1,4 +1,3 @@
-import {Tab} from "../../Tab";
import {Model} from "../../Model";
import type {App} from "../../../index";
import {AgentHttpError, fetchAgentSSE, IEditorContext, ISSEResult, IToolEffects} from "./agentSSE";
@@ -10,10 +9,8 @@ import "./frontendActions";
import {listActions, lookupAction} from "./frontendActions";
import {AgentSession, SessionStore} from "./SessionStore";
import {AgentSessionPanel} from "./AgentSessionPanel";
-import {getDockByType} from "../../tabUtil";
import {updateHotkeyAfterTip} from "../../../protyle/util/compatibility";
import {getAgentLute} from "../../../protyle/render/setLute";
-import {setPanelFocus} from "../../util";
import {escapeAriaLabel, escapeHtml} from "../../../util/escape";
import {setPosition} from "../../../util/setPosition";
import {fetchPost} from "../../../util/fetch";
@@ -40,11 +37,26 @@ import {
} from "./AgentMessageRenderer";
import {getAgentReasoningEffortOptions} from "./AgentReasoning";
import {mountGroupedModelPicker, type IGroupedModelPicker} from "../../../config/tabs/ai/aiProviderUi";
+import {isEncryptedBox} from "../../../util/pathName";
// 限制注入用户轮次上下文的可见块 ID 数量,以控制 token 开销。
// 与 kernel/agent/agent.go 中的 maxVisibleBlockIDs 保持一致。
const maxVisibleBlockIDs = 50;
+export type AgentChatStatus = "idle" | "running";
+export type AgentChatNotification = "confirm" | "done";
+
+export interface AgentChatHost {
+ element: HTMLElement;
+ mobile?: boolean;
+ close: () => void;
+ focus?: () => void;
+ openAiSetting?: () => void;
+ onNavigate?: () => void;
+ notify?: (type: AgentChatNotification) => void;
+ onStatusChange?: (status: AgentChatStatus) => void;
+}
+
type EntryBase = { id?: string };
type AgentReference = { id: string; title: string };
type UserEntry = EntryBase & {
@@ -88,6 +100,8 @@ type SessionEntry =
| (EntryBase & { type: "rollback"; snapshotID: string });
export class AgentChat extends Model {
+ private host: AgentChatHost;
+ private panelElement: HTMLElement;
private messagesContainer: HTMLElement;
private composerHost: HTMLElement;
private composer: ReturnType<typeof mountComposer> | null = null;
@@ -180,9 +194,10 @@ export class AgentChat extends Model {
// 用于计算本轮新增的工具(避免 step.toolNames 累积重复历史工具)。
private lastStepToolCount = 0;
- constructor(app: App, tab: Tab) {
+ constructor(app: App, host: AgentChatHost) {
super({app: app});
- this.parent = tab;
+ this.host = host;
+ this.panelElement = host.element;
this.lute = getAgentLute({
emojiSite: "/emojis",
emojis: {}
@@ -246,8 +261,9 @@ export class AgentChat extends Model {
}
private initUI() {
- const panel = this.parent.panelElement;
+ const panel = this.panelElement;
panel.classList.add("fn__flex-column", "file-tree", "sy__agentChat", "dockPanel");
+ panel.classList.toggle("sy__agentChat--mobile", !!this.host.mobile);
const L = window.siyuan.languages;
@@ -262,8 +278,10 @@ export class AgentChat extends Model {
'<svg><use xlink:href="#iconFolderClock"></use></svg>' +
"</span>" +
'<span class="fn__space"></span>' +
- '<span data-type="min" class="block__icon ariaLabel" data-position="north" aria-label="' + window.siyuan.languages.min + updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom) + '">' +
- '<svg><use xlink:href="#iconMin"></use></svg>' +
+ '<span data-type="' + (this.host.mobile ? "close" : "min") + '" class="block__icon ariaLabel" data-position="north" aria-label="' +
+ (this.host.mobile ? window.siyuan.languages.close : window.siyuan.languages.min +
+ updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)) + '">' +
+ '<svg><use xlink:href="#' + (this.host.mobile ? "iconCloseRound" : "iconMin") + '"></use></svg>' +
"</span>" +
"</div>" +
'<div class="agent-chat__messages-wrap">' +
@@ -339,11 +357,14 @@ export class AgentChat extends Model {
}, () => {
// 内容变化时刷新发送按钮可用性(含用户输入、IME、程序化 clear 等所有 doc 变更)。
this.updateSendButtonState();
+ }, {
+ submitMode: this.host.mobile ? "mod-enter" : "enter",
+ placeholder: this.host.mobile ? this.mobileComposerPlaceholder() : undefined,
});
// 块拖拽由 protyle 统一处理(复制块/引用/嵌入块→引用),无需自定义 drop handler。
this.sessionPanel = new AgentSessionPanel(
this.sessionMenuBtn,
- this.parent.panelElement,
+ this.panelElement,
() => this.sessionId,
() => this.defaultTitle,
{
@@ -362,7 +383,8 @@ export class AgentChat extends Model {
}
await SessionStore.rename(id, title);
},
- }
+ },
+ !!this.host.mobile,
);
// 监听滚动容器尺寸:dock 面板折叠时容器尺寸归零、浏览器把 scrollTop 钳制到 0;
// 这里在面板重新展开后恢复当前会话的滚动位置。dock 展开/折叠有 CSS 宽高过渡(约 0.2s),
@@ -388,7 +410,7 @@ export class AgentChat extends Model {
private initModelSelect() {
this.refreshModelOptions();
- this.groupedModelPicker = mountGroupedModelPicker(this.parent.panelElement, "agent", {
+ this.groupedModelPicker = mountGroupedModelPicker(this.panelElement, "agent", {
menuId: "agent-chat-model-picker",
getSelectedModelId: () => this.selectedModel,
onSelect: (nextModel) => {
@@ -428,6 +450,10 @@ export class AgentChat extends Model {
// 打开设置面板并切换到「人工智能」tab。动态 import config 模块避免与 AgentChat 的循环依赖。
private async openAiSetting() {
+ if (this.host.openAiSetting) {
+ this.host.openAiSetting();
+ return;
+ }
const {openSetting} = await import("../../../config");
// openSetting 若已有设置对话框会先销毁重建,先检测复用避免闪烁。
const existing = window.siyuan.dialogs.find(d => d.element.querySelector(".config__tab-container"));
@@ -436,13 +462,26 @@ export class AgentChat extends Model {
}
}
- // 将外部块引用以 mention chip 形式追加到发送框末尾,等价于拖拽块到发送框或在框内 @ 搜索选块。
+ // 将外部块引用以 mention chip 形式追加到发送框末尾,等价于拖拽块到发送框或在框内搜索选块。
public insertBlockMentions(mentions: Array<{ id: string; label: string }>) {
if (this.composer && mentions.length > 0) {
this.composer.insertMentions(mentions);
}
}
+ public back(): boolean {
+ if (!this.sessionPanel?.isOpen()) {
+ return false;
+ }
+ this.sessionPanel.close();
+ return true;
+ }
+
+ private mobileComposerPlaceholder() {
+ const placeholder = window.siyuan.languages.agentInputPlaceholder || "";
+ return placeholder.split(/[,,、،؛।]/)[0] || window.siyuan.languages.agentChat;
+ }
+
// 从 window.siyuan.config.ai 重新计算可用模型列表,幂等可重复调用。
// 与后端 HasAnyProvider()/GetModel() 判定一致:provider 和 model 均需 enabled。
// 零模型时显式置空 selectedModel(避免 undefined 透传到后端),失效选择自动重置。
@@ -697,25 +736,25 @@ export class AgentChat extends Model {
});
this.newSessionBtn.addEventListener("click", (e: MouseEvent) => {
e.stopPropagation();
- setPanelFocus(this.parent.panelElement);
+ this.host.focus?.();
this.createSession();
});
this.sessionMenuBtn.addEventListener("click", (e: MouseEvent) => {
e.stopPropagation();
- setPanelFocus(this.parent.panelElement);
+ this.host.focus?.();
this.sessionPanel.toggle();
});
- this.parent.panelElement.addEventListener("click", (e: MouseEvent) => {
- setPanelFocus(this.parent.panelElement);
+ this.panelElement.addEventListener("click", (e: MouseEvent) => {
+ this.host.focus?.();
const t = e.target as HTMLElement;
let target = t;
- while (target && !target.isEqualNode(this.parent.panelElement)) {
+ while (target && !target.isEqualNode(this.panelElement)) {
if (target.classList.contains("block__icon")) {
const type = target.getAttribute("data-type");
- if (type === "min") {
+ if (type === "min" || type === "close") {
e.stopPropagation();
- getDockByType("agentChat").toggleModel("agentChat", false, true);
+ this.host.close();
return;
}
break;
@@ -1165,7 +1204,7 @@ export class AgentChat extends Model {
}
el.innerHTML = '<div class="agent-chat__body b3-typography">' + (this.lute.ProtylePreviewStr("", content) || escapeHtml(content)) + "</div>";
this.messagesContainer.appendChild(el);
- postRender(el, this.app);
+ postRender(el, this.app, this.host.onNavigate);
this.addCopyButton(el, content, timestamp);
}
@@ -1629,7 +1668,8 @@ export class AgentChat extends Model {
private captureEditorContext(): IEditorContext | undefined {
/// #if MOBILE
const mobEditor = window.siyuan.mobile.editor || window.siyuan.mobile.popEditor;
- if (mobEditor?.protyle && !mobEditor.protyle.element.classList.contains("fn__none")) {
+ if (mobEditor?.protyle && !mobEditor.protyle.element.classList.contains("fn__none") &&
+ !isEncryptedBox(mobEditor.protyle.notebookId)) {
return this.readEditorContext(mobEditor);
}
return undefined;
@@ -1638,14 +1678,18 @@ export class AgentChat extends Model {
if (!allEditor || allEditor.length === 0) {
return undefined;
}
- const isEditable = (e: { protyle: { element: HTMLElement } }) =>
+ const isEditable = (e: { protyle: { element: HTMLElement; notebookId?: string } }) =>
!e.protyle.element.classList.contains("fn__none") &&
+ !isEncryptedBox(e.protyle.notebookId) &&
e.protyle.element.closest(".layout__center") !== null;
// Aggregate selected block IDs across ALL editors (user may have selected blocks
// in one editor while a different one is "active").
let allSelected: string[] = [];
allEditor.forEach(e => {
+ if (isEncryptedBox(e.protyle?.notebookId)) {
+ return;
+ }
e.protyle?.wysiwyg?.element?.querySelectorAll("[data-node-id].protyle-wysiwyg--select")
?.forEach(el => {
const id = (el as HTMLElement).getAttribute("data-node-id");
@@ -1662,6 +1706,9 @@ export class AgentChat extends Model {
block?: { id?: string; rootID?: string };
wysiwyg?: { element?: HTMLElement };
element: HTMLElement;
+ contentElement?: HTMLElement;
+ notebookId?: string;
+ title?: { editElement?: HTMLElement };
model?: { parent?: { headElement?: HTMLElement } }
}
} | undefined;
@@ -1674,13 +1721,17 @@ export class AgentChat extends Model {
const domSel = window.getSelection();
const range = domSel && domSel.rangeCount > 0 ? domSel.getRangeAt(0) : null;
if (range) {
- candidate = allEditor.find(e => e.protyle.element.contains(range.startContainer));
+ candidate = allEditor.find(e => !isEncryptedBox(e.protyle.notebookId) &&
+ e.protyle.element.contains(range.startContainer));
}
}
// 3) The most-recently-activated focused document tab (data-activetime).
if (!candidate) {
let activeTime = 0;
allEditor.forEach(e => {
+ if (isEncryptedBox(e.protyle.notebookId)) {
+ return;
+ }
let head = e.protyle.model?.parent?.headElement;
if (!head && e.protyle.element.getBoundingClientRect().height > 0) {
const tabBody = e.protyle.element.closest(".fn__flex-1[data-id]");
@@ -1698,7 +1749,8 @@ export class AgentChat extends Model {
}
// 4) Any visible (non-fn__none) editor.
if (!candidate) {
- candidate = allEditor.find(e => !e.protyle.element.classList.contains("fn__none"));
+ candidate = allEditor.find(e => !e.protyle.element.classList.contains("fn__none") &&
+ !isEncryptedBox(e.protyle.notebookId));
}
const ctx = candidate ? this.readEditorContext(candidate) : undefined;
@@ -1728,7 +1780,7 @@ export class AgentChat extends Model {
};
}): IEditorContext | undefined {
const p = editor.protyle;
- if (!p) {
+ if (!p || isEncryptedBox(p.notebookId)) {
return undefined;
}
const activeDocID = p.block?.rootID;
@@ -2042,7 +2094,7 @@ export class AgentChat extends Model {
private renderUserMessage(el: HTMLElement) {
const body = el.querySelector(".agent-chat__body") as HTMLElement;
- postRender(el, this.app);
+ postRender(el, this.app, this.host.onNavigate);
this.composer?.renderBlockHTML(body, () => {
disabledWYSIWYG(body);
});
@@ -2688,7 +2740,7 @@ export class AgentChat extends Model {
if (content) {
// 富渲染只在此处执行一次,避免流式期间每帧 O(n²) 重建带来的卡顿。
bodyEl.innerHTML = this.lute.ProtylePreviewStr("", content) || escapeHtml(content);
- postRender(bodyEl, this.app);
+ postRender(bodyEl, this.app, this.host.onNavigate);
this.addCopyButton(this.currentAIElement, undefined, ts);
this.scrollToBottom(true);
}
@@ -2719,7 +2771,7 @@ export class AgentChat extends Model {
el.setAttribute("data-message-id", this.currentAssistantEntryId);
el.innerHTML = '<div class="agent-chat__body b3-typography">' + (this.lute.ProtylePreviewStr("", savedContent) || escapeHtml(savedContent)) + "</div>";
this.messagesContainer.appendChild(el);
- postRender(el, this.app);
+ postRender(el, this.app, this.host.onNavigate);
this.currentAIElement = el;
this.currentContent = savedContent;
this.fullContent = savedFullContent;
@@ -2795,9 +2847,13 @@ export class AgentChat extends Model {
await this.saveSession();
}
this.rebuildNavMarkers();
- if (notify && savedContent && (!document.hasFocus() || document.hidden)) {
- const L = window.siyuan.languages;
- sendNotification({title: L.agentNotifyDone, timeoutType: "default"});
+ if (notify && savedContent) {
+ if (this.host.notify) {
+ this.host.notify("done");
+ } else if (!document.hasFocus() || document.hidden) {
+ const L = window.siyuan.languages;
+ sendNotification({title: L.agentNotifyDone, timeoutType: "default"});
+ }
}
}
@@ -2985,7 +3041,7 @@ export class AgentChat extends Model {
el.setAttribute("data-message-id", this.currentAssistantEntryId);
el.innerHTML = '<div class="agent-chat__body b3-typography">' + (this.lute.ProtylePreviewStr("", savedContent) || escapeHtml(savedContent)) + "</div>";
this.messagesContainer.appendChild(el);
- postRender(el, this.app);
+ postRender(el, this.app, this.host.onNavigate);
this.currentAIElement = el;
this.currentContent = savedContent;
this.fullContent = savedFullContent;
@@ -3129,7 +3185,9 @@ export class AgentChat extends Model {
this.insertBeforeAI(el);
this.scrollToBottom(true);
this.hasInterveningCard = true;
- if (!document.hasFocus() || document.hidden) {
+ if (this.host.notify) {
+ this.host.notify("confirm");
+ } else if (!document.hasFocus() || document.hidden) {
sendNotification({title: L.agentNotifyConfirm, body: "", timeoutType: "default"});
}
}
@@ -3402,7 +3460,7 @@ export class AgentChat extends Model {
bindThinkingCardToggle(el);
this.messagesContainer.appendChild(el);
- postRender(el, this.app);
+ postRender(el, this.app, this.host.onNavigate);
}
// 由 duration 经 i18n 生成"已思考:Xs"标题文本;无 duration 时回退到"思考中..."。
@@ -3681,6 +3739,7 @@ export class AgentChat extends Model {
private setStreaming(streaming: boolean) {
this.isStreaming = streaming;
+ this.host.onStatusChange?.(streaming ? "running" : "idle");
this.sendBtn.classList.toggle("fn__none", streaming);
this.stopBtn.classList.toggle("fn__none", !streaming);
this.updateSendButtonState();
diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.ts
index 627a43b6fa..28767ed94a 100644
--- a/app/src/layout/dock/agent/AgentComposer.ts
+++ b/app/src/layout/dock/agent/AgentComposer.ts
@@ -34,6 +34,7 @@ interface ComposerOptions {
initialContent?: string;
initialBlockHTML?: string;
submitMode?: "enter" | "mod-enter";
+ placeholder?: string;
onCancel?: () => void;
enableHistory?: boolean;
}
@@ -192,7 +193,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
wysiwyg.element.innerHTML = "";
const emptyElement = genEmptyElement(false, false);
emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");
- emptyElement.firstElementChild.setAttribute("placeholder", L.agentInputPlaceholder);
+ emptyElement.firstElementChild.setAttribute("placeholder", options.placeholder || L.agentInputPlaceholder);
wysiwyg.element.appendChild(emptyElement);
};
if (options.initialBlockHTML) {
diff --git a/app/src/layout/dock/agent/AgentMessageRenderer.ts b/app/src/layout/dock/agent/AgentMessageRenderer.ts
index 44e27d1042..8a35142b27 100644
--- a/app/src/layout/dock/agent/AgentMessageRenderer.ts
+++ b/app/src/layout/dock/agent/AgentMessageRenderer.ts
@@ -260,7 +260,7 @@ const createCopyButton = (getText: () => string): HTMLElement => {
return btn;
};
-export const postRender = (container: HTMLElement, app?: App): void => {
+export const postRender = (container: HTMLElement, app?: App, onNavigate?: () => void): void => {
container.querySelectorAll(".language-math").forEach((el) => {
if (el.hasAttribute("data-subtype")) {
return;
@@ -366,6 +366,7 @@ export const postRender = (container: HTMLElement, app?: App): void => {
if (refID && container.contains(ref)) {
event.preventDefault();
event.stopPropagation();
+ onNavigate?.();
void processSiYuanUri(app, "siyuan://blocks/" + refID);
return;
}
@@ -374,6 +375,7 @@ export const postRender = (container: HTMLElement, app?: App): void => {
if (fileID && container.contains(fileRef)) {
event.preventDefault();
event.stopPropagation();
+ onNavigate?.();
openLink(app, fileID, event, event.ctrlKey || event.metaKey);
return;
}
@@ -381,6 +383,7 @@ export const postRender = (container: HTMLElement, app?: App): void => {
if (tag && container.contains(tag)) {
event.preventDefault();
event.stopPropagation();
+ onNavigate?.();
/// #if !MOBILE
openGlobalSearch(app, `#${tag.textContent}#`, true, {method: 0});
/// #else
@@ -404,6 +407,7 @@ export const postRender = (container: HTMLElement, app?: App): void => {
if (href) {
event.preventDefault();
event.stopPropagation();
+ onNavigate?.();
if (!processSiYuanUri(app, href)) {
openLink(app, href, event, event.ctrlKey || event.metaKey);
}
diff --git a/app/src/layout/dock/agent/AgentSessionPanel.ts b/app/src/layout/dock/agent/AgentSessionPanel.ts
index 9ccb100c88..ac52b05323 100644
--- a/app/src/layout/dock/agent/AgentSessionPanel.ts
+++ b/app/src/layout/dock/agent/AgentSessionPanel.ts
@@ -28,10 +28,15 @@ export class AgentSessionPanel {
onSwitch: (id: string) => Promise<void>;
onDelete: (id: string) => Promise<void>;
onRename: (id: string, title: string) => Promise<void>;
- }
+ },
+ private mobile = false,
) {
}
+ isOpen() {
+ return !!this.popup;
+ }
+
toggle() {
if (this.isRendering) {
return;
@@ -45,6 +50,7 @@ export class AgentSessionPanel {
close() {
this.closeAllSubmenus();
+ this.popup?.remove();
document.querySelectorAll(".agent-session-popup").forEach(function (el) {
el.remove();
});
@@ -73,11 +79,16 @@ export class AgentSessionPanel {
this.page = 1;
this.popup = document.createElement("div");
- this.popup.className = "agent-session-popup b3-menu";
+ this.popup.className = this.mobile ?
+ "agent-session-popup agent-session-popup--mobile fn__flex-column" :
+ "agent-session-popup b3-menu";
const L = window.siyuan.languages;
- let html = '<input class="b3-text-field agent-session-popup__search" placeholder="' + L.agentSessionSearch + '">';
+ let html = this.mobile ? '<div class="toolbar toolbar--border">' +
+ '<svg class="toolbar__icon" data-type="back"><use xlink:href="#iconLeft"></use></svg>' +
+ '<span class="toolbar__text">' + L.manageSessions + "</span></div>" : "";
+ html += '<input class="b3-text-field agent-session-popup__search" placeholder="' + L.agentSessionSearch + '">';
html += '<div class="b3-list b3-list--background fn__flex-1"></div>';
this.popup.innerHTML = html;
@@ -85,6 +96,7 @@ export class AgentSessionPanel {
const itemsContainer = this.popup.querySelector(".b3-list") as HTMLElement;
this.renderItems(itemsContainer, result.sessions, false);
const searchInput = this.popup.querySelector(".agent-session-popup__search") as HTMLInputElement;
+ this.popup.querySelector('[data-type="back"]')?.addEventListener("click", () => this.close());
searchInput.addEventListener("input", (event: InputEvent) => {
event.stopPropagation();
if (event.isComposing) {
@@ -116,8 +128,10 @@ export class AgentSessionPanel {
this.host.appendChild(this.popup);
this.popup.style.zIndex = (++window.siyuan.zIndex).toString();
- const btnRect = this.triggerBtn.getBoundingClientRect();
- setPosition(this.popup, btnRect.right - 280, btnRect.bottom, btnRect.height, btnRect.width);
+ if (!this.mobile) {
+ const btnRect = this.triggerBtn.getBoundingClientRect();
+ setPosition(this.popup, btnRect.right - 280, btnRect.bottom, btnRect.height, btnRect.width);
+ }
this.popup.addEventListener("click", (e: MouseEvent) => {
e.stopPropagation();
@@ -134,7 +148,9 @@ export class AgentSessionPanel {
setTimeout(() => {
document.addEventListener("click", closeOut);
}, 10);
- searchInput.focus();
+ if (!this.mobile) {
+ searchInput.focus();
+ }
} finally {
this.isRendering = false;
}
@@ -155,7 +171,8 @@ export class AgentSessionPanel {
for (let i = 0; i < listItems.length; i++) {
const s = listItems[i];
const isActive = s.id === currentId;
- html += '<div class="b3-list-item b3-list-item--hide-action' + (isActive ? " b3-list-item--focus" : "") + '" data-id="' + s.id + '">' +
+ html += '<div class="b3-list-item' + (this.mobile ? "" : " b3-list-item--hide-action") +
+ (isActive ? " b3-list-item--focus" : "") + '" data-id="' + s.id + '">' +
'<span class="b3-list-item__text ariaLabel" data-position="parentW" aria-label="' + escapeHtml(s.title || defaultTitle) + '">' + escapeHtml(s.title || defaultTitle) + "</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") + '">' +
diff --git a/app/src/layout/dock/agent/frontendActions.ts b/app/src/layout/dock/agent/frontendActions.ts
index 1ade3b3ee4..ac4a66db75 100644
--- a/app/src/layout/dock/agent/frontendActions.ts
+++ b/app/src/layout/dock/agent/frontendActions.ts
@@ -135,4 +135,85 @@ registerAction({
return {result: query ? `Opened search dialog with query "${query}".` : "Opened search dialog."};
},
});
+/// #else
+registerAction({
+ name: "open_setting",
+ handler: async (args, app) => {
+ const query = (args.query as string | undefined)?.trim();
+ const [{hideMobileAgent, reopenMobileAgent}, {openMobileSetting}] = await Promise.all([
+ import("../../../mobile/agent/MobileAgentChat"),
+ import("../../../mobile/menu"),
+ ]);
+ hideMobileAgent();
+ openMobileSetting(app, undefined, reopenMobileAgent);
+ return {result: query ? `Opened mobile settings for "${query}".` : "Opened mobile settings."};
+ },
+});
+
+registerAction({
+ name: "focus_block",
+ handler: async (args) => {
+ const id = args.id as string | undefined;
+ if (!id) {
+ return {error: "missing required argument: id"};
+ }
+ const [{getCurrentEditor}, {hideMobileAgent}] = await Promise.all([
+ import("../../../mobile/editor"),
+ import("../../../mobile/agent/MobileAgentChat"),
+ ]);
+ const editor = getCurrentEditor();
+ const block = editor?.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) as HTMLElement | null;
+ if (!block) {
+ return {error: `Block ${id} is not loaded in the current editor. Use open_document to open it first.`};
+ }
+ hideMobileAgent();
+ block.scrollIntoView({behavior: "smooth", block: "center"});
+ block.classList.add("protyle-wysiwyg--hl");
+ setTimeout(() => block.classList.remove("protyle-wysiwyg--hl"), 2000);
+ return {result: `Focused block ${id} in the active editor.`};
+ },
+});
+
+registerAction({
+ name: "open_document",
+ handler: async (args, app) => {
+ const id = args.id as string | undefined;
+ if (!id) {
+ return {error: "missing required argument: id"};
+ }
+ try {
+ const [{openMobileFileById}, {hideMobileAgent}, {Constants}] = await Promise.all([
+ import("../../../mobile/editor"),
+ import("../../../mobile/agent/MobileAgentChat"),
+ import("../../../constants"),
+ ]);
+ hideMobileAgent();
+ openMobileFileById(app, id, [Constants.CB_GET_FOCUS]);
+ return {result: `Opened document ${id}.`};
+ } catch (e) {
+ return {error: `Failed to open document ${id}: ${(e as Error).message}`};
+ }
+ },
+});
+
+registerAction({
+ name: "open_search",
+ handler: async (args, app) => {
+ const query = (args.query as string | undefined)?.trim();
+ const [{popSearch}, {hideMobileAgent}] = await Promise.all([
+ import("../../../mobile/menu/search"),
+ import("../../../mobile/agent/MobileAgentChat"),
+ ]);
+ hideMobileAgent();
+ popSearch(app);
+ if (query) {
+ const input = document.getElementById("toolbarSearch") as HTMLInputElement | null;
+ if (input) {
+ input.value = query;
+ input.dispatchEvent(new InputEvent("input", {bubbles: true}));
+ }
+ }
+ return {result: query ? `Opened mobile search with query "${query}".` : "Opened mobile search."};
+ },
+});
/// #endif
diff --git a/app/src/layout/dock/index.ts b/app/src/layout/dock/index.ts
index 2e23c18d16..371e2e2d22 100644
--- a/app/src/layout/dock/index.ts
+++ b/app/src/layout/dock/index.ts
@@ -634,7 +634,11 @@ export class Dock {
case "agentChat":
tab = new Tab({
callback: (tab: Tab) => {
- tab.addModel(new AgentChat(this.app, tab));
+ tab.addModel(new AgentChat(this.app, {
+ element: tab.panelElement,
+ close: () => this.toggleModel("agentChat", false, true),
+ focus: () => setPanelFocus(tab.panelElement),
+ }));
}
});
break;
diff --git a/app/src/mobile/agent/MobileAgentChat.ts b/app/src/mobile/agent/MobileAgentChat.ts
new file mode 100644
index 0000000000..90224c91bf
--- /dev/null
+++ b/app/src/mobile/agent/MobileAgentChat.ts
@@ -0,0 +1,144 @@
+import type {App} from "../../index";
+import {
+ AgentChat,
+ type AgentChatNotification,
+ type AgentChatStatus,
+} from "../../layout/dock/agent/AgentChat";
+import {openModel} from "../menu/model";
+import {closeModel, closePanel} from "../util/closePanel";
+import {showMessage} from "../../dialog/message";
+import {sendNotification} from "../../plugin/platformUtils";
+
+let app: App | undefined;
+let agentChat: AgentChat | undefined;
+let rootElement: HTMLElement | undefined;
+let detachedRoot: DocumentFragment | undefined;
+let visible = false;
+let running = false;
+let unread: AgentChatNotification | undefined;
+
+const updateMenuStatus = () => {
+ const item = document.getElementById("menuAgentChat");
+ if (!item) {
+ return;
+ }
+ const icon = item.querySelector(".b3-menu__icon");
+ icon?.classList.toggle("fn__rotate", running);
+ const status = item.querySelector('[data-type="agent-status"]');
+ if (!status) {
+ return;
+ }
+ status.classList.toggle("fn__none", !unread);
+ status.classList.toggle("agent-menu-status--warning", unread === "confirm");
+ status.textContent = unread === "confirm" ? window.siyuan.languages.agentConfirmPending : "●";
+};
+
+const detach = () => {
+ visible = false;
+ document.getElementById("model")?.classList.remove("model--agent");
+ if (rootElement?.parentElement) {
+ detachedRoot = detachedRoot || document.createDocumentFragment();
+ detachedRoot.appendChild(rootElement);
+ }
+};
+
+const notify = (type: AgentChatNotification) => {
+ if (visible) {
+ return;
+ }
+ unread = type;
+ updateMenuStatus();
+ const title = type === "confirm" ?
+ window.siyuan.languages.agentNotifyConfirm : window.siyuan.languages.agentNotifyDone;
+ if (!document.hasFocus() || document.hidden) {
+ void sendNotification({title, timeoutType: "default"});
+ } else {
+ showMessage(title, 3000, "info");
+ }
+};
+
+const setStatus = (status: AgentChatStatus) => {
+ running = status === "running";
+ updateMenuStatus();
+};
+
+const ensureAgentChat = (currentApp: App) => {
+ app = currentApp;
+ if (agentChat && rootElement) {
+ return;
+ }
+ rootElement = document.createElement("div");
+ rootElement.className = "fn__flex-1";
+ detachedRoot = document.createDocumentFragment();
+ detachedRoot.appendChild(rootElement);
+ agentChat = new AgentChat(currentApp, {
+ element: rootElement,
+ mobile: true,
+ close: hideMobileAgent,
+ openAiSetting: () => {
+ hideMobileAgent();
+ void import("../menu").then(({openMobileSetting}) => openMobileSetting(currentApp, "ai", reopenMobileAgent));
+ },
+ onNavigate: hideMobileAgent,
+ notify,
+ onStatusChange: setStatus,
+ });
+ window.siyuan.mobile.agentChat = agentChat;
+ window.siyuan.mobile.agentChatController = {
+ handleBack: handleMobileAgentBack,
+ refreshStatus: updateMenuStatus,
+ };
+};
+
+export const openMobileAgent = (currentApp: App) => {
+ ensureAgentChat(currentApp);
+ closePanel();
+ openModel({
+ title: "",
+ html: "",
+ bindEvent(modelMainElement) {
+ modelMainElement.appendChild(rootElement!);
+ },
+ destroyCallback: detach,
+ });
+ document.getElementById("model").classList.add("model--agent");
+ visible = true;
+ unread = undefined;
+ updateMenuStatus();
+};
+
+export const hideMobileAgent = () => {
+ if (!visible) {
+ return;
+ }
+ visible = false;
+ document.getElementById("model")?.classList.remove("model--agent");
+ closeModel();
+};
+
+export const handleMobileAgentBack = () => {
+ if (!visible) {
+ return false;
+ }
+ if (agentChat?.back()) {
+ return true;
+ }
+ hideMobileAgent();
+ return true;
+};
+
+export const insertMobileAgentMentions = (currentApp: App, mentions: Array<{id: string; label: string}>) => {
+ if (mentions.length === 0) {
+ return;
+ }
+ openMobileAgent(currentApp);
+ agentChat?.insertBlockMentions(mentions);
+};
+
+export const isMobileAgentVisible = () => visible;
+
+export const reopenMobileAgent = () => {
+ if (app) {
+ openMobileAgent(app);
+ }
+};
diff --git a/app/src/mobile/menu/index.ts b/app/src/mobile/menu/index.ts
index 22045ac8b7..295ae595f4 100644
--- a/app/src/mobile/menu/index.ts
+++ b/app/src/mobile/menu/index.ts
@@ -34,7 +34,7 @@ const getSettingTabsMenuHTML = () => getSettingTabDefs().map(def =>
<span class="b3-menu__label">${def.title}</span>
</div>`).join("");
-const openSettingTab = (app: App, settingTabDef: ISettingTabShell<TSettingTab>) => {
+const openSettingTab = (app: App, settingTabDef: ISettingTabShell<TSettingTab>, returnCallback?: () => void) => {
openModel({
title: settingTabDef.title,
icon: "iconLeft",
@@ -45,13 +45,17 @@ const openSettingTab = (app: App, settingTabDef: ISettingTabShell<TSettingTab>)
void getSettingTab(settingTabDef.id).mount(root, undefined, app);
},
backCallback() {
- openSettingMenu(app, "back");
+ if (returnCallback) {
+ returnCallback();
+ } else {
+ openSettingMenu(app, "back");
+ }
},
transition: "forward",
});
};
-const openSettingMenu = (app: App, transition?: "back") => {
+const openSettingMenu = (app: App, transition?: "back", returnCallback?: () => void) => {
openModel({
title: window.siyuan.languages.config,
icon: "iconLeft",
@@ -64,25 +68,29 @@ const openSettingMenu = (app: App, transition?: "back") => {
modelMainElement.addEventListener("click", (event) => {
const def = getSettingTabFromMenuTarget(event.target as HTMLElement);
if (def) {
- openSettingTab(app, def);
+ openSettingTab(app, def, () => openSettingMenu(app, "back", returnCallback));
}
});
},
backCallback() {
- closeModel();
+ if (returnCallback) {
+ returnCallback();
+ } else {
+ closeModel();
+ }
},
transition,
});
};
-export const openMobileSetting = (app: App, tab?: TSettingTab) => {
+export const openMobileSetting = (app: App, tab?: TSettingTab, returnCallback?: () => void) => {
activeBlur();
const settingTabDef = tab ? getSettingTabDefs().find(def => def.id === tab) : undefined;
if (settingTabDef) {
- openSettingTab(app, settingTabDef);
+ openSettingTab(app, settingTabDef, returnCallback);
return;
}
- openSettingMenu(app);
+ openSettingMenu(app, undefined, returnCallback);
};
export const popMenu = () => {
@@ -109,6 +117,11 @@ export const initRightMenu = (app: App) => {
<div id="menuSearch" class="b3-menu__item">
<svg class="b3-menu__icon"><use xlink:href="#iconSearch"></use></svg><span class="b3-menu__label">${window.siyuan.languages.search}</span>
</div>
+ <div id="menuAgentChat" class="b3-menu__item${window.siyuan.config.readonly || window.siyuan.isPublish ? " fn__none" : ""}">
+ <svg class="b3-menu__icon"><use xlink:href="#iconSparkles"></use></svg>
+ <span class="b3-menu__label">${window.siyuan.languages.agentChat}</span>
+ <span data-type="agent-status" class="b3-menu__accelerator fn__none"></span>
+ </div>
<div id="menuCommand" class="b3-menu__item">
<svg class="b3-menu__icon"><use xlink:href="#iconTerminal"></use></svg><span class="b3-menu__label">${window.siyuan.languages.commandPanel}</span>
</div>
@@ -179,6 +192,7 @@ export const initRightMenu = (app: App) => {
</div>
</div>
</div>`;
+ window.siyuan.mobile.agentChatController?.refreshStatus();
processSync();
afterLayoutReady(app);
// 只能用 click,否则无法上下滚动 https://github.com/siyuan-note/siyuan/issues/6628
@@ -200,6 +214,11 @@ export const initRightMenu = (app: App) => {
event.preventDefault();
event.stopPropagation();
break;
+ } else if (target.id === "menuAgentChat") {
+ void import("../agent/MobileAgentChat").then(({openMobileAgent}) => openMobileAgent(app));
+ event.preventDefault();
+ event.stopPropagation();
+ break;
} else if (target.id === "menuCommand") {
closePanel();
commandPanel(app);
diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.ts
index fd3a661180..f56cd61380 100644
--- a/app/src/mobile/util/MobileBackFoward.ts
+++ b/app/src/mobile/util/MobileBackFoward.ts
@@ -32,6 +32,8 @@ export const goBack = () => {
} else if (window.siyuan.dialogs.length !== 0) {
window.siyuan.dialogs[window.siyuan.dialogs.length - 1].destroy();
return;
+ } else if (window.siyuan.mobile.agentChatController?.handleBack()) {
+ return;
} else if (document.getElementById("model").style.transform === "translateX(0px)") {
const searchAssetsPanelElement = document.getElementById("searchAssetsPanel");
if (!searchAssetsPanelElement || searchAssetsPanelElement.classList.contains("fn__none")) {
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index c979775985..53b64fbdf1 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -564,6 +564,14 @@ export const showKeyboardToolbar = () => {
}
const toolbarElement = document.getElementById("keyboardToolbar");
window.dispatchEvent(new CustomEvent("siyuan-mobile-keyboard-change", {detail: true}));
+ const selection = getSelection();
+ if (selection.rangeCount > 0 &&
+ hasClosestByClassName(selection.getRangeAt(0).startContainer, "agent-chat__composer-host", true)) {
+ // 智能体发送框自带操作栏,不能显示会作用于下层文档的移动端编辑工具栏。
+ toolbarElement.classList.add("fn__none");
+ document.getElementById("model").style.paddingBottom = "";
+ return;
+ }
if (!toolbarElement.classList.contains("fn__none") || getSelection().rangeCount === 0) {
return;
}
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 02bee19c48..9c0329127c 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -1263,7 +1263,6 @@ export class Gutter {
addEditorToDatabase(protyle, getEditorRange(selectsElement[0]));
}
}).element);
- /// #if !MOBILE
// 加密笔记本中的块不暴露该菜单:避免把受保护内容引入智能体会话。
if (!isEncryptedBox(protyle.notebookId)) {
window.siyuan.menus.menu.append(new MenuItem({
@@ -1275,7 +1274,6 @@ export class Gutter {
}
}).element);
}
- /// #endif
window.siyuan.menus.menu.append(new MenuItem({
id: "delete",
label: window.siyuan.languages.delete,
@@ -1845,7 +1843,6 @@ export class Gutter {
}
this.appendAddToDatabaseMenu(protyle, nodeElement);
if (!protyle.disabled) {
- /// #if !MOBILE
// 加密笔记本中的块不暴露该菜单:避免把受保护内容引入智能体会话。
if (!isEncryptedBox(protyle.notebookId)) {
window.siyuan.menus.menu.append(new MenuItem({
@@ -1857,7 +1854,6 @@ export class Gutter {
}
}).element);
}
- /// #endif
}
if (allowRemoval) {
window.siyuan.menus.menu.append(new MenuItem({
@@ -3437,14 +3433,30 @@ interface AgentChatLike {
insertBlockMentions: (mentions: Array<{ id: string; label: string }>) => void;
}
-// 将选中的块以 @ 引用形式追加到智能体会话发送框末尾,等价于拖拽块到发送框或在框内 @ 搜索选块。
-// 仅桌面端可用:智能体面板(dock)在移动端不存在。
-/// #if !MOBILE
+// 将选中的块以区块引用形式追加到智能体会话发送框末尾,等价于拖拽块到发送框或在框内搜索选块。
export const addBlockToAgent = async (blockIds: string[]) => {
const ids = blockIds.filter(Boolean);
if (ids.length === 0) {
return;
}
+ // 用 getRefText API 并行获取每个块的引用文本作为 label(与输入框搜索、拖拽一致),失败时回退到 blockId。
+ // Promise.all 按输入顺序返回结果,确保多选块的引用顺序稳定。
+ const mentions = await Promise.all(ids.map(async (id) => {
+ let label = id;
+ try {
+ const resp = await fetchSyncPost("/api/block/getRefText", {id});
+ if (resp && resp.data) {
+ label = resp.data;
+ }
+ } catch {
+ label = id;
+ }
+ return {id, label};
+ }));
+ /// #if MOBILE
+ const {insertMobileAgentMentions} = await import("../../mobile/agent/MobileAgentChat");
+ insertMobileAgentMentions(window.siyuan.ws.app, mentions);
+ /// #else
const dock = getDockByType("agentChat");
if (!dock) {
return;
@@ -3465,20 +3477,6 @@ export const addBlockToAgent = async (blockIds: string[]) => {
// 极端情况下实例仍未就绪,放弃插入避免报错。
return;
}
- // 用 getRefText API 并行获取每个块的引用文本作为 label(与 @ 搜索、拖拽一致),失败时回退到 blockId。
- const mentions: Array<{ id: string; label: string }> = [];
- await Promise.all(ids.map(async (id) => {
- let label = id;
- try {
- const resp = await fetchSyncPost("/api/block/getRefText", {id});
- if (resp && resp.data) {
- label = resp.data;
- }
- } catch {
- label = id;
- }
- mentions.push({id, label});
- }));
agentChat.insertBlockMentions(mentions);
+ /// #endif
};
-/// #endif
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 4d2b6e1614..5754d636a3 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -587,6 +587,11 @@ interface ISiyuan {
editor?: import("../protyle").Protyle
popEditor?: import("../protyle").Protyle
tabs?: import("../mobile/tabs/MobileTabs").MobileTabs
+ agentChat?: import("../layout/dock/agent/AgentChat").AgentChat
+ agentChatController?: {
+ handleBack: () => boolean
+ refreshStatus: () => void
+ }
docks?: {
outline: import("../mobile/dock/MobileOutline").MobileOutline | null,
file: import("../mobile/dock/MobileFiles").MobileFiles | null,