diff --git a/app/electron/main.js b/app/electron/main.js index 657056171..e42ded131 100644 --- a/app/electron/main.js +++ b/app/electron/main.js @@ -20,6 +20,7 @@ const { BrowserWindow, Notification, shell, + session, Menu, MenuItem, screen, @@ -76,7 +77,6 @@ app.commandLine.appendSwitch("auto-detect", "false"); app.commandLine.appendSwitch("no-proxy-server"); app.commandLine.appendSwitch("enable-features", "PlatformHEVCDecoderSupport"); app.commandLine.appendSwitch("xdg-portal-required-version", "4"); -app.commandLine.appendSwitch("max-connections-per-host", "32"); // Support set Chromium command line arguments on the desktop https://github.com/siyuan-note/siyuan/issues/9696 writeLog("app is packaged [" + app.isPackaged + "], command line args [" + process.argv.join(", ") + "]"); @@ -286,7 +286,7 @@ const exitApp = (port, errorWindowId) => { } }; -const localServer = "http://127.0.0.1"; +const localServer = "https://127.0.0.1"; const getServer = (port = kernelPort) => { return localServer + ":" + port; @@ -735,6 +735,15 @@ const initKernel = (workspace, port, lang) => { }; app.whenReady().then(() => { + // Trust self-signed TLS certificates for local HTTPS server + session.defaultSession.setCertificateVerifyProc((request, callback) => { + if (request.hostname === "127.0.0.1" || request.hostname === "localhost") { + callback(0); // VERIFY_OK + } else { + callback(-3); // default Chromium handling + } + }); + const resetTrayMenu = (tray, lang, mainWindow) => { if (!mainWindow || mainWindow.isDestroyed()) { return; diff --git a/app/package.json b/app/package.json index 0aee1d2d6..35f420e06 100644 --- a/app/package.json +++ b/app/package.json @@ -78,10 +78,7 @@ "typescript": "^4.7.4", "webpack": "^5.104.1", "webpack-bundle-analyzer": "^4.5.0", - "webpack-cli": "^4.10.0" - }, - "dependencies": { - "@electron/remote": "^2.1.3", + "webpack-cli": "^4.10.0", "@tiptap/core": "^3.24.0", "@tiptap/extension-document": "^3.24.0", "@tiptap/extension-hard-break": "^3.24.0", @@ -92,5 +89,8 @@ "@tiptap/extension-text": "^3.24.0", "@tiptap/pm": "^3.24.0", "@tiptap/suggestion": "^3.24.0" + }, + "dependencies": { + "@electron/remote": "^2.1.3" } } diff --git a/app/pnpm-lock.yaml b/app/pnpm-lock.yaml index 0b5bed758..62b497354 100644 --- a/app/pnpm-lock.yaml +++ b/app/pnpm-lock.yaml @@ -11,6 +11,13 @@ importers: '@electron/remote': specifier: ^2.1.3 version: 2.1.3(electron@41.7.1) + devDependencies: + '@eslint/eslintrc': + specifier: ^3.3.1 + version: 3.3.5 + '@eslint/js': + specifier: ^9.24.0 + version: 9.39.4 '@tiptap/core': specifier: ^3.24.0 version: 3.24.0(@tiptap/pm@3.24.0) @@ -41,13 +48,6 @@ importers: '@tiptap/suggestion': specifier: ^3.24.0 version: 3.24.0(@tiptap/core@3.24.0(@tiptap/pm@3.24.0))(@tiptap/pm@3.24.0) - devDependencies: - '@eslint/eslintrc': - specifier: ^3.3.1 - version: 3.3.5 - '@eslint/js': - specifier: ^9.24.0 - version: 9.39.4 '@types/node': specifier: ^18.13.0 version: 18.13.0 diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scss index 6f1af446e..276df05ac 100644 --- a/app/src/assets/scss/business/_agentChat.scss +++ b/app/src/assets/scss/business/_agentChat.scss @@ -311,6 +311,26 @@ align-items: stretch; } +.agent-chat__tool-line { + font-size: 12px; + color: var(--b3-theme-on-surface-light); + padding: 2px 0; + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; + + &:hover { + color: var(--b3-theme-on-surface); + } +} + +.agent-chat__tool-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + .agent-chat__tool-card { border: 1px solid var(--b3-border-color); border-radius: var(--b3-border-radius); @@ -333,6 +353,14 @@ background: var(--b3-theme-background); } +.agent-chat__msg--thinking-done { + opacity: 0.6; + + .agent-chat__thinking-text { + font-style: italic; + } +} + .agent-chat__thinking-header { display: flex; align-items: center; @@ -363,9 +391,13 @@ } .agent-chat__thinking-arrow { - font-size: 10px; - color: var(--b3-theme-on-surface-light); flex-shrink: 0; + color: var(--b3-theme-primary); + + svg { + width: 14px; + height: 14px; + } } .agent-chat__thinking-body { @@ -547,7 +579,6 @@ .agent-chat__buttons { display: flex; - justify-content: flex-end; gap: 8px; margin-top: 8px; } diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts index 0fea2aba1..737d08eca 100644 --- a/app/src/layout/dock/AgentChat.ts +++ b/app/src/layout/dock/AgentChat.ts @@ -47,7 +47,11 @@ export class AgentChat extends Model { private currentToolCalls: Array<{name: string; arguments: Record; result?: string}> = []; private abortController: AbortController | null = null; private isRenderingSessionList = false; - private messageHistory: Record = {}; + private thinkingSteps: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}> = []; + private currentThinkingText = ""; + private currentThinkingReasoning = ""; + private currentThinkingReasoningContent = ""; + private modelSelect: HTMLSelectElement; constructor(app: App, tab: Tab) { super({app: app}); @@ -84,7 +88,9 @@ export class AgentChat extends Model { '
' + '
' + '
' + + '' + '' + + '' + '" + '" + "
" + @@ -99,12 +105,31 @@ export class AgentChat extends Model { this.sessionMenuBtn = panel.querySelector('.block__icon[data-type="session-menu"]') as HTMLElement; this.titleElement = panel.querySelector(".agent-chat__title") as HTMLElement; this.tokenDisplayEl = panel.querySelector(".agent-chat__tokens") as HTMLElement; + this.modelSelect = panel.querySelector(".agent-chat__model") as HTMLSelectElement; + + this.initModelSelect(); const self = this; this.composer = mountComposer(this.composerHost, function () { self.sendMessage(); }); this.initSessions(); } + private initModelSelect() { + const aiConfig = window.siyuan.config.ai; + const mainModel = aiConfig.openAI.apiModel; + const providers = aiConfig.providers || []; + let html = '"; + for (const p of providers) { + if (p.enabled === false) { continue; } + html += '"; + } + this.modelSelect.innerHTML = html; + } + + private getSelectedModel(): string { + return this.modelSelect.value; + } + private showWelcome() { const L = window.siyuan.languages; const html = '
' + @@ -126,6 +151,10 @@ export class AgentChat extends Model { // 不支持 setSendText,直接用 sendMessage 发送 self.messages.push({role: "user", content: text}); self.appendUserMessage(text); + if (!self.hasTitled) { + self.hasTitled = true; + self.generateTitle(); + } self.setStreaming(true); const apiMessages = self.messages.map(function (m) { return {role: m.role as "user" | "assistant", content: m.content}; }); self.abortController = new AbortController(); @@ -140,7 +169,8 @@ export class AgentChat extends Model { self.handleError(err); }, self.abortController.signal, - self.sessionId); + self.sessionId, + self.getSelectedModel()); } }; }(examples[i] as HTMLElement)); @@ -167,6 +197,7 @@ export class AgentChat extends Model { getDockByType("agentChat").toggleModel("agentChat", false, true); return; } + if (t.closest(".agent-chat__model")) { return; } if (self.composer) { self.composer.focus(); } }); } @@ -175,7 +206,7 @@ export class AgentChat extends Model { await SessionStore.init(); const list = await SessionStore.list(); if (list.length > 0) { - list.sort(function (a, b) { return b.updatedAt - a.updatedAt; }); + list.sort(function (a, b) { return b.createdAt - a.createdAt; }); const last = list[0]; const session = await SessionStore.load(last.id); if (session) { @@ -183,24 +214,17 @@ export class AgentChat extends Model { this.sessionCreatedAt = session.createdAt || Date.now(); this.sessionTitle = session.title; this.messages = session.messages as IAgentMessage[]; + this.thinkingSteps = session.thinkingSteps || []; this.hasTitled = true; this.sessionPromptTokens = session.promptTokens || 0; this.sessionCompletionTokens = session.completionTokens || 0; this.sessionTotalDuration = session.totalDuration || 0; + if (this.composer) { + this.composer.restoreHistory(session.messageHistory || []); + } this.titleElement.textContent = session.title; this.updateTokenDisplay(); - for (let i = 0; i < session.messages.length; i++) { - const msg = session.messages[i]; - if (msg.role === "user") { - this.appendUserMessage(msg.content); - } else if (msg.role === "assistant") { - if (msg.toolCalls && msg.toolCalls.length > 0) { - this.appendPersistedToolCalls(msg.content, msg.toolCalls); - } else { - this.appendPersistedAssistant(msg.content); - } - } - } + this.renderLoadedSession(session); this.scrollToBottom(); return; } @@ -346,26 +370,27 @@ export class AgentChat extends Model { totalDuration: this.sessionTotalDuration, createdAt: this.sessionCreatedAt, updatedAt: Date.now(), + messageHistory: this.composer?.getHistory() || [], + thinkingSteps: this.thinkingSteps, }; await SessionStore.save(session); } private async switchSession(id: string) { this.setStreaming(false); - if (this.composer) { - this.messageHistory[this.sessionId] = this.composer.getHistory(); - } + this.flushThinkingStep(); await this.saveSession(); const session = await SessionStore.load(id); if (!session) { return; } this.sessionId = session.id; if (this.composer) { this.composer.clearHistory(); - this.composer.restoreHistory(this.messageHistory[id] || []); + this.composer.restoreHistory(session.messageHistory || []); } this.sessionCreatedAt = session.createdAt || Date.now(); this.sessionTitle = session.title; this.messages = session.messages as IAgentMessage[]; + this.thinkingSteps = session.thinkingSteps || []; this.hasTitled = true; this.currentAIElement = null; this.currentContent = ""; @@ -378,22 +403,12 @@ export class AgentChat extends Model { } this.messagesContainer.innerHTML = ""; this.titleElement.textContent = session.title; - for (let i = 0; i < session.messages.length; i++) { - const msg = session.messages[i]; - if (msg.role === "user") { - this.appendUserMessage(msg.content); - } else if (msg.role === "assistant") { - if (msg.toolCalls && msg.toolCalls.length > 0) { - this.appendPersistedToolCalls(msg.content, msg.toolCalls); - } else { - this.appendPersistedAssistant(msg.content); - } - } - } + this.renderLoadedSession(session); this.scrollToBottom(); } private appendPersistedAssistant(content: string) { + if (!content || !content.trim()) { return; } const el = document.createElement("div"); el.className = "agent-chat__msg agent-chat__msg--ai"; el.innerHTML = '
' + (this.lute.MarkdownStr("", content) || this.escapeHtml(content)) + "
"; @@ -402,50 +417,67 @@ export class AgentChat extends Model { } private appendPersistedToolCalls(content: string, toolCalls: Array<{name: string; arguments: Record; result?: string}>) { - const L = window.siyuan.languages; + let hasRendered = false; for (let i = 0; i < toolCalls.length; i++) { const tc = toolCalls[i]; - const argsStr = JSON.stringify(tc.arguments, null, 2); - const el = document.createElement("div"); - el.className = "agent-chat__msg agent-chat__msg--tool"; - el.innerHTML = '
' + - '
' + - '🛠' + - '' + (L.agentToolCall || "Calling tool") + ": " + tc.name + "" + - "
" + - '
' + this.escapeHtml(argsStr) + "
" + -"
"; - const header = el.querySelector(".agent-chat__tool-header") as HTMLElement; - const body = el.querySelector(".agent-chat__tool-body") as HTMLElement; - header.addEventListener("click", function () { - body.classList.toggle("fn__none"); - }); - this.messagesContainer.appendChild(el); - - if (tc.result) { + if (tc.result && tc.name === "todo_write") { const rel = document.createElement("div"); rel.className = "agent-chat__msg agent-chat__msg--tool"; - if (tc.name === "todo_write") { - rel.innerHTML = this.renderTodoList(tc.result); - } else { - rel.innerHTML = '
' + - '
' + - '📄' + - '' + (L.agentToolResult || "Tool result") + ": " + tc.name + "" + - "
" + - '
' + this.escapeHtml(tc.result) + "
" + -"
"; - const rheader = rel.querySelector(".agent-chat__tool-header") as HTMLElement; - const rbody = rel.querySelector(".agent-chat__tool-body") as HTMLElement; - rheader.addEventListener("click", function () { - rbody.classList.toggle("fn__none"); - }); - } + rel.innerHTML = this.renderTodoList(tc.result); this.messagesContainer.appendChild(rel); + hasRendered = true; } } - if (content) { + if (content && content.trim()) { this.appendPersistedAssistant(content); + hasRendered = true; + } + if (!hasRendered) { + // 无可见内容,不创建 air 空 DOM + return; + } + } + + private renderLoadedSession(session: AgentSession) { + const messages = session.messages as IAgentMessage[]; + const steps = session.thinkingSteps || []; + const groups: Array> = []; + let cur: Array = []; + for (let s = 0; s < steps.length; s++) { + const step = steps[s]; + if (step.reasoning === "analyzing" && cur.length > 0) { + groups.push(cur); + cur = []; + } + cur.push(step); + } + if (cur.length > 0) { + groups.push(cur); + } + let groupIdx = 0; + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + if (msg.role === "user") { + this.appendUserMessage(msg.content); + } else if (msg.role === "assistant") { + if (groupIdx < groups.length) { + for (let s = 0; s < groups[groupIdx].length; s++) { + this.renderSingleThinkingCard(groups[groupIdx][s]); + } + groupIdx++; + } + if (msg.toolCalls && msg.toolCalls.length > 0) { + this.appendPersistedToolCalls(msg.content, msg.toolCalls); + } else { + this.appendPersistedAssistant(msg.content); + } + } + } + while (groupIdx < groups.length) { + for (let s = 0; s < groups[groupIdx].length; s++) { + this.renderSingleThinkingCard(groups[groupIdx][s]); + } + groupIdx++; } } @@ -455,15 +487,18 @@ export class AgentChat extends Model { this.abortController = null; } this.setStreaming(false); + this.flushThinkingStep(); await this.saveSession(); this.sessionId = SessionStore.newSessionId(); this.sessionCreatedAt = Date.now(); + if (this.composer) { this.composer.clearHistory(); } this.sessionTitle = this.defaultTitle; this.messages = []; this.hasTitled = false; this.currentAIElement = null; this.currentContent = ""; this.fullContent = ""; + this.thinkingSteps = []; this.sessionPromptTokens = 0; this.sessionCompletionTokens = 0; this.sessionTotalDuration = 0; @@ -536,6 +571,11 @@ export class AgentChat extends Model { this.appendUserMessage(text); if (this.composer) { this.composer.pushHistory(text); } + if (!this.hasTitled && this.messages.length === 1) { + this.hasTitled = true; + this.generateTitle(); + } + this.requestStartTime = Date.now(); const apiMessages = this.messages.map(function (m) { return {role: m.role as "user" | "assistant", content: m.content}; }); @@ -558,6 +598,7 @@ export class AgentChat extends Model { }, this.abortController.signal, this.sessionId, + this.getSelectedModel(), ); } @@ -600,6 +641,9 @@ export class AgentChat extends Model { case "question": this.appendQuestion(event.questionID, event.arguments); break; + case "reasoning": + this.appendReasoning(event.token); + break; } } catch (e) { console.error("agent SSE event handler error:", e, event); @@ -636,7 +680,7 @@ export class AgentChat extends Model { private appendToken(token: string) { if (!this.currentAIElement) { - this.clearThinking(); + this.finishActiveThinking(); this.currentAIElement = this.createAIMessagePlaceholder(); } this.currentContent += token; @@ -668,47 +712,15 @@ export class AgentChat extends Model { } private appendToolCall(name: string, args: Record) { - const el = document.createElement("div"); - el.className = "agent-chat__msg agent-chat__msg--tool"; - const argsStr = JSON.stringify(args, null, 2); - const L = window.siyuan.languages; - el.innerHTML = '
' + - '
' + - '🛠' + - '' + (L.agentToolCall || "Calling tool") + ": " + name + "" + - "
" + - '
' + this.escapeHtml(argsStr) + "
" + -"
"; - const header = el.querySelector(".agent-chat__tool-header") as HTMLElement; - const body = el.querySelector(".agent-chat__tool-body") as HTMLElement; - header.addEventListener("click", function () { - body.classList.toggle("fn__none"); - }); - this.insertBeforeAI(el); - this.scrollToBottom(); + // Tool calls are tracked in currentToolCalls, no DOM needed } private appendToolResult(name: string, result: string) { + if (name !== "todo_write") { return; } + const el = document.createElement("div"); el.className = "agent-chat__msg agent-chat__msg--tool"; - const L = window.siyuan.languages; - - if (name === "todo_write") { - el.innerHTML = this.renderTodoList(result); - } else { - el.innerHTML = '
' + - '
' + - '📄' + - '' + (L.agentToolResult || "Tool result") + ": " + name + "" + - "
" + - '
' + this.escapeHtml(result) + "
" + -"
"; - const header = el.querySelector(".agent-chat__tool-header") as HTMLElement; - const body = el.querySelector(".agent-chat__tool-body") as HTMLElement; - header.addEventListener("click", function () { - body.classList.toggle("fn__none"); - }); - } + el.innerHTML = this.renderTodoList(result); this.insertBeforeAI(el); this.scrollToBottom(); } @@ -738,6 +750,20 @@ export class AgentChat extends Model { } private appendThinking(reasoning: string) { + if (this.currentThinkingText) { + const tc = this.currentToolCalls.map(function (t) { return {name: t.name, result: t.result}; }); + this.thinkingSteps.push({ + reasoning: this.currentThinkingReasoning, + text: this.currentThinkingText, + toolCalls: tc, + reasoningContent: this.currentThinkingReasoningContent, + }); + this.saveSession(); + } + this.finishActiveThinking(); + this.currentThinkingText = ""; + this.currentThinkingReasoning = reasoning; + this.currentThinkingReasoningContent = ""; const L = window.siyuan.languages; let text = reasoning; let roundLabel = ""; @@ -749,17 +775,15 @@ export class AgentChat extends Model { roundLabel = "Continuing..."; } + this.currentThinkingText = text; + let detailLines = ""; - if (reasoning === "processing") { - const toolCards = this.messagesContainer.querySelectorAll(".agent-chat__tool-card--call"); - if (toolCards.length > 0) { - detailLines += '
' + (L.agentToolCall || "Tool call") + "s:
"; - for (let i = 0; i < toolCards.length; i++) { - const name = toolCards[i].getAttribute("data-tool") || ""; - if (name) { - detailLines += '
' + this.escapeHtml(name) + "
"; - } - } + if (reasoning === "processing" && this.currentToolCalls.length > 0) { + detailLines += '
' + (L.agentToolCall || "Tool call") + "s:
"; + for (let i = 0; i < this.currentToolCalls.length; i++) { + const tc = this.currentToolCalls[i]; + const name = tc.name + (tc.result ? " \u2713" : " \u25CC"); + detailLines += '
' + this.escapeHtml(name) + "
"; } } @@ -774,7 +798,10 @@ export class AgentChat extends Model { '
' + '' + '' + this.escapeHtml(text) + "" + - '▾' + + '' + + '' + + '' + + "" + "
" + bodyHTML + "
"; @@ -790,16 +817,25 @@ export class AgentChat extends Model { const header = el.querySelector(".agent-chat__thinking-header") as HTMLElement; const body = el.querySelector(".agent-chat__thinking-body") as HTMLElement; - const arrow = el.querySelector(".agent-chat__thinking-arrow") as HTMLElement; + const expandIcon = el.querySelector(".agent-chat__thinking-arrow--expand") as HTMLElement; + const contractIcon = el.querySelector(".agent-chat__thinking-arrow--contract") as HTMLElement; header.addEventListener("click", function () { body.classList.toggle("fn__none"); const isHidden = body.classList.contains("fn__none"); - arrow.innerHTML = isHidden ? "▾" : "▴"; + expandIcon.classList.toggle("fn__none", !isHidden); + contractIcon.classList.toggle("fn__none", isHidden); }); this.insertBeforeAI(el); this.scrollToBottom(); } + private appendReasoning(token: string) { + this.currentThinkingReasoningContent += token; + const thinking = this.messagesContainer.querySelector(".agent-chat__msg--thinking:last-child .agent-chat__thinking-body"); + if (!thinking) { return; } + thinking.innerHTML += token; + } + private finalizeCurrentRound() { if (!this.currentAIElement) { return; @@ -862,6 +898,13 @@ export class AgentChat extends Model { if (all[i].classList.contains("agent-chat__msg--user")) { break; } all[i].remove(); } + // Remove last group of thinking steps + for (let i = this.thinkingSteps.length - 1; i >= 0; i--) { + if (this.thinkingSteps[i].reasoning === "analyzing") { + this.thinkingSteps.splice(i); + break; + } + } this.currentAIElement = null; this.currentContent = ""; this.fullContent = ""; @@ -887,20 +930,18 @@ export class AgentChat extends Model { }, this.abortController.signal, this.sessionId, + this.getSelectedModel(), ); } private finishResponse() { if (!this.currentAIElement) { - return; - } - this.flushTokenUpdate(); - this.clearThinking(); - if (!this.currentContent) { - this.currentAIElement.remove(); - this.currentAIElement = null; - this.currentContent = ""; - this.fullContent = ""; + if (this.currentToolCalls.length === 0) { + this.setStreaming(false); + return; + } + this.flushThinkingStep(); + this.messages.push({role: "assistant", content: "", toolCalls: this.currentToolCalls.slice()}); this.currentToolCalls = []; if (this.requestStartTime) { this.sessionTotalDuration += Date.now() - this.requestStartTime; @@ -908,11 +949,26 @@ export class AgentChat extends Model { } this.updateTokenDisplay(); this.setStreaming(false); - // line 754 area - if (!this.hasTitled && this.messages.length >= 2) { - this.hasTitled = true; - this.generateTitle(); + this.saveSession(); + return; + } + this.flushTokenUpdate(); + if (!this.currentContent) { + this.currentAIElement.remove(); + this.currentAIElement = null; + this.currentContent = ""; + this.fullContent = ""; + if (this.currentToolCalls.length > 0) { + this.flushThinkingStep(); + this.messages.push({role: "assistant", content: "", toolCalls: this.currentToolCalls.slice()}); } + this.currentToolCalls = []; + if (this.requestStartTime) { + this.sessionTotalDuration += Date.now() - this.requestStartTime; + this.requestStartTime = 0; + } + this.updateTokenDisplay(); + this.setStreaming(false); this.saveSession(); return; } @@ -925,6 +981,7 @@ export class AgentChat extends Model { this.currentAIElement = null; this.currentContent = ""; this.fullContent = ""; + this.flushThinkingStep(); this.currentToolCalls = []; if (this.requestStartTime) { this.sessionTotalDuration += Date.now() - this.requestStartTime; @@ -933,10 +990,21 @@ export class AgentChat extends Model { this.updateTokenDisplay(); this.setStreaming(false); - if (!this.hasTitled && this.messages.length >= 2) { - this.hasTitled = true; - this.generateTitle(); + this.saveSession(); + } + + private flushThinkingStep() { + if (!this.currentThinkingText) { + return; } + const tc = this.currentToolCalls.map(function (t) { return {name: t.name, result: t.result}; }); + this.thinkingSteps.push({ + reasoning: this.currentThinkingReasoning, + text: this.currentThinkingText, + toolCalls: tc, + reasoningContent: this.currentThinkingReasoningContent, + }); + this.currentThinkingText = ""; this.saveSession(); } @@ -967,6 +1035,7 @@ export class AgentChat extends Model { el.innerHTML = '
' + this.escapeHtml(message) + "
"; this.messagesContainer.appendChild(el); this.scrollToBottom(); + this.flushThinkingStep(); this.saveSession(); } @@ -1011,6 +1080,8 @@ export class AgentChat extends Model { } this.updateTokenDisplay(); this.setStreaming(false); + this.flushThinkingStep(); + this.saveSession(); } private insertBeforeAI(el: HTMLElement) { @@ -1183,6 +1254,49 @@ export class AgentChat extends Model { } } + private renderSingleThinkingCard(step: {reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}) { + let detail = ""; + if (step.toolCalls.length > 0) { + detail += '
Tool calls:
'; + for (let j = 0; j < step.toolCalls.length; j++) { + const tc = step.toolCalls[j]; + detail += '
' + this.escapeHtml(tc.name + (tc.result ? " \u2713" : " \u25CC")) + "
"; + } + } + if (step.reasoningContent) { + detail += '
Reasoning:
'; + detail += '
' + this.escapeHtml(step.reasoningContent) + "
"; + } + + const el = document.createElement("div"); + el.className = "agent-chat__msg agent-chat__msg--thinking agent-chat__msg--thinking-done"; + el.innerHTML = '
' + + '
' + + '' + + '' + this.escapeHtml(step.text) + "" + + '' + + '' + + '' + + "" + + "
" + + '
' + + detail + + "
" + +"
"; + + const header = el.querySelector(".agent-chat__thinking-header") as HTMLElement; + const body = el.querySelector(".agent-chat__thinking-body") as HTMLElement; + const expandIcon = el.querySelector(".agent-chat__thinking-arrow--expand") as HTMLElement; + const contractIcon = el.querySelector(".agent-chat__thinking-arrow--contract") as HTMLElement; + header.addEventListener("click", function () { + body.classList.toggle("fn__none"); + const isHidden = body.classList.contains("fn__none"); + expandIcon.classList.toggle("fn__none", !isHidden); + contractIcon.classList.toggle("fn__none", isHidden); + }); + this.messagesContainer.appendChild(el); + } + private updateTokenDisplay() { if (!this.tokenDisplayEl) { return; @@ -1215,6 +1329,22 @@ export class AgentChat extends Model { } } + private finishActiveThinking() { + const items = this.messagesContainer.querySelectorAll(".agent-chat__msg--thinking"); + for (let i = 0; i < items.length; i++) { + const el = items[i] as HTMLElement; + el.classList.add("agent-chat__msg--thinking-done"); + const dot = el.querySelector(".agent-chat__thinking-dot"); + if (dot) { dot.classList.add("fn__none"); } + const textEl = el.querySelector(".agent-chat__thinking-text"); + if (textEl) { + const raw = textEl.textContent || ""; + if (raw.indexOf("分析") >= 0) { textEl.textContent = raw.replace("正在分析", "已分析"); } + else if (raw.indexOf("处理") >= 0) { textEl.textContent = raw.replace("正在处理", "已处理"); } + } + } + } + private setStreaming(streaming: boolean) { this.isStreaming = streaming; this.sendBtn.classList.toggle("fn__none", streaming); diff --git a/app/src/layout/dock/AgentComposer.ts b/app/src/layout/dock/AgentComposer.ts index 9be66ba6a..4563d7690 100644 --- a/app/src/layout/dock/AgentComposer.ts +++ b/app/src/layout/dock/AgentComposer.ts @@ -52,6 +52,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHa const history: string[] = []; let historyIdx = -1; + let savedDraft = ""; const updateHighlight = () => { if (!suggestionMenu) { return; } @@ -212,11 +213,15 @@ export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHa return true; } if (event.key === "ArrowUp" && !suggestionMenu) { - const isEmpty = _view.state.doc.textContent.trim() === ""; - if (isEmpty && history.length > 0) { + const navigating = historyIdx >= 0; + const isEmpty = _view.state.doc.childCount === 1 && + _view.state.doc.firstChild?.childCount === 0; + if ((navigating || isEmpty) && history.length > 0) { event.preventDefault(); - if (historyIdx === -1) { historyIdx = history.length - 1; } - else if (historyIdx > 0) { historyIdx--; } + if (historyIdx === -1) { + savedDraft = editor.state.doc.textContent; + historyIdx = history.length - 1; + } else if (historyIdx > 0) { historyIdx--; } if (historyIdx >= 0) { editor.commands.setContent(history[historyIdx]); } @@ -228,12 +233,17 @@ export function mountComposer(host: HTMLElement, onSend: () => void): ComposerHa historyIdx++; if (historyIdx >= history.length) { historyIdx = -1; - editor.commands.clearContent(); + editor.commands.setContent(savedDraft || ""); + savedDraft = ""; } else { editor.commands.setContent(history[historyIdx]); } return true; } + if (historyIdx >= 0 && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { + historyIdx = -1; + savedDraft = ""; + } return false; }, }, diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts index f707432b4..29f6dea0d 100644 --- a/app/src/layout/dock/SessionStore.ts +++ b/app/src/layout/dock/SessionStore.ts @@ -25,6 +25,13 @@ export interface AgentSession { promptTokens?: number; completionTokens?: number; totalDuration?: number; + messageHistory?: string[]; + thinkingSteps?: Array<{ + reasoning: string; + text: string; + toolCalls: Array<{name: string; result?: string}>; + reasoningContent: string; + }>; createdAt: number; updatedAt: number; } diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.ts index 80a86cefd..7a0adeaa1 100644 --- a/app/src/util/agentSSE.ts +++ b/app/src/util/agentSSE.ts @@ -34,6 +34,9 @@ export type ISSEResult = { type: "question"; questionID: string; arguments: Record; +} | { + type: "reasoning"; + token: string; }; export async function fetchAgentSSE( @@ -44,10 +47,12 @@ export async function fetchAgentSSE( onError: (err: Error) => void, signal?: AbortSignal, sessionID?: string, + model?: string, ): Promise { try { const body: Record = {messages: messages, language: language, references: references}; if (sessionID) { body.sessionID = sessionID; } + if (model) { body.model = model; } const response = await fetch("/api/ai/agent/chat", { method: "POST", @@ -177,6 +182,8 @@ function buildSSEResult(event: string, data: Record): ISSEResul questionID: data.questionID as string, arguments: (data.arguments || {}) as Record, }; + case "reasoning": + return {type: "reasoning", token: data.token as string}; default: return null; } diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go index 68a36d695..02b0f0710 100644 --- a/kernel/agent/agent.go +++ b/kernel/agent/agent.go @@ -159,15 +159,29 @@ type Reference struct { Title string `json:"title"` } +type checkpointThinkingStep struct { + Reasoning string `json:"reasoning"` + Text string `json:"text"` + ToolCalls []checkpointBriefTC `json:"toolCalls"` + ReasoningContent string `json:"reasoningContent"` +} + +type checkpointBriefTC struct { + Name string `json:"name"` + Result string `json:"result,omitempty"` +} + type agentCheckpoint struct { - ID string `json:"id"` - Title string `json:"title"` - Messages []AgentMessage `json:"messages"` - PromptTokens int `json:"promptTokens"` - CompletionTokens int `json:"completionTokens"` - TotalDuration int64 `json:"totalDuration"` - CreatedAt int64 `json:"createdAt"` - UpdatedAt int64 `json:"updatedAt"` + ID string `json:"id"` + Title string `json:"title"` + Messages []AgentMessage `json:"messages"` + PromptTokens int `json:"promptTokens"` + CompletionTokens int `json:"completionTokens"` + TotalDuration int64 `json:"totalDuration"` + CreatedAt int64 `json:"createdAt"` + UpdatedAt int64 `json:"updatedAt"` + MessageHistory []string `json:"messageHistory,omitempty"` + ThinkingSteps []checkpointThinkingStep `json:"thinkingSteps,omitempty"` } func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, history []UserMessage, language string, references []Reference, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent { @@ -263,6 +277,10 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session sendEvent(ch, AgentEvent{Type: "content", Token: choice.Delta.Content}) } + if choice.Delta.ReasoningContent != "" { + sendEvent(ch, AgentEvent{Type: "reasoning", Token: choice.Delta.ReasoningContent}) + } + for _, tcd := range choice.Delta.ToolCalls { idx := 0 if tcd.Index != nil { @@ -419,7 +437,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session } content := contentBuilder.String() - checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content}) + if content != "" { + checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content}) + } saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime) if content == "" { content = " " @@ -652,6 +672,12 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int, if old.CreatedAt > 0 { cp.CreatedAt = old.CreatedAt } + if len(old.MessageHistory) > 0 { + cp.MessageHistory = old.MessageHistory + } + if len(old.ThinkingSteps) > 0 { + cp.ThinkingSteps = old.ThinkingSteps + } } data, err := json.MarshalIndent(cp, "", " ") diff --git a/kernel/api/agent.go b/kernel/api/agent.go index 0f8691c0f..050a57fae 100644 --- a/kernel/api/agent.go +++ b/kernel/api/agent.go @@ -36,6 +36,7 @@ type agentChatReq struct { Messages []agent.UserMessage `json:"messages"` Language string `json:"language"` References []agent.Reference `json:"references"` + Model string `json:"model,omitempty"` } type runningSession struct { @@ -46,7 +47,7 @@ var sessionsMu sync.Mutex var runningSessions = map[string]*runningSession{} func agentChat(c *gin.Context) { - if "" == model.Conf.AI.OpenAI.APIKey { + if !model.Conf.AI.HasAnyProvider() { ret := gulu.Ret.NewResult() ret.Code = -1 ret.Msg = model.Conf.Language(193) @@ -63,27 +64,28 @@ func agentChat(c *gin.Context) { return } + selectedProvider := model.Conf.AI.GetProvider(req.Model) client := util.NewOpenAIClient( - model.Conf.AI.OpenAI.APIKey, - model.Conf.AI.OpenAI.APIProxy, - model.Conf.AI.OpenAI.APIBaseURL, - model.Conf.AI.OpenAI.APIUserAgent, - model.Conf.AI.OpenAI.APIVersion, - model.Conf.AI.OpenAI.APIProvider, + selectedProvider.APIKey, + selectedProvider.APIProxy, + selectedProvider.APIBaseURL, + selectedProvider.APIUserAgent, + selectedProvider.APIVersion, + selectedProvider.APIProvider, ) - confirmTimeout := time.Duration(model.Conf.AI.OpenAI.AgentConfirmTimeout) * time.Second + confirmTimeout := time.Duration(selectedProvider.AgentConfirmTimeout) * time.Second if confirmTimeout <= 0 { confirmTimeout = 120 * time.Second } - maxRetries := model.Conf.AI.OpenAI.AgentMaxRetries + maxRetries := selectedProvider.AgentMaxRetries if maxRetries <= 0 { maxRetries = 3 } var eventCh <-chan agent.AgentEvent - eventCh = agent.AgentChat(context.Background(), client, model.Conf.AI.OpenAI.APIModel, req.SessionID, req.Messages, req.Language, req.References, confirmTimeout, maxRetries) + eventCh = agent.AgentChat(context.Background(), client, selectedProvider.APIModel, req.SessionID, req.Messages, req.Language, req.References, confirmTimeout, maxRetries) sessionsMu.Lock() runningSessions[req.SessionID] = &runningSession{eventCh: eventCh} sessionsMu.Unlock() @@ -97,11 +99,11 @@ func agentChat(c *gin.Context) { return } - timeout := model.Conf.AI.OpenAI.APITimeout + timeout := selectedProvider.APITimeout if timeout <= 0 { timeout = 30 } - totalTimeout := time.Duration(model.Conf.AI.OpenAI.AgentTimeout) * time.Second + totalTimeout := time.Duration(selectedProvider.AgentTimeout) * time.Second if totalTimeout <= 0 { totalTimeout = time.Duration(timeout) * time.Second * 10 } @@ -184,16 +186,17 @@ func agentChatTitle(c *gin.Context) { return } + selectedProvider := model.Conf.AI.GetProvider("") client := util.NewOpenAIClient( - model.Conf.AI.OpenAI.APIKey, - model.Conf.AI.OpenAI.APIProxy, - model.Conf.AI.OpenAI.APIBaseURL, - model.Conf.AI.OpenAI.APIUserAgent, - model.Conf.AI.OpenAI.APIVersion, - model.Conf.AI.OpenAI.APIProvider, + selectedProvider.APIKey, + selectedProvider.APIProxy, + selectedProvider.APIBaseURL, + selectedProvider.APIUserAgent, + selectedProvider.APIVersion, + selectedProvider.APIProvider, ) - title := agent.GenerateTitle(client, model.Conf.AI.OpenAI.APIModel, req.Message) + title := agent.GenerateTitle(client, selectedProvider.APIModel, req.Message) ret := gulu.Ret.NewResult() ret.Data = title c.JSON(http.StatusOK, ret) @@ -205,6 +208,8 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error { return writeSSEEvent(c, "content", map[string]string{"token": event.Token}) case "thinking": return writeSSEEvent(c, "thinking", map[string]string{"reasoning": event.Reasoning}) + case "reasoning": + return writeSSEEvent(c, "reasoning", map[string]string{"token": event.Token}) case "confirm": return writeSSEEvent(c, "confirm", map[string]interface{}{ "name": event.Name, diff --git a/kernel/cli/cmd/attr.go b/kernel/cli/cmd/attr.go index 808271592..8f44d7e6e 100644 --- a/kernel/cli/cmd/attr.go +++ b/kernel/cli/cmd/attr.go @@ -59,6 +59,18 @@ var attrGetCmd = &cobra.Command{ var attrSetCmd = &cobra.Command{ Use: "set --id --attr name=value", Short: "Set block attributes", + Long: `Set custom attributes on a block. + +Common attributes: + icon Emoji hex codepoint (e.g. "1f4ca"), emoji character (e.g. "📊"), custom image path (e.g. "1/b3log.png"), or dynamic icon URL (e.g. + "api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx"). + title-img CSS background-image format (e.g. 'background-image:url("assets/example.jpg")'). + DO NOT use a bare asset path. + tags Comma-separated tag names. + +Examples: + siyuan-kernel attr set --id 20260605100657-v080a4j --attr icon=1f4ca + siyuan-kernel attr set --id 20260605100657-v080a4j --attr title-img='background-image:url("assets/example.jpg")'`, RunE: func(cmd *cobra.Command, args []string) error { id, _ := cmd.Flags().GetString("id") if id == "" { diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go index 38aeeefb0..3b41a51e5 100644 --- a/kernel/conf/ai.go +++ b/kernel/conf/ai.go @@ -26,8 +26,9 @@ import ( ) type AI struct { - OpenAI *OpenAI `json:"openAI"` - MCP *MCPConfig `json:"mcp"` + OpenAI *OpenAI `json:"openAI"` + MCP *MCPConfig `json:"mcp"` + Providers []*OpenAI `json:"providers,omitempty"` } type MCPConfig struct { @@ -63,6 +64,7 @@ type OpenAI struct { AgentTimeout int `json:"agentTimeout"` // total session timeout, seconds, 0 = no limit AgentConfirmTimeout int `json:"agentConfirmTimeout"` // confirmation timeout, seconds AgentMaxRetries int `json:"agentMaxRetries"` // max API retry attempts on failure + Enabled *bool `json:"enabled,omitempty"` } func NewAI() *AI { @@ -146,3 +148,39 @@ func NewAI() *AI { } return &AI{OpenAI: openAI} } + +func (p *OpenAI) IsEnabled() bool { + return p.Enabled == nil || *p.Enabled +} + +func (ai *AI) HasAnyProvider() bool { + if ai.OpenAI != nil && ai.OpenAI.APIKey != "" && ai.OpenAI.IsEnabled() { + return true + } + for _, p := range ai.Providers { + if p != nil && p.APIKey != "" && p.IsEnabled() { + return true + } + } + return false +} + +func (ai *AI) GetProvider(model string) *OpenAI { + if model == "" { + if ai.OpenAI != nil && ai.OpenAI.IsEnabled() && ai.OpenAI.APIKey != "" { + return ai.OpenAI + } + for _, p := range ai.Providers { + if p != nil && p.IsEnabled() && p.APIKey != "" { + return p + } + } + return ai.OpenAI + } + for _, p := range ai.Providers { + if p != nil && p.APIModel == model && p.IsEnabled() && p.APIKey != "" { + return p + } + } + return ai.OpenAI +} diff --git a/kernel/mcp/handler.go b/kernel/mcp/handler.go index 4329d86cb..994493b84 100644 --- a/kernel/mcp/handler.go +++ b/kernel/mcp/handler.go @@ -133,8 +133,8 @@ func handleToolsCall(req *JsonRpcRequest) any { } } - t, exists := tools.Registry[toolName] - if !exists { + t := tools.LookupTool(toolName) + if t == nil { return &JsonRpcResponse{ JsonRpc: "2.0", Result: tools.CallToolResult{ diff --git a/kernel/mcp/tools/attr.go b/kernel/mcp/tools/attr.go index 352e619ea..229c979e2 100644 --- a/kernel/mcp/tools/attr.go +++ b/kernel/mcp/tools/attr.go @@ -33,7 +33,7 @@ var AttrTool = &Tool{ "action": {Type: "string", Description: "Operation", Enum: []string{"get", "set", "batch-get"}}, "id": {Type: "string", Description: "Block ID"}, "ids": {Type: "string", Description: "Comma-separated block IDs (for batch-get)"}, - "attrs": {Type: "object", Description: "Attribute key-value pairs (for set). Note: title-img value must use CSS format like 'background-image:url(\"assets/example.jpg\")', not just the asset path"}, + "attrs": {Type: "object", Description: "Attribute key-value pairs (for set).\nCommon attributes:\n- icon: emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\"\n- title-img: CSS format like 'background-image:url(\"assets/example.jpg\")', NOT a bare asset path\n- tags: comma-separated tag names"}, }, Required: []string{"action"}, }, diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go index 160862888..e86989bf4 100644 --- a/kernel/mcp/tools/document.go +++ b/kernel/mcp/tools/document.go @@ -27,7 +27,7 @@ import ( var DocumentTool = &Tool{ Name: "document", - Description: "Document operations for SiYuan notebooks.\n- get: Get document content by ID. Requires: id.\n- create: Create a new document. Requires: notebook, path (hPath, e.g. /folder/doc), title. Optional: markdown.\n- list: List documents at an hPath. Requires: notebook. Optional: path (hPath, default /).\n- delete: Delete a document by ID. Requires: id.\n- rename: Rename a document by ID. Requires: id, title.\n- move: Move a document to a different notebook/hPath. Requires: id, notebook, path (target hPath, e.g. /folder or / for root).\n- duplicate: Duplicate a document by ID. Requires: id.\n- search_docs: Search documents by keyword. Requires: keyword.", + Description: "Document operations for SiYuan.\n- get: Get document content by ID. Requires: id.\n- create: Create a new document. Requires: notebook, path (hPath, e.g. /folder/doc), title. Optional: markdown.\n- list: List documents at an hPath. Requires: notebook. Optional: path (hPath, default /).\n- delete: Delete a document by ID. Requires: id.\n- rename: Rename a document by ID. Requires: id, title.\n- move: Move a document to a different notebook/hPath. Requires: id, notebook, path (target hPath, e.g. /folder or / for root).\n- duplicate: Duplicate a document by ID. Requires: id.\n- search_docs: Search documents by keyword. Requires: keyword.", InputSchema: ToolSchema{ Type: "object", Properties: map[string]Property{ diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.go index a40c7c80f..22ffc0a73 100644 --- a/kernel/mcp/tools/register.go +++ b/kernel/mcp/tools/register.go @@ -16,15 +16,45 @@ package tools -import "sync" +import ( + "strings" + "sync" +) var registryMu sync.RWMutex var Registry = map[string]*Tool{} func GetTool(name string) *Tool { + return LookupTool(name) +} + +func LookupTool(name string) *Tool { registryMu.RLock() defer registryMu.RUnlock() - return Registry[name] + + name = strings.TrimSpace(name) + + if t := Registry[name]; t != nil { + return t + } + + lower := strings.ToLower(name) + for k, v := range Registry { + if strings.ToLower(k) == lower { + return v + } + } + + if prefix := "siyuan_"; strings.HasPrefix(lower, prefix) { + base := strings.TrimPrefix(lower, prefix) + for k, v := range Registry { + if strings.ToLower(k) == base { + return v + } + } + } + + return nil } func GetAllTools() []*Tool { diff --git a/kernel/model/blockial.go b/kernel/model/blockial.go index 246c04b21..f129f9270 100644 --- a/kernel/model/blockial.go +++ b/kernel/model/blockial.go @@ -19,6 +19,7 @@ package model import ( "errors" "fmt" + "strconv" "strings" "time" @@ -277,6 +278,10 @@ func setNodeAttrs0(node *ast.Node, nameValues map[string]string) (oldAttrs map[s } } + if lowerName == "icon" && "" != value { + value = normalizeIconValue(value) + } + if "" == value { // 删除属性 if name != lowerName { @@ -349,6 +354,29 @@ func validateChars(name string, startIdx, n int) bool { return true } +func normalizeIconValue(value string) string { + if strings.ContainsAny(value, "./") { + return value + } + + allASCII := true + for _, r := range value { + if r > 127 { + allASCII = false + break + } + } + if allASCII { + return value + } + + var parts []string + for _, r := range value { + parts = append(parts, strconv.FormatInt(int64(r), 16)) + } + return strings.Join(parts, "-") +} + func pushBlockAttrs(oldAttrs map[string]string, node *ast.Node) { newAttrs := parse.IAL2Map(node.KramdownIAL) data := map[string]any{"old": oldAttrs, "new": newAttrs} diff --git a/kernel/model/conf.go b/kernel/model/conf.go index 61863cd26..7a9cb7811 100644 --- a/kernel/model/conf.go +++ b/kernel/model/conf.go @@ -570,6 +570,10 @@ func InitConf() { if 1 > Conf.AI.OpenAI.APIMaxContexts || 64 < Conf.AI.OpenAI.APIMaxContexts { Conf.AI.OpenAI.APIMaxContexts = 7 } + if nil == Conf.AI.OpenAI.Enabled && Conf.AI.OpenAI.APIBaseURL != "" && Conf.AI.OpenAI.APIKey != "" { + t := true + Conf.AI.OpenAI.Enabled = &t + } if "" != Conf.AI.OpenAI.APIKey { logging.LogInfof("OpenAI API enabled\n"+ diff --git a/kernel/server/proxy/fixedport.go b/kernel/server/proxy/fixedport.go index ca36df053..1929a359d 100644 --- a/kernel/server/proxy/fixedport.go +++ b/kernel/server/proxy/fixedport.go @@ -28,7 +28,7 @@ import ( "github.com/soheilhy/cmux" ) -func InitFixedPortService(host string, useTLS bool, certPath, keyPath string) { +func InitFixedPortService(host string, certPath, keyPath string) { if util.FixedPort != util.ServerPort { if util.IsPortOpen(util.FixedPort) { return @@ -38,17 +38,16 @@ func InitFixedPortService(host string, useTLS bool, certPath, keyPath string) { // 启动一个固定 6806 端口的反向代理服务器,这样浏览器扩展才能直接使用 127.0.0.1:6806,不用配置端口 proxy := httputil.NewSingleHostReverseProxy(util.ServerURL) + proxy.Transport = &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } - if useTLS { - proxy.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - + if "" != certPath { logging.LogInfof("fixed port service [%s] is running (HTTP/HTTPS dual mode)", addr) - ln, err := net.Listen("tcp", addr) - if err != nil { - logging.LogWarnf("boot fixed port service [%s] failed: %s", addr, err) + ln, listenErr := net.Listen("tcp", addr) + if listenErr != nil { + logging.LogWarnf("boot fixed port service [%s] failed: %s", addr, listenErr) return } diff --git a/kernel/server/serve.go b/kernel/server/serve.go index 34c0d8109..ce4a45186 100644 --- a/kernel/server/serve.go +++ b/kernel/server/serve.go @@ -135,7 +135,6 @@ var ( func Serve(fastMode bool, cookieKey string) { gin.SetMode(gin.ReleaseMode) ginServer := gin.New() - ginServer.UseH2C = true ginServer.MaxMultipartMemory = 1024 * 1024 * 32 // 插入较大的资源文件时内存占用较大 https://github.com/siyuan-note/siyuan/issues/5023 ginServer.Use( model.ControlConcurrency, // 请求串行化 Concurrency control when requesting the kernel API https://github.com/siyuan-note/siyuan/issues/9939 @@ -205,7 +204,18 @@ func Serve(fastMode bool, cookieKey string) { model.Conf.ServerAddrs = util.GetServerAddrs() model.Conf.Save() - util.ServerURL, err = url.Parse("http://127.0.0.1:" + port) + // Generate TLS certificates for local HTTPS + HTTP/2 support + certPath, keyPath, certErr := util.GetOrCreateTLSCert() + if certErr != nil { + logging.LogWarnf("failed to get TLS certificates, local HTTPS/HTTP2 unavailable: %s", certErr) + certPath = "" + } + + if "" != certPath { + util.ServerURL, err = url.Parse("https://127.0.0.1:" + port) + } else { + util.ServerURL, err = url.Parse("http://127.0.0.1:" + port) + } if err != nil { logging.LogErrorf("parse server url failed: %s", err) } @@ -215,21 +225,11 @@ func Serve(fastMode bool, cookieKey string) { rewritePortJSON(pid, port) } - // Prepare TLS if enabled - var certPath, keyPath string useTLS := model.Conf.System.NetworkServeTLS && model.Conf.System.NetworkServe if useTLS { - // Ensure TLS certificates exist (proxy will use them directly) - var tlsErr error - certPath, keyPath, tlsErr = util.GetOrCreateTLSCert() - if tlsErr != nil { - logging.LogErrorf("failed to get TLS certificates: %s", tlsErr) - if !fastMode { - os.Exit(logging.ExitCodeUnavailablePort) - } - return - } logging.LogInfof("kernel [pid=%s] http server [%s] is booting (TLS will be enabled on fixed port proxy)", pid, host+":"+port) + } else if "" != certPath { + logging.LogInfof("kernel [pid=%s] http server [%s] is booting (local HTTPS + HTTP/2 enabled)", pid, host+":"+port) } else { logging.LogInfof("kernel [pid=%s] http server [%s] is booting", pid, host+":"+port) } @@ -239,21 +239,17 @@ func Serve(fastMode bool, cookieKey string) { go func() { time.Sleep(1 * time.Second) - go proxy.InitFixedPortService(host, useTLS, certPath, keyPath) + go proxy.InitFixedPortService(host, certPath, keyPath) go proxy.InitPublishService() // 反代服务器启动失败不影响核心服务器启动 }() httpHandler := ginServer.Handler() - p := &http.Protocols{} - p.SetHTTP1(true) - p.SetUnencryptedHTTP2(true) util.HttpServer = &http.Server{ - Handler: httpHandler, - Protocols: p, + Handler: httpHandler, } - if useTLS && (util.FixedPort == util.ServerPort || util.IsPortOpen(util.FixedPort)) { + if "" != certPath { if err = util.ServeMultiplexed(ln, httpHandler, certPath, keyPath, util.HttpServer); err != nil { if errors.Is(err, http.ErrServerClosed) || errors.Is(err, cmux.ErrListenerClosed) { return