An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Keep Agent question content outside thinking https://github.com/siyuan-note/siyuan/issues/18726
Danielfa537eada8a2
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 1ded40d306..12867d354e 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -104,7 +104,14 @@ type SessionEntry =timestamp?: number})| (EntryBase & { type: "confirm"; name: string; args: Record<string, unknown>; confirmID: string; effects?: IToolEffects; status?: string })- | (EntryBase & { type: "question"; questionID: string; questions: Array<Record<string, unknown>>; status?: string; answers?: string[] })+ | (EntryBase & {+ type: "question";+ questionID: string;+ questions: Array<Record<string, unknown>>;+ roundID?: string;+ status?: string;+ answers?: string[]+})| (EntryBase & { type: "todo"; result: string; callID?: string; roundID?: string })| (EntryBase & { type: "snapshot"; snapshotID: string; roundID?: string })| (EntryBase & { type: "rollback"; snapshotID: string });@@ -2068,7 +2075,7 @@ export class AgentChat extends Model {this.appendRetry(event.attempt, event.maxRetries);break;case "question":- this.appendQuestion(event.questionID, event.arguments);+ this.appendQuestion(event.questionID, event.arguments, event.roundID);break;case "reasoning":this.appendReasoning(event.token);@@ -3452,9 +3459,29 @@ export class AgentChat extends Model {}}- private appendQuestion(questionID: string, args: Record<string, unknown>) {+ private appendQuestion(questionID: string, args: Record<string, unknown>, roundID?: string) {+ this.flushTokenUpdate();+ const content = this.currentContent;this.finishActiveThinking();this.flushThinkingStep();+ const timestamp = Date.now();+ if (this.currentAIElement) {+ if (content.trim()) {+ this.finalizeStreamingBody(content, timestamp);+ } else {+ this.currentAIElement.remove();+ }+ this.currentAIElement = null;+ this.observeStickTarget(null);+ } else if (content.trim()) {+ this.appendPersistedAssistant(+ content,+ timestamp,+ this.currentAssistantEntryId || SessionStore.newSessionId(),+ );+ }+ this.currentAssistantEntryId = "";+ this.currentContent = "";const L = window.siyuan.languages;const rawQuestions = args.questions as Array<Record<string, unknown>>;if (!rawQuestions || rawQuestions.length === 0) {@@ -3474,6 +3501,7 @@ export class AgentChat extends Model {type: "question",questionID: questionID,questions: rawQuestions,+ roundID: roundID || this.currentRoundID || undefined,status: "pending",});diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.tsindex 93f57d81ac..ef112b8690 100644--- a/app/src/layout/dock/agent/AgentHistory.test.ts+++ b/app/src/layout/dock/agent/AgentHistory.test.ts@@ -144,6 +144,122 @@ describe("AgentHistory", () => {]);});+ it("renders question content before its question card instead of inside thinking", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "choose"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{+ roundID: "round-1",+ reasoningContent: "partial reasoning",+ toolNames: ["question"],+ toolCallIDs: ["call-question"],+ content: "Choose a color",+ }],+ },+ {id: "question-1", type: "question", roundID: "round-1"},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "Choose a color",+ reasoningContent: "authoritative reasoning",+ toolCalls: [{id: "call-question", name: "question"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);++ assert.deepEqual(display.map(entry => entry.id), [+ "user-1", "thinking-1", "assistant-1", "question-1", "assistant-2",+ ]);+ assert.equal(display.find(entry => entry.id === "thinking-1")?.steps?.[0].content, undefined);+ assert.equal(display.find(entry => entry.id === "thinking-1")?.steps?.[0].reasoningContent,+ "authoritative reasoning");+ assert.deepEqual(display.filter(entry => entry.type === "assistant" && entry.content?.trim())+ .map(entry => entry.content), ["Choose a color", "Done"]);+ });++ it("restores legacy question content without question round IDs", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "choose"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{+ reasoningContent: "reasoning",+ toolNames: ["question"],+ content: "Choose a color",+ }],+ },+ {id: "question-1", type: "question"},+ {+ id: "assistant-1",+ type: "assistant",+ content: "Choose a color",+ toolCalls: [{name: "question"}],+ },+ ]);++ assert.deepEqual(display.map(entry => entry.id), [+ "user-1", "thinking-1", "assistant-1", "question-1",+ ]);+ assert.equal(display.find(entry => entry.id === "thinking-1")?.steps?.[0].content, undefined);+ });++ it("matches legacy question content after a contentless question", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "choose"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{reasoningContent: "first", toolNames: ["question"]}],+ },+ {id: "question-1", type: "question"},+ {+ id: "thinking-2",+ type: "thinking",+ steps: [{reasoningContent: "second", toolNames: ["question"], content: "Choose again"}],+ },+ {id: "question-2", type: "question"},+ {id: "assistant-1", type: "assistant", toolCalls: [{name: "question"}]},+ {+ id: "assistant-2",+ type: "assistant",+ content: "Choose again",+ toolCalls: [{name: "question"}],+ },+ ]);++ const secondContentIndex = display.findIndex(entry => entry.id === "assistant-2");+ assert.ok(secondContentIndex > display.findIndex(entry => entry.id === "thinking-2"));+ assert.ok(secondContentIndex < display.findIndex(entry => entry.id === "question-2"));+ assert.ok(secondContentIndex > display.findIndex(entry => entry.id === "question-1"));+ assert.equal(display.find(entry => entry.id === "thinking-2")?.steps?.[0].content, undefined);+ });++ it("places recovered thinking and question content before the question card", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "choose"},+ {id: "question-1", type: "question", roundID: "round-1"},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "Choose a color",+ reasoningContent: "reasoning",+ toolCalls: [{id: "call-question", name: "question"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);++ assert.deepEqual(display.map(entry => entry.id || entry.type), [+ "user-1", "thinking", "assistant-1", "question-1", "assistant-2",+ ]);+ assert.equal(display[1].steps?.[0].content, undefined);+ assert.equal(display[1].steps?.[0].roundID, "round-1");+ });+it("uses round IDs to restore authoritative process content", () => {const display = buildAgentPresentationEntries([{id: "user-1", type: "user", content: "work"},diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.tsindex bfc06578a3..8e4e0d854b 100644--- a/app/src/layout/dock/agent/AgentHistory.ts+++ b/app/src/layout/dock/agent/AgentHistory.ts@@ -201,6 +201,13 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorconst thinkingSteps = prepared.flatMap(entry => entry.type === "thinking" ? (entry.steps || []) : []);const matchedSteps = new Set<AgentHistoryThinkingStep>();const recovered: Array<{ entry: AgentHistoryEntry; step: AgentHistoryThinkingStep }> = [];+ const questionEntries = prepared.filter(entry => entry.type === "question");+ const matchedQuestionEntries = new Set<AgentHistoryEntry>();+ const questionContentInsertions: Array<{+ sourceEntry: AgentHistoryEntry;+ anchorStep?: AgentHistoryThinkingStep;+ questionEntry?: AgentHistoryEntry+ }> = [];const todoInsertions: Array<{sourceEntry: AgentHistoryEntry;anchorStep?: AgentHistoryThinkingStep;@@ -213,6 +220,26 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor}const isProcess = !!entry.toolCalls?.length;const toolNames = entry.toolCalls?.map(call => call.name || "").filter(Boolean) || [];+ const questionCallCount = entry.toolCalls?.filter(call => call.name === "question").length || 0;+ const hasQuestion = questionCallCount > 0;+ const hasQuestionContent = hasQuestion && !!entry.content?.trim();+ let questionEntry: AgentHistoryEntry | undefined;+ for (let i = 0; i < questionCallCount; i++) {+ let matchedQuestion: AgentHistoryEntry | undefined;+ if (entry.roundID) {+ matchedQuestion = questionEntries.find(item =>+ !matchedQuestionEntries.has(item) && item.roundID === entry.roundID);+ }+ if (!matchedQuestion) {+ matchedQuestion = questionEntries.find(item =>+ !matchedQuestionEntries.has(item) && (!entry.roundID || !item.roundID));+ }+ if (!matchedQuestion) {+ break;+ }+ matchedQuestionEntries.add(matchedQuestion);+ questionEntry = questionEntry || matchedQuestion;+ }let step: AgentHistoryThinkingStep | undefined;let relatedSteps: AgentHistoryThinkingStep[] = [];if (entry.roundID) {@@ -228,16 +255,28 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor}let presentationStep = step;if (step) {- enrichThinkingStep(step, entry, isProcess);+ enrichThinkingStep(step, entry, isProcess && !hasQuestionContent);enrichThinkingStepTools(step, relatedSteps.length > 0 ? relatedSteps : [step], entry);matchedSteps.add(step);} else if (isProcess || entry.reasoningContent?.trim()) {- presentationStep = buildRecoveredThinkingStep(entry, isProcess);+ presentationStep = buildRecoveredThinkingStep(entry, isProcess && !hasQuestionContent);recovered.push({entry, step: presentationStep});}+ if (hasQuestionContent) {+ if (presentationStep) {+ presentationStep.content = undefined;+ }+ questionContentInsertions.push({+ sourceEntry: entry,+ anchorStep: presentationStep,+ questionEntry,+ });+ }if (isProcess) {- // 带工具调用的 assistant 是模型协议过程,不单独渲染为回答气泡。- entry.content = undefined;+ // 普通工具调用的 assistant 是模型协议过程,不单独渲染为回答气泡;question 的同轮正文用于引出提问。+ if (!hasQuestionContent) {+ entry.content = undefined;+ }const remainingToolCalls: NonNullable<AgentHistoryEntry["toolCalls"]> = [];for (const call of entry.toolCalls || []) {if (call.name === "todo_write" && call.result?.trim()) {@@ -307,6 +346,34 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor}}+ for (const item of questionContentInsertions) {+ const anchorEntry = item.anchorStep+ ? prepared.find(entry => entry.type === "thinking" && entry.steps?.includes(item.anchorStep!))+ : undefined;+ if (anchorEntry && item.questionEntry) {+ const anchorIndex = prepared.indexOf(anchorEntry);+ const questionIndex = prepared.indexOf(item.questionEntry);+ if (anchorIndex > questionIndex) {+ prepared.splice(anchorIndex, 1);+ prepared.splice(prepared.indexOf(item.questionEntry), 0, anchorEntry);+ }+ }++ const sourceIndex = prepared.indexOf(item.sourceEntry);+ if (sourceIndex < 0) {+ continue;+ }+ prepared.splice(sourceIndex, 1);+ const questionIndex = item.questionEntry ? prepared.indexOf(item.questionEntry) : -1;+ if (questionIndex >= 0) {+ prepared.splice(questionIndex, 0, item.sourceEntry);+ } else if (anchorEntry) {+ prepared.splice(prepared.indexOf(anchorEntry) + 1, 0, item.sourceEntry);+ } else {+ prepared.splice(Math.min(sourceIndex, prepared.length), 0, item.sourceEntry);+ }+ }+const todoOffsets = new Map<AgentHistoryEntry, number>();for (const item of todoInsertions) {const anchorEntry = item.anchorStep@@ -348,8 +415,8 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorreturn prepared;};-// 将持久化协议消息投影为 UI 条目:同一用户轮次中的工具调用消息归入思考卡片,-// 只有不带工具调用的 assistant 作为最终回答展示。+// 将持久化协议消息投影为 UI 条目:普通工具调用消息归入思考卡片,+// question 的同轮正文保留在提问卡片前,其余不带工具调用的 assistant 作为回答展示。export const buildAgentPresentationEntries = (entries: AgentHistoryEntry[]): AgentHistoryEntry[] => {const result: AgentHistoryEntry[] = [];let turnEntries: AgentHistoryEntry[] = [];diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.tsindex 14e4dd973c..8cb2cd7e0b 100644--- a/app/src/layout/dock/agent/agentSSE.ts+++ b/app/src/layout/dock/agent/agentSSE.ts@@ -55,6 +55,7 @@ export type ISSEResult = {} | {type: "question";questionID: string;+ roundID?: string;arguments: Record<string, unknown>;} | {type: "reasoning";@@ -333,6 +334,7 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulreturn {type: "question",questionID: data.questionID as string,+ roundID: data.roundID as string || undefined,arguments: (data.arguments || {}) as Record<string, unknown>,};case "reasoning":diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 8c5fabc822..ad3fe16740 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -1265,7 +1265,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitresultStr = toolInputErr.Error()isErr = true} else if tc.Function.Name == "question" {- resultStr = handleQuestion(ctx, tc.Function.Arguments, ch, 5*time.Minute)+ resultStr = handleQuestion(ctx, tc.Function.Arguments, roundID, ch, 5*time.Minute)} else if registration.isBrowser() {executed := handleBrowserCapability(ctx, tc, registration, ch, confirmTimeout)resultStr = executed.Text@@ -1597,7 +1597,7 @@ func needsLocalSnapshot(toolName, action string) bool {}}-func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent, timeout time.Duration) string {+func handleQuestion(ctx context.Context, argsJSON, roundID string, ch chan<- AgentEvent, timeout time.Duration) string {args := parseToolArgs(argsJSON)questionID := ast.NewNodeID()ch2 := make(chan QuestionAnswer, 1)@@ -1608,6 +1608,7 @@ func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent,sendCriticalEvent(ctx, ch, AgentEvent{Type: "question",QuestionID: questionID,+ RoundID: roundID,Arguments: args,})diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex ef3386d5e9..ffc4214131 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -381,6 +381,26 @@ func TestQuestionAndBrowserCapabilityResultsAreAcceptedOnce(t *testing.T) {}}+func TestQuestionEventIncludesRoundID(t *testing.T) {+ const roundID = "test-round"+ events := make(chan AgentEvent, 1)+ resultCh := make(chan string, 1)+ go func() {+ resultCh <- handleQuestion(context.Background(), `{"questions":[]}`, roundID, events, time.Second)+ }()++ event := <-events+ if event.Type != "question" || event.RoundID != roundID || event.QuestionID == "" {+ t.Fatalf("unexpected question event: %#v", event)+ }+ if !AnswerQuestion(event.QuestionID, []string{"answer"}) {+ t.Fatal("question answer was rejected")+ }+ if result := <-resultCh; result != "answer" {+ t.Fatalf("unexpected question result: %q", result)+ }+}+func TestWaitCompletionKeepsConcurrentlyAcceptedResults(t *testing.T) {const questionID = "test-question-timeout-race"questionCh := make(chan QuestionAnswer, 1)diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 08f8569ca0..d9eec55de6 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -733,6 +733,7 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {case "question":return writeSSEEvent(c, "question", map[string]any{"questionID": event.QuestionID,+ "roundID": event.RoundID,"arguments": event.Arguments,})case "browser_capability_call":