diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c05f7c9..808981a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,6 +91,21 @@ platform API version. reader last left it, in any diagram of the product (kept in the webview's storage under `.palette`, as the view options' headings are). +- **The chat's agent starts when the chat is first used.** Each editor's + chat panel started its profile's agent at its handshake, whether or not + the chat was used: a product with two profiles kept two agents (an ACP + process and its server each, some 400 MB together) from its first editors + on, until the window closed. The agent now starts at the chat's first use: + a message sent, a chat made or opened from the list, a chat deleted (so + the agent's copy goes too), Diagnose Connection. Until then the panel + reads "Not started", and the first use shows "Connecting…". Once the + profile's last editor has closed and no turn has run for 30 s, the agent + is stopped; the next use starts it again, and each chat is loaded into it + again when it is next opened or written to, as after a reload. An editor + opened within the 30 s keeps it. A change of the connector setting starts + no agent before the first use. `DiagramChatConfig.agentStart: 'eager'` + (the toolkit's `chat.agentStart`) keeps the start at the handshake, and the + agent until the window closes. ### Fixed diff --git a/packages/diagram-client/src/chat-panel-integrated.ts b/packages/diagram-client/src/chat-panel-integrated.ts index 94ca2e9b..28fcef31 100644 --- a/packages/diagram-client/src/chat-panel-integrated.ts +++ b/packages/diagram-client/src/chat-panel-integrated.ts @@ -254,7 +254,8 @@ export class ChatPanel implements IDiagramStartup, ISelectionListener { private currentModel = ''; /** True when the session is in a reverted state (shows the redo banner). */ private reverted = false; - private connection: 'unknown' | 'connected' | 'disconnected' = 'unknown'; + /** `notStarted`: the host starts the agent at the chat's first use, not before. */ + private connection: 'unknown' | 'connected' | 'disconnected' | 'notStarted' = 'unknown'; private connectionReason = ''; /** The ACP connector the chat is (or was) connected to, as the host names it. */ private connectionAgent = ''; @@ -758,7 +759,9 @@ export class ChatPanel implements IDiagramStartup, ISelectionListener { break; case 'chat.connectionStatus': - if (!data?.connected && data?.connecting) { + if (!data?.connected && data?.notStarted) { + this.setNotStarted(); + } else if (!data?.connected && data?.connecting) { this.setConnecting(); } else { this.setConnectionStatus(!!data?.connected, data?.reason, data?.agent, data?.images); @@ -1206,6 +1209,21 @@ export class ChatPanel implements IDiagramStartup, ISelectionListener { this.update(); } + /** The agent starts at the chat's first use: "Not started", a state and + * not a fault, so no row in the timeline; the next status is news. */ + private setNotStarted(): void { + this.receivedStatus = true; + if (this.statusHandshakeTimer !== null) { + clearTimeout(this.statusHandshakeTimer); + this.statusHandshakeTimer = null; + } + this.connection = 'notStarted'; + this.connectionReason = ''; + this.agentTakesImages = undefined; + this.lastStatusKey = ''; + this.update(); + } + // ── Outbound actions ─────────────────────────────────────────────────── private sendMessage(): void { @@ -1957,13 +1975,17 @@ export class ChatPanel implements IDiagramStartup, ISelectionListener { ? this.handOver ? `In the CLI · ${this.handOver.agent}` : 'Disconnected' - : 'Connecting…'; + : status === 'notStarted' + ? 'Not started' + : 'Connecting…'; const statusTitle = status === 'disconnected' && this.connectionReason ? `${agent || 'agent'}: ${this.connectionReason}` : status === 'connected' && agent ? `Connected to the ${agent} ACP connector` - : 'agent connection'; + : status === 'notStarted' + ? 'The agent starts when a message is sent, or a chat is made or opened' + : 'agent connection'; return html`
diff --git a/packages/diagram-client/src/chat-panel.css b/packages/diagram-client/src/chat-panel.css index ee1fed9b..9bf82e97 100644 --- a/packages/diagram-client/src/chat-panel.css +++ b/packages/diagram-client/src/chat-panel.css @@ -201,6 +201,9 @@ .chat-status.status-disconnected .chat-status-dot { background: var(--vscode-testing-iconFailed, #f14c4c); } +.chat-status.status-notStarted .chat-status-dot { + background: var(--chat-muted); +} /* ── Message area: fixed-height drawer that slides open ── */ .chat-scroll { diff --git a/packages/diagram-client/test/chat-panel-connected-agent.test.ts b/packages/diagram-client/test/chat-panel-connected-agent.test.ts index d682abb4..1487aecc 100644 --- a/packages/diagram-client/test/chat-panel-connected-agent.test.ts +++ b/packages/diagram-client/test/chat-panel-connected-agent.test.ts @@ -108,3 +108,27 @@ describe('a change of agent in the panel', () => { expect((panel as any).models).toEqual([{ id: 'sonnet', name: 'Sonnet' }]); }); }); + +describe('an agent the host starts at the chat\'s first use', () => { + const systemRows = (panel: ChatPanel) => + ((panel as any).timeline as any[]).filter((t) => t.kind === 'message' && t.role === 'system').map((t) => t.content); + + it('reads "Not started", with no row, until the first use starts it', () => { + const panel = makePanel(); + (panel as any).handleIncomingMessage('chat.connectionStatus', { + connected: false, notStarted: true, reason: 'the agent starts when the chat is first used' + }); + const before = JSON.stringify((panel as any).topbarTemplate().values); + expect(before).toContain('Not started'); + expect(before).not.toContain('Disconnected'); + expect(systemRows(panel)).toEqual([]); + // The handshake was answered: no "No response from extension host" later. + expect((panel as any).receivedStatus).toBe(true); + + (panel as any).handleIncomingMessage('chat.connectionStatus', { connected: false, connecting: true }); + expect(JSON.stringify((panel as any).topbarTemplate().values)).toContain('Connecting…'); + (panel as any).handleIncomingMessage('chat.connectionStatus', { connected: true, agent: 'opencode' }); + expect(JSON.stringify((panel as any).topbarTemplate().values)).toContain('Connected · opencode'); + expect(systemRows(panel)).toEqual([]); + }); +}); diff --git a/packages/extension-core/src/api.ts b/packages/extension-core/src/api.ts index 51e9996a..983ce7a1 100644 --- a/packages/extension-core/src/api.ts +++ b/packages/extension-core/src/api.ts @@ -253,6 +253,16 @@ export interface DiagramChatConfig { * opencode. */ acpConnector?: AcpConnectorConfig; + /** + * When the chat's agent processes start. `on-demand` (the default): at the + * chat's first use (a message sent, a chat made or opened, Diagnose + * Connection), not when an editor opens; once the profile's last editor + * has closed and no turn runs, they end after a short grace, and the next + * use starts them again, its chats loaded again. `eager`: when an editor's + * chat panel opens, kept until the window closes, as before this option. + * A Dialogram older than it ignores it and starts eagerly. + */ + agentStart?: "on-demand" | "eager"; } /** diff --git a/packages/extension-core/src/extension/chat/chat-runtime.ts b/packages/extension-core/src/extension/chat/chat-runtime.ts index 5e22dab1..11b7757b 100644 --- a/packages/extension-core/src/extension/chat/chat-runtime.ts +++ b/packages/extension-core/src/extension/chat/chat-runtime.ts @@ -115,6 +115,12 @@ export interface ChatRuntimeConfig { watchAcpAgent?: (listener: (change: AcpConnectorChange) => void) => vscode.Disposable; /** The setting naming the chat's connector, for the warning's "Open Settings". */ acpAgentSetting?: string; + /** + * When the agent starts (`DiagramChatConfig.agentStart`): at the chat's + * first use, given back once no editor is open ({@link ChatRuntime.setOpenEditors}), + * by default; with a panel's handshake, kept, when `eager`. + */ + agentStart?: "on-demand" | "eager"; /** * A named connector's `resume` template as a workspace sees it (for a run's * agents, which name their connector); undefined (or no hook) falls back to @@ -268,6 +274,22 @@ export function agentKey(agent: AcpAgentSpec | undefined): string { /** The chosen connector could not be resolved: no agent was spawned, so none is named. */ class AgentChoiceError extends Error {} +/** The status of an agent that could not be started, as the panels say it. */ +function startFailedStatus(err: unknown, agent: string): ChatPayload { + const choice = err instanceof AgentChoiceError; + return { + type: "chat.connectionStatus", + data: { connected: false, reason: choice ? err.message : String(err), ...(choice ? {} : { agent }) }, + }; +} + +/** An agent started on demand, before the chat's first use: a state, not a fault. */ +const NOT_STARTED: ChatPayload = { + type: "chat.connectionStatus", + // `reason` is for a panel older than `notStarted`, which says it as a disconnect. + data: { connected: false, notStarted: true, reason: "the agent starts when the chat is first used" }, +}; + export class ChatRuntime { private readonly acp = new ACPClientService(); private readonly sessions: SessionManager; @@ -358,6 +380,10 @@ export class ChatRuntime { private readonly prompted = new Set(); /** The agent last started: its folder, and the connector it was started as. */ private startedWith: { cwd: string; agent: AcpAgentSpec | undefined } | undefined; + /** How many of the profile's editors are open; unknown until told ({@link setOpenEditors}). */ + private openEditors: number | undefined; + /** Gives the agent back once the grace after the last editor and the last turn has passed. */ + private releaseTimer: ReturnType | undefined; /** A running agent's question, waiting for the panel's `chat.runAnswer`. */ private readonly pendingRunQuestions = new Map< @@ -496,6 +522,7 @@ export class ChatRuntime { * so a connection that never comes up would otherwise be invisible until * the user opens the chat. If opencode is still not connected 30 s after * the diagram's handshake, surface one VS Code dialog with escape hatches. + * An agent started on demand arms it when its start begins. */ private armConnectWatchdog(): void { if ( @@ -553,6 +580,13 @@ export class ChatRuntime { const again = takingBack ? this.startedWith : undefined; const startIn = again?.cwd ?? cwd; let resolved: AcpAgentSpec | undefined; + // Started at a use of the chat: its panels say "Connecting…" until it + // is up, or why it is not, and the watchdog says one that never comes. + const onDemand = !takingBack && !this.eagerStart(); + if (onDemand) { + this.broadcast({ type: "chat.connectionStatus", data: { connected: false, connecting: true } }); + this.armConnectWatchdog(); + } const starting: Promise = Promise.resolve() .then(() => (again ? again.agent : this.config.acpAgent?.(startIn))) .catch((err) => { @@ -574,11 +608,16 @@ export class ChatRuntime { this.started = true; this.runningAgent = { cwd: startIn, key: agentKey(resolved), name: this.acp.agent }; this.startedWith = { cwd: startIn, agent: resolved }; + // Started with no editor open (the diagnosis command): given back too. + this.scheduleRelease(); }) .catch((err) => { if (this.startPromise === starting) { this.startPromise = undefined; } + if (onDemand) { + this.broadcast(startFailedStatus(err, this.acp.agent)); + } throw err; }); this.startPromise = starting; @@ -586,6 +625,88 @@ export class ChatRuntime { await this.startPromise; } + /** Whether the agent starts with a panel's handshake and is kept ({@link ChatRuntimeConfig.agentStart}). */ + private eagerStart(): boolean { + return this.config.agentStart === "eager"; + } + + /** + * How long an agent started on demand is kept once the profile's last + * editor has closed and no turn runs: long enough to go from a diagram + * closed to the next one opened without a start between, short enough + * that its processes' memory comes back soon after. + */ + private static readonly AGENT_RELEASE_GRACE_MS = 30_000; + + /** + * How many of the profile's editors are open. With none, an agent started + * on demand is stopped once {@link AGENT_RELEASE_GRACE_MS} have passed with + * no turn running; the chat's next use starts it again, and its chats are + * loaded again into it, as after a reload. An editor opened in the grace + * keeps it. + */ + setOpenEditors(count: number): void { + this.openEditors = count; + if (count > 0) { + this.cancelRelease(); + } else { + this.scheduleRelease(); + } + } + + /** The grace begins again: no editor open, an agent started on demand, perhaps a turn just ended. */ + private scheduleRelease(): void { + this.cancelRelease(); + if (this.eagerStart() || this.openEditors !== 0 || !this.startPromise) { + return; + } + this.releaseTimer = setTimeout(() => { + this.releaseTimer = undefined; + void this.release().catch((err) => this.output.appendLine(`agent: could not be stopped: ${String(err)}`)); + }, ChatRuntime.AGENT_RELEASE_GRACE_MS); + } + + private cancelRelease(): void { + if (this.releaseTimer) { + clearTimeout(this.releaseTimer); + this.releaseTimer = undefined; + } + } + + /** Stop the agent: no editor is open, and no turn has run for the grace. */ + private async release(): Promise { + await this.startPromise?.catch(() => undefined); + // A return from the agent's CLI, or a change of agent, under way: the + // grace begins again once it has ended. + const busy = this.returning ?? this.agentSwitch; + if (busy) { + await busy.catch(() => undefined); + this.scheduleRelease(); + return; + } + // An editor opened, a turn runs (its end begins the grace again), or the + // agent is stopped for its CLI: it is kept. + if (this.openEditors !== 0 || !this.started || this.messagesInFlight.size > 0 || this.handOver) { + return; + } + const name = this.acp.agent; + this.output.appendLine( + `agent: no editor open and no turn running for ${ChatRuntime.AGENT_RELEASE_GRACE_MS / 1000} s: ${name} is stopped; the chat's next use starts it again`, + ); + const ended = this.stopOnPurpose(() => this.acp.stopAndWait()); + this.started = false; + this.startPromise = undefined; + this.runningAgent = undefined; + // The agent started next holds none of its chats: each is loaded again + // at its next use, and its models come with it. + this.acp.forgetSessions(); + this.toLoadAgain.clear(); + this.loadFailures.clear(); + if (!(await ended)) { + this.output.appendLine(`agent: ${name} had not ended after it was stopped`); + } + } + /** How long the agent's setting and files are left to settle before a change is applied. */ private static readonly AGENT_CHOICE_SETTLE_MS = 300; /** How long a change of agent waits for the answers on their way before cancelling them. */ @@ -660,6 +781,12 @@ export class ChatRuntime { this.broadcast({ type: "chat.connectionStatus", data: { connected: false, reason: problem } }); return; } + if (!running && !this.eagerStart()) { + // None runs, and none is started for a setting: the chat's next use + // starts the agent it names. A problem said before is gone. + this.broadcast(NOT_STARTED); + return; + } let release!: () => void; this.agentSwitch = new Promise((resolve) => { release = resolve; }); let failure: ChatPayload | undefined; @@ -668,11 +795,7 @@ export class ChatRuntime { await this.stopAgentWhenIdle(running.name, problem ? "none that can be spawned" : effectiveAgent(next).name); } await this.ensureStarted(cwd).catch((err) => { - const choice = err instanceof AgentChoiceError; - failure = { - type: "chat.connectionStatus", - data: { connected: false, reason: choice ? err.message : String(err), ...(choice ? {} : { agent: this.acp.agent }) }, - }; + failure = startFailedStatus(err, this.acp.agent); }); } finally { this.agentSwitch = undefined; @@ -759,6 +882,8 @@ export class ChatRuntime { this.messagesInFlight.delete(token); if (this.messagesInFlight.size === 0) { for (const resolve of this.idleWaiters.splice(0)) resolve(); + // The last turn ended: with no editor open, the grace begins now. + if (this.openEditors === 0) this.scheduleRelease(); } } @@ -1264,10 +1389,7 @@ export class ChatRuntime { const reason = choice ? err.message : String(err); const message = choice ? `Could not start the chat agent: ${reason}` : `Could not start the chat agent (${this.acp.agent}): ${reason}`; this.output.appendLine(message); - this.postToWebview(uri, { - type: "chat.connectionStatus", - data: { connected: false, reason, ...(choice ? {} : { agent: this.acp.agent }) }, - }); + this.postToWebview(uri, startFailedStatus(err, this.acp.agent)); // The status's own row says the reason: the error ends what waited on // the connection (a session asked for) without saying it twice. this.postToWebview(uri, { type: "chat.error", data: { message, inStatus: true } }); @@ -1352,16 +1474,27 @@ export class ChatRuntime { await this.sendSessions(uri, file); return; } + if (!this.eagerStart() && !this.startPromise && !this.acp.isClientConnected()) { + // An editor opened: its panel says the agent is not started, and + // nothing is spawned until the chat is used. + this.postToWebview(uri, NOT_STARTED); + await this.sendSessions(uri, file); + return; + } // Post the current status immediately: the integrated panel's 5 s - // handshake must not wait out an opencode spawn. - this.postToWebview(uri, { - type: "chat.connectionStatus", - data: { - connected: this.acp.isClientConnected(), - agent: this.acp.agent, - images: this.acp.takesImages(), - }, - }); + // handshake must not wait out an opencode spawn. A start on demand + // under way (another panel's first use) reads as the others hear it. + const connected = this.acp.isClientConnected(); + this.postToWebview(uri, !connected && this.startPromise && !this.eagerStart() + ? { type: "chat.connectionStatus", data: { connected: false, connecting: true } } + : { + type: "chat.connectionStatus", + data: { + connected, + agent: this.acp.agent, + images: this.acp.takesImages(), + }, + }); this.armConnectWatchdog(); await this.sendSessions(uri, file); // Eagerly connect on panel open so the panel shows Connected @@ -1428,6 +1561,9 @@ export class ChatRuntime { // status → …) and flood the channel. Only `chat.ready` reports. if (this.acp.isClientConnected()) { await this.sendModels(uri); + } else if (!this.eagerStart() && !this.startPromise) { + // Not started: the models come with the agent, at the chat's first use. + this.postToWebview(uri, { type: "chat.providers", data: { providers: [] } }); } else { await this.connectAndSendModels(uri, cwd); } @@ -1559,6 +1695,10 @@ export class ChatRuntime { "Delete", ); if (choice !== "Delete") return; + // The agent's copy goes with it: an agent not started yet is started for it. + await this.ensureStarted(cwd).catch((err) => + this.output.appendLine(`agent: not started, so the chat stays in it: ${String(err)}`), + ); // Pick the next session to fall back to (most-recent sibling), from // the list as it is now: the question may have waited a long time. await this.sessions.refresh(file).catch((error) => this.reportStoreError(error, "read")); @@ -2393,6 +2533,9 @@ export class ChatRuntime { dispose(): void { this.clearConnectWatchdog(); + this.cancelRelease(); + // Nor is a give-back scheduled again (one waiting on a return, a turn's end). + this.openEditors = undefined; this.agentWatch?.dispose(); if (this.agentChoiceTimer) { clearTimeout(this.agentChoiceTimer); diff --git a/packages/extension-core/src/extension/diagram/diagram-editor-provider.ts b/packages/extension-core/src/extension/diagram/diagram-editor-provider.ts index 08088553..e77cf049 100644 --- a/packages/extension-core/src/extension/diagram/diagram-editor-provider.ts +++ b/packages/extension-core/src/extension/diagram/diagram-editor-provider.ts @@ -186,6 +186,13 @@ export class WorkflowEditorProvider extends GlspEditorProvider { private readonly registerEditorEmitter = new vscode.EventEmitter<{ uri: string; clientId: string }>(); readonly onDidRegisterEditor: vscode.Event<{ uri: string; clientId: string }> = this.registerEditorEmitter.event; + /** How many diagram editors are open, told each time one opens or closes: the chat gives its agent back with none. */ + private readonly openEditorsEmitter = new vscode.EventEmitter(); + readonly onDidChangeOpenEditors: vscode.Event = this.openEditorsEmitter.event; + get openEditorCount(): number { + return this.editors.size; + } + /** Injected live-overlay signature source (the run driver). The provider drives * live-execution glow purely off the signatures this source publishes; the * file read + out-dir resolution now live in the driver. */ @@ -283,7 +290,7 @@ export class WorkflowEditorProvider extends GlspEditorProvider { ) { super(glspVscodeConnector); - extensionContext.subscriptions.push(this.registerEditorEmitter); + extensionContext.subscriptions.push(this.registerEditorEmitter, this.openEditorsEmitter); // Listen for document changes for live preview (debounced) extensionContext.subscriptions.push( @@ -373,11 +380,15 @@ export class WorkflowEditorProvider extends GlspEditorProvider { this.stopLiveOverlayWatch(canonicalDocumentUri); this.tellProfile('onEditorClosed', document.uri.toString()); } + if (gone) { + this.openEditorsEmitter.fire(this.editors.size); + } }); if (first) { this.tellProfile('onEditorOpened', document.uri.toString()); } + this.openEditorsEmitter.fire(this.editors.size); const webview = webviewPanel.webview; diff --git a/packages/extension-core/src/extension/profile-runtime.ts b/packages/extension-core/src/extension/profile-runtime.ts index d5096fb0..a0fde3b7 100644 --- a/packages/extension-core/src/extension/profile-runtime.ts +++ b/packages/extension-core/src/extension/profile-runtime.ts @@ -95,6 +95,11 @@ export async function activateProfileRuntime( glsp.setRunQuestionHandler((question, uri) => runtime.askRunQuestion(uri, question)); glsp.setChatTaskHandler(async (task, uri) => runtime.startTask(uri, task)); glsp.setChatConfirmHandler((confirm, uri) => runtime.confirmInChat(uri, confirm)); + // With no editor of the profile left, the chat gives its agent back. + runtime.setOpenEditors(glsp.editorProvider.openEditorCount); + context.subscriptions.push( + glsp.editorProvider.onDidChangeOpenEditors((open) => runtime.setOpenEditors(open)), + ); // A diagram's session putting a card or a message to the person (the chat's untangle). glsp.setDiagramChatHost({ canAsk: (uri) => runtime.canAsk(uri), @@ -184,6 +189,7 @@ export function assembleChatRuntimeConfig( acpAgentSetting: chat.acpConnector ? `${profile.settingsNamespace}.${chat.acpConnector.settingKey}` : undefined, + agentStart: chat.agentStart, selectionContext: chat.selectionContext, // The profile's own tools, plus the platform's: "what can open this file" // is a question about the EDITOR, not about any one product's graph, so it diff --git a/packages/extension-core/test/chat-functions-over-api.test.ts b/packages/extension-core/test/chat-functions-over-api.test.ts index 7dbaa87f..b51ffd83 100644 --- a/packages/extension-core/test/chat-functions-over-api.test.ts +++ b/packages/extension-core/test/chat-functions-over-api.test.ts @@ -36,7 +36,10 @@ vi.mock('../src/extension/diagram/glsp-activation', () => ({ sendNotification: (_type: unknown, _to: unknown, payload: { type: string; data: any }) => { hoisted.sent.push(payload); } } }, - editorProvider: { postLoadingToDocument: () => undefined, postToWebview: () => undefined, dispatchToWebview: () => undefined }, + editorProvider: { + postLoadingToDocument: () => undefined, postToWebview: () => undefined, dispatchToWebview: () => undefined, + openEditorCount: 1, onDidChangeOpenEditors: () => ({ dispose: () => undefined }) + }, executionOverlay: {}, mcpServerUrl: undefined, setRunQuestionHandler: () => undefined, diff --git a/packages/extension-core/test/chat-runtime-agent-choice.test.ts b/packages/extension-core/test/chat-runtime-agent-choice.test.ts index 19bb7668..6c1cc16d 100644 --- a/packages/extension-core/test/chat-runtime-agent-choice.test.ts +++ b/packages/extension-core/test/chat-runtime-agent-choice.test.ts @@ -26,6 +26,9 @@ function makeRuntime() { key: 'test', displayName: 'Test', settingsSection: 'test.chat', + // Started by the panel's handshake: a change of connector moves the + // agent that runs (one started on demand: chat-runtime-agent-on-demand). + agentStart: 'eager', acpAgent: () => choose(), acpAgentSetting: 'test.acp.connector', watchAcpAgent: (listener: (change: AcpConnectorChange) => void) => { diff --git a/packages/extension-core/test/chat-runtime-agent-on-demand.test.ts b/packages/extension-core/test/chat-runtime-agent-on-demand.test.ts new file mode 100644 index 00000000..2b819c14 --- /dev/null +++ b/packages/extension-core/test/chat-runtime-agent-on-demand.test.ts @@ -0,0 +1,455 @@ +/** + * The chat's agent starts when the chat is first used, not when an editor + * opens, and is given back once the profile's last editor has closed and no + * turn has run for a grace; the next use starts it again, with the chat + * loaded again into it. Before, every editor's panel started its profile's + * agent at its handshake: a product with two profiles kept two agents (two + * processes each) from its first editors on, used or not, until the window + * closed. `agentStart: 'eager'` keeps that. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ChatRuntime } from '../src/extension/chat/chat-runtime'; +import type { AcpConnectorChange } from '../src/extension/chat/acp-connectors'; +import type { ChatPayload, DiagramProfile } from '../src/api'; + +const glsp = vi.hoisted(() => ({ editors: undefined as undefined | { count: number; listeners: Array<(open: number) => void> } })); + +vi.mock('../src/extension/diagram/glsp-activation', () => ({ + activateGlspIntegration: vi.fn(async () => ({ + connector: { messenger: { onNotification: () => undefined, sendNotification: () => undefined } }, + editorProvider: { + get openEditorCount() { + return glsp.editors!.count; + }, + onDidChangeOpenEditors: (listener: (open: number) => void) => { + glsp.editors!.listeners.push(listener); + return { dispose: () => undefined }; + } + }, + executionOverlay: {}, + outline: {}, + viewOptions: {}, + setRunQuestionHandler: () => undefined, + setChatTaskHandler: () => undefined, + setChatConfirmHandler: () => undefined, + setDiagramChatHost: () => undefined, + dispose: () => undefined + })) +})); + +const { activateProfileRuntime, assembleChatRuntimeConfig } = await import('../src/extension/profile-runtime'); + +const URI = 'file:///w/top.dsl'; +const FILE = '/w/top.dsl'; +/** The grace an agent is kept for once no editor is open and no turn runs. */ +const GRACE_MS = 30_000; + +function makeRuntime(config: Record = {}) { + const posts: Array<{ uri: string; payload: ChatPayload }> = []; + const context = { workspaceState: { get: (_k: string, d?: unknown) => d, update: async () => undefined, keys: () => [] } } as any; + let changed: ((change: AcpConnectorChange) => void) | undefined; + const runtime = new ChatRuntime(context, { + key: 'test', + displayName: 'Test', + settingsSection: 'test.chat', + watchAcpAgent: (listener: (change: AcpConnectorChange) => void) => { + changed = listener; + return { dispose: () => undefined }; + }, + ...config + } as any, (uri, payload) => void posts.push({ uri, payload })); + + // The harness, faked on the chat's own client: what it spawns, stops, + // loads and is prompted, in order. A start spawns its two processes (the + // ACP process and its server), a stop ends them. + const acp = (runtime as any).acp; + const done: string[] = []; + let processes = 0; + let connected = false; + let made = 0; + let answer: () => Promise = async () => undefined; + let startGate: Promise = Promise.resolve(); + /** The agent each start was given (its connector), in order. */ + const startedAs: unknown[] = []; + /** The sessions the client holds: a stop keeps them, `forgetSessions` drops them. */ + const held = new Map(); + acp.isClientConnected = () => connected; + acp.start = async (_cwd: string, agent?: unknown) => { + done.push('start'); + startedAs.push(agent); + await startGate; + processes = 2; + connected = true; + acp.emit('connected'); + }; + const stop = () => { + done.push('stop'); + processes = 0; + connected = false; + acp.emit('disconnected'); + }; + acp.stop = stop; + acp.stopAndWait = async () => { + stop(); + return true; + }; + acp.forgetSessions = () => held.clear(); + acp.createSession = async () => { + const id = `s${++made}`; + held.set(id, { id }); + done.push(`create ${id}`); + return id; + }; + acp.loadSession = async (id: string) => { + if (!connected) throw new Error('ACP client is not connected'); + held.set(id, { id }); + done.push(`load ${id}`); + }; + acp.deleteSession = async (id: string) => { + if (!connected) throw new Error('ACP client is not connected'); + held.delete(id); + done.push(`delete ${id}`); + }; + acp.sendPrompt = async (id: string) => { + done.push(`prompt ${id}`); + await answer(); + }; + acp.getSession = (id: string) => held.get(id); + acp.getAllSessions = () => [...held.values()]; + acp.getSessionMode = () => 'build'; + acp.getSessionModel = () => undefined; + acp.setSessionMode = async () => undefined; + acp.setProvider = async () => undefined; + acp.getMessagesWithIds = async () => []; + acp.getRevertState = async () => false; + acp.warmUpModelCatalog = async () => undefined; + acp.listProviders = async () => [{ id: 'model-a', name: 'Model A' }]; + acp.takesImages = () => undefined; + + return { + runtime, posts, done, acp, startedAs, + processes: () => processes, + ready: (uri = URI) => runtime.handleMessage(uri, { type: 'chat.ready', data: {} }), + send: (text: string, sessionId: string | null = null) => + runtime.handleMessage(URI, { type: 'chat.sendMessage', data: { sessionId, text, mode: 'build' } }), + change: (change: AcpConnectorChange = 'setting') => changed!(change), + /** Prompts from now on are answered when the returned function is called. */ + holdAnswers: () => { + let release!: () => void; + const answered = new Promise(resolve => { release = resolve; }); + answer = () => answered; + return release; + }, + /** Starts from now on connect when the returned function is called. */ + holdStart: () => { + let release!: () => void; + startGate = new Promise(resolve => { release = resolve; }); + return release; + } + }; +} + +/** The connection statuses the panels were sent, in order; those of one panel when `uri` is given. */ +const statuses = (posts: Array<{ uri: string; payload: ChatPayload }>, uri?: string) => + posts.filter(p => p.payload.type === 'chat.connectionStatus' && (!uri || p.uri === uri)).map(p => p.payload.data as any); + +/** A second editor of the profile. */ +const OTHER = 'file:///w/other.dsl'; + +/** Let the work started settle, I/O included, until `done` holds (3 s of real time at most). */ +async function until(done: () => boolean): Promise { + const giveUpAt = Date.now() + 3_000; + while (!done()) { + if (Date.now() > giveUpAt) throw new Error('until: the work did not get there in 3 s'); + await new Promise(resolve => setImmediate(resolve)); + } +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + glsp.editors = { count: 0, listeners: [] }; +}); +afterEach(() => vi.useRealTimers()); + +describe('the chat\'s agent, started on demand', () => { + it('is not started when an editor opens: its panel\'s handshake and its model list spawn nothing, and the panel is told so', async () => { + const t = makeRuntime(); + await t.ready(); + await t.runtime.handleMessage(URI, { type: 'chat.getProviders' }); + await t.runtime.handleMessage(URI, { type: 'chat.getSessions' }); + await t.runtime.handleMessage(URI, { type: 'chat.getCommands', data: { mode: 'build' } }); + + expect(t.done).toEqual([]); + expect(t.processes()).toBe(0); + expect(statuses(t.posts)).toEqual([expect.objectContaining({ connected: false, notStarted: true })]); + expect(t.posts.find(p => p.payload.type === 'chat.providers')?.payload.data).toEqual({ providers: [] }); + }); + + it('is started by the chat\'s first use, with "Connecting…" until it is up', async () => { + const t = makeRuntime(); + await t.ready(); + expect(t.done).toEqual([]); + + await t.send('hello'); + + expect(t.done).toEqual(['start', 'create s1', 'prompt s1']); + expect(statuses(t.posts).slice(1)).toEqual([ + { connected: false, connecting: true }, + expect.objectContaining({ connected: true }) + ]); + }); + + it('is given back once the last editor has closed and the grace has passed', async () => { + const t = makeRuntime(); + t.runtime.setOpenEditors(1); + await t.ready(); + await t.send('hello'); + expect(t.processes()).toBe(2); + + t.runtime.setOpenEditors(0); + await vi.advanceTimersByTimeAsync(GRACE_MS - 1_000); + expect(t.processes()).toBe(2); + await vi.advanceTimersByTimeAsync(1_000); + + expect(t.processes()).toBe(0); + expect(t.done.at(-1)).toBe('stop'); + // Stopped on purpose: not said to any panel as the agent going away. + expect(statuses(t.posts).some(s => /disconnected/.test(s.reason ?? ''))).toBe(false); + }); + + it('is kept when an editor opens again within the grace', async () => { + const t = makeRuntime(); + t.runtime.setOpenEditors(1); + await t.ready(); + await t.send('hello'); + + t.runtime.setOpenEditors(0); + await vi.advanceTimersByTimeAsync(GRACE_MS / 2); + t.runtime.setOpenEditors(1); + await vi.advanceTimersByTimeAsync(10 * GRACE_MS); + + expect(t.processes()).toBe(2); + expect(t.done).not.toContain('stop'); + }); + + it('is not given back while a turn runs; the grace begins when it ends', async () => { + const t = makeRuntime(); + t.runtime.setOpenEditors(1); + await t.ready(); + const answer = t.holdAnswers(); + const sending = t.send('a long one'); + await until(() => t.done.includes('prompt s1')); + + t.runtime.setOpenEditors(0); + await vi.advanceTimersByTimeAsync(5 * GRACE_MS); + expect(t.processes()).toBe(2); + + answer(); + await sending; + await vi.advanceTimersByTimeAsync(GRACE_MS - 1_000); + expect(t.processes()).toBe(2); + await vi.advanceTimersByTimeAsync(1_000); + expect(t.processes()).toBe(0); + }); + + it('is started again by the next use, with the chat loaded again into it', async () => { + const t = makeRuntime(); + t.runtime.setOpenEditors(1); + await t.ready(); + await t.send('hello'); + t.runtime.setOpenEditors(0); + await vi.advanceTimersByTimeAsync(GRACE_MS); + expect(t.processes()).toBe(0); + + // An editor opens again: its panel says the agent is not started. + t.runtime.setOpenEditors(1); + await t.ready(); + expect(t.processes()).toBe(0); + expect(statuses(t.posts).at(-1)).toEqual(expect.objectContaining({ connected: false, notStarted: true })); + + // The chat picked from the list: the agent starts, and holds it again. + t.done.length = 0; + await t.runtime.handleMessage(URI, { type: 'chat.loadSession', data: { sessionId: 's1' } }); + expect(t.done).toEqual(['start', 'load s1']); + const history = t.posts.filter(p => p.payload.type === 'chat.sessionHistory').at(-1)!.payload.data as any; + expect(history.sessionId).toBe('s1'); + expect(history.messages.map((m: any) => m.content)).toContain('hello'); + + await t.send('and again', 's1'); + expect(t.done).toEqual(['start', 'load s1', 'prompt s1']); + }); + + it('is not started by a change of its connector, before any use', async () => { + const t = makeRuntime({ acpAgent: async () => ({ name: 'claude', argv: ['claude-acp'] }) }); + await t.ready(); + + t.change(); + await vi.advanceTimersByTimeAsync(400); + + expect(t.done).toEqual([]); + expect(statuses(t.posts).at(-1)).toEqual(expect.objectContaining({ connected: false, notStarted: true })); + }); + + it('is started to delete a chat in the agent as well, when that is the first use', async () => { + const t = makeRuntime(); + // A chat kept from an earlier window. + await (t.runtime as any).sessions.store.create({ + id: 's7', name: 'Kept', workflowFile: FILE, createdAt: 1, updatedAt: 1, mode: 'build', messages: [] + }); + await t.ready(); + const confirm = vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue('Delete' as any); + try { + await t.runtime.handleMessage(URI, { type: 'chat.deleteSession', data: { sessionId: 's7' } }); + } finally { + confirm.mockRestore(); + } + + expect(t.done).toEqual(['start', 'delete s7']); + expect(t.posts.find(p => p.payload.type === 'chat.sessionDeleted')?.payload.data).toEqual(expect.objectContaining({ sessionId: 's7' })); + }); + + it('reads "Connecting…" in an editor opened while it starts, as in the one that started it', async () => { + const t = makeRuntime(); + const connect = t.holdStart(); + await t.ready(); + const sending = t.send('hello'); + await until(() => t.done.includes('start')); + + const other = t.ready(OTHER); + await until(() => statuses(t.posts, OTHER).length > 0); + expect(statuses(t.posts, OTHER)[0]).toEqual({ connected: false, connecting: true }); + + connect(); + await Promise.all([sending, other]); + expect(statuses(t.posts, OTHER).at(-1)).toEqual(expect.objectContaining({ connected: true })); + }); + + it('arms the connect watchdog when its start begins: a start that never connects is said after 30 s', async () => { + const t = makeRuntime(); + t.holdStart(); + const warn = vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue(undefined as any); + try { + await t.ready(); + void t.send('hello'); + await until(() => t.done.includes('start')); + await vi.advanceTimersByTimeAsync(29_000); + expect(warn).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1_000); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('within 30 seconds'); + } finally { + warn.mockRestore(); + } + }); + + it('says a start that failed to every open panel, not only to the one that used the chat', async () => { + const t = makeRuntime(); + t.acp.start = async () => { + t.done.push('start'); + throw new Error('the agent is not on the PATH'); + }; + await t.ready(); + await t.ready(OTHER); + await t.send('hello'); + + expect(t.done).toEqual(['start']); + expect(statuses(t.posts, OTHER)).toEqual([ + expect.objectContaining({ connected: false, notStarted: true }), + { connected: false, connecting: true }, + expect.objectContaining({ connected: false, reason: expect.stringContaining('the agent is not on the PATH') }) + ]); + }); + + it('is switched when its connector changes while it runs', async () => { + const OPENCODE = { name: 'opencode', argv: ['opencode', 'acp'] }; + const CLAUDE = { name: 'claude', argv: ['claude-acp'] }; + let named: unknown = OPENCODE; + const t = makeRuntime({ acpAgent: async () => named }); + t.runtime.setOpenEditors(1); + await t.ready(); + await t.send('hello'); + expect(t.startedAs).toEqual([OPENCODE]); + + named = CLAUDE; + t.change(); + await vi.advanceTimersByTimeAsync(400); + await until(() => t.startedAs.length === 2); + + expect(t.done.slice(-2)).toEqual(['stop', 'start']); + expect(t.startedAs).toEqual([OPENCODE, CLAUDE]); + expect(t.processes()).toBe(2); + }); + + it('is given back after a return from its CLI that outlasted the grace, once the return has ended', async () => { + const t = makeRuntime(); + Object.defineProperty(t.acp, 'resumeTemplate', { get: () => 'agent resume {sessionId}', configurable: true }); + t.acp.sessionCwd = () => undefined; + t.runtime.setOpenEditors(1); + await t.ready(); + await t.send('hello'); + // The chat handed over to the agent's own CLI: the agent is stopped. + await t.runtime.handleMessage(URI, { type: 'chat.openSessionNatively', data: { sessionId: 's1' } }); + expect(t.processes()).toBe(0); + t.runtime.setOpenEditors(0); + + // The return starts the agent again; loading the session takes longer than the grace. + let loaded!: () => void; + const loading = new Promise(resolve => { loaded = resolve; }); + const load = t.acp.loadSession; + t.acp.loadSession = async (...args: unknown[]) => { + await loading; + return load(...args); + }; + const returning = t.runtime.handleMessage(URI, { type: 'chat.returnToChat' }); + await until(() => t.processes() === 2); + await vi.advanceTimersByTimeAsync(GRACE_MS); + expect(t.processes()).toBe(2); + + loaded(); + await vi.advanceTimersByTimeAsync(1_000); + await returning; + expect(t.posts.some(p => p.payload.type === 'chat.returnedToChat')).toBe(true); + expect(t.processes()).toBe(2); + await vi.advanceTimersByTimeAsync(GRACE_MS); + expect(t.processes()).toBe(0); + }); + + it('hears how many of the profile\'s editors are open', async () => { + const setOpenEditors = vi.spyOn(ChatRuntime.prototype, 'setOpenEditors'); + try { + glsp.editors!.count = 1; + const context = { subscriptions: [] as Array<{ dispose(): void }>, workspaceState: { get: (_k: string, d?: unknown) => d, update: async () => undefined } } as any; + await activateProfileRuntime(context, { + key: 'diag', displayName: 'Diagram', settingsNamespace: 'diag', chat: { fullName: 'Diagram' } + } as unknown as DiagramProfile); + expect(setOpenEditors.mock.calls).toEqual([[1]]); + + glsp.editors!.listeners.forEach(listener => listener(0)); + expect(setOpenEditors.mock.calls).toEqual([[1], [0]]); + context.subscriptions.forEach((s: { dispose(): void }) => s.dispose()); + } finally { + setOpenEditors.mockRestore(); + } + }); +}); + +describe('the chat\'s agent, started eagerly', () => { + it('is the profile\'s choice', () => { + const profile = { key: 'diag', displayName: 'Diagram', settingsNamespace: 'diag', chat: { fullName: 'Diagram', agentStart: 'eager' } }; + expect(assembleChatRuntimeConfig(profile as unknown as DiagramProfile, undefined).agentStart).toBe('eager'); + }); + + it('starts when an editor\'s panel opens and is kept after the last editor closes, as before', async () => { + const t = makeRuntime({ agentStart: 'eager' }); + t.runtime.setOpenEditors(1); + await t.ready(); + expect(t.done).toEqual(['start']); + + t.runtime.setOpenEditors(0); + await vi.advanceTimersByTimeAsync(20 * GRACE_MS); + + expect(t.processes()).toBe(2); + expect(t.done).toEqual(['start']); + }); +}); diff --git a/packages/extension-core/test/chat-runtime.test.ts b/packages/extension-core/test/chat-runtime.test.ts index a4b512dd..e92465c0 100644 --- a/packages/extension-core/test/chat-runtime.test.ts +++ b/packages/extension-core/test/chat-runtime.test.ts @@ -350,15 +350,32 @@ describe('unified runtime absorbed features', () => { ).resolves.toBeUndefined(); }); - it('chat.ready posts an immediate connection status before connecting', async () => { - const { runtime, posts, acp } = makeRuntime({}); + it('chat.ready posts an immediate connection status before connecting (eager start)', async () => { + const { runtime, posts, acp } = makeRuntime({ agentStart: 'eager' }); // Simulate a not-yet-connected agent so the immediate status reflects the // pre-connect (disconnected) reality the panel must see instantly. acp.isClientConnected = () => false; + let postedBeforeStart = -1; + acp.start = async () => { + postedBeforeStart = posts.length; + }; await runtime.handleMessage('file:///ws/wf.py', { type: 'chat.ready', data: {} }); const status = posts.filter(p => p.payload.type === 'chat.connectionStatus'); expect(status.length).toBeGreaterThanOrEqual(1); expect(status[0].payload.data).toEqual(expect.objectContaining({ connected: false })); + // Posted, and then the agent started. + expect(posts.indexOf(status[0])).toBeLessThan(postedBeforeStart); + }); + + it('chat.ready answers at once that the agent is not started, and starts none (on-demand start)', async () => { + const { runtime, posts, acp } = makeRuntime({}); + acp.isClientConnected = () => false; + const start = vi.fn(async () => undefined); + acp.start = start; + await runtime.handleMessage('file:///ws/wf.py', { type: 'chat.ready', data: {} }); + const status = posts.filter(p => p.payload.type === 'chat.connectionStatus'); + expect(status.map(s => s.payload.data)).toEqual([expect.objectContaining({ connected: false, notStarted: true })]); + expect(start).not.toHaveBeenCalled(); }); }); @@ -408,12 +425,13 @@ describe('new-session input box (single source of truth + duplicate guard)', () }); }); +// The handshake starts the agent where the profile asks for an eager start. describe('connect watchdog (30 s dialog on stuck connection)', () => { it('shows a warning dialog when still disconnected 30 s after the handshake', async () => { vi.useFakeTimers(); const warn = vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue(undefined as any); try { - const { runtime } = makeRuntime({}); + const { runtime } = makeRuntime({ agentStart: 'eager' }); const acp = (runtime as any).acp; acp.isClientConnected = () => false; acp.start = () => new Promise(() => undefined); // spawn hangs forever @@ -435,7 +453,7 @@ describe('connect watchdog (30 s dialog on stuck connection)', () => { vi.useFakeTimers(); const warn = vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue(undefined as any); try { - const { runtime } = makeRuntime({}); + const { runtime } = makeRuntime({ agentStart: 'eager' }); const acp = (runtime as any).acp; acp.isClientConnected = () => false; acp.start = async () => undefined; // spawn succeeds immediately @@ -455,7 +473,7 @@ describe('connect watchdog (30 s dialog on stuck connection)', () => { vi.useFakeTimers(); const warn = vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue(undefined as any); try { - const { runtime } = makeRuntime({}); + const { runtime } = makeRuntime({ agentStart: 'eager' }); const acp = (runtime as any).acp; acp.isClientConnected = () => false; acp.start = () => new Promise(() => undefined); diff --git a/packages/extension-core/test/diagram-editor-provider-two-editors.test.ts b/packages/extension-core/test/diagram-editor-provider-two-editors.test.ts index 417c703d..2ef1996d 100644 --- a/packages/extension-core/test/diagram-editor-provider-two-editors.test.ts +++ b/packages/extension-core/test/diagram-editor-provider-two-editors.test.ts @@ -332,6 +332,25 @@ describe('the profile told of a file\'s editors (onEditorOpened, onEditorClosed) }); }); +describe('how many editors the profile has open (what the chat gives its agent back by)', () => { + it('is told as each opens and closes, whatever its file, down to none', () => { + const { provider, open } = makeProvider(); + const counts: number[] = []; + provider.onDidChangeOpenEditors((open: number) => counts.push(open)); + const first = open(FILE, 'client-0'); + const second = open(FILE, 'client-1'); + const other = open(OTHER, 'client-2'); + + first.close(); + other.close(); + expect(provider.openEditorCount).toBe(1); + second.close(); + + expect(counts).toEqual([1, 2, 3, 2, 1, 0]); + expect(provider.openEditorCount).toBe(0); + }); +}); + describe('what a product says its diagram is doing (DiagramProfileHandle.loading)', () => { it('reaches every editor of the file, as one trimmed line, and its end too', () => { const { provider, open } = makeProvider(); diff --git a/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts b/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts index e40fa574..f8363e9f 100644 --- a/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts +++ b/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts @@ -424,6 +424,8 @@ export interface SidecarProfileInput { * context before the question is read. */ sourceContext?: 'embed' | 'reference'; + /** When the chat's agent starts: `on-demand` (the default) or `eager` (`DiagramChatConfig.agentStart`). */ + agentStart?: 'on-demand' | 'eager'; }; // Diagram source-file watch globs (default derived from the source extensions). @@ -947,7 +949,8 @@ export function createSidecarDiagramProfile(givenInput: SidecarProfileInput) { // read. Without it the chat keeps its opencode default. acpConnector: input.acpConnectorSettingKey && input.acpConnectorFiles ? { settingKey: input.acpConnectorSettingKey, files: input.acpConnectorFiles } - : undefined + : undefined, + agentStart: input.chat.agentStart }, runDriver, statusSource: input.statusSource ? createCliStatusSource(input.statusSource, runtimeConfig) : undefined,