diff --git a/src/vs/platform/agentHost/node/agentChatContext.ts b/src/vs/platform/agentHost/node/agentChatContext.ts index 113be985988c30..f6f30f0f440752 100644 --- a/src/vs/platform/agentHost/node/agentChatContext.ts +++ b/src/vs/platform/agentHost/node/agentChatContext.ts @@ -51,10 +51,12 @@ function createAgentChatSessionSettings(snapshot: ISessionStateSnapshot | undefi * registry at every {@link IAgentChatOwnerRef.get}. Before the chat is * registered (a provider creating it) it answers `session`, the session the * operation was issued for; after the chat leaves the registry it answers the - * last owner it saw, so teardown keeps addressing that session. + * last owner it saw, so teardown keeps addressing that session. Before the + * session is registered, `recordedDefaultChat` supplies its persisted chat format. */ -export function createChatOwnerRef(stateManager: AgentHostStateManager, chat: URI | ProtocolURI, session: URI | ProtocolURI): IAgentChatOwnerRef { +export function createChatOwnerRef(stateManager: AgentHostStateManager, chat: URI | ProtocolURI, session: URI | ProtocolURI, recordedDefaultChat?: ProtocolURI): IAgentChatOwnerRef { const chatKey = toKey(chat); + const sessionKey = toKey(session); let last = toKey(session); let lastUri = toUri(session); const getOwner = () => { @@ -67,7 +69,10 @@ export function createChatOwnerRef(stateManager: AgentHostStateManager, chat: UR }; return { get: getOwner, - getSubagentChatUriFormat: () => chatUriFormatOf(stateManager.getDefaultChat(getOwner().toString())), + getSubagentChatUriFormat: () => { + const owner = getOwner().toString(); + return chatUriFormatOf(stateManager.getDefaultChat(owner) ?? (owner === sessionKey ? recordedDefaultChat : undefined)); + }, isDefaultChat: () => { const defaultChat = stateManager.getDefaultChat(getOwner().toString()); return defaultChat === undefined ? undefined : defaultChat === chatKey; @@ -171,9 +176,10 @@ function buildAgentChatContext(stateManager: AgentHostStateManager, authenticati : isChatWorkspaceless(stateManager, chatKey, sessionState, sessionSettings?.workspaceless === true); const isToolChat = typeof origin === 'object' && origin !== null && !Array.isArray(origin) && origin.kind === ChatOriginKind.Tool; const chatSurface = stateManager.getSessionSurfaceMeta(sessionKey)?.surface; + const recordedDefaultChat = sessionState && [...sessionState.chats].find(([, entry]) => entry.isDefault)?.[0]; return { resource: storageResource === sessionKey ? sessionUri : storageResource === chatKey ? toUri(chat) : URI.parse(storageResource), - owner: createChatOwnerRef(stateManager, chat, session), + owner: createChatOwnerRef(stateManager, chat, session, recordedDefaultChat), sessionSettings, workspaceless, launchWorkingDirectories: isToolChat || workspaceless || !launch?.length ? undefined : launch.map(entry => URI.parse(entry)), diff --git a/src/vs/platform/agentHost/node/copilot/copilotAgent.ts b/src/vs/platform/agentHost/node/copilot/copilotAgent.ts index 2467a481657737..b42a14d69df5cb 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotAgent.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotAgent.ts @@ -9510,6 +9510,7 @@ export class CopilotAgent extends Disposable implements IAgent { const backing = this._chatBackings.get(context.chatKey); const result = await mapSessionEvents(context.resource, reference.object, events, context.chat, context.ownerSession, createCopilotSessionPathMapper(metadata.workingDirectory && toCopilotWorkspace(metadata.workingDirectory), resourceJoinPath(this._copilotHomeService.home, 'session-state', sdkSessionId)), { logService: this._logService, + resolveSubagentChatUri: toolCallId => subagentChatUri(context.ownerRef.getSubagentChatUriFormat(), context.ownerSession.toString(), context.chatKey, toolCallId), workingDirectory: metadata.workingDirectory, clientToolNames: new Set(this._activeClients.get(context.ownerSession)?.toolSet.merged().map(tool => tool.name) ?? []), model: backing?.model ?? metadata.model, diff --git a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts index 329423fdfb7e08..d0d96a5e8074c1 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts @@ -1441,6 +1441,10 @@ export class CopilotAgentSession extends Disposable { markdownPartIds: new Map(), }; private readonly _resolveAgentName = (agentId: string) => this._subagents.getDisplayName(agentId); + private readonly _resolveSubagentChat = (agentId: string) => { + const toolCallId = this._subagents.getToolCallId(agentId); + return toolCallId === undefined ? undefined : this._subagentChatUri(toolCallId); + }; readonly modelCallTurnCorrelation = new ModelCallTurnCorrelation(); readonly compactionTurnCorrelation = new CompactionTurnCorrelation(); private readonly _subagentDirectUsageByToolCallId = new Map(); @@ -3425,6 +3429,7 @@ export class CopilotAgentSession extends Disposable { continue; } agentTaskIds.add(task.id); + this._subagents.seedToolCallId(task.id, task.toolCallId); const displayName = subagentChatTitle(task.description, task.displayName); if (displayName) { this._subagents.seedDisplayName(task.id, displayName); @@ -3708,7 +3713,7 @@ export class CopilotAgentSession extends Disposable { return { parameters, meta: this._createToolCallMeta(toolName, parameters), - invocationMessage: getStreamingInvocationMessage(toolName, getToolDisplayName(toolName), partialInput, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getStreamingInvocationMessage(toolName, getToolDisplayName(toolName), partialInput, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), }; } @@ -3864,7 +3869,7 @@ export class CopilotAgentSession extends Disposable { toolCallId, ...(toolCall.contributor ? { contributor: toolCall.contributor } : {}), ...(toolCall.intention !== undefined ? { intention: toolCall.intention } : {}), - invocationMessage: getInvocationMessage(toolCall.toolName, toolCall.displayName, toolCall.parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getInvocationMessage(toolCall.toolName, toolCall.displayName, toolCall.parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), toolInput: getToolInputString(toolCall.toolName, toolCall.parameters, tryStringify(toolCall.parameters)), confirmed: ToolCallConfirmationReason.NotNeeded, _meta: toolCall.meta && toToolCallMeta(toolCall.meta), @@ -4834,7 +4839,7 @@ export class CopilotAgentSession extends Disposable { toolCallId, ...(tracked.contributor ? { contributor: tracked.contributor } : {}), ...(tracked.intention !== undefined ? { intention: tracked.intention } : {}), - invocationMessage: getInvocationMessage(tracked.toolName, tracked.displayName, tracked.parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getInvocationMessage(tracked.toolName, tracked.displayName, tracked.parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), toolInput: getToolInputString(tracked.toolName, tracked.parameters, tracked.parameters ? tryStringify(tracked.parameters) : undefined), confirmed: ToolCallConfirmationReason.NotNeeded, _meta: toToolCallMeta({ ...(tracked.meta ?? {}), toolSearchCandidates: candidates }), @@ -8049,6 +8054,7 @@ export class CopilotAgentSession extends Disposable { return this._withDatabase(async db => { const result = await mapSessionEvents(this._storageUri, db, events, this._chatChannelUri, this._ownerSessionUri, this._pathMapper, { logService: this._logService, + resolveSubagentChatUri: toolCallId => this._subagentChatUri(toolCallId), workingDirectory: this._workingDirectory, clientToolNames: this._clientToolNames, resolveSkill: (name, origin) => this._mcpCustomizations.skillForInvocation(name, origin), @@ -8078,6 +8084,11 @@ export class CopilotAgentSession extends Disposable { } private _seedSubagentDisplayNames(events: readonly SessionEvent[]): void { + for (const event of events) { + if ((event.type === 'subagent.started' || event.type === 'subagent.completed' || event.type === 'subagent.failed') && event.agentId) { + this._subagents.seedToolCallId(event.agentId, event.data.toolCallId); + } + } for (const [agentId, displayName] of getCopilotSubagentDisplayNames(events)) { this._subagents.seedDisplayName(agentId, displayName); } @@ -9000,7 +9011,7 @@ export class CopilotAgentSession extends Disposable { toolCallId, toolName: request.toolName, displayName, - invocationMessage: getInvocationMessage(request.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getInvocationMessage(request.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), toolInput: getToolInputString(request.toolName, parameters, tryStringify(parameters)), riskAssessment: judgeRationale ? { @@ -11023,7 +11034,7 @@ export class CopilotAgentSession extends Disposable { this._nonPtyShellTerminals.completeBackgroundShell(e.data.kind.shellId, e.data.kind.exitCode); } this._seedSubagentDisplayNames([e]); - const notification = buildCopilotSystemNotification(e, this._resolveAgentName); + const notification = buildCopilotSystemNotification(e, this._resolveAgentName, this._resolveSubagentChat); if (!notification) { this._logService.trace(`[Copilot:${sessionId}] Ignoring system.notification kind=${e.data.kind.type}`); return; @@ -11576,7 +11587,7 @@ export class CopilotAgentSession extends Disposable { toolCallId: e.data.toolCallId, ...(contributor ? { contributor } : {}), ...(intention !== undefined ? { intention } : {}), - invocationMessage: getInvocationMessage(e.data.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getInvocationMessage(e.data.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), toolInput: getToolInputString(e.data.toolName, parameters, toolArgs), confirmed: ToolCallConfirmationReason.NotNeeded, _meta: toToolCallMeta(meta), @@ -11616,7 +11627,7 @@ export class CopilotAgentSession extends Disposable { toolCallId: e.data.toolCallId, ...(contributor ? { contributor } : {}), ...(intention !== undefined ? { intention } : {}), - invocationMessage: getInvocationMessage(e.data.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName), + invocationMessage: getInvocationMessage(e.data.toolName, displayName, parameters, path => this._resolveDisplayFilePath(path), this._resolveAgentName, this._resolveSubagentChat), toolInput: getToolInputString(e.data.toolName, parameters, toolArgs), confirmed: ToolCallConfirmationReason.NotNeeded, _meta: toToolCallMeta(clientToolAutoApproved ? { ...meta, autoApproveBySetting: true } : meta), @@ -11829,7 +11840,7 @@ export class CopilotAgentSession extends Disposable { const complete = (authoritativeOutput?: string) => { const result: ToolCallResult = { success: e.data.success, - pastTenseMessage: getPastTenseMessage(tracked.toolName, displayName, tracked.parameters, e.data.success, e.data.success ? toolOutput : undefined, path => this._resolveDisplayFilePath(path), this._resolveAgentName, tracked.meta?.[imageGenerationToolMetaKey]), + pastTenseMessage: getPastTenseMessage(tracked.toolName, displayName, tracked.parameters, e.data.success, e.data.success ? toolOutput : undefined, path => this._resolveDisplayFilePath(path), this._resolveAgentName, tracked.meta?.[imageGenerationToolMetaKey], this._resolveSubagentChat), content: content.length > 0 ? content : undefined, structuredContent: e.data.result?.structuredContent as Record | undefined, resultMetadata: getSdkMcpResultMeta(e.data.result), diff --git a/src/vs/platform/agentHost/node/copilot/copilotSubagentTracking.ts b/src/vs/platform/agentHost/node/copilot/copilotSubagentTracking.ts index 0a1a03154541bb..3a6e1e7fb3f031 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotSubagentTracking.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotSubagentTracking.ts @@ -132,6 +132,12 @@ export class CopilotSubagentTracking extends Disposable { return this._toolCallsByAgent.get(agentId); } + seedToolCallId(agentId: string, toolCallId: string): void { + if (!this._toolCallsByAgent.has(agentId)) { + this._toolCallsByAgent.set(agentId, toolCallId); + } + } + getAgentId(toolCallId: string): string | undefined { for (const [agentId, candidate] of this._toolCallsByAgent) { if (candidate === toolCallId) { diff --git a/src/vs/platform/agentHost/node/copilot/copilotSystemNotification.ts b/src/vs/platform/agentHost/node/copilot/copilotSystemNotification.ts index 9adf2ed598f99e..3837b8bf272cf0 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotSystemNotification.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotSystemNotification.ts @@ -8,7 +8,7 @@ import { softAssertNever } from '../../../../base/common/assert.js'; import { appendEscapedMarkdownInlineCode } from '../../../../base/common/htmlContent.js'; import { localize } from '../../../../nls.js'; import { subagentChatTitle } from '../../common/agent.js'; -import { getSubagentMetadata, getToolKind, type ToolAgentNameResolver } from './copilotToolDisplay.js'; +import { formatSubagentChatLink, getSubagentMetadata, getToolKind, type ToolAgentNameResolver } from './copilotToolDisplay.js'; export interface ICopilotSystemNotification { /** Text for a new system-origin AHP turn; derived from SDK `data.kind` metadata, e.g. shell completion `description`. */ @@ -69,7 +69,7 @@ export function getCopilotSubagentDisplayNames(events: readonly SessionEvent[]): return names; } -export function buildCopilotSystemNotification(event: SessionEventPayload<'system.notification'>, resolveAgentName?: ToolAgentNameResolver): ICopilotSystemNotification | undefined { +export function buildCopilotSystemNotification(event: SessionEventPayload<'system.notification'>, resolveAgentName?: ToolAgentNameResolver, resolveAgentChat?: (agentId: string) => string | undefined): ICopilotSystemNotification | undefined { const data = event.data; const kind: SystemNotification = data.kind; const content = cleanSystemNotificationContent(data.content); @@ -91,6 +91,18 @@ export function buildCopilotSystemNotification(event: SessionEventPayload<'syste case 'agent_completed': case 'agent_idle': { const name = resolveAgentName?.(kind.agentId)?.trim() || getCopilotSubagentDisplayInfo(event)?.displayName; + const chat = name ? resolveAgentChat?.(kind.agentId) : undefined; + if (name && chat) { + const link = formatSubagentChatLink(name, chat); + return { + messageText: kind.type === 'agent_idle' + ? localize('agentHost.copilot.systemNotification.linkedAgentIdle', "{0} is complete", link) + : kind.status === 'failed' + ? localize('agentHost.copilot.systemNotification.linkedAgentFailed', "{0} failed", link) + : localize('agentHost.copilot.systemNotification.linkedAgentCompleted', "{0} completed", link), + startsTurn: true, + }; + } const formattedName = name ? appendEscapedMarkdownInlineCode(name) : undefined; if (kind.type === 'agent_idle') { return { diff --git a/src/vs/platform/agentHost/node/copilot/copilotToolDisplay.ts b/src/vs/platform/agentHost/node/copilot/copilotToolDisplay.ts index 7979c399d7725c..92c19bc226d523 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotToolDisplay.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotToolDisplay.ts @@ -7,7 +7,7 @@ import type { AssistantMessageToolRequest, McpSkillOrigin, PermissionRequest, Se import { assertNever } from '../../../../base/common/assert.js'; import { hasKey, isObject } from '../../../../base/common/types.js'; import { URI } from '../../../../base/common/uri.js'; -import { appendEscapedMarkdownInlineCode, escapeMarkdownLinkLabel, escapeMarkdownSyntaxTokens, escapeUntrustedMarkdown, MarkdownString } from '../../../../base/common/htmlContent.js'; +import { appendEscapedMarkdownInlineCode, escapeMarkdownLinkLabel, escapeMarkdownLinkText, escapeMarkdownSyntaxTokens, escapeUntrustedMarkdown, MarkdownString } from '../../../../base/common/htmlContent.js'; import { hash } from '../../../../base/common/hash.js'; import { escapeIcons } from '../../../../base/common/iconLabels.js'; import { isAbsolute } from '../../../../base/common/path.js'; @@ -281,16 +281,24 @@ interface ICopilotLongRunningSearchToolArgs { } export type ToolAgentNameResolver = (agentId: string) => string | undefined; +export type ToolAgentChatResolver = (agentId: string) => string | undefined; + +export function formatSubagentChatLink(name: string, chat: string): string { + return new MarkdownString().appendLink(chat, escapeMarkdownLinkText(name)).value; +} /** * Resolves SDK agent ids to their subagent chat titles for presentation without changing invocation arguments. * Unknown ids and blank titles fall back to the raw id. */ -function getAgentLabel(agentId: unknown, resolveAgentName: ToolAgentNameResolver | undefined): string | undefined { +function formatAgentLabel(agentId: unknown, resolveAgentName: ToolAgentNameResolver | undefined, resolveAgentChat: ToolAgentChatResolver | undefined): string | undefined { if (typeof agentId !== 'string' || agentId.length === 0) { return undefined; } - return resolveAgentName?.(agentId)?.trim() || agentId; + const name = resolveAgentName?.(agentId)?.trim(); + const chat = name ? resolveAgentChat?.(agentId) : undefined; + const label = name || agentId; + return chat ? formatSubagentChatLink(label, chat) : appendEscapedMarkdownInlineCode(label); } /** @@ -756,7 +764,7 @@ export function getToolDisplayName(toolName: string, metadata?: Pick | undefined, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver): StringOrMarkdown { +export function getInvocationMessage(toolName: string, displayName: string, parameters: Record | undefined, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver, resolveAgentChat?: ToolAgentChatResolver): StringOrMarkdown { const serverDisplay = getServerToolDisplay(toolName, parameters)?.invocationMessage; if (serverDisplay !== undefined) { return serverDisplay; @@ -916,25 +924,26 @@ export function getInvocationMessage(toolName: string, displayName: string, para case CopilotToolName.ListAgents: return localize('toolInvoke.listAgents', "List agents"); case CopilotToolName.ReadAgent: { - const agentLabel = getAgentLabel(parameters?.agent_id, resolveAgentName); + const agentLabel = formatAgentLabel(parameters?.agent_id, resolveAgentName, resolveAgentChat); if (agentLabel) { - return md(localize('toolInvoke.readAgent', "Read agent {0}", appendEscapedMarkdownInlineCode(agentLabel))); + return md(localize('toolInvoke.readAgent', "Read agent {0}", agentLabel)); } return localize('toolInvoke.readAgentGeneric', "Read agent"); } case CopilotToolName.WriteAgent: { - const agentLabel = getAgentLabel(parameters?.agent_id, resolveAgentName); - if (agentLabel) { - return md(localize('toolInvoke.writeAgent', "Write to agent {0}", appendEscapedMarkdownInlineCode(agentLabel))); + const formatAgent = (agentId: unknown) => formatAgentLabel(agentId, resolveAgentName, resolveAgentChat); + const agent = formatAgent(parameters?.agent_id); + if (agent) { + return md(localize('toolInvoke.writeAgent', "Write to agent {0}", agent)); } const agentLabels = Array.isArray(parameters?.agent_ids) - ? parameters.agent_ids.map(agentId => getAgentLabel(agentId, resolveAgentName)).filter(label => label !== undefined) + ? parameters.agent_ids.map(formatAgent).filter(label => label !== undefined) : []; if (agentLabels.length === 1) { - return md(localize('toolInvoke.writeAgent', "Write to agent {0}", appendEscapedMarkdownInlineCode(agentLabels[0]))); + return md(localize('toolInvoke.writeAgent', "Write to agent {0}", agentLabels[0])); } if (agentLabels.length > 1) { - return md(localize('toolInvoke.writeAgents', "Write to agents {0}", agentLabels.map(label => appendEscapedMarkdownInlineCode(label)).join(', '))); + return md(localize('toolInvoke.writeAgents', "Write to agents {0}", agentLabels.join(', '))); } if (parameters?.scope === 'children') { return localize('toolInvoke.writeChildAgents', "Write to child agents"); @@ -952,7 +961,7 @@ export function getInvocationMessage(toolName: string, displayName: string, para /** * Returns the progressively refined message shown while Copilot generates tool input. */ -export function getStreamingInvocationMessage(toolName: string, displayName: string, parameters: unknown, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver): StringOrMarkdown { +export function getStreamingInvocationMessage(toolName: string, displayName: string, parameters: unknown, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver, resolveAgentChat?: ToolAgentChatResolver): StringOrMarkdown { const objectParameters = parameters !== null && typeof parameters === 'object' && !Array.isArray(parameters) ? parameters as Record : undefined; @@ -993,7 +1002,7 @@ export function getStreamingInvocationMessage(toolName: string, displayName: str return getStreamingPatchMessage(getEditFilePaths(parameters), streamingToolTextLineCount(patch), resolvePath); } default: - return getInvocationMessage(toolName, displayName, objectParameters, resolvePath, resolveAgentName); + return getInvocationMessage(toolName, displayName, objectParameters, resolvePath, resolveAgentName, resolveAgentChat); } } @@ -1013,7 +1022,7 @@ export function getSdkImageGenerationMetadata(data: unknown, toolUsage?: unknown return parseImageGenerationToolMetadata({ requestedModel, usage: toolUsage }); } -export function getPastTenseMessage(toolName: string, displayName: string, parameters: Record | undefined, success: boolean, resultText?: string, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver, imageGeneration?: IImageGenerationToolMetadata): StringOrMarkdown { +export function getPastTenseMessage(toolName: string, displayName: string, parameters: Record | undefined, success: boolean, resultText?: string, resolvePath: ToolPathResolver = identityPathResolver, resolveAgentName?: ToolAgentNameResolver, imageGeneration?: IImageGenerationToolMetadata, resolveAgentChat?: ToolAgentChatResolver): StringOrMarkdown { if (!success) { return localize('toolComplete.failed', "\"{0}\" failed", displayName); } @@ -1065,7 +1074,7 @@ export function getPastTenseMessage(toolName: string, displayName: string, param case CopilotToolName.Task: return localize('toolComplete.task', "Delegated task"); default: - return getInvocationMessage(toolName, displayName, parameters, resolvePath, resolveAgentName); + return getInvocationMessage(toolName, displayName, parameters, resolvePath, resolveAgentName, resolveAgentChat); } } diff --git a/src/vs/platform/agentHost/node/copilot/mapSessionEvents.ts b/src/vs/platform/agentHost/node/copilot/mapSessionEvents.ts index cc44a2dfa57864..df2b58fc2c8b30 100644 --- a/src/vs/platform/agentHost/node/copilot/mapSessionEvents.ts +++ b/src/vs/platform/agentHost/node/copilot/mapSessionEvents.ts @@ -359,6 +359,7 @@ export interface IMapSessionEventsOptions { readonly agent?: AgentSelection; readonly interruptedTurnError?: ErrorInfo; readonly resolveSkill?: SkillToolCallResolver; + readonly resolveSubagentChatUri?: (toolCallId: string) => string; } function newTurnBuilder(id: string, text: string, options?: { attachments?: MessageAttachment[]; model?: ModelSelection; agent?: AgentSelection; origin?: MessageKind; startedAt?: string }): ITurnBuilder { @@ -405,7 +406,7 @@ function readMcpUiResourceUri(source: unknown): string | undefined { return readStringProperty(ui, 'resourceUri'); } -function makeToolStartInfo(toolName: string, rawArguments: unknown, parentToolCallId: string | undefined, pathMapper: ICopilotSdkPathMapper, workingDirectory: URI | undefined, source: unknown, resolveAgentName: ToolAgentNameResolver, toolTitle?: string, intentionSummary?: string | null): IToolStartInfo | undefined { +function makeToolStartInfo(toolName: string, rawArguments: unknown, parentToolCallId: string | undefined, pathMapper: ICopilotSdkPathMapper, workingDirectory: URI | undefined, source: unknown, resolveAgentName: ToolAgentNameResolver, resolveAgentChat: (agentId: string) => string | undefined, toolTitle?: string, intentionSummary?: string | null): IToolStartInfo | undefined { if (isHiddenTool(toolName)) { return undefined; } @@ -426,7 +427,7 @@ function makeToolStartInfo(toolName: string, rawArguments: unknown, parentToolCa return { toolName, displayName, - invocationMessage: getInvocationMessage(toolName, displayName, parameters, path => resolveToolDisplayPath(path, pathMapper, workingDirectory), resolveAgentName), + invocationMessage: getInvocationMessage(toolName, displayName, parameters, path => resolveToolDisplayPath(path, pathMapper, workingDirectory), resolveAgentName, resolveAgentChat), toolInput: getToolInputString(toolName, parameters, toolArgs), toolKind, language: toolKind === 'terminal' ? getShellLanguage(toolName) : undefined, @@ -513,6 +514,15 @@ export async function mapSessionEvents( // `agentId` and the parent tool call id it was spawned from, so we map // one to the other and resolve every later sub-agent event through it. const parentToolCallIdByAgentId = new Map(); + for (const event of events) { + if ((event.type === 'subagent.started' || event.type === 'subagent.completed' || event.type === 'subagent.failed') && event.agentId && !parentToolCallIdByAgentId.has(event.agentId)) { + parentToolCallIdByAgentId.set(event.agentId, event.data.toolCallId); + } + } + const resolveAgentChat = (agentId: string) => { + const toolCallId = parentToolCallIdByAgentId.get(agentId); + return toolCallId === undefined ? undefined : options?.resolveSubagentChatUri?.(toolCallId); + }; const resolveParentToolCallId = (agentId: string | undefined, deprecatedParentToolCallId: string | undefined): string | undefined => { const mapped = agentId ? parentToolCallIdByAgentId.get(agentId) : undefined; return mapped ?? deprecatedParentToolCallId; @@ -576,6 +586,8 @@ export async function mapSessionEvents( if (e.agentId) { parentToolCallIdByAgentId.set(e.agentId, e.data.toolCallId); } + } else if ((e.type === 'subagent.completed' || e.type === 'subagent.failed') && e.agentId && !parentToolCallIdByAgentId.has(e.agentId)) { + parentToolCallIdByAgentId.set(e.agentId, e.data.toolCallId); } if (e.type === 'assistant.message' && !e.agentId) { for (const request of e.data.toolRequests ?? []) { @@ -607,7 +619,7 @@ export async function mapSessionEvents( if (e.type === 'tool.execution_start') { const d = e.data; const parentToolCallId = resolveParentToolCallId(e.agentId, d.parentToolCallId) ?? resolveFusionPhaseToolCallId(e.agentId, d.fusion); - const info = makeToolStartInfo(d.toolName, d.arguments, parentToolCallId, pathMapper, workingDirectory, d, resolveAgentName, toolTitlesByCallId.get(d.toolCallId), toolIntentionsByCallId.get(d.toolCallId)); + const info = makeToolStartInfo(d.toolName, d.arguments, parentToolCallId, pathMapper, workingDirectory, d, resolveAgentName, resolveAgentChat, toolTitlesByCallId.get(d.toolCallId), toolIntentionsByCallId.get(d.toolCallId)); if (!info) { continue; } @@ -1006,7 +1018,7 @@ export async function mapSessionEvents( break; } case 'system.notification': { - const notification = buildCopilotSystemNotification(e, resolveAgentName); + const notification = buildCopilotSystemNotification(e, resolveAgentName, resolveAgentChat); if (!notification) { break; } @@ -1093,7 +1105,7 @@ export async function mapSessionEvents( // No active turn to attach this completion to. continue; } - const completedPart = makeToolCallPart(d.toolCallId, d, info, sessionUriStr, routingSession, providerId, rawSessionId, routingChatUri, storedEdits, storedResources, subagentInfoByToolCallId.get(d.toolCallId), pathMapper, workingDirectory, resolveAgentName, binaryAssets, readEventTimestamp(e)); + const completedPart = makeToolCallPart(d.toolCallId, d, info, sessionUriStr, routingSession, providerId, rawSessionId, routingChatUri, storedEdits, storedResources, subagentInfoByToolCallId.get(d.toolCallId), pathMapper, workingDirectory, resolveAgentName, resolveAgentChat, binaryAssets, readEventTimestamp(e)); builder.responseParts.push(completedPart); // Background task launch completion is not a child-turn boundary. if (!parentToolCallId && subagentInfoByToolCallId.has(d.toolCallId) && info.parameters?.mode !== 'background') { @@ -1181,7 +1193,7 @@ export async function mapSessionEvents( continue; } const info = toolInfoByCallId.get(request.toolCallId) - ?? makeToolStartInfo(request.name, request.arguments, parentToolCallId, pathMapper, workingDirectory, request, resolveAgentName, request.toolTitle, request.intentionSummary); + ?? makeToolStartInfo(request.name, request.arguments, parentToolCallId, pathMapper, workingDirectory, request, resolveAgentName, resolveAgentChat, request.toolTitle, request.intentionSummary); if (!info) { continue; } @@ -1205,6 +1217,7 @@ export async function mapSessionEvents( pathMapper, workingDirectory, resolveAgentName, + resolveAgentChat, binaryAssets, )); } @@ -1376,6 +1389,7 @@ function makeToolCallPart( pathMapper: ICopilotSdkPathMapper, workingDirectory: URI | undefined, resolveAgentName: ToolAgentNameResolver, + resolveAgentChat: (agentId: string) => string | undefined, binaryAssets: ReadonlyMap, completedAt?: string, ): ResponsePart { @@ -1517,7 +1531,7 @@ function makeToolCallPart( ...base, status: ToolCallStatus.Completed, success: d.success, - pastTenseMessage: getPastTenseMessage(info.toolName, info.displayName, info.parameters, d.success, d.success ? toolOutput : undefined, path => resolveToolDisplayPath(path, pathMapper, workingDirectory), resolveAgentName, imageGeneration), + pastTenseMessage: getPastTenseMessage(info.toolName, info.displayName, info.parameters, d.success, d.success ? toolOutput : undefined, path => resolveToolDisplayPath(path, pathMapper, workingDirectory), resolveAgentName, imageGeneration, resolveAgentChat), content: content.length > 0 ? content : undefined, structuredContent: d.result?.structuredContent as Record | undefined, resultMetadata: getSdkMcpResultMeta(d.result), diff --git a/src/vs/platform/agentHost/test/node/agentService.test.ts b/src/vs/platform/agentHost/test/node/agentService.test.ts index f44c959c8c52ba..d4cb55adff8717 100644 --- a/src/vs/platform/agentHost/test/node/agentService.test.ts +++ b/src/vs/platform/agentHost/test/node/agentService.test.ts @@ -28439,50 +28439,63 @@ suite('AgentService (node dispatcher)', () => { } }); - test('restored historical subagents retain an advertised physical default parent', async () => { - const session = URI.parse('ahp-session:/historical-advertised-default'); - const physical = buildChatUri(session, 'physical-default'); - const child = buildSubagentChatUri(session.toString(), 'historical-task'); - const database = disposables.add(new AgentHostDatabase(':memory:')); - await database.registerSessionV2(session.toString(), { provider: 'copilot', startTime: 1, source: 'explicit' }, { checkTombstone: false }); - await database.updateSessionV2External([{ session: session.toString(), external: false }]); - await database.registerChatCatalogV2(session.toString(), { - defaultChat: { chat: physical, order: 0, providerData: 'physical-backing' }, - peers: [], privateDescendants: [], - }); - class HistoricalAgent extends MockAgent { - override async getChatMetadata(chat: URI): Promise { - return { chat, startTime: 1, modifiedTime: 1, summary: 'Owner' }; + for (const format of ['shaped', 'opaque'] as const) { + test(`restored historical subagent references match the advertised child chat (${format})`, async () => { + const session = URI.parse('ahp-session:/historical-advertised-default'); + const physical = format === 'opaque' ? 'ahp-chat:/11111111-1111-5111-8111-111111111111' : buildChatUri(session, 'physical-default'); + const child = subagentChatUri(format, session.toString(), physical, 'historical-task'); + const database = disposables.add(new AgentHostDatabase(':memory:')); + await database.registerSessionV2(session.toString(), { provider: 'copilot', startTime: 1, source: 'explicit' }, { checkTombstone: false }); + await database.updateSessionV2External([{ session: session.toString(), external: false }]); + await database.registerChatCatalogV2(session.toString(), { + defaultChat: { chat: physical, order: 0, providerData: 'physical-backing' }, + peers: [], privateDescendants: [], + }); + class HistoricalAgent extends MockAgent { + override async getChatMetadata(chat: URI): Promise { + return { chat, startTime: 1, modifiedTime: 1, summary: 'Owner' }; + } + override async materializeChat(): Promise { } } - override async materializeChat(): Promise { } - } - const agent = disposables.add(new HistoricalAgent('copilot')); - agent.sessionMessages = [ - { type: 'message', session, role: 'user', messageId: 'user', content: 'Delegate', toolRequests: [] }, - { type: 'message', session, role: 'assistant', messageId: 'assistant', content: '', toolRequests: [{ toolCallId: 'historical-task', name: 'task' }] }, - { type: 'tool_start', session, toolCallId: 'historical-task', toolName: 'task', displayName: 'Task', invocationMessage: 'Delegating', toolKind: 'subagent', subagentDescription: 'Historical Worker', subagentAgentName: 'explore' }, - { type: 'subagent_started', session, toolCallId: 'historical-task', agentName: 'explore', agentDisplayName: 'Explore', agentDescription: 'Explore' }, - { type: 'tool_complete', session, toolCallId: 'historical-task', result: { success: true, pastTenseMessage: 'Delegated', content: [] } }, - ]; - const svc = disposables.add(createTestAgentService( - new NullLogService(), fileService, createPerSessionDataService().service, { _serviceBrand: undefined } as IProductService, createNoopGitService(), - undefined, undefined, undefined, undefined, undefined, [], undefined, undefined, database, - )); - registerTestAgentProvider(svc, agent); - await svc.restoreSession(session); - const row = (await database.readChatV2(session.toString(), child)).chat; - assert.deepStrictEqual({ - physical: getStateManager(svc).getDefaultChat(session.toString()), - parent: row?.parentChat, - origin: row?.origin, - publicOrder: row?.order, - }, { - physical, - parent: physical, - origin: JSON.stringify({ kind: ChatOriginKind.Tool, chat: physical, toolCallId: 'historical-task' }), - publicOrder: undefined, + const agent = disposables.add(new HistoricalAgent('copilot')); + let providerChild: string | undefined; + const getMessages = agent.chats.getMessages; + agent.chats.getMessages = async (chat, operationContext) => { + const context = resolveAgentChatContext(operationContext, chat); + providerChild = subagentChatUri(context.owner.getSubagentChatUriFormat(), context.owner.get().toString(), chat.toString(), 'historical-task'); + return getMessages(chat, operationContext); + }; + agent.sessionMessages = [ + { type: 'message', session, role: 'user', messageId: 'user', content: 'Delegate', toolRequests: [] }, + { type: 'message', session, role: 'assistant', messageId: 'assistant', content: '', toolRequests: [{ toolCallId: 'historical-task', name: 'task' }] }, + { type: 'tool_start', session, toolCallId: 'historical-task', toolName: 'task', displayName: 'Task', invocationMessage: 'Delegating', toolKind: 'subagent', subagentDescription: 'Historical Worker', subagentAgentName: 'explore' }, + { type: 'subagent_started', session, toolCallId: 'historical-task', agentName: 'explore', agentDisplayName: 'Explore', agentDescription: 'Explore' }, + { type: 'tool_complete', session, toolCallId: 'historical-task', result: { success: true, pastTenseMessage: 'Delegated', content: [] } }, + ]; + const svc = disposables.add(createTestAgentService( + new NullLogService(), fileService, createPerSessionDataService().service, { _serviceBrand: undefined } as IProductService, createNoopGitService(), + undefined, undefined, undefined, undefined, undefined, [], undefined, undefined, database, + )); + registerTestAgentProvider(svc, agent); + await svc.restoreSession(session); + const row = (await database.readChatV2(session.toString(), child)).chat; + assert.deepStrictEqual({ + physical: getStateManager(svc).getDefaultChat(session.toString()), + providerChild, + registeredChild: getStateManager(svc).getSessionState(session.toString())?.chats.find(chat => chat.origin?.kind === ChatOriginKind.Tool)?.resource, + parent: row?.parentChat, + origin: row?.origin, + publicOrder: row?.order, + }, { + physical, + providerChild: child, + registeredChild: child, + parent: physical, + origin: JSON.stringify({ kind: ChatOriginKind.Tool, chat: physical, toolCallId: 'historical-task' }), + publicOrder: undefined, + }); }); - }); + } test('persists a materialized historical subagent before workspace metadata updates', async () => { const session = URI.parse('ahp-session:/materialized-historical-subagent'); diff --git a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts index 658dc950bbc6f2..46e77524544cc3 100644 --- a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts @@ -12433,6 +12433,7 @@ suite('CopilotAgentSession', () => { mockSession.fire('tool.execution_complete', { toolCallId: 'read', success: true, result: { content: 'The review is done.' } }); await timeout(0); + const chat = subagentChatUri('shaped', session.ownerSessionUri.toString(), session.chatChannelUri.toString(), 'tc-task'); assert.deepStrictEqual({ messages: getActions(signals).flatMap(action => action.type === ActionType.ChatToolCallReady && action.toolCallId === 'read' ? [action.invocationMessage] @@ -12440,7 +12441,7 @@ suite('CopilotAgentSession', () => { ? [action.result.pastTenseMessage] : []), parameters, }, { - messages: [{ markdown: 'Read agent `catalog-perf`' }, { markdown: 'Read agent `catalog-perf`' }], + messages: [{ markdown: `Read agent [catalog\\-perf](${chat})` }, { markdown: `Read agent [catalog\\-perf](${chat})` }], parameters: { agent_id: agentId, wait: false }, }); }); @@ -12486,6 +12487,7 @@ suite('CopilotAgentSession', () => { for (const kind of notifications) { mockSession.fire('system.notification', { content: 'Agent finished', kind }); } + const chat = subagentChatUri('shaped', session.ownerSessionUri.toString(), session.chatChannelUri.toString(), 'tc-task'); assert.deepStrictEqual({ chatTitles: signals.flatMap(signal => signal.kind === 'subagent_started' ? [SubagentChatSignal.toSpawnEvent(signal, chat => { const owner = mintedTestChatOwner(chat); return owner === undefined ? undefined : { owner, format: 'shaped' }; })?.title] : []), toolMessages: getActions(signals).flatMap(action => { @@ -12499,15 +12501,15 @@ suite('CopilotAgentSession', () => { }, { chatTitles: restored ? [] : ['Fix Take-all ground pickup'], toolMessages: [ - { markdown: 'Read agent `Fix Take-all ground pickup`' }, - { markdown: 'Read agent `Fix Take-all ground pickup`' }, - { markdown: 'Write to agent `Fix Take-all ground pickup`' }, - { markdown: 'Write to agent `Fix Take-all ground pickup`' }, + { markdown: `Read agent [Fix Take\\-all ground pickup](${chat})` }, + { markdown: `Read agent [Fix Take\\-all ground pickup](${chat})` }, + { markdown: `Write to agent [Fix Take\\-all ground pickup](${chat})` }, + { markdown: `Write to agent [Fix Take\\-all ground pickup](${chat})` }, ], notifications: [ - 'Background agent `Fix Take-all ground pickup` is complete', - 'Background agent `Fix Take-all ground pickup` completed', - 'Background agent `Fix Take-all ground pickup` failed', + `[Fix Take\\-all ground pickup](${chat}) is complete`, + `[Fix Take\\-all ground pickup](${chat}) completed`, + `[Fix Take\\-all ground pickup](${chat}) failed`, ], coordinationParameters: { agent_id: agentId }, }); @@ -12561,12 +12563,13 @@ suite('CopilotAgentSession', () => { mockSession.fire('tool.execution_start', { toolCallId: 'write', toolName: 'write_agent', arguments: { agent_id: 'agent-1', message: 'Follow up' } }); mockSession.fire('tool.execution_complete', { toolCallId: 'write', success: true }); + const chat = subagentChatUri('shaped', session.ownerSessionUri.toString(), session.chatChannelUri.toString(), 'launch'); assert.deepStrictEqual(getActions(signals).flatMap(action => action.type === ActionType.ChatToolCallReady && action.toolCallId === 'write' ? [action.invocationMessage] : action.type === ActionType.ChatToolCallComplete && action.toolCallId === 'write' ? [action.result.pastTenseMessage] : []), [ - { markdown: 'Write to agent `Review the history`' }, - { markdown: 'Write to agent `Review the history`' }, + { markdown: `Write to agent [Review the history](${chat})` }, + { markdown: `Write to agent [Review the history](${chat})` }, ]); }); @@ -12586,12 +12589,13 @@ suite('CopilotAgentSession', () => { mockSession.fire('tool.execution_start', { toolCallId: 'write', toolName: 'write_agent', arguments: { agent_id: 'agent-1', message: 'Follow up' } }); mockSession.fire('tool.execution_complete', { toolCallId: 'write', success: true }); + const chat = subagentChatUri('shaped', session.ownerSessionUri.toString(), session.chatChannelUri.toString(), 'launch'); assert.deepStrictEqual(getActions(signals).flatMap(action => action.type === ActionType.ChatToolCallReady && action.toolCallId === 'write' ? [action.invocationMessage] : action.type === ActionType.ChatToolCallComplete && action.toolCallId === 'write' ? [action.result.pastTenseMessage] : []), [ - { markdown: 'Write to agent `History reviewer`' }, - { markdown: 'Write to agent `History reviewer`' }, + { markdown: `Write to agent [History reviewer](${chat})` }, + { markdown: `Write to agent [History reviewer](${chat})` }, ]); }); @@ -20173,6 +20177,17 @@ Use the attached image as context. ]); }); + test('agent notification links escape labels and destinations', () => { + const event: SessionEventPayload<'system.notification'> = { + id: 'notification', parentId: null, timestamp: '2026-09-08T00:00:00.000Z', type: 'system.notification', + data: { content: 'Agent finished', kind: { type: 'agent_completed', agentId: 'agent', agentType: 'task', status: 'completed' } }, + }; + assert.deepStrictEqual(buildCopilotSystemNotification(event, () => 'Review [x] `y` & \nnext', () => 'ahp-chat://subagent/path(a) b'), { + messageText: '[Review \\[x\\] \\`y\\` \\& \\ next](ahp-chat://subagent/path\\(a\\)%20b) completed', + startsTurn: true, + }); + }); + test('agent activity titles retain the chat title truncation and markdown escaping', () => { const descriptions = [' Review `permissions` ', ` ${'a'.repeat(80)} `, ' ']; const titles = ['Review `permissions`', `${'a'.repeat(60)}\u2026`, 'reviewer']; @@ -20224,6 +20239,28 @@ Use the attached image as context. }); }); + test('restored subagent completion starts a turn linked to its exact chat', async () => { + const { session, mockSession, signals } = await createAgentSession(disposables, { + resume: true, + configureMockSession: mock => { + mock.messages = toSessionEvents([ + { type: 'subagent.started', agentId: 'first', data: { toolCallId: 'task-first', agentName: 'review', agentDisplayName: 'First', agentDescription: '' } }, + { type: 'subagent.started', agentId: 'second', data: { toolCallId: 'task-second', agentName: 'review', agentDisplayName: 'Second', agentDescription: '' } }, + ]); + }, + }); + await session.getMessages(); + mockSession.fire('system.notification', { + content: 'Finished', + kind: { type: 'agent_completed', agentId: 'second', agentType: 'review', status: 'failed' }, + }); + const childChat = subagentChatUri('shaped', session.ownerSessionUri.toString(), session.chatChannelUri.toString(), 'task-second'); + assert.deepStrictEqual(getActions(signals).find(action => action.type === ActionType.ChatTurnStarted)?.message, { + text: `[Second](${childChat}) failed`, + origin: { kind: MessageKind.SystemNotification }, + }); + }); + test('agent idle notification during an active turn appends a SystemNotification response part', async () => { const { session, mockSession, signals } = await createAgentSession(disposables); session.resetTurnState('turn-active'); diff --git a/src/vs/platform/agentHost/test/node/copilotToolDisplay.test.ts b/src/vs/platform/agentHost/test/node/copilotToolDisplay.test.ts index d7630ef01bee1e..fd71678773368c 100644 --- a/src/vs/platform/agentHost/test/node/copilotToolDisplay.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotToolDisplay.test.ts @@ -1021,6 +1021,32 @@ suite('copilotToolDisplay — built-in tool invocation/past-tense messages', () }); }); + test('links known write recipients in streaming, ready, and completed messages', () => { + const names = new Map([['agent-1', 'Renderer reviewer'], ['agent-2', 'Review [permissions]']]); + const chats = new Map([['agent-1', 'ahp-chat:/renderer'], ['agent-2', 'ahp-chat:/permissions(a)']]); + const parameters = { agent_ids: ['agent-1', 'agent-2', 'unknown-agent'], message: 'Follow up' }; + const resolveName = (id: string) => names.get(id); + const resolveChat = (id: string) => chats.get(id); + assert.deepStrictEqual([ + getStreamingInvocationMessage('write_agent', 'Write to Agent', parameters, undefined, resolveName, resolveChat), + getInvocationMessage('write_agent', 'Write to Agent', parameters, undefined, resolveName, resolveChat), + getPastTenseMessage('write_agent', 'Write to Agent', parameters, true, undefined, undefined, resolveName, undefined, resolveChat), + ], Array(3).fill({ markdown: 'Write to agents [Renderer reviewer](ahp-chat:/renderer), [Review \\[permissions\\]](ahp-chat:/permissions\\(a\\)), `unknown-agent`' })); + }); + + for (const [toolName, verb] of [['read_agent', 'Read agent'], ['write_agent', 'Write to agent']]) { + test(`links the named child chat in streaming, ready, and completed ${toolName} messages`, () => { + const parameters = { agent_id: 'agent-1' }; + const resolveName = () => 'Review [permissions]'; + const resolveChat = () => 'ahp-chat:/11111111-1111-5111-8111-111111111111'; + assert.deepStrictEqual([ + getStreamingInvocationMessage(toolName, 'Agent', parameters, undefined, resolveName, resolveChat), + getInvocationMessage(toolName, 'Agent', parameters, undefined, resolveName, resolveChat), + getPastTenseMessage(toolName, 'Agent', parameters, true, undefined, undefined, resolveName, undefined, resolveChat), + ], Array(3).fill({ markdown: `${verb} [Review \\[permissions\\]](${resolveChat()})` })); + }); + } + test('describes scoped writes and tolerates incomplete streaming recipients', () => { assert.deepStrictEqual([ invocation('write_agent', { scope: 'children' }), diff --git a/src/vs/platform/agentHost/test/node/mapSessionEvents.test.ts b/src/vs/platform/agentHost/test/node/mapSessionEvents.test.ts index 211e054e5852e3..c952f9093472a9 100644 --- a/src/vs/platform/agentHost/test/node/mapSessionEvents.test.ts +++ b/src/vs/platform/agentHost/test/node/mapSessionEvents.test.ts @@ -821,7 +821,68 @@ suite('mapSessionEvents — history replay', () => { }); } + test('restores completion notifications with the mapped child chats', async () => { + const chats = new Map([ + ['task-a', 'ahp-chat:/11111111-1111-5111-8111-111111111111'], + ['task-b', 'ahp-chat:/22222222-2222-5222-8222-222222222222'], + ]); + const { turns } = await mapSessionEvents(session, undefined, toSessionEvents([ + { type: 'user.message', data: { content: 'Review' } }, + { type: 'system.notification', data: { content: 'Finished', kind: { type: 'agent_completed', agentId: 'agent-b', agentType: 'review', status: 'failed' } } }, + { type: 'subagent.started', agentId: 'agent-a', data: { toolCallId: 'task-a', agentName: 'review', agentDisplayName: 'First', agentDescription: '' } }, + { type: 'subagent.completed', agentId: 'agent-b', data: { toolCallId: 'task-b', agentName: 'review', agentDisplayName: 'Second' } }, + { type: 'system.notification', data: { content: 'Finished', kind: { type: 'agent_idle', agentId: 'agent-a', agentType: 'review' } } }, + ]), { resolveSubagentChatUri: toolCallId => chats.get(toolCallId)! }); + assert.deepStrictEqual(turns.flatMap(turn => turn.responseParts.flatMap(part => part.kind === ResponsePartKind.SystemNotification ? [part.content] : [])), [ + '[Second](ahp-chat:/22222222-2222-5222-8222-222222222222) failed', + '[First](ahp-chat:/11111111-1111-5111-8111-111111111111) is complete', + ]); + }); + for (const hasExecutionEvents of [true, false]) { + test(`restores linked read recipients (${hasExecutionEvents ? 'execution events' : 'tool request fallback'})`, async () => { + const parameters = { agent_id: 'renderer-agent', wait: false }; + const chat = 'ahp-chat:/11111111-1111-5111-8111-111111111111'; + const { turns } = await mapSessionEvents(session, undefined, toSessionEvents([ + { type: 'user.message', data: { content: 'Read the review.' } }, + { type: 'assistant.message', data: { messageId: 'read-request', content: '', toolRequests: [{ toolCallId: 'tc-read', name: 'read_agent', arguments: parameters }] } }, + ...(hasExecutionEvents ? [{ type: 'tool.execution_start', data: { toolCallId: 'tc-read', toolName: 'read_agent', arguments: parameters } }] : []), + { type: 'tool.execution_complete', data: { toolCallId: 'tc-read', success: true } }, + { type: 'subagent.started', agentId: 'renderer-agent', data: { toolCallId: 'renderer-task', agentName: 'code-review', agentDisplayName: 'Renderer reviewer', agentDescription: '' } }, + ]), { resolveSubagentChatUri: () => chat }); + assert.deepStrictEqual(turns.flatMap(turn => turn.responseParts.flatMap(part => part.kind === ResponsePartKind.ToolCall + && part.toolCall.toolCallId === 'tc-read' && part.toolCall.status === ToolCallStatus.Completed + ? [{ invocation: part.toolCall.invocationMessage, completed: part.toolCall.pastTenseMessage, input: part.toolCall.toolInput }] + : [])), [{ + invocation: { markdown: `Read agent [Renderer reviewer](${chat})` }, + completed: { markdown: `Read agent [Renderer reviewer](${chat})` }, + input: JSON.stringify(parameters, null, 2), + }]); + }); + + test(`restores linked write recipients (${hasExecutionEvents ? 'execution events' : 'tool request fallback'})`, async () => { + const parameters = { agent_ids: ['renderer-agent', 'history-agent'], message: 'Follow up' }; + const events: ISessionEvent[] = [ + { type: 'user.message', data: { content: 'Continue the review.' } }, + { type: 'assistant.message', data: { messageId: 'write-request', content: '', toolRequests: [{ toolCallId: 'tc-write', name: 'write_agent', arguments: parameters }] } }, + ...(hasExecutionEvents ? [{ type: 'tool.execution_start', data: { toolCallId: 'tc-write', toolName: 'write_agent', arguments: parameters } }] : []), + { type: 'tool.execution_complete', data: { toolCallId: 'tc-write', success: true } }, + { type: 'subagent.started', agentId: 'renderer-agent', data: { toolCallId: 'renderer-task', agentName: 'code-review', agentDisplayName: 'Renderer reviewer', agentDescription: '' } }, + { type: 'subagent.completed', agentId: 'history-agent', data: { toolCallId: 'history-task', agentName: 'code-review', agentDisplayName: 'History reviewer' } }, + ]; + const { turns } = await mapSessionEvents(session, undefined, toSessionEvents(events), { + resolveSubagentChatUri: toolCallId => `ahp-chat:/opaque/${toolCallId}`, + }); + assert.deepStrictEqual(turns.flatMap(turn => turn.responseParts.flatMap(part => part.kind === ResponsePartKind.ToolCall + && part.toolCall.toolCallId === 'tc-write' && part.toolCall.status === ToolCallStatus.Completed + ? [{ invocation: part.toolCall.invocationMessage, completed: part.toolCall.pastTenseMessage, input: part.toolCall.toolInput }] + : [])), [{ + invocation: { markdown: 'Write to agents [Renderer reviewer](ahp-chat:/opaque/renderer-task), [History reviewer](ahp-chat:/opaque/history-task)' }, + completed: { markdown: 'Write to agents [Renderer reviewer](ahp-chat:/opaque/renderer-task), [History reviewer](ahp-chat:/opaque/history-task)' }, + input: JSON.stringify(parameters, null, 2), + }]); + }); + test(`restores write recipients from background completion notifications (${hasExecutionEvents ? 'execution events' : 'tool request fallback'})`, async () => { const parameters = { agent_ids: ['renderer-agent', 'history-agent'], message: 'Follow up' }; const events: ISessionEvent[] = [ diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 576bea8792c93d..145c32e03c480b 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -235,7 +235,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.inputBlocked', 'When another Codex app is using a conversation, a banner above the input explains how to release it. You can keep editing your draft, but sending is disabled. Quit the app holding the conversation, such as ChatGPT, or exit the Codex CLI session. Use Tab to focus Retry in the banner, then press Enter or Space to check again. Retry does not send your draft.')); content.push(localize('chat.policyInputBlocked', 'If your organization configures managed permissions or requires sandboxing, opening an existing Local chat automatically moves its conversation and draft to Copilot without sending. The original chat is archived only after the new conversation opens with its history. If moving fails, the original stays read-only. Use Tab to focus Move to Copilot in the banner, then press Enter or Space to try again. Archived originals remain available without moving again, and in remote windows they still offer Move to Copilot so you can recover chats that an earlier move archived without copying their history. Empty chats offer New Copilot Chat instead. When the Agent Host cannot import history, nothing moves automatically. Use Tab to focus Continue in Copilot in the banner, then press Enter or Space to start a new Copilot chat with the conversation attached as context and your draft, without sending. The original chat stays available and is not archived, and archived chats offer this too.')); content.push(localize('chat.agentHostPolicyContinuation', "When your organization disables Claude or Codex, their Agent Host conversations remain listed and read-only. If your organization also requires the new Copilot experience, an open, idle conversation automatically moves to Copilot with its title, history, and draft. Nothing is sent automatically. The original is archived only after the copy opens and other conversations in its session can still be reached. Opening an archived original does not move it again. If moving needs a workspace or trust decision, or fails, use Tab to focus Continue in Copilot in the banner, then press Enter or Space. This action reopens an existing copy when available. Subagent chats require the manual action. For a managed checkout, choose an independent workspace; uncommitted files stay in the original checkout. If saved history cannot load, use Retry in the error banner.")); - content.push(localize('chat.subagentPills', "Subagents appear as pills in the response. Use Tab to focus a subagent pill, then Enter or Space to open its chat to the side. If the subagent has no separate chat, Enter or Space expands or collapses its inline details instead. The pill announces its running state, model settings, and any pending confirmations. File and markdown links in its activity row can be focused with Tab and opened independently with Enter.")); + content.push(localize('chat.subagentPills', "Subagents appear as pills in the response, completion notifications, and read-agent and write-to-agent messages. Use Tab to focus a subagent pill, then Enter or Space to open its chat to the side. If the subagent has no separate chat, Enter or Space expands or collapses its inline details instead. The pill announces its running state, model settings, and any pending confirmations. File and markdown links in its activity row can be focused with Tab and opened independently with Enter.")); content.push(localize('chat.nestedSubagentActivity', "When a subagent starts another subagent, its activity row identifies the nested subagent by name. Focus that link with Tab and press Enter or Space to open the nested subagent's chat to the side. The enclosing pill still opens the parent subagent.")); content.push(localize('chat.vscodePet', 'Type /vscode-pet to show or hide Blobby, the VS Code pet, above the input. One pet appears in whichever editor or Agents window is active. Drag it around the chat with the mouse and release it to drop it, or flick it in any direction to throw it along the gesture before gravity pulls it down. Pointer collisions are ignored for half a second after a drag release. After that, while the pet is falling, move the pointer into it to bounce it upward; pointer movement and where it catches the pet affect the bounce. Sideways and upward travel do not start the bounce counter. A counter beside the pet tracks consecutive bounces and remains for up to five seconds after landing, or until the pet next reacts or interacts. Landing with at least twenty bounces triggers confetti unless reduced motion is enabled. If it falls past the input, a despawn effect appears at the bottom and a respawn effect appears at the top before it automatically returns to the input. Moving the pointer rapidly between the pet\u2019s left and right sides makes it dizzy. With the keyboard, use Tab to focus the pet, then the left and right arrows to make it hop along the input until it reaches an edge. Hold Shift with the left or right arrow to throw it toward a wall; while it is airborne, press Enter or Space to bounce it upward. Rapidly alternate the unmodified arrows to make it dizzy. Press Enter or Space while it is resting to interact with it. When an achievement unlocks, the pet shows a gold star for ten seconds; activate the pet during that time to open Achievements. Open its context menu{0} (for example Shift+F10), use the up and down arrow keys to choose Achievements, Grow, Shrink, Reset Size, or Change Color, and press Enter to activate the choice. Grow and Shrink change its size in twenty-percent steps, while Reset Size restores its default size. The pet position and size are shared across chats and windows. Its color and hat are shared by editor windows and the Agents window unless you give one of them its own in Customize Blobby. All of these are remembered after you restart.', '')); content.push(localize('chat.vscodePetPainting', "While an image-generation tool is running, Blobby paints at a small easel, then returns to its normal activity. Reduced motion shows a still painting pose.")); @@ -288,7 +288,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui if (type === 'agentView') { content.push(localize('chat.systemNotificationDisclosure', 'Some session status messages have additional details. Use Tab to focus the status message and press Enter or Space to show or hide its details.')); } - content.push(localize('chat.subagentPill', 'When a subagent pill appears in a response, use Tab to focus it and press Enter or Space to open that subagent chat to the side.')); + content.push(localize('chat.subagentPill', 'When a subagent pill appears in a response, completion notification, read-agent message, or write-to-agent message, use Tab to focus it and press Enter or Space to open that subagent chat to the side.')); content.push(localize('chat.backgroundActivityProgressDropdown', "Running-subagent and background-command statuses at the bottom of a response open dropdowns showing only in-progress work, including subagents waiting for input. Finished subagents and background work disappear from these dropdowns as they complete, regardless of the input pills' Show All setting. When both kinds are running, one combined status opens a Background Activity dropdown containing both groups. The separate pills above the input keep their existing filters. In a subagent chat, the status still opens that chat's own running work when the input activity pills are hidden. Use Tab to focus the status and Enter or Space to open it. Use the Up and Down arrow keys to choose an entry, then Enter to open a subagent or the shell's live command details. Escape closes the dropdown and returns focus to the status. If the focused status disappears when work finishes, focus returns to the chat input. The label retains the progress shimmer; reduced motion shows static text.")); content.push(localize('chat.mcpStartupSkip', "When a chat turn is waiting for MCP servers to start, a Skip link may appear. Use Tab to focus Skip and press Enter or Space to continue the turn while those servers start in the background. The current startup message disappears immediately and focus returns to the chat input. New server startups may show another message.")); content.push(localize('chat.readOnlyThinking', "In read-only chats, thinking details preview while streaming and collapse when finished, regardless of your thinking-style setting. Focus a thinking header and press Enter or Space to expand or collapse its details.")); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts index 785367591b5e4c..4e494b14182abb 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts @@ -18,7 +18,7 @@ import { Schemas } from '../../../../../../base/common/network.js'; import { posix, win32 } from '../../../../../../base/common/path.js'; import { URI } from '../../../../../../base/common/uri.js'; import { generateUuid } from '../../../../../../base/common/uuid.js'; -import { getTurnError, MessageKind, ToolCallCancellationReason, ToolCallContributorKind, ToolCallRiskAssessmentStatus, ToolCallStatus, ResponsePartKind, TurnState, getInlineToolInput, getToolFileEdits, getToolOutputText, getToolSubagentContent, hasReportedUsage, ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, type ActiveTurn, type ChatInputAnswer, type ChatInputQuestion, type ChatInputRequest, type ICompletedToolCall, type InputRequestResponsePart, type Message, type TerminalCommandResult, type ToolCallPendingConfirmationState, type ToolCallState, type ToolResultSubagentContent, type Turn, FileEditKind, ToolResultContentType, type ToolResultContent, type UsageInfo } from '../../../../../../platform/agentHost/common/state/sessionState.js'; +import { getTurnError, MessageKind, ToolCallCancellationReason, ToolCallContributorKind, ToolCallRiskAssessmentStatus, ToolCallStatus, ResponsePartKind, TurnState, getInlineToolInput, getToolFileEdits, getToolOutputText, getToolSubagentContent, hasReportedUsage, ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, type ActiveTurn, type ChatInputAnswer, type ChatInputQuestion, type ChatInputRequest, type ICompletedToolCall, type InputRequestResponsePart, type Message, type TerminalCommandResult, type ToolCallPendingConfirmationState, type ToolCallState, type ToolResultSubagentContent, type Turn, FileEditKind, ToolResultContentType, type ToolResultContent, type UsageInfo, AHP_CHAT_SCHEME } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { readAgentPlanReview, type IAgentPlanReview } from '../../../../../../platform/agentHost/common/meta/agentPlanReview.js'; import { ChatInputRequestPurpose, readChatInputRequestPurpose } from '../../../../../../platform/agentHost/common/meta/agentChatInputRequestMeta.js'; import { getShellAuthenticationTitle, readShellAuthentication, type IShellAuthenticationPrompt } from '../../../../../../platform/agentHost/common/meta/agentShellAuthenticationMeta.js'; @@ -2619,6 +2619,7 @@ const EXTERNAL_LINK_SCHEMES: ReadonlySet = new Set([ product.urlProtocol, AGENT_HOST_SCHEME, AGENT_HOST_SESSION_LINK_SCHEME, + AHP_CHAT_SCHEME, ]); /** diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts index 6cd3f9ccab5d7f..548abb3cc3c7ad 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts @@ -20,6 +20,7 @@ import product from '../../../../../platform/product/common/product.js'; import { Schemas } from '../../../../../base/common/network.js'; import { AGENT_HOST_SCHEME, getLocalAgentHostWindowSchemes } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { AGENT_HOST_SESSION_LINK_SCHEME } from '../../../../../platform/agentHost/common/openSessionLink.js'; +import { AHP_CHAT_SCHEME } from '../../../../../platform/agentHost/common/state/sessionState.js'; const trustedChatImageSources = new Map([ ['raw.githubusercontent.com', '/'], @@ -166,7 +167,7 @@ export function getChatMarkdownRenderOptions(options?: MarkdownRenderOptions): M override: allowedChatMarkdownHtmlTags, }, ...options?.sanitizerConfig, - allowedLinkSchemes: { augment: [product.urlProtocol, 'copilot-skill', Schemas.vscodeBrowser, AGENT_HOST_SCHEME, AGENT_HOST_SESSION_LINK_SCHEME, ...getLocalAgentHostWindowSchemes()] }, + allowedLinkSchemes: { augment: [product.urlProtocol, 'copilot-skill', Schemas.vscodeBrowser, AGENT_HOST_SCHEME, AGENT_HOST_SESSION_LINK_SCHEME, AHP_CHAT_SCHEME, ...getLocalAgentHostWindowSchemes()] }, remoteImageIsAllowed: uri => isRemoteImageAllowed(uri) || (uri.scheme === AGENT_HOST_SCHEME && options?.sanitizerConfig?.remoteImageIsAllowed?.(uri) === true), } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConfirmationWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConfirmationWidget.ts index 8949f53daca7f6..dfe589bd2c98e5 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConfirmationWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConfirmationWidget.ts @@ -27,6 +27,7 @@ import { IRenderFileWidgetsOptions, renderFileWidgets } from './chatInlineAnchor import { IChatContentPartRenderContext } from './chatContentParts.js'; import { IChatMarkdownAnchorService } from './chatMarkdownAnchorService.js'; import { ChatMarkdownContentPart, IChatMarkdownContentPartOptions } from './chatMarkdownContentPart.js'; +import { renderSubagentChatLinks } from './chatSubagentOpenChat.js'; import './media/chatConfirmationWidget.css'; export interface IChatConfirmationButton { @@ -60,6 +61,7 @@ export interface IChatConfirmationWidgetOptions { export interface IChatQueryTitlePartOptions { readonly markdownRenderOptions?: MarkdownRenderOptions; readonly renderFileWidgets?: boolean; + readonly parentSessionResource?: string; } export class ChatQueryTitlePart extends Disposable { @@ -131,6 +133,9 @@ export class ChatQueryTitlePart extends Disposable { return { element, dispose: () => { } }; } const renderedTitle = this._renderer.render(markdown, this.getRenderOptions()); + if (this.options?.parentSessionResource) { + this._fileWidgetStore.add(renderSubagentChatLinks(renderedTitle.element, this.options.parentSessionResource, this._instantiationService)); + } if (this.options?.renderFileWidgets) { renderFileWidgets(renderedTitle.element, this._instantiationService, this._chatMarkdownAnchorService, this._fileWidgetStore); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts index 83571b4eff0d54..fc176c4dad0ce8 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts @@ -43,6 +43,7 @@ import { ChatDropdownPillActionViewItem } from '../../../../../browser/chatDropd import { ChatPillsWidget, type IChatPill } from '../../../../../browser/chatPills.js'; import { sessionBackgroundShellsPillOptions, sessionSubagentsPillOptions } from '../../sessionChatPillOptions.js'; import { SessionBackgroundShellsControl } from '../../sessionBackgroundShellsControl.js'; +import { renderSubagentChatLinks } from './chatSubagentOpenChat.js'; export class ChatProgressContentPart extends Disposable implements IChatContentPart { public readonly domNode: HTMLElement; @@ -59,6 +60,7 @@ export class ChatProgressContentPart extends Disposable implements IChatContentP protected progressIconElement: HTMLElement | undefined; private readonly progressId: string | undefined; private readonly progressAction: IChatContentPartRenderContext['progressMessageAction']; + private readonly parentSessionResource: string; constructor( progress: IChatProgressMessage | IChatTask | IChatTaskSerialized | { content: IMarkdownString }, @@ -78,6 +80,7 @@ export class ChatProgressContentPart extends Disposable implements IChatContentP this.currentContent = progress.content; this.progressId = hasKey(progress, { kind: true }) && progress.kind === 'progressMessage' ? progress.id : undefined; this.progressAction = context.progressMessageAction; + this.parentSessionResource = context.element.sessionResource.toString(); this.persistentProgress = !!context.suppressProgressShimmer; const followingContent = context.content.slice(context.contentIndex + 1); @@ -107,6 +110,7 @@ export class ChatProgressContentPart extends Disposable implements IChatContentP const result = this.chatContentMarkdownRenderer.render(progress.content); result.element.classList.add('progress-step'); renderFileWidgets(result.element, this.instantiationService, this.chatMarkdownAnchorService, this._fileWidgetStore); + this._fileWidgetStore.add(renderSubagentChatLinks(result.element, this.parentSessionResource, this.instantiationService)); if (this.useShimmer) { this.applyShimmer(result.element); } @@ -239,6 +243,7 @@ export class ChatProgressContentPart extends Disposable implements IChatContentP result.element.classList.add('progress-step'); this._fileWidgetStore.clear(); renderFileWidgets(result.element, this.instantiationService, this.chatMarkdownAnchorService, this._fileWidgetStore); + this._fileWidgetStore.add(renderSubagentChatLinks(result.element, this.parentSessionResource, this.instantiationService)); if (this.persistentProgress && this.useShimmer) { this.applyShimmer(result.element); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentContentPart.ts index 0c319cc8597ad8..cddd605492fce6 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentContentPart.ts @@ -3,11 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; import * as dom from '../../../../../../base/browser/dom.js'; import { $, AnimationFrameScheduler, DisposableResizeObserver } from '../../../../../../base/browser/dom.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; -import { Action } from '../../../../../../base/common/actions.js'; import { Event } from '../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { Lazy } from '../../../../../../base/common/lazy.js'; @@ -18,18 +16,11 @@ import { rcut } from '../../../../../../base/common/strings.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { generateUuid } from '../../../../../../base/common/uuid.js'; import { localize } from '../../../../../../nls.js'; -import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; -import { HiddenItemStrategy, WorkbenchToolBar } from '../../../../../../platform/actions/browser/toolbar.js'; -import { IMenuService, MenuId, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; -import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; -import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { IMarkdownRenderer } from '../../../../../../platform/markdown/browser/markdownRenderer.js'; -import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; -import { CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID } from '../../../common/constants.js'; import { getSubagentIsActive, IChatHookPart, IChatToolInvocation, IChatToolInvocationSerialized, isLegacyChatTerminalToolInvocationData, ToolConfirmKind } from '../../../common/chatService/chatService.js'; import { IChatRendererContent, isResponseVM } from '../../../common/model/chatViewModel.js'; import { IRunSubagentToolInputParams } from '../../../common/tools/builtinTools/runSubagentTool.js'; @@ -44,7 +35,7 @@ import { ChatThinkingStyleContentPart, createThinkingIcon } from './chatThinking import { ChatToolInvocationPart } from './toolInvocationParts/chatToolInvocationPart.js'; import { getToolInvocationIcon } from './toolInvocationParts/chatToolPartUtilities.js'; import { FusionPhasePillActionViewItem, type ISubagentPhaseContext } from './fusionPhasePillActionViewItem.js'; -import { IInlineSubagentDetailsContext, ISubagentActivity, OpenSubagentChatActionViewItem } from './chatSubagentOpenChat.js'; +import { IInlineSubagentDetailsContext, ISubagentActivity, SubagentChatToolbar } from './chatSubagentOpenChat.js'; import './media/chatSubagentContent.css'; const MAX_TITLE_LENGTH = 100; @@ -156,8 +147,7 @@ export class ChatSubagentContentPart extends ChatThinkingStyleContentPart implem // The subagent tool invocation, kept so the "Open Subagent" action can re-read // the subagent chat resource as it arrives/changes. private readonly _subagentToolInvocation: IChatToolInvocation | IChatToolInvocationSerialized; - private _openChatToolbar: WorkbenchToolBar | undefined; - private readonly _openChatActionViewRegistration = this._register(new MutableDisposable()); + private _openChatToolbar: SubagentChatToolbar | undefined; // Confirmation auto-expand tracking private toolsWaitingForConfirmation: number = 0; @@ -268,48 +258,14 @@ export class ChatSubagentContentPart extends ChatThinkingStyleContentPart implem return; } const isPhase = this._isPhasePresentation(); - const menuAction = this._getOpenChatMenuAction() ?? this._register(new Action( - CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, - localize('chat.subagent.openChat', "Open Subagent"), - undefined, - false, - context => this.commandService.executeCommand(CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, context), - )); - const actionViewItemProvider = this.actionViewItemService.lookUp(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID); - if (!isPhase && !actionViewItemProvider) { - this._openChatActionViewRegistration.value = Event.once(Event.filter( - this.actionViewItemService.onDidChange, - menuId => menuId === MenuId.ChatSubagentContent - ))(() => { - this._openChatActionViewRegistration.clear(); - this._openChatToolbar?.setActions([menuAction]); - this._updateOpenChatToolbarContext(); - }); - } - const container = $('.chat-subagent-open-chat-toolbar'); this.headerContainer.appendChild(container); - this._openChatToolbar = this._register(this.instantiationService.createInstance(WorkbenchToolBar, container, { - hiddenItemStrategy: HiddenItemStrategy.Ignore, - actionViewItemProvider: (action, options) => isPhase - ? this.instantiationService.createInstance(FusionPhasePillActionViewItem, undefined, action, { ...options, showElapsedOnly: true }, false) - : this.actionViewItemService.lookUp(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID)?.(action, options, this.instantiationService, dom.getWindow(container).vscodeWindowId) - ?? this.instantiationService.createInstance(OpenSubagentChatActionViewItem, undefined, action, options, !this.environmentService.isSessionsWindow && !ChatContextKeys.inSessionsChat.getValue(this.contextKeyService)), - })); - this._openChatToolbar.setActions([menuAction]); + this._openChatToolbar = this._register(this.instantiationService.createInstance(SubagentChatToolbar, container, isPhase + ? (action, options) => this.instantiationService.createInstance(FusionPhasePillActionViewItem, undefined, action, { ...options, showElapsedOnly: true }, false) + : undefined)); this._updateOpenChatOnlyMode(); } - private _getOpenChatMenuAction(): MenuItemAction | undefined { - for (const [, actions] of this.menuService.getMenuActions(MenuId.ChatSubagentContent, this.contextKeyService, { shouldForwardArgs: true })) { - const action = actions.find(action => action.id === CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID); - if (action instanceof MenuItemAction) { - return action; - } - } - return undefined; - } - private _updateOpenChatOnlyMode(): void { const openChatOnly = !!this._getChatResource() || this._isPhasePresentation(); this.domNode.classList.toggle('chat-subagent-open-chat-only', openChatOnly); @@ -358,23 +314,23 @@ export class ChatSubagentContentPart extends ChatThinkingStyleContentPart implem ...(this.isActive && displayedTool ? { activeToolCallId: displayedTool.callId, activeToolLabel: displayedTool.label, activeToolIcon: displayedTool.icon, activeToolSubagent: displayedTool.subagent } : {}), }; if (data?.kind === 'subagent' && data.presentation === 'phase') { - this._openChatToolbar.context = { + this._openChatToolbar.setContext({ ...commonContext, presentation: 'phase', phaseStatus: data.phaseStatus, activityLabel: data.activityDescription ? new MarkdownString().appendText(data.activityDescription).value : undefined, ...(chatResource ? { chatResource, isChatAvailable: data.isChatAvailable } : {}), - } satisfies ISubagentPhaseContext; + } satisfies ISubagentPhaseContext); } else if (chatResource) { - this._openChatToolbar.context = { ...commonContext, chatResource, isChatAvailable: data?.kind === 'subagent' ? data.isChatAvailable : undefined }; + this._openChatToolbar.setContext({ ...commonContext, chatResource, isChatAvailable: data?.kind === 'subagent' ? data.isChatAvailable : undefined }); } else { - this._openChatToolbar.context = { + this._openChatToolbar.setContext({ ...commonContext, presentation: 'inline', expanded: this.isExpanded(), contentId: this.detailsId, toggleDetails: this.toggleDetails, - } satisfies IInlineSubagentDetailsContext; + } satisfies IInlineSubagentDetailsContext); } this._updateOpenChatOnlyMode(); } @@ -409,11 +365,6 @@ export class ChatSubagentContentPart extends ChatThinkingStyleContentPart implem @IHoverService hoverService: IHoverService, @ITelemetryService telemetryService: ITelemetryService, @IConfigurationService private readonly configurationService: IConfigurationService, - @IActionViewItemService private readonly actionViewItemService: IActionViewItemService, - @IMenuService private readonly menuService: IMenuService, - @IContextKeyService private readonly contextKeyService: IContextKeyService, - @ICommandService private readonly commandService: ICommandService, - @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, ) { // Extract subagent metadata from the tool invocation const { description, isDefaultDescription, agentDisplayName, agentName, prompt, modelName, credits } = ChatSubagentContentPart.extractSubagentInfo(toolInvocation); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts index f83d7d564627db..06c4f2bd9febc8 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts @@ -6,13 +6,13 @@ import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; import './media/chatSubagentOpenChat.css'; -import { $, addDisposableListener, EventHelper, EventLike, EventType, isHTMLElement, WindowIntervalTimer } from '../../../../../../base/browser/dom.js'; +import { $, addDisposableListener, EventHelper, EventLike, EventType, getWindow, isHTMLElement, WindowIntervalTimer } from '../../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../../base/browser/keyboardEvent.js'; import { BaseActionViewItem, IActionViewItemOptions } from '../../../../../../base/browser/ui/actionbar/actionViewItems.js'; import { createPixelSpinner } from '../../../../../../base/browser/ui/pixelSpinner/pixelSpinner.js'; import { Action, IAction } from '../../../../../../base/common/actions.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; -import { Emitter } from '../../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { KeyCode } from '../../../../../../base/common/keyCodes.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; @@ -22,11 +22,13 @@ import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { URI } from '../../../../../../base/common/uri.js'; import { localize, localize2 } from '../../../../../../nls.js'; import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; -import { Action2, MenuId, MenuItemAction, registerAction2 } from '../../../../../../platform/actions/common/actions.js'; -import { getAgentHostChatId } from '../../../../../../platform/agentHost/common/state/sessionState.js'; +import { HiddenItemStrategy, IWorkbenchToolBarOptions, WorkbenchToolBar } from '../../../../../../platform/actions/browser/toolbar.js'; +import { Action2, IMenuService, MenuId, MenuItemAction, registerAction2 } from '../../../../../../platform/actions/common/actions.js'; +import { getAgentHostChatId, isAhpChatChannel } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { IAgentRuntimeModelConfiguration } from '../../../../../../platform/agentHost/common/meta/agentModelConfigurationMeta.js'; import { getReasoningEffortLabel } from '../../../../../../platform/agentHost/common/reasoningEffort.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { IInstantiationService, ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; import { IMarkdownRendererService } from '../../../../../../platform/markdown/browser/markdownRenderer.js'; @@ -85,6 +87,72 @@ export interface ISubagentActivity { export type SubagentPillContext = Omit; +export class SubagentChatToolbar extends Disposable { + private readonly toolbar: WorkbenchToolBar; + private context: SubagentPillContext | undefined; + + constructor( + container: HTMLElement, + actionViewItemProvider: IWorkbenchToolBarOptions['actionViewItemProvider'], + @IInstantiationService instantiationService: IInstantiationService, + @IActionViewItemService actionViewItemService: IActionViewItemService, + @IMenuService menuService: IMenuService, + @IContextKeyService contextKeyService: IContextKeyService, + @ICommandService commandService: ICommandService, + @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, + ) { + super(); + container.classList.add('chat-subagent-open-chat-toolbar'); + const menuAction = menuService.getMenuActions(MenuId.ChatSubagentContent, contextKeyService, { shouldForwardArgs: true }) + .flatMap(([, actions]) => actions) + .find(action => action.id === CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID && action instanceof MenuItemAction); + const action = menuAction ?? this._register(new Action( + CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, + localize('chat.subagent.openChat', "Open Subagent"), + undefined, + false, + context => commandService.executeCommand(CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, context), + )); + this.toolbar = this._register(instantiationService.createInstance(WorkbenchToolBar, container, { + hiddenItemStrategy: HiddenItemStrategy.Ignore, + actionViewItemProvider: actionViewItemProvider ?? ((item, options) => actionViewItemService.lookUp(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID)?.(item, options, instantiationService, getWindow(container).vscodeWindowId) + ?? instantiationService.createInstance(OpenSubagentChatActionViewItem, undefined, item, options, !environmentService.isSessionsWindow && !ChatContextKeys.inSessionsChat.getValue(contextKeyService))), + })); + this.toolbar.setActions([action]); + if (!actionViewItemProvider && !actionViewItemService.lookUp(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID)) { + this._register(Event.once(Event.filter(actionViewItemService.onDidChange, menuId => menuId === MenuId.ChatSubagentContent))(() => { + this.toolbar.setActions([action]); + this.toolbar.context = this.context; + })); + } + } + + setContext(context: T): void { + this.context = context; + this.toolbar.context = context; + } + + focus(): void { + this.toolbar.focus(); + } +} + +export function renderSubagentChatLinks(element: HTMLElement, parentSessionResource: string, instantiationService: IInstantiationService): IDisposable { + const store = new DisposableStore(); + // eslint-disable-next-line eslint-js/no-restricted-syntax + for (const anchor of element.querySelectorAll('a')) { + const chatResource = anchor.getAttribute('data-href'); + if (!chatResource || !isAhpChatChannel(chatResource)) { + continue; + } + const container = $('span.chat-subagent-open-chat-inline'); + const toolbar = store.add(instantiationService.createInstance(SubagentChatToolbar, container, undefined)); + toolbar.setContext({ chatResource, parentSessionResource, title: anchor.textContent ?? '' }); + anchor.replaceWith(container); + } + return store; +} + export interface IInlineSubagentDetailsContext extends SubagentPillContext { readonly presentation: 'inline'; readonly expanded: boolean; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.ts index 8fcceeac7025bd..095ad04f0637b2 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.ts @@ -21,6 +21,7 @@ import './media/chatSystemNotificationContentPart.css'; import { ChatCollapsibleContentPart } from './chatCollapsibleContentPart.js'; import { IChatContentPart } from './chatContentParts.js'; import { ChatProgressSubPart } from './chatProgressContentPart.js'; +import { renderSubagentChatLinks } from './chatSubagentOpenChat.js'; const transparentButtonStyles: IButtonStyles = { buttonBackground: undefined, @@ -46,6 +47,7 @@ export class ChatSystemNotificationContentPart extends Disposable implements ICh constructor( private readonly notification: IChatSystemNotificationPart, renderer: IMarkdownRenderer, + private readonly parentSessionResource: string | undefined = undefined, @IInstantiationService instantiationService: IInstantiationService, @IHoverService private readonly hoverService: IHoverService, ) { @@ -115,6 +117,9 @@ export class ChatSystemNotificationContentPart extends Disposable implements ICh private _renderNotification(notification: IChatSystemNotificationPart, renderer: IMarkdownRenderer, instantiationService: IInstantiationService): HTMLElement { const rendered = this._register(renderer.render(notification.content)); + if (this.parentSessionResource) { + this._register(renderSubagentChatLinks(rendered.element, this.parentSessionResource, instantiationService)); + } return this._register(instantiationService.createInstance(ChatProgressSubPart, rendered.element, notification.icon ?? Codicon.check, undefined)).domNode; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatToolInputOutputContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatToolInputOutputContentPart.ts index 28ce4fa195bb27..2e907f03cdc4a0 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatToolInputOutputContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatToolInputOutputContentPart.ts @@ -124,7 +124,7 @@ export class ChatCollapsibleInputOutputContentPart extends Disposable { titleEl.root, title, subtitle, - { markdownRenderOptions: getChatMarkdownRenderOptions(), renderFileWidgets: true }, + { markdownRenderOptions: getChatMarkdownRenderOptions(), renderFileWidgets: true, parentSessionResource: context.element.sessionResource.toString() }, )); const spacer = document.createElement('span'); spacer.style.flexGrow = '1'; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSubagentOpenChat.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSubagentOpenChat.css index cf74b9bfeef424..c9bdcf23b3f931 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSubagentOpenChat.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSubagentOpenChat.css @@ -8,6 +8,25 @@ max-width: 100%; } +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline { + display: inline-flex; + width: auto; + vertical-align: middle; +} + +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .monaco-toolbar, +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .monaco-action-bar, +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .actions-container, +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .actions-container .action-item.chat-subagent-pill-widget { + width: auto; +} + +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .monaco-action-bar .actions-container, +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .monaco-action-bar .action-item { + margin: 0; + padding: 0; +} + .chat-subagent-open-chat-toolbar .monaco-toolbar, .chat-subagent-open-chat-toolbar .monaco-action-bar, .chat-subagent-open-chat-toolbar .actions-container { @@ -61,6 +80,15 @@ cursor: default; } +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .action-item.chat-subagent-pill-widget { + font-size: var(--vscode-chat-font-size-body-s); + line-height: 1.2em; +} + +.chat-subagent-open-chat-toolbar.chat-subagent-open-chat-inline .action-item.chat-subagent-pill-widget .chat-subagent-pill-content { + padding: 0 var(--vscode-spacing-size40); +} + .chat-subagent-open-chat-toolbar .action-item.chat-subagent-pill-widget .chat-subagent-pill-failure { flex-shrink: 0; color: var(--vscode-errorForeground); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts index dfc40839f2c530..3ae7165f591be2 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts @@ -3728,6 +3728,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer { assert.strictEqual(value, 'See ![diagram](vscode-agent-host://my-host/a/b.png?_ah%3DeyJzY2hlbWUiOiJmaWxlIn0).'); }); + test('preserves named chat links instead of rewriting them as file references', () => { + const links = [ + '[Review \\[permissions\\]](ahp-chat:/11111111-1111-5111-8111-111111111111)', + '[Legacy child](ahp-chat://subagent/opaque-parent/spawn-id)', + ]; + assert.deepStrictEqual(['local', 'remote-host'].flatMap(authority => links.map(link => ({ + markdown: rewriteMarkdownLinks(`Read agent ${link}`, authority), + target: rewriteAgentHostLinkTarget(link.slice(link.indexOf('](') + 2, -1), authority), + }))), ['local', 'remote-host'].flatMap(() => links.map(link => ({ + markdown: `Read agent ${link}`, + target: link.slice(link.indexOf('](') + 2, -1), + })))); + }); + test('error turn produces error details in history', () => { const turn = createTurn({ state: TurnState.Error, diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSubagentContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSubagentContentPart.test.ts index 9648d7d87648d8..8ede1d0870b4b5 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSubagentContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSubagentContentPart.test.ts @@ -411,7 +411,7 @@ suite('ChatSubagentContentPart', () => { } function getOpenChatContext(part: ChatSubagentContentPart): IOpenSubagentChatContext | undefined { - return (part as unknown as { _openChatToolbar?: { actionBar?: { context?: IOpenSubagentChatContext } } })._openChatToolbar?.actionBar?.context; + return (part as unknown as { _openChatToolbar?: { toolbar?: { actionBar?: { context?: IOpenSubagentChatContext } } } })._openChatToolbar?.toolbar?.actionBar?.context; } suite('Basic rendering', () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts index 7d202e3b5277f1..51eee7175d6f15 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts @@ -10,18 +10,29 @@ import '../../../../../../../base/browser/ui/codicons/codiconStyles.js'; import { IDelayedHoverOptions, IHoverLifecycleOptions } from '../../../../../../../base/browser/ui/hover/hover.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; import { Codicon } from '../../../../../../../base/common/codicons.js'; +import { timeout } from '../../../../../../../base/common/async.js'; +import { Event } from '../../../../../../../base/common/event.js'; import { appendEscapedMarkdownInlineCode, IMarkdownString, MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { mock } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; import { agentMergeEnabledNotice, defaultAgentMergeConfiguration } from '../../../../../../../platform/agentHost/common/agentMerge.js'; +import { ICommandService } from '../../../../../../../platform/commands/common/commands.js'; import { IHoverService } from '../../../../../../../platform/hover/browser/hover.js'; +import { NullHoverService } from '../../../../../../../platform/hover/test/browser/nullHoverService.js'; import { IMarkdownRenderer } from '../../../../../../../platform/markdown/browser/markdownRenderer.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../services/environment/common/environmentService.js'; import { getIconsStyleSheet } from '../../../../../../../platform/theme/browser/iconsStyleSheet.js'; import '../../../../../../browser/media/style.css'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { ChatCollapsibleContentPart } from '../../../../browser/widget/chatContentParts/chatCollapsibleContentPart.js'; +import { ChatContentMarkdownRenderer } from '../../../../browser/widget/chatContentMarkdownRenderer.js'; +import { ChatMarkdownAnchorService, IChatMarkdownAnchorService } from '../../../../browser/widget/chatContentParts/chatMarkdownAnchorService.js'; import { ChatSystemNotificationContentPart } from '../../../../browser/widget/chatContentParts/chatSystemNotificationContentPart.js'; +import { rawMarkdownToString } from '../../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID } from '../../../../common/constants.js'; +import { ILanguageModelsService } from '../../../../common/languageModels.js'; +import '../../../../browser/widget/media/chat.css'; suite('ChatSystemNotificationContentPart', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -41,6 +52,73 @@ suite('ChatSystemNotificationContentPart', () => { } } + test('renders the subagent pill and opens the linked child', async () => { + const disposables = store.add(new DisposableStore()); + const instantiationService = workbenchInstantiationService(undefined, disposables); + instantiationService.stub(IChatMarkdownAnchorService, disposables.add(new ChatMarkdownAnchorService())); + instantiationService.stub(IHoverService, { ...NullHoverService }); + instantiationService.stub(IWorkbenchEnvironmentService, { isSessionsWindow: true }); + const calls: { command: string; args: unknown[] }[] = []; + instantiationService.stub(ICommandService, new class extends mock() { + override async executeCommand(command: string, ...args: unknown[]): Promise { + calls.push({ command, args }); + return undefined; + } + }()); + instantiationService.stub(ILanguageModelsService, { + lookupLanguageModel: () => undefined, + getLanguageModelIds: () => [], + onDidChangeLanguageModels: Event.None, + }); + const renderer = instantiationService.createInstance(ChatContentMarkdownRenderer); + const chatResource = 'ahp-chat:/22222222-2222-5222-8222-222222222222'; + const parentSessionResource = 'agent-host-copilotcli:/parent'; + const part = disposables.add(instantiationService.createInstance(ChatSystemNotificationContentPart, { + kind: 'systemNotification', + content: rawMarkdownToString(`[Review \\[x\\]](${chatResource}) completed\n\n- Unrelated list item`, 'remote-host'), + }, renderer, parentSessionResource)); + const host = mainWindow.document.body.appendChild($('.interactive-session')); + for (const [name, value] of [ + ['--vscode-chat-font-size-body-s', '12px'], + ['--vscode-spacing-size40', '4px'], + ['--vscode-spacing-size60', '6px'], + ['--vscode-strokeThickness', '1px'], + ]) { + host.style.setProperty(name, value); + } + const row = host.appendChild($('.interactive-item-container.interactive-request.system-initiated-request')); + const value = row.appendChild($('.value')); + value.appendChild(part.domNode); + disposables.add(toDisposable(() => host.remove())); + const pill = part.domNode.querySelector('.chat-subagent-pill-widget .chat-subagent-pill-content'); + assert.ok(pill); + const actions = part.domNode.querySelector('.actions-container'); + const item = part.domNode.querySelector('.action-item'); + const markdownList = part.domNode.querySelector('.rendered-markdown > ul'); + assert.ok(actions && item && markdownList); + assert.deepStrictEqual({ + title: pill.querySelector('.chat-subagent-pill-label')?.textContent, + leftOffset: pill.getBoundingClientRect().left - part.domNode.getBoundingClientRect().left, + toolbarPadding: mainWindow.getComputedStyle(actions).paddingInlineStart, + itemMargin: mainWindow.getComputedStyle(item).margin, + listPadding: mainWindow.getComputedStyle(markdownList).paddingInlineStart, + compact: pill.getBoundingClientRect().height <= 20, + }, { + title: 'Review [x]', + leftOffset: 0, + toolbarPadding: '0px', + itemMargin: '0px', + listPadding: '24px', + compact: true, + }); + pill.dispatchEvent(new mainWindow.MouseEvent('click', { bubbles: true })); + await timeout(0); + assert.deepStrictEqual(calls, [{ + command: CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, + args: [{ chatResource, parentSessionResource, title: 'Review [x]' }], + }]); + }); + test('renders persistent checked notification content', () => { const disposables = store.add(new DisposableStore()); const instantiationService = workbenchInstantiationService(undefined, disposables); @@ -55,11 +133,13 @@ suite('ChatSystemNotificationContentPart', () => { ChatSystemNotificationContentPart, { kind: 'systemNotification', content: new MarkdownString('Background command completed') }, renderer, + undefined, )); const inlineTimingPart = disposables.add(instantiationService.createInstance( ChatSystemNotificationContentPart, { kind: 'systemNotification', content: new MarkdownString('Agent Merge started'), icon: Codicon.gitMerge, renderInlineTiming: true }, renderer, + undefined, )); assert.deepStrictEqual({ @@ -96,7 +176,7 @@ suite('ChatSystemNotificationContentPart', () => { kind: 'systemNotification', presentation: 'workflow', content: new MarkdownString('Selected Single workflow\n\nUsing Single: one solver will work on your request.\n\nMain pass'), } as const; - const part = store.add(instantiationService.createInstance(ChatSystemNotificationContentPart, notification, renderer)); + const part = store.add(instantiationService.createInstance(ChatSystemNotificationContentPart, notification, renderer, undefined)); assert.deepStrictEqual({ title: part.domNode.querySelector('.chat-system-notification-workflow-title')?.textContent?.trim(), body: [...part.domNode.querySelectorAll('.chat-system-notification-workflow-body > p')].map(p => p.textContent), @@ -116,7 +196,7 @@ suite('ChatSystemNotificationContentPart', () => { const renderer: IMarkdownRenderer = { render: markdown => renderMarkdown(markdown) }; const part = store.add(instantiationService.createInstance(ChatSystemNotificationContentPart, { kind: 'systemNotification', presentation: 'workflow', content: new MarkdownString('Selected Single workflow'), - }, renderer)); + }, renderer, undefined)); assert.deepStrictEqual({ title: part.domNode.textContent?.trim(), body: part.domNode.querySelector('.chat-system-notification-workflow-body'), @@ -130,7 +210,7 @@ suite('ChatSystemNotificationContentPart', () => { const names = ['Renderer reviewer', 'Review `permissions`', '[Renderer](command:unused)']; const rendered = names.map(name => { const content = new MarkdownString(`Background agent ${appendEscapedMarkdownInlineCode(name)} is complete`); - const part = disposables.add(instantiationService.createInstance(ChatSystemNotificationContentPart, { kind: 'systemNotification', content }, renderer)); + const part = disposables.add(instantiationService.createInstance(ChatSystemNotificationContentPart, { kind: 'systemNotification', content }, renderer, undefined)); return { titles: [...part.domNode.querySelectorAll('code')].map(code => code.textContent), text: part.domNode.textContent, @@ -169,6 +249,7 @@ suite('ChatSystemNotificationContentPart', () => { ChatSystemNotificationContentPart, notification, renderer, + undefined, )); const header = part.domNode.querySelector('.chat-system-notification-disclosure-header')!; const details = part.domNode.querySelector('.chat-system-notification-disclosure-body')!; @@ -251,6 +332,7 @@ suite('ChatSystemNotificationContentPart', () => { content: new MarkdownString('Automatically Fix CI is enabled for this pull request and will repair failing checks.\n\n- The agent will fix failing checks and push the repair.'), }, renderer, + undefined, )); container.appendChild(part.domNode); const header = part.domNode.querySelector('.chat-system-notification-disclosure-header')!; @@ -304,6 +386,7 @@ suite('ChatSystemNotificationContentPart', () => { ChatSystemNotificationContentPart, { kind: 'systemNotification', icon: Codicon.gitPullRequest, collapsible: true, content: new MarkdownString('Autopilot updated\n\n- Automatically Fix CI enabled') }, renderer, + undefined, )); container.appendChild(part.domNode); const chevron = part.domNode.querySelector('.chat-collapsible-hover-chevron')!; @@ -325,11 +408,13 @@ suite('ChatSystemNotificationContentPart', () => { ChatSystemNotificationContentPart, { kind: 'systemNotification', content: new MarkdownString('Summary\n\n- Detail'), collapsible: true }, renderer, + undefined, )); const withoutDetails = disposables.add(instantiationService.createInstance( ChatSystemNotificationContentPart, { kind: 'systemNotification', content: new MarkdownString('Summary\n\n'), collapsible: true }, renderer, + undefined, )); assert.deepStrictEqual({ @@ -356,7 +441,7 @@ suite('ChatSystemNotificationContentPart', () => { content: new MarkdownString(agentMergeEnabledNotice({ branchName: 'feature' }, { ...defaultAgentMergeConfiguration, mergePullRequest })), icon: Codicon.gitMerge, collapsible: true, - }, renderer)); + }, renderer, undefined)); const header = part.domNode.querySelector('.chat-system-notification-disclosure-header')!; assert.deepStrictEqual({ @@ -393,7 +478,7 @@ suite('ChatSystemNotificationContentPart', () => { workspaceName: 'working', accessibilityLabel: 'Workspace changed. This session is now working in working using an isolated worktree.', }; - const part = disposables.add(instantiationService.createInstance(ChatSystemNotificationContentPart, notification, renderer)); + const part = disposables.add(instantiationService.createInstance(ChatSystemNotificationContentPart, notification, renderer, undefined)); part.domNode.style.setProperty('--vscode-codiconFontSize-compact', '12px'); mainWindow.document.body.appendChild(part.domNode); disposables.add({ dispose: () => part.domNode.remove() }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolProgressPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolProgressPart.test.ts index 9ca57dd4a895ca..689748421185c1 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolProgressPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolProgressPart.test.ts @@ -6,7 +6,7 @@ import assert from 'assert'; import * as sinon from 'sinon'; import { $ } from '../../../../../../../base/browser/dom.js'; -import { retry } from '../../../../../../../base/common/async.js'; +import { retry, timeout } from '../../../../../../../base/common/async.js'; import { Event } from '../../../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { ISettableObservable, observableValue } from '../../../../../../../base/common/observable.js'; @@ -14,17 +14,22 @@ import { IRenderedMarkdown, MarkdownRenderOptions, renderAsPlaintext, renderMark import { IMarkdownString, MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { mock } from '../../../../../../../base/test/common/mock.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; import { ILinkPresentation, ILinkPresentationService } from '../../../../../../../platform/dataChannel/common/dataChannel.js'; import { IHoverService } from '../../../../../../../platform/hover/browser/hover.js'; import { IMarkdownRenderer } from '../../../../../../../platform/markdown/browser/markdownRenderer.js'; import { IOpenerService } from '../../../../../../../platform/opener/common/opener.js'; import { IConfigurationService } from '../../../../../../../platform/configuration/common/configuration.js'; +import { ICommandService } from '../../../../../../../platform/commands/common/commands.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../services/environment/common/environmentService.js'; import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { IChatMarkdownAnchorService } from '../../../../browser/widget/chatContentParts/chatMarkdownAnchorService.js'; import { IChatContentPartRenderContext, InlineTextModelCollection } from '../../../../browser/widget/chatContentParts/chatContentParts.js'; import { ChatProgressContentPart } from '../../../../browser/widget/chatContentParts/chatProgressContentPart.js'; +import { ChatContentMarkdownRenderer } from '../../../../browser/widget/chatContentMarkdownRenderer.js'; +import { rawMarkdownToString } from '../../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; import { ChatAutomationConfiguredResultSubPart } from '../../../../browser/widget/chatContentParts/toolInvocationParts/chatAutomationConfiguredResultSubPart.js'; import { ChatSessionTargetResultPillSubPart } from '../../../../browser/widget/chatContentParts/toolInvocationParts/chatSessionTargetResultPillSubPart.js'; import { ChatToolInvocationPart } from '../../../../browser/widget/chatContentParts/toolInvocationParts/chatToolInvocationPart.js'; @@ -36,6 +41,8 @@ import { hasToolInvocationError, isAskQuestionsToolInvocation, isMcpToolInvocati import { DiffEditorPool, EditorPool } from '../../../../browser/widget/chatContentParts/chatContentCodePools.js'; import { IChatAutomationConfiguredData, IChatSessionTargetData, IChatTerminalToolInvocationData, IChatToolInvocation, IChatToolInvocationSerialized, ToolConfirmKind } from '../../../../common/chatService/chatService.js'; import { IChatResponseViewModel } from '../../../../common/model/chatViewModel.js'; +import { ILanguageModelsService } from '../../../../common/languageModels.js'; +import { CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID } from '../../../../common/constants.js'; import { ToolDataSource, type ToolDataSource as ToolDataSourceType } from '../../../../common/tools/languageModelToolsService.js'; import { CollapsibleListPool } from '../../../../browser/widget/chatContentParts/chatReferencesContentPart.js'; import { IChatTodoListService } from '../../../../common/tools/chatTodoListService.js'; @@ -612,6 +619,87 @@ suite('ChatToolProgressSubPart', () => { }); }); + function stubSubagentNavigation() { + const calls: { command: string; args: unknown[] }[] = []; + instantiationService.stub(ICommandService, new class extends mock() { + override async executeCommand(command: string, ...args: unknown[]): Promise { + calls.push({ command, args }); + return undefined; + } + }()); + instantiationService.stub(IWorkbenchEnvironmentService, { isSessionsWindow: true }); + instantiationService.stub(ILanguageModelsService, { + lookupLanguageModel: () => undefined, + getLanguageModelIds: () => [], + onDidChangeLanguageModels: Event.None, + }); + return calls; + } + + test('renders read and write recipients through the agent host adapter as navigable pills', async () => { + const calls = stubSubagentNavigation(); + const context = createRenderContext(); + const renderer = instantiationService.createInstance(ChatContentMarkdownRenderer); + const chats = ['ahp-chat:/11111111-1111-5111-8111-111111111111', 'ahp-chat:/22222222-2222-5222-8222-222222222222']; + const part = disposables.add(instantiationService.createInstance( + ChatProgressContentPart, + { content: rawMarkdownToString(`Write to agents [Renderer](${chats[0]}), [History](${chats[1]})`, 'local') }, + renderer, context, false, true, undefined, undefined, false, undefined, + )); + const host = mainWindow.document.body.appendChild($('.interactive-item-container')); + host.appendChild($('.value')).appendChild(part.domNode); + disposables.add(toDisposable(() => host.remove())); + const initialPills = part.domNode.querySelectorAll('.chat-subagent-pill-content'); + assert.deepStrictEqual(Array.from(initialPills, pill => pill.querySelector('.chat-subagent-pill-label')?.textContent), ['Renderer', 'History']); + initialPills[0].click(); + part.updateMessage(rawMarkdownToString(`Read agent [History](${chats[1]})`, 'remote-host')); + const updatedPills = part.domNode.querySelectorAll('.chat-subagent-pill-content'); + assert.strictEqual(updatedPills.length, 1); + updatedPills[0].focus(); + assert.strictEqual(mainWindow.document.activeElement, updatedPills[0]); + updatedPills[0].dispatchEvent(new mainWindow.KeyboardEvent('keyup', { key: 'Tab', keyCode: 9, bubbles: true })); + for (const type of ['keydown', 'keyup']) { + updatedPills[0].dispatchEvent(new mainWindow.KeyboardEvent(type, { key: 'Enter', keyCode: 13, bubbles: true })); + } + await timeout(0); + assert.deepStrictEqual(calls, ['Renderer', 'History'].map((title, index) => ({ + command: CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, + args: [{ chatResource: chats[index], parentSessionResource: context.element.sessionResource.toString(), title }], + }))); + }); + + test('opens read and write agent links in collapsible tool titles without expanding the tool', async () => { + const calls = stubSubagentNavigation(); + const chatResource = 'ahp-chat:/11111111-1111-5111-8111-111111111111'; + const renderer = instantiationService.createInstance(ChatContentMarkdownRenderer); + const rendered = []; + for (const [toolId, verb] of [['read_agent', 'Read agent'], ['write_agent', 'Write to agent']]) { + const part = renderToolInvocation({ + ...createSerializedToolInvocation({ + isComplete: true, + toolId, + invocationMessage: rawMarkdownToString(`${verb} [Renderer](${chatResource})`, 'local'), + }), + resultDetails: { input: '{}', output: [] }, + }, renderer); + const pill = part.domNode.querySelector('.chat-query-title-part .chat-subagent-pill-content'); + assert.ok(pill, `${verb} must render its child-chat link as a pill`); + pill.click(); + rendered.push({ + title: pill.querySelector('.chat-subagent-pill-label')?.textContent, + expanded: part.domNode.querySelector('.chat-confirmation-widget-title')?.getAttribute('aria-expanded'), + }); + } + await timeout(0); + assert.deepStrictEqual({ rendered, calls }, { + rendered: Array(2).fill({ title: 'Renderer', expanded: 'false' }), + calls: Array(2).fill({ + command: CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, + args: [{ chatResource, parentSessionResource: createRenderContext().element.sessionResource.toString(), title: 'Renderer' }], + }), + }); + }); + test('preserves and escapes the MCP origin when progress messages are updated', () => { const originMessage = 'GitHub **tools** (MCP Server)'; const part = disposables.add(instantiationService.createInstance( diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatAgentMergeNotice.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatAgentMergeNotice.fixture.ts index 0db026144059af..8d9224988c0db3 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatAgentMergeNotice.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatAgentMergeNotice.fixture.ts @@ -6,6 +6,8 @@ import * as dom from '../../../../../base/browser/dom.js'; import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; +import { IActionViewItemService, NullActionViewItemService } from '../../../../../platform/actions/browser/actionViewItemService.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; import { agentMergeConfigurationChangedNotice, agentMergeDisableReasons, agentMergeDisabledNotice, agentMergeEnabledNotice, defaultAgentMergeConfiguration } from '../../../../../platform/agentHost/common/agentMerge.js'; import { AgentSystemNotificationKind, toAgentSystemNotificationMeta } from '../../../../../platform/agentHost/common/meta/agentSystemNotificationMeta.js'; import { ILabelService } from '../../../../../platform/label/common/label.js'; @@ -14,6 +16,7 @@ import { systemNotificationToChatPart } from '../../../../contrib/chat/browser/a import { ChatContentMarkdownRenderer } from '../../../../contrib/chat/browser/widget/chatContentMarkdownRenderer.js'; import { ChatSystemNotificationContentPart } from '../../../../contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.js'; import { IChatMarkdownAnchorService } from '../../../../contrib/chat/browser/widget/chatContentParts/chatMarkdownAnchorService.js'; +import { TestMenuService } from '../../workbenchTestServices.js'; import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup } from '../fixtureUtils.js'; import '../../../../contrib/chat/browser/widget/media/chat.css'; @@ -42,6 +45,8 @@ function renderNotice(context: ComponentFixtureContext, content: string, kind: A }()); reg.define(IMarkdownRendererService, MarkdownRendererService); reg.defineInstance(IChatMarkdownAnchorService, anchorService); + reg.define(IActionViewItemService, NullActionViewItemService); + reg.define(IMenuService, TestMenuService); }, }); @@ -51,7 +56,7 @@ function renderNotice(context: ComponentFixtureContext, content: string, kind: A } const markdownRenderer = instantiationService.createInstance(ChatContentMarkdownRenderer); - const part = disposableStore.add(instantiationService.createInstance(ChatSystemNotificationContentPart, progress, markdownRenderer)); + const part = disposableStore.add(instantiationService.createInstance(ChatSystemNotificationContentPart, progress, markdownRenderer, undefined)); if (expanded) { part.domNode.querySelector('.chat-system-notification-disclosure-header')?.click(); } diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatProgressContentPart.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatProgressContentPart.fixture.ts index 0334bcd425ba71..6ab8d36b77e934 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatProgressContentPart.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatProgressContentPart.fixture.ts @@ -41,6 +41,7 @@ import { type IChatBackgroundShell } from '../../../../common/chatBackgroundShel function createMockContext(opts?: { isComplete?: boolean; hasFollowingContent?: boolean }): IChatContentPartRenderContext { const element = new class extends mock() { override readonly isComplete = opts?.isComplete ?? false; + override readonly sessionResource = URI.parse('chat-session:/progress-fixture'); }(); return { element, diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatSubagentContent.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatSubagentContent.fixture.ts index bc01f8365843cd..835cbf4b6a28c8 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatSubagentContent.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatSubagentContent.fixture.ts @@ -19,13 +19,11 @@ import { editorBackground, editorForeground } from '../../../../../platform/them import { IMarkerService } from '../../../../../platform/markers/common/markers.js'; import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; import { AgentHostSubagentProgress } from '../../../../contrib/chat/browser/agentSessions/agentHost/agentHostSubagentProgress.js'; -import { toolCallStateToInvocation } from '../../../../contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { rawMarkdownToString, toolCallStateToInvocation } from '../../../../contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.js'; import { ToolCallConfirmationReason, ToolCallStatus } from '../../../../../platform/agentHost/common/state/sessionState.js'; import { IChatWidgetService } from '../../../../contrib/chat/browser/chat.js'; -import { ChatContentMarkdownRenderer } from '../../../../contrib/chat/browser/widget/chatContentMarkdownRenderer.js'; import { ChatListItemRenderer } from '../../../../contrib/chat/browser/widget/chatListRenderer.js'; import { ChatEditorOptions } from '../../../../contrib/chat/browser/widget/chatOptions.js'; -import { ChatSystemNotificationContentPart } from '../../../../contrib/chat/browser/widget/chatContentParts/chatSystemNotificationContentPart.js'; import { IChatSubagentToolInvocationData } from '../../../../contrib/chat/common/chatService/chatService.js'; import { CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, ChatAgentLocation, ChatConfiguration, ChatModeKind, CollapsedToolsDisplayMode, ThinkingDisplayMode } from '../../../../contrib/chat/common/constants.js'; import { ChatModel } from '../../../../contrib/chat/common/model/chatModel.js'; @@ -41,7 +39,7 @@ import '../../../../contrib/chat/browser/widget/media/chat.css'; type FusionFixtureState = 'fusion-routing' | 'fusion-single' | 'fusion-cascade' | 'fusion-critique' | 'fusion-failed' | 'fusion-cancelled' | 'fusion-permission'; -async function renderSubagent(context: ComponentFixtureContext, state: 'pending' | 'initializing' | 'running' | 'thinking' | 'parent-complete' | 'inline' | 'inline-expanded' | 'nested' | 'nested-unavailable' | FusionFixtureState, readOnly = false, thinkingStyle = ThinkingDisplayMode.FixedScrolling): Promise { +async function renderSubagent(context: ComponentFixtureContext, state: 'pending' | 'initializing' | 'running' | 'thinking' | 'parent-complete' | 'inline' | 'inline-expanded' | 'nested' | 'nested-unavailable' | 'references' | FusionFixtureState, readOnly = false, thinkingStyle = ThinkingDisplayMode.FixedScrolling): Promise { const { container, disposableStore } = context; const width = 620; const instantiationService = createEditorServices(disposableStore, { @@ -239,7 +237,7 @@ async function renderSubagent(context: ComponentFixtureContext, state: 'pending' kind: 'subagent', hasStarted: false, description, - chatResource: `ahp-chat://subagent/Y29waWxvdGNsaTovc2Vzc2lvbg/review-${index}`, + chatResource: state === 'references' ? `ahp-chat:/11111111-1111-5111-8111-11111111111${index}` : `ahp-chat://subagent/Y29waWxvdGNsaTovc2Vzc2lvbg/review-${index}`, agentName: 'code-review', isChatAvailable: state === 'initializing', isActive: false, @@ -260,6 +258,37 @@ async function renderSubagent(context: ComponentFixtureContext, state: 'pending' ); await normalTool.didExecuteTool(undefined); publisher.publish([normalTool]); + if (state === 'references') { + for (const [index, invocation] of launches.entries()) { + const data = invocation.toolSpecificData; + if (data?.kind !== 'subagent' || !data.chatResource || !data.description) { + throw new Error('Missing fixture subagent chat'); + } + data.hasStarted = true; + data.isChatAvailable = true; + invocation.notifyToolSpecificDataChanged(); + const link = new MarkdownString().appendLink(data.chatResource, data.description).value; + publisher.publish([{ kind: 'systemNotification', content: rawMarkdownToString(`${link} completed`, 'local') }]); + const read = new ChatToolInvocation( + { invocationMessage: rawMarkdownToString(`Read agent ${link}`, 'local'), pastTenseMessage: rawMarkdownToString(`Read agent ${link}`, 'local'), toolSpecificData: { kind: 'input', rawInput: { agent_id: `review-${index}` } } }, + { id: 'read_agent', displayName: 'Read Agent', modelDescription: 'Read Agent', source: ToolDataSource.Internal }, + `read-${index}`, undefined, {}, + ); + await read.didExecuteTool({ content: [], toolResultDetails: { input: '{}', output: [] } }); + publisher.publish([read]); + const write = new ChatToolInvocation( + { invocationMessage: rawMarkdownToString(`Write to agent ${link}`, 'local'), pastTenseMessage: rawMarkdownToString(`Write to agent ${link}`, 'local'), toolSpecificData: { kind: 'input', rawInput: { agent_id: `review-${index}` } } }, + { id: 'write_agent', displayName: 'Write to Agent', modelDescription: 'Write to Agent', source: ToolDataSource.Internal }, + `write-${index}`, undefined, {}, + ); + if (index === 0) { + await write.didExecuteTool({ content: [], toolResultDetails: { input: '{}', output: [] } }); + } + publisher.publish([write]); + } + publisher.publish([{ kind: 'markdownContent', content: new MarkdownString('Continuing the review with both agents.') }]); + return; + } if (state === 'parent-complete') { request.response?.complete(); } @@ -315,27 +344,6 @@ async function renderSubagent(context: ComponentFixtureContext, state: 'pending' } } -function renderCompletionNotices(context: ComponentFixtureContext): void { - const { container, disposableStore } = context; - const instantiationService = createEditorServices(disposableStore, { - colorTheme: context.theme, - additionalServices: registerChatFixtureServices, - }); - container.classList.add('interactive-session'); - container.style.width = '620px'; - container.style.padding = '12px'; - const transcript = dom.append(container, dom.$('.interactive-item-container')); - const renderer = instantiationService.createInstance(ChatContentMarkdownRenderer); - for (const content of [ - 'Background agent `Renderer reviewer` is complete', - 'Background agent `History reviewer` completed', - 'Background agent `Lifecycle reviewer` failed', - ]) { - const part = disposableStore.add(instantiationService.createInstance(ChatSystemNotificationContentPart, { kind: 'systemNotification', content: new MarkdownString(content) }, renderer)); - transcript.appendChild(part.domNode); - } -} - export default defineThemedFixtureGroup({ path: 'chat/' }, { FusionRouting: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'fusion-routing') }), FusionSingle: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'fusion-single') }), @@ -352,7 +360,7 @@ export default defineThemedFixtureGroup({ path: 'chat/' }, { Inline: defineComponentFixture({ additionalThemes: ['darkHighContrast', 'lightHighContrast'], labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'inline') }), InlineExpanded: defineComponentFixture({ additionalThemes: ['darkHighContrast', 'lightHighContrast'], labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'inline-expanded') }), StartedAfterParentComplete: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'parent-complete') }), - CompletionNotices: defineComponentFixture({ labels: { kind: 'screenshot' }, render: renderCompletionNotices }), + CompletionNotices: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'references') }), ThinkingAcrossCompletion: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'thinking') }), ReadOnlyThinkingAcrossCompletion: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'thinking', true) }), CollapsedThinkingAcrossCompletion: defineComponentFixture({ labels: { kind: 'screenshot' }, render: context => renderSubagent(context, 'thinking', false, ThinkingDisplayMode.Collapsed) }),