An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Extract the agent session run controller https://github.com/siyuan-note/siyuan/issues/20297
Daniel18ab036bad42
diff --git a/app/src/layout/dock/agent/AgentChat.error.test.ts b/app/src/layout/dock/agent/AgentChat.error.test.tsindex 9fe0add81e..824a7e4d61 100644--- a/app/src/layout/dock/agent/AgentChat.error.test.ts+++ b/app/src/layout/dock/agent/AgentChat.error.test.ts@@ -1,3 +1,4 @@+import {AgentRunController} from "./AgentRunController";import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";@@ -18,6 +19,7 @@ const createChat = () => {runInNewContext(compiled, {exports,require: () => ({+ AgentRunController,Model: class {},SessionStore: {load: async (id: string) => sessions.get(id)},buildAgentPresentationEntries: (entries: unknown[]) => entries,@@ -118,7 +120,7 @@ test("recovery errors remain scoped to their session when switching views", asyntest("a new run clears the previous interruption even when regenerating the same user turn", async () => {const {chat, elements} = createChat();chat.appendError("Session timed out");- chat.beginSessionRun();+ chat.runController.begin();await chat.reloadFromDisk(true);assert.equal(elements.length, 0);assert.equal(chat.sessionErrors.size, 0);diff --git a/app/src/layout/dock/agent/AgentChat.sessions.test.ts b/app/src/layout/dock/agent/AgentChat.sessions.test.tsindex 177a58983a..b58190fab7 100644--- a/app/src/layout/dock/agent/AgentChat.sessions.test.ts+++ b/app/src/layout/dock/agent/AgentChat.sessions.test.ts@@ -1,3 +1,4 @@+import {AgentRunController} from "./AgentRunController";import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";@@ -14,7 +15,7 @@ const createChat = (load: (id: string) => Promise<AgentSession>) => {const exports = {} as {AgentChat: {prototype: object}};runInNewContext(compiled, {exports,- require: () => ({Model: class {}, SessionStore: {load}}),+ require: () => ({AgentRunController, Model: class {}, SessionStore: {load}}),window: {siyuan: {languages: {}},setTimeout: (callback: () => void) => { queueMicrotask(callback); return 1; },@@ -60,7 +61,7 @@ const createChat = (load: (id: string) => Promise<AgentSession>) => {isScrolledToBottom: () => true,});for (const method of ["destroyEditingComposer", "flushTokenUpdate", "cancelTokenUpdate",- "updateHostRunStatus", "prepareSessionRunForDetach", "captureSessionRunView", "renderLoadedSession",+ "updateHostRunStatus", "prepareRunViewForDetach", "captureRunView", "captureRunViewState", "renderLoadedSession","rebuildNavMarkers", "scrollToBottom", "removeMirrorPlaceholder", "showMirrorPlaceholder","applyPermissionMode", "applySessionModelIfValid", "updateTokenDisplay", "finishActiveThinking","clearThinking", "observeStickTarget", "flushThinkingStep"]) {@@ -84,7 +85,7 @@ test("a background turn ending during a session switch releases the stale mirrorconst {chat, attributes} = createChat(async () => {loads++;if (loads === 1) {- await chat.finishSessionRun(firstRun);+ await chat.runController.finish(firstRun);return session({agentRunning: true});}return session({recoveryTurnID: "first-turn", recoveryState: "finished"});@@ -153,10 +154,10 @@ test("a completed background turn does not change the foreground stream or its cchat.abortController = secondRun.controller;chat.currentThinkingReasoningContent = "second session reasoning";- await chat.handleSessionRunEvent(firstRun, {type: "snapshot", snapshotID: "snapshot-id"});- await chat.handleSessionRunEvent(firstRun, {type: "done", turnID: "first-turn"});+ await chat.runController.handleEvent(firstRun, {type: "snapshot", snapshotID: "snapshot-id"});+ await chat.runController.handleEvent(firstRun, {type: "done", turnID: "first-turn"});- await chat.finishSessionRun(firstRun);+ await chat.runController.finish(firstRun);assert.equal(chat.isStreaming, true);assert.equal(chat.abortController, secondRun.controller);diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 511e65e976..5b1b5b503b 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -57,7 +57,8 @@ import {isEncryptedBox} from "../../../util/pathName";import {Menu} from "../../../plugin/Menu";import {getAgentDefaultModelID, getUsableAgentModels} from "./agentModel";import {AgentScrollStateMode, resolveAgentScrollState} from "./AgentScrollState";-import {AgentSessionRun, AgentSessionRuns} from "./AgentSessionRuns";+import {AgentSessionRuns} from "./AgentSessionRuns";+import {AgentRunController, ManagedAgentRun, PendingAgentInteraction} from "./AgentRunController";import {fullscreen} from "../../../protyle/breadcrumb/action";import {AgentWelcomeGreeting} from "./AgentWelcomeGreeting";@@ -82,7 +83,6 @@ export interface AgentChatHost {type EntryBase = { id?: string };type AgentReference = { id: string; title: string };-type PendingAgentInteraction = Extract<ISSEResult, {type: "confirm" | "question"}>;type UserEntry = EntryBase & {type: "user";content: string;@@ -187,7 +187,7 @@ type AgentSessionRunViewState = {permissionMode: AgentPermissionMode;};-type ManagedAgentSessionRun = AgentSessionRun<PendingAgentInteraction, ISSEResult, AgentSessionRunViewState>;+type ManagedAgentSessionRun = ManagedAgentRun<AgentSessionRunViewState>;export class AgentChat extends Model {private welcomeGreeting = new AgentWelcomeGreeting();@@ -867,11 +867,11 @@ export class AgentChat extends Model {this.currentRoundID = "";const selectedModel = this.getSelectedModel();const reasoningEffort = this.selectedReasoningEffort;- const run = this.beginSessionRun();+ const run = this.runController.begin();try {await this.saveSession();} catch (e) {- this.discardSessionRun(run);+ this.runController.discard(run);if (this.sessionId === run.sessionID) {this.rollbackUserEntry(userEntryId);await this.reloadFromDisk();@@ -881,7 +881,7 @@ export class AgentChat extends Model {void this.sessionPanel?.refresh();try {await fetchAgentSSE(text, window.siyuan.config.appearance.lang, [],- (event: ISSEResult) => this.handleSessionRunEvent(run, event),+ (event: ISSEResult) => this.runController.handleEvent(run, event),(err: Error) => this.handleSessionRunError(run, err, userEntryId),run.controller.signal,run.sessionID,@@ -893,7 +893,7 @@ export class AgentChat extends Model {userEntryId,SessionStore.getRevision(run.sessionID));} finally {- await this.finishSessionRun(run);+ await this.runController.finish(run);}}});@@ -1167,38 +1167,135 @@ export class AgentChat extends Model {return result.session ?? null;}- private beginSessionRun(): ManagedAgentSessionRun {- this.sessionErrors.delete(this.sessionId);- this.messagesContainer.querySelectorAll(".agent-chat__msg--error").forEach(el => el.remove());- const run = this.sessionRuns.begin(this.sessionId);- this.abortController = run.controller;- this.sessionRuns.markRead(this.sessionId);- this.updateHostRunStatus();- this.updateSendButtonState();- void this.sessionPanel?.refresh();- return run;- }+ private sessionRunController: AgentRunController<AgentSessionRunViewState>;- private detachSessionRun(sessionID: string): boolean {- const run = this.sessionRuns.get(sessionID);- if (!run) {- return false;+ private get runController(): AgentRunController<AgentSessionRunViewState> {+ if (!this.sessionRunController) {+ this.sessionRunController = new AgentRunController(this.sessionRuns, {+ currentSessionID: () => this.sessionId,+ beforeBegin: () => {+ this.sessionErrors.delete(this.sessionId);+ this.messagesContainer.querySelectorAll(".agent-chat__msg--error").forEach(el => el.remove());+ },+ activate: run => { this.abortController = run.controller; },+ detached: run => {+ this.pendingRecoverySessionIDs.add(run.sessionID);+ this.clearRunAbortController(run);+ },+ completed: run => this.clearRunAbortController(run),+ discarded: (run, current) => {+ this.clearRunAbortController(run);+ if (current) {+ this.setStreaming(false);+ }+ },+ changed: () => {+ this.updateHostRunStatus();+ this.updateSendButtonState();+ void this.sessionPanel?.refresh();+ },+ finishedDetached: (run, attached) => this.finishDetachedRunView(run, attached),+ snapshot: () => this.captureRunViewState(),+ prepareDetach: () => this.prepareRunViewForDetach(),+ captureView: state => this.captureRunView(state),+ restore: (state, consumed) => this.restoreRunView(state, consumed),+ notifyInteraction: () => this.notifyRunInteraction(),+ renderInteraction: event => this.renderRunInteractionView(event),+ handleEvent: event => this.handleSSEEvent(event),+ handleBrowserCall: event => this.handleBrowserCapabilityCall(event.callID, event.capabilityID, event.generation, event.arguments),+ startReplay: run => {+ this.abortController = run.controller;+ this.currentTurnID = run.turnID;+ this.removeMirrorPlaceholder();+ this.setStreaming(true);+ },+ prepareReplayContent: () => {+ if (!this.currentContent.trim() && this.messagesContainer.querySelector(+ ".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)")) {+ this.finishActiveThinking();+ this.flushThinkingStep();+ }+ },+ idleReplay: () => {+ const activeThinking = this.messagesContainer.querySelector(+ ".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)"+ );+ if (this.isStreaming && activeThinking) {+ this.startThinkingTimer();+ }+ },+ recoverUnavailable: run => {+ if (this.sessionId === run.sessionID && this.pendingRecoverySessionIDs.has(run.sessionID)) {+ void this.recoverInterruptedTurn(run.sessionID, run.turnID);+ }+ },+ });}- this.sessionRuns.detach(sessionID);- this.pendingRecoverySessionIDs.add(sessionID);+ return this.sessionRunController;+ }++ private clearRunAbortController(run: ManagedAgentSessionRun) {if (this.abortController === run.controller) {this.abortController = null;}- this.updateHostRunStatus();- this.updateSendButtonState();- void this.sessionPanel?.refresh();- return true;}- private snapshotSessionRunState(run: ManagedAgentSessionRun) {+ private notifyRunInteraction() {+ if (this.host.notify) {+ this.host.notify("confirm");+ } else if (!document.hasFocus() || document.hidden) {+ const L = window.siyuan.languages;+ sendNotification({title: L.agentNotifyConfirm, body: "", timeoutType: "default"});+ }+ }++ private async renderRunInteractionView(event: PendingAgentInteraction) {+ this.removeMirrorPlaceholder();+ if (event.type === "confirm") {+ await this.appendConfirm(event.name, event.arguments, event.confirmID, event.effects, event.forced, false);+ } else {+ this.appendQuestion(event.questionID, event.arguments, event.roundID);+ }+ }++ private finishDetachedRunView(run: ManagedAgentSessionRun, attached: boolean) {+ this.pendingRecoverySessionIDs.add(run.sessionID);+ if (attached) {+ const pendingTitle = this.pendingSessionTitles.get(run.sessionID);+ if (pendingTitle) {+ this.sessionTitle = pendingTitle;+ this.pendingSessionTitle = pendingTitle;+ this.titleElement.textContent = pendingTitle;+ }+ this.currentTurnID = run.turnID;+ this.setStreaming(false);+ this.removeMirrorPlaceholder();+ void this.recoverInterruptedTurn(run.sessionID, run.turnID).then(() => {+ if (!this.pendingSessionTitles.has(run.sessionID)) {+ return;+ }+ if (this.sessionId === run.sessionID && !this.isCurrentSessionRunning() &&+ !this.pendingRecoverySessionIDs.has(run.sessionID) && !this.currentTurnID) {+ void this.saveSession();+ } else if (this.sessionId !== run.sessionID) {+ this.persistPendingSessionTitle(run.sessionID);+ }+ });+ } else {+ this.persistPendingSessionTitle(run.sessionID);+ 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"});+ }+ }+ }++ private captureRunViewState(): AgentSessionRunViewState {this.flushTokenUpdate();this.flushReasoningUpdate();- run.viewState = {+ return {entries: this.entries,hasTitled: this.hasTitled,currentAIElement: this.currentAIElement,@@ -1227,7 +1324,7 @@ export class AgentChat extends Model {};}- private prepareSessionRunForDetach(run: ManagedAgentSessionRun) {+ private prepareRunViewForDetach() {this.flushTokenUpdate();this.flushReasoningUpdate();if (this.currentContent.trim()) {@@ -1236,27 +1333,19 @@ export class AgentChat extends Model {} else {this.stopThinkingTimer();}- this.snapshotSessionRunState(run);}- private captureSessionRunView(run: ManagedAgentSessionRun) {- if (!run.viewState) {- return;- }+ private captureRunView(state: AgentSessionRunViewState) {this.cancelTokenUpdate();const view = document.createDocumentFragment();this.observeStickTarget(null);while (this.messagesContainer.firstChild) {view.appendChild(this.messagesContainer.firstChild);}- run.viewState.view = view;+ state.view = view;}- private restoreSessionRunState(run: ManagedAgentSessionRun): boolean {- const state = run.viewState;- if (!state) {- return false;- }+ private restoreRunView(state: AgentSessionRunViewState, consumed: () => void): boolean {this.cancelTokenUpdate();this.observeStickTarget(null);if (state.view?.hasChildNodes()) {@@ -1288,7 +1377,7 @@ export class AgentChat extends Model {this.hasInterveningCard = state.hasInterveningCard;this.lastStepToolCount = state.lastStepToolCount;this.applyPermissionMode(state.permissionMode);- run.viewState = undefined;+ consumed();this.updateTokenDisplay();this.rebuildNavMarkers();const body = this.currentAIElement?.querySelector<HTMLElement>(".agent-chat__body--streaming");@@ -1325,82 +1414,12 @@ export class AgentChat extends Model {});}- private interactionKey(event: PendingAgentInteraction): string {- return event.type === "confirm" ? `confirm:${event.confirmID}` : `question:${event.questionID}`;- }-- private queueRunInteraction(run: ManagedAgentSessionRun, event: PendingAgentInteraction,- notify = true) {- const key = this.interactionKey(event);- if (!run.pendingInteractions.some(item => this.interactionKey(item) === key)) {- run.pendingInteractions.push(event);- if (notify) {- if (this.host.notify) {- this.host.notify("confirm");- } else if (!document.hasFocus() || document.hidden) {- const L = window.siyuan.languages;- sendNotification({title: L.agentNotifyConfirm, body: "", timeoutType: "default"});- }- }- }- }-- private removeRunInteraction(sessionID: string, type: PendingAgentInteraction["type"], id: string) {- const run = this.sessionRuns.get(sessionID);- if (!run) {- return;- }- const key = `${type}:${id}`;- run.pendingInteractions = run.pendingInteractions.filter(item => this.interactionKey(item) !== key);- run.renderedInteractionKeys.delete(key);- }-- private async renderRunInteraction(run: ManagedAgentSessionRun, event: PendingAgentInteraction) {- if (this.sessionId !== run.sessionID || !run.interactionViewReady) {- return;- }- const key = this.interactionKey(event);- if (run.renderedInteractionKeys.has(key)) {- return;- }- run.renderedInteractionKeys.add(key);- this.removeMirrorPlaceholder();- if (event.type === "confirm") {- await this.appendConfirm(event.name, event.arguments, event.confirmID, event.effects, event.forced, false);- } else {- this.appendQuestion(event.questionID, event.arguments, event.roundID);- }- }-- private async renderPendingRunInteractions(run: ManagedAgentSessionRun) {- for (const event of run.pendingInteractions) {- await this.renderRunInteraction(run, event);- }- }-- private async processSessionRunView(run: ManagedAgentSessionRun, task: () => Promise<void>) {- const processingPromise = task();- run.processingPromise = processingPromise;- try {- await processingPromise;- } finally {- if (run.processingPromise === processingPromise) {- run.processingPromise = undefined;- }- }- }-- private async waitForSessionRunView(run: ManagedAgentSessionRun) {- const pending = [run.processingPromise, run.replayPromise].filter(Boolean) as Promise<void>[];- await Promise.all(pending.map(promise => promise.catch(() => undefined)));- }-private async handleSessionRunError(run: ManagedAgentSessionRun, err: Error, userEntryId?: string,restoreSession = false) {if (run.detached || this.sessionId !== run.sessionID) {return;}- await this.processSessionRunView(run, async () => {+ await this.runController.processView(run, async () => {if (err instanceof AgentHttpError && err.status === 409) {await this.handleConflictReject();return;@@ -1409,183 +1428,6 @@ export class AgentChat extends Model {});}- private enqueueSessionRunEvent(run: ManagedAgentSessionRun, event: ISSEResult) {- if (this.sessionRuns.get(run.sessionID) !== run) {- return;- }- const lastIndex = run.pendingEvents.length - 1;- const lastEvent = run.pendingEvents[lastIndex];- if (event.type === "content" && lastEvent?.type === "content") {- run.pendingEvents[lastIndex] = {...lastEvent, token: lastEvent.token + event.token};- return;- }- if (event.type === "reasoning" && lastEvent?.type === "reasoning") {- run.pendingEvents[lastIndex] = {...lastEvent, token: lastEvent.token + event.token};- return;- }- this.sessionRuns.enqueue(run, event);- }-- private async handleSessionRunEvent(run: ManagedAgentSessionRun, event: ISSEResult) {- if (event.type === "turn") {- run.turnID = event.turnID;- }- if (!run.detached && !run.replaying && this.sessionId === run.sessionID) {- if (event.type === "confirm" || event.type === "question") {- this.queueRunInteraction(run, event, false);- run.renderedInteractionKeys.add(this.interactionKey(event));- }- await this.processSessionRunView(run, () => this.handleSSEEvent(event));- return;- }- if (event.type === "browser_capability_call") {- await this.handleBrowserCapabilityCall(event.callID, event.capabilityID, event.generation, event.arguments);- return;- }- if (event.type === "confirm" || event.type === "question") {- this.queueRunInteraction(run, event, this.sessionId !== run.sessionID);- return;- }- this.enqueueSessionRunEvent(run, event);- }-- private async finishSessionRun(run: ManagedAgentSessionRun) {- const replayPromise = run.replayPromise;- if (replayPromise) {- await replayPromise;- }- const current = this.sessionId === run.sessionID;- const detached = run.detached;- const attached = current && run.interactionViewReady;- if (!this.sessionRuns.complete(run, detached && !attached)) {- return;- }- if (this.abortController === run.controller) {- this.abortController = null;- }- this.updateHostRunStatus();- this.updateSendButtonState();- void this.sessionPanel?.refresh();- if (!detached) {- return;- }- this.pendingRecoverySessionIDs.add(run.sessionID);- if (attached) {- const pendingTitle = this.pendingSessionTitles.get(run.sessionID);- if (pendingTitle) {- this.sessionTitle = pendingTitle;- this.pendingSessionTitle = pendingTitle;- this.titleElement.textContent = pendingTitle;- }- this.currentTurnID = run.turnID;- this.setStreaming(false);- this.removeMirrorPlaceholder();- void this.recoverInterruptedTurn(run.sessionID, run.turnID).then(() => {- if (!this.pendingSessionTitles.has(run.sessionID)) {- return;- }- if (this.sessionId === run.sessionID && !this.isCurrentSessionRunning() &&- !this.pendingRecoverySessionIDs.has(run.sessionID) && !this.currentTurnID) {- void this.saveSession();- } else if (this.sessionId !== run.sessionID) {- this.persistPendingSessionTitle(run.sessionID);- }- });- } else {- this.persistPendingSessionTitle(run.sessionID);- 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"});- }- }- }-- private discardSessionRun(run: ManagedAgentSessionRun) {- this.sessionRuns.complete(run, false);- if (this.abortController === run.controller) {- this.abortController = null;- }- if (this.sessionId === run.sessionID) {- this.setStreaming(false);- }- this.updateHostRunStatus();- this.updateSendButtonState();- void this.sessionPanel?.refresh();- }-- private hasUnrenderedRunInteraction(run: ManagedAgentSessionRun): boolean {- return run.pendingInteractions.some(event => !run.renderedInteractionKeys.has(this.interactionKey(event)));- }-- private async replaySessionRun(run: ManagedAgentSessionRun) {- run.replaying = true;- this.restoreSessionRunState(run);- run.interactionViewReady = true;- this.abortController = run.controller;- this.currentTurnID = run.turnID;- this.removeMirrorPlaceholder();- this.setStreaming(true);- try {- while (this.sessionId === run.sessionID && run.interactionViewReady &&- this.sessionRuns.get(run.sessionID) === run) {- const events = this.sessionRuns.drain(run);- for (const event of events) {- if (event.type === "content" && !this.currentContent.trim() &&- this.messagesContainer.querySelector(- ".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)")) {- this.finishActiveThinking();- this.flushThinkingStep();- }- await this.handleSSEEvent(event);- if (this.sessionId !== run.sessionID || !run.interactionViewReady ||- this.sessionRuns.get(run.sessionID) !== run) {- return;- }- }- await this.renderPendingRunInteractions(run);- if (run.pendingEvents.length === 0 && !this.hasUnrenderedRunInteraction(run)) {- run.detached = false;- const activeThinking = this.messagesContainer.querySelector(- ".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)"- );- if (this.isStreaming && activeThinking) {- this.startThinkingTimer();- }- return;- }- }- } finally {- run.replaying = false;- if (this.sessionId !== run.sessionID || !run.interactionViewReady) {- run.detached = true;- run.interactionViewReady = false;- }- }- }-- private attachSessionRun(run: ManagedAgentSessionRun) {- if (this.sessionRuns.get(run.sessionID) !== run) {- if (this.sessionId === run.sessionID && this.pendingRecoverySessionIDs.has(run.sessionID)) {- void this.recoverInterruptedTurn(run.sessionID, run.turnID);- }- return;- }- if (run.replayPromise) {- return;- }- const replayPromise = this.replaySessionRun(run).catch((e) => {- console.error("replay background agent events failed:", e);- });- run.replayPromise = replayPromise;- void replayPromise.finally(() => {- if (run.replayPromise === replayPromise) {- run.replayPromise = undefined;- }- });- }-private updateHostRunStatus() {this.host.onStatusChange?.(this.isStreaming || this.sessionRuns.hasRunning() ? "running" : "idle");}@@ -1943,15 +1785,15 @@ export class AgentChat extends Model {this.pendingRecoverySessionIDs.add(previousSessionID);}if (previousRun) {- this.detachSessionRun(previousSessionID);- await this.waitForSessionRunView(previousRun);+ this.runController.detach(previousSessionID);+ await this.runController.waitForView(previousRun);}this.abortController = null;this.setStreaming(false);this.mirrorLocked = false;this.removeMirrorPlaceholder();if (previousRun) {- this.prepareSessionRunForDetach(previousRun);+ this.runController.prepareForDetach(previousRun);} else {this.finishActiveThinking();this.flushThinkingStep();@@ -1963,7 +1805,7 @@ export class AgentChat extends Model {if (!session) {if (previousRun) {this.sessionRuns.markRead(previousSessionID);- this.attachSessionRun(previousRun);+ this.runController.attach(previousRun);void this.sessionPanel?.refresh();}return;@@ -2039,7 +1881,7 @@ export class AgentChat extends Model {return;}if (previousRun) {- this.captureSessionRunView(previousRun);+ this.runController.captureView(previousRun);}this.messagesContainer.innerHTML = "";this.titleElement.textContent = session.title;@@ -2053,7 +1895,7 @@ export class AgentChat extends Model {}const activeRun = this.sessionRuns.get(session.id);if (activeRun) {- this.attachSessionRun(activeRun);+ this.runController.attach(activeRun);} else if (this.mirrorLocked) {this.showMirrorPlaceholder();} else {@@ -2398,15 +2240,15 @@ export class AgentChat extends Model {this.pendingRecoverySessionIDs.add(previousSessionID);}if (previousRun) {- this.detachSessionRun(previousSessionID);- await this.waitForSessionRunView(previousRun);+ this.runController.detach(previousSessionID);+ await this.runController.waitForView(previousRun);}this.abortController = null;this.setStreaming(false);this.mirrorLocked = false;this.removeMirrorPlaceholder();if (previousRun) {- this.prepareSessionRunForDetach(previousRun);+ this.runController.prepareForDetach(previousRun);} else {this.finishActiveThinking();this.flushThinkingStep();@@ -2451,7 +2293,7 @@ export class AgentChat extends Model {this.tokenDisplayEl.classList.add("fn__none");}if (previousRun) {- this.captureSessionRunView(previousRun);+ this.runController.captureView(previousRun);}this.messagesContainer.innerHTML = "";this.currentThinkingSteps = [];@@ -2548,11 +2390,11 @@ export class AgentChat extends Model {this.currentThinkingDuration = 0;this.currentTurnID = "";this.currentRoundID = "";- const run = this.beginSessionRun();+ const run = this.runController.begin();try {await this.saveSession();} catch (e) {- this.discardSessionRun(run);+ this.runController.discard(run);if (this.sessionId === run.sessionID) {this.rollbackUserEntry(userEntryId);await this.reloadFromDisk();@@ -2566,7 +2408,7 @@ export class AgentChat extends Model {text,window.siyuan.config.appearance.lang,refs,- (event: ISSEResult) => this.handleSessionRunEvent(run, event),+ (event: ISSEResult) => this.runController.handleEvent(run, event),(err: Error) => this.handleSessionRunError(run, err, userEntryId),run.controller.signal,run.sessionID,@@ -2579,7 +2421,7 @@ export class AgentChat extends Model {SessionStore.getRevision(run.sessionID),);} finally {- await this.finishSessionRun(run);+ await this.runController.finish(run);}}@@ -3681,13 +3523,13 @@ export class AgentChat extends Model {const editorContext = this.captureEditorContext();lastUserEntry.editorContext = editorContext;const frontendCapabilities = listCapabilityManifests();- const run = this.beginSessionRun();+ const run = this.runController.begin();try {await fetchAgentSSE(lastUserText,window.siyuan.config.appearance.lang,lastUserEntry.references || [],- (event: ISSEResult) => this.handleSessionRunEvent(run, event),+ (event: ISSEResult) => this.runController.handleEvent(run, event),(err: Error) => this.handleSessionRunError(run, err, undefined, true),run.controller.signal,run.sessionID,@@ -3701,7 +3543,7 @@ export class AgentChat extends Model {editedData?.blockHTML,);} finally {- await this.finishSessionRun(run);+ await this.runController.finish(run);}}@@ -4228,7 +4070,7 @@ export class AgentChat extends Model {console.error("agent confirm request error:", e);return false;}- this.removeRunInteraction(sessionID, "confirm", confirmID);+ this.runController.removeInteraction(sessionID, "confirm", confirmID);if (this.sessionId !== sessionID) {return true;}@@ -4434,7 +4276,7 @@ export class AgentChat extends Model {console.error("agent question request error:", e);return false;}- this.removeRunInteraction(sessionID, "question", questionID);+ this.runController.removeInteraction(sessionID, "question", questionID);if (this.sessionId !== sessionID) {return true;}diff --git a/app/src/layout/dock/agent/AgentRunController.test.ts b/app/src/layout/dock/agent/AgentRunController.test.tsnew file mode 100644index 0000000000..82ed8d53a0--- /dev/null+++ b/app/src/layout/dock/agent/AgentRunController.test.ts@@ -0,0 +1,155 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {AgentRunController, AgentRunView, PendingAgentInteraction} from "./AgentRunController";+import {AgentSessionRuns} from "./AgentSessionRuns";+import type {ISSEResult} from "./agentSSE";++type Snapshot = {sessionID: string, captured?: boolean};++const deferred = () => {+ let resolve: () => void;+ let reject: (error: Error) => void;+ const promise = new Promise<void>((done, fail) => { resolve = done; reject = fail; });+ return {promise, resolve, reject};+};++const fixture = () => {+ let sessionID = "first";+ const events: ISSEResult[] = [];+ const interactions: PendingAgentInteraction[] = [];+ const browserCalls: string[] = [];+ const finished: Array<[string, boolean]> = [];+ let notifications = 0;+ let captures = 0;+ const runs = new AgentSessionRuns<PendingAgentInteraction, ISSEResult, Snapshot>();+ const view: AgentRunView<Snapshot> = {+ currentSessionID: () => sessionID,+ beforeBegin: () => {}, activate: () => {}, detached: () => {}, completed: () => {},+ discarded: () => {}, changed: () => {},+ finishedDetached: (run, attached) => { finished.push([run.sessionID, attached]); },+ snapshot: () => ({sessionID}), prepareDetach: () => {},+ captureView: state => { state.captured = true; captures++; },+ restore: (_state, consumed) => { consumed(); return true; },+ notifyInteraction: () => { notifications++; },+ renderInteraction: async event => { interactions.push(event); },+ handleEvent: async event => { events.push(event); },+ handleBrowserCall: async event => { browserCalls.push(event.callID); },+ startReplay: () => {}, prepareReplayContent: () => {}, idleReplay: () => {}, recoverUnavailable: () => {},+ };+ return {controller: new AgentRunController(runs, view), runs, view, events, interactions, browserCalls, finished,+ setSession: (value: string) => { sessionID = value; }, notifications: () => notifications, captures: () => captures};+};++test("background runs coalesce text and replay distinct interactions without touching the foreground", async () => {+ const h = fixture();+ const first = h.controller.begin();+ h.controller.prepareForDetach(first);+ h.controller.captureView(first);+ assert.equal(h.captures(), 1);+ assert.deepEqual(first.viewState, {sessionID: "first", captured: true});+ h.controller.detach("first");+ h.setSession("second");+ const second = h.controller.begin();+ for (const event of [+ {type: "turn", turnID: "turn-first"}, {type: "content", token: "a"}, {type: "content", token: "b"},+ {type: "reasoning", token: "x"}, {type: "reasoning", token: "y"},+ ] satisfies ISSEResult[]) {+ await h.controller.handleEvent(first, event);+ }+ const confirm: PendingAgentInteraction = {type: "confirm", confirmID: "shared", name: "tool", arguments: {}};+ const question: PendingAgentInteraction = {type: "question", questionID: "shared", arguments: {}};+ for (const event of [confirm, confirm, question]) {+ await h.controller.handleEvent(first, event);+ }+ await h.controller.handleEvent(first, {type: "browser_capability_call", callID: "browser", name: "browser", capabilityID: "capability", generation: 1, arguments: {}});+ assert.deepEqual(h.events, []);+ assert.deepEqual(h.browserCalls, ["browser"]);+ assert.equal(h.notifications(), 2);+ assert.equal(first.turnID, "turn-first");+ assert.equal(second.controller.signal.aborted, false);+ h.setSession("first");+ h.controller.attach(first);+ await first.replayPromise;+ assert.deepEqual(h.events, [{type: "turn", turnID: "turn-first"}, {type: "content", token: "ab"}, {type: "reasoning", token: "xy"}]);+ assert.deepEqual(h.interactions, [confirm, question]);+ assert.equal(first.viewState, undefined);+ assert.equal(first.detached, false);+ h.controller.removeInteraction("first", "confirm", "shared");+ assert.deepEqual(first.pendingInteractions, [question]);+ assert.equal(first.renderedInteractionKeys.has("confirm:shared"), false);+});++test("finishing waits for replay and ignores a completed or replaced run", async () => {+ const h = fixture();+ const run = h.controller.begin();+ h.controller.detach("first");+ h.setSession("second");+ const replay = deferred();+ run.replayPromise = replay.promise;+ const finish = h.controller.finish(run);+ assert.equal(h.runs.get("first"), run);+ replay.resolve();+ await finish;+ assert.deepEqual(h.finished, [["first", false]]);+ assert.equal(h.runs.resolveStatus("first"), "unread");+ h.setSession("first");+ const replacement = h.controller.begin();+ h.controller.enqueue(run, {type: "content", token: "stale"});+ await h.controller.finish(run);+ assert.equal(h.runs.get("first"), replacement);+ assert.deepEqual(h.finished, [["first", false]]);+ assert.deepEqual(replacement.pendingEvents, []);+});++test("duplicate attachment shares replay and a switch stops subsequent view work", async () => {+ const h = fixture();+ const run = h.controller.begin();+ h.controller.detach("first");+ h.controller.enqueue(run, {type: "content", token: "first"});+ const processing = deferred();+ h.view.handleEvent = async event => { h.events.push(event); await processing.promise; };+ h.controller.attach(run);+ const replay = run.replayPromise;+ h.controller.attach(run);+ assert.equal(run.replayPromise, replay);+ await h.controller.handleEvent(run, {type: "content", token: "later"});+ h.setSession("second");+ processing.resolve();+ await replay;+ assert.deepEqual(h.events, [{type: "content", token: "first"}]);+ assert.deepEqual(run.pendingEvents, [{type: "content", token: "later"}]);+ assert.equal(run.detached, true);+ assert.equal(run.interactionViewReady, false);+ assert.equal(run.replaying, false);+});++test("view processing keeps the newest promise and waits through a rejection", async () => {+ const h = fixture();+ const run = h.controller.begin();+ const first = deferred();+ const second = deferred();+ const oldProcessing = h.controller.processView(run, () => first.promise);+ const newProcessing = h.controller.processView(run, () => second.promise);+ const failure = assert.rejects(newProcessing, /fixture/);+ first.resolve();+ await oldProcessing;+ assert.equal(run.processingPromise, second.promise);+ const waiting = h.controller.waitForView(run);+ second.reject(new Error("fixture"));+ await Promise.all([failure, waiting]);+ assert.equal(run.processingPromise, undefined);+});++test("restore consumes the snapshot at the view adapter's original completion point", () => {+ const h = fixture();+ const run = h.controller.begin();+ h.controller.snapshot(run);+ h.view.restore = (state, consumed) => {+ assert.equal(run.viewState, state);+ consumed();+ assert.equal(run.viewState, undefined);+ return true;+ };+ assert.equal(h.controller.restore(run), true);+ assert.equal(h.controller.restore(run), false);+});diff --git a/app/src/layout/dock/agent/AgentRunController.ts b/app/src/layout/dock/agent/AgentRunController.tsnew file mode 100644index 0000000000..09904c1a8e--- /dev/null+++ b/app/src/layout/dock/agent/AgentRunController.ts@@ -0,0 +1,259 @@+import type {ISSEResult} from "./agentSSE";+import {AgentSessionRun, AgentSessionRuns} from "./AgentSessionRuns";++export type PendingAgentInteraction = Extract<ISSEResult, {type: "confirm" | "question"}>;+export type ManagedAgentRun<TState> = AgentSessionRun<PendingAgentInteraction, ISSEResult, TState>;++export interface AgentRunView<TState> {+ currentSessionID: () => string;+ beforeBegin: () => void;+ activate: (run: ManagedAgentRun<TState>) => void;+ detached: (run: ManagedAgentRun<TState>) => void;+ completed: (run: ManagedAgentRun<TState>) => void;+ discarded: (run: ManagedAgentRun<TState>, current: boolean) => void;+ changed: () => void;+ finishedDetached: (run: ManagedAgentRun<TState>, attached: boolean) => void;+ snapshot: () => TState;+ prepareDetach: () => void;+ captureView: (state: TState) => void;+ restore: (state: TState, consumed: () => void) => boolean;+ notifyInteraction: () => void;+ renderInteraction: (event: PendingAgentInteraction) => Promise<void>;+ handleEvent: (event: ISSEResult) => Promise<void>;+ handleBrowserCall: (event: Extract<ISSEResult, {type: "browser_capability_call"}>) => Promise<void>;+ startReplay: (run: ManagedAgentRun<TState>) => void;+ prepareReplayContent: () => void;+ idleReplay: () => void;+ recoverUnavailable: (run: ManagedAgentRun<TState>) => void;+}++// 控制器管理每次运行的状态与异步时序,界面通过快照和渲染回调提供当前会话的视图。+export class AgentRunController<TState> {+ constructor(private runs: AgentSessionRuns<PendingAgentInteraction, ISSEResult, TState>,+ private view: AgentRunView<TState>) {+ }++ private isCurrent(run: ManagedAgentRun<TState>) {+ return this.view.currentSessionID() === run.sessionID;+ }++ begin(): ManagedAgentRun<TState> {+ this.view.beforeBegin();+ const run = this.runs.begin(this.view.currentSessionID());+ this.view.activate(run);+ this.runs.markRead(this.view.currentSessionID());+ this.view.changed();+ return run;+ }++ detach(sessionID: string): boolean {+ const run = this.runs.get(sessionID);+ if (!run) {+ return false;+ }+ this.runs.detach(sessionID);+ this.view.detached(run);+ this.view.changed();+ return true;+ }++ snapshot(run: ManagedAgentRun<TState>) {+ run.viewState = this.view.snapshot();+ }++ prepareForDetach(run: ManagedAgentRun<TState>) {+ this.view.prepareDetach();+ this.snapshot(run);+ }++ captureView(run: ManagedAgentRun<TState>) {+ if (run.viewState) {+ this.view.captureView(run.viewState);+ }+ }++ restore(run: ManagedAgentRun<TState>): boolean {+ if (!run.viewState) {+ return false;+ }+ return this.view.restore(run.viewState, () => { run.viewState = undefined; });+ }++ private interactionKey(event: PendingAgentInteraction): string {+ return event.type === "confirm" ? `confirm:${event.confirmID}` : `question:${event.questionID}`;+ }++ queueInteraction(run: ManagedAgentRun<TState>, event: PendingAgentInteraction, notify = true) {+ const key = this.interactionKey(event);+ if (!run.pendingInteractions.some(item => this.interactionKey(item) === key)) {+ run.pendingInteractions.push(event);+ if (notify) {+ this.view.notifyInteraction();+ }+ }+ }++ removeInteraction(sessionID: string, type: PendingAgentInteraction["type"], id: string) {+ const run = this.runs.get(sessionID);+ if (!run) {+ return;+ }+ const key = `${type}:${id}`;+ run.pendingInteractions = run.pendingInteractions.filter(item => this.interactionKey(item) !== key);+ run.renderedInteractionKeys.delete(key);+ }++ private async renderInteraction(run: ManagedAgentRun<TState>, event: PendingAgentInteraction) {+ if (!this.isCurrent(run) || !run.interactionViewReady) {+ return;+ }+ const key = this.interactionKey(event);+ if (run.renderedInteractionKeys.has(key)) {+ return;+ }+ run.renderedInteractionKeys.add(key);+ await this.view.renderInteraction(event);+ }++ private async renderPendingInteractions(run: ManagedAgentRun<TState>) {+ for (const event of run.pendingInteractions) {+ await this.renderInteraction(run, event);+ }+ }++ async processView(run: ManagedAgentRun<TState>, task: () => Promise<void>) {+ const processingPromise = task();+ run.processingPromise = processingPromise;+ try {+ await processingPromise;+ } finally {+ if (run.processingPromise === processingPromise) {+ run.processingPromise = undefined;+ }+ }+ }++ async waitForView(run: ManagedAgentRun<TState>) {+ const pending = [run.processingPromise, run.replayPromise].filter((promise): promise is Promise<void> => !!promise);+ await Promise.all(pending.map(promise => promise.catch(() => undefined)));+ }++ enqueue(run: ManagedAgentRun<TState>, event: ISSEResult) {+ if (this.runs.get(run.sessionID) !== run) {+ return;+ }+ const lastIndex = run.pendingEvents.length - 1;+ const lastEvent = run.pendingEvents[lastIndex];+ if (event.type === "content" && lastEvent?.type === "content") {+ run.pendingEvents[lastIndex] = {...lastEvent, token: lastEvent.token + event.token};+ return;+ }+ if (event.type === "reasoning" && lastEvent?.type === "reasoning") {+ run.pendingEvents[lastIndex] = {...lastEvent, token: lastEvent.token + event.token};+ return;+ }+ this.runs.enqueue(run, event);+ }++ async handleEvent(run: ManagedAgentRun<TState>, event: ISSEResult) {+ if (event.type === "turn") {+ run.turnID = event.turnID;+ }+ if (!run.detached && !run.replaying && this.isCurrent(run)) {+ if (event.type === "confirm" || event.type === "question") {+ this.queueInteraction(run, event, false);+ run.renderedInteractionKeys.add(this.interactionKey(event));+ }+ await this.processView(run, () => this.view.handleEvent(event));+ return;+ }+ if (event.type === "browser_capability_call") {+ await this.view.handleBrowserCall(event);+ return;+ }+ if (event.type === "confirm" || event.type === "question") {+ this.queueInteraction(run, event, !this.isCurrent(run));+ return;+ }+ this.enqueue(run, event);+ }++ async finish(run: ManagedAgentRun<TState>) {+ const replayPromise = run.replayPromise;+ if (replayPromise) {+ await replayPromise;+ }+ const detached = run.detached;+ const attached = this.isCurrent(run) && run.interactionViewReady;+ if (!this.runs.complete(run, detached && !attached)) {+ return;+ }+ this.view.completed(run);+ this.view.changed();+ if (detached) {+ this.view.finishedDetached(run, attached);+ }+ }++ discard(run: ManagedAgentRun<TState>) {+ this.runs.complete(run, false);+ this.view.discarded(run, this.isCurrent(run));+ this.view.changed();+ }++ private hasUnrenderedInteraction(run: ManagedAgentRun<TState>): boolean {+ return run.pendingInteractions.some(event => !run.renderedInteractionKeys.has(this.interactionKey(event)));+ }++ private async replay(run: ManagedAgentRun<TState>) {+ run.replaying = true;+ this.restore(run);+ run.interactionViewReady = true;+ this.view.startReplay(run);+ try {+ while (this.isCurrent(run) && run.interactionViewReady && this.runs.get(run.sessionID) === run) {+ const events = this.runs.drain(run);+ for (const event of events) {+ if (event.type === "content") {+ this.view.prepareReplayContent();+ }+ await this.view.handleEvent(event);+ if (!this.isCurrent(run) || !run.interactionViewReady || this.runs.get(run.sessionID) !== run) {+ return;+ }+ }+ await this.renderPendingInteractions(run);+ if (run.pendingEvents.length === 0 && !this.hasUnrenderedInteraction(run)) {+ run.detached = false;+ this.view.idleReplay();+ return;+ }+ }+ } finally {+ run.replaying = false;+ if (!this.isCurrent(run) || !run.interactionViewReady) {+ run.detached = true;+ run.interactionViewReady = false;+ }+ }+ }++ attach(run: ManagedAgentRun<TState>) {+ if (this.runs.get(run.sessionID) !== run) {+ this.view.recoverUnavailable(run);+ return;+ }+ if (run.replayPromise) {+ return;+ }+ const replayPromise = this.replay(run).catch(e => {+ console.error("replay background agent events failed:", e);+ });+ run.replayPromise = replayPromise;+ void replayPromise.finally(() => {+ if (run.replayPromise === replayPromise) {+ run.replayPromise = undefined;+ }+ });+ }+}diff --git a/app/src/layout/dock/agent/AgentWelcome.test.ts b/app/src/layout/dock/agent/AgentWelcome.test.tsindex 4e8c6b0fae..18996edefc 100644--- a/app/src/layout/dock/agent/AgentWelcome.test.ts+++ b/app/src/layout/dock/agent/AgentWelcome.test.ts@@ -90,10 +90,10 @@ test("plugin suggestion uses the existing localized message sending path", asyncwelcomeGreeting: {getKey: () => ""},messagesContainer: {innerHTML: "", querySelectorAll: () => [example]},getSelectedModel: () => "model",- beginSessionRun: () => ({sessionID: "session", controller: {signal: {}}}),+ sessionRunController: {begin: () => ({sessionID: "session", controller: {signal: {}}}), finish: () => {}},});for (const method of ["destroyEditingComposer", "appendUserMessage", "rebuildNavMarkers", "tryGenerateTitle",- "setStreaming", "saveSession", "finishSessionRun"]) {+ "setStreaming", "saveSession"]) {chat[method] = (): void => undefined;}chat.showWelcome();