| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420 |
- import {
- TID_CHAT_ASSISTANT_HISTORY_CONTENT,
- TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
- TID_CHAT_ASSISTANT_MESSAGE,
- } from "@zcode/shared";
- import {
- getLatestUpstreamToolResultByToolCallId,
- type UpstreamToolResultSnapshot,
- } from "./conversation-session-network.js";
- import {
- expandAssistantHistoriesWithContent,
- expandVisibleToolCallGroups,
- getToolCallDiagnostics,
- type ToolCallBlockSnapshot,
- type ToolCallDiagnostics,
- type ToolCallMatcher,
- } from "./conversation-session-tool-diagnostics.js";
- export { expandAssistantHistoriesWithContent } from "./conversation-session-tool-diagnostics.js";
- interface AssistantHistoryOpenSnapshot {
- assistantText: string;
- contentExists: boolean;
- contentOpen: string | null;
- expanded: boolean;
- reason: string | null;
- triggerTestId: string | null;
- }
- export async function waitForToolCallBlockContaining(
- text: string,
- timeout = 20000,
- ): Promise<ToolCallBlockSnapshot> {
- return waitForToolCallBlock({ type: "text", value: text }, timeout);
- }
- export async function waitForToolCallBlockByToolName(
- toolName: string,
- timeout = 20000,
- ): Promise<ToolCallBlockSnapshot> {
- return waitForToolCallBlock({ type: "toolName", value: toolName }, timeout);
- }
- export async function waitForToolCallBlockByToolCallId(
- toolCallId: string,
- timeout = 20000,
- ): Promise<ToolCallBlockSnapshot> {
- return waitForToolCallBlock({ type: "toolCallId", value: toolCallId }, timeout);
- }
- export async function listToolCallBlocks(): Promise<ToolCallBlockSnapshot[]> {
- const diagnostics = await getToolCallDiagnostics(null);
- return diagnostics.blocks;
- }
- export interface SuccessfulToolCallSnapshot {
- output: string;
- status: "completed";
- toolCallId: string;
- toolName: string | null;
- }
- export async function assertToolCallNotFailedByToolCallId(
- toolCallId: string,
- ): Promise<void> {
- const diagnostics = await getToolCallDiagnostics({
- type: "toolCallId",
- value: toolCallId,
- });
- const toolCall = findRendererStoreToolCall(diagnostics, toolCallId);
- if (
- toolCall?.status === "failed" ||
- diagnostics.matchedBlock?.status === "failed"
- ) {
- throw createToolCallFailure(
- toolCallId,
- toolCall,
- diagnostics.matchedBlock,
- );
- }
- const providerResult =
- await getLatestUpstreamToolResultByToolCallId(toolCallId);
- if (providerResult?.isError) {
- // Bug 根因:V4 历史投影可能在工具已经返回 is_error 后仍短暂显示 pending,
- // 直接读取模型实际收到的 tool_result,避免错误再次退化为 guest/UI 超时。
- throw createProviderToolResultFailure(providerResult);
- }
- }
- export async function waitForSuccessfulToolCallByToolCallId(
- toolCallId: string,
- expectedOutputIncludes: readonly string[] = [],
- timeout = 20000,
- ): Promise<SuccessfulToolCallSnapshot> {
- const deadline = Date.now() + timeout;
- let latest: ReturnType<typeof findRendererStoreToolCall> = null;
- while (Date.now() <= deadline) {
- const diagnostics = await getToolCallDiagnostics({
- type: "toolCallId",
- value: toolCallId,
- });
- latest = findRendererStoreToolCall(diagnostics, toolCallId);
- const block = diagnostics.matchedBlock;
- if (latest?.status === "failed" || block?.status === "failed") {
- // Bug 根因:Browser 无状态化后旧 fixture 的跨 cell binding 会直接令工具失败,
- // 但旧 E2E 继续等待 guest/UI,最终只报焦点超时。工具错误必须在真实边界立即暴露。
- throw createToolCallFailure(toolCallId, latest, block);
- }
- const providerResult =
- await getLatestUpstreamToolResultByToolCallId(toolCallId);
- if (providerResult?.isError) {
- throw createProviderToolResultFailure(providerResult);
- }
- if (latest?.status === "completed") {
- const output = latest.output ?? "";
- assertToolResultContains(toolCallId, output, expectedOutputIncludes);
- return {
- output,
- status: "completed",
- toolCallId: latest.toolId ?? toolCallId,
- toolName: latest.toolName,
- };
- }
- if (providerResult) {
- assertToolResultContains(
- toolCallId,
- providerResult.content,
- expectedOutputIncludes,
- );
- return {
- output: providerResult.content,
- status: "completed",
- toolCallId,
- toolName: block?.toolName ?? latest?.toolName ?? null,
- };
- }
- if (
- block?.status === "completed" &&
- expectedOutputIncludes.length === 0
- ) {
- // V4 history case 的 renderer-store 旧消息投影可能为空,但 DOM tool block 是
- // 真实执行终态;要求 marker 时必须继续等模型实际收到的 provider tool_result。
- return {
- output: block.text,
- status: "completed",
- toolCallId: block.toolCallId ?? toolCallId,
- toolName: block.toolName,
- };
- }
- await new Promise<void>((resolveDelay) =>
- setTimeout(resolveDelay, 100),
- );
- }
- throw new Error(
- `toolCallId=${toolCallId} 没有在 ${timeout}ms 内成功完成; latest=${JSON.stringify(
- latest,
- )}`,
- );
- }
- export async function openAssistantHistoryForAssistantContaining(
- text: string,
- timeout = 15000,
- ): Promise<AssistantHistoryOpenSnapshot> {
- let latest: AssistantHistoryOpenSnapshot | null = null;
- try {
- await browser.waitUntil(
- async () => {
- latest = await clickAssistantHistoryForAssistantContaining(text);
- return latest.expanded;
- },
- {
- timeout,
- timeoutMsg: `没有展开包含指定内容的 assistant history: ${text}`,
- },
- );
- } catch {
- latest = await safeClickAssistantHistoryForAssistantContaining(text, latest);
- throw new Error(
- `没有展开包含指定内容的 assistant history: ${text}; latest=${JSON.stringify(
- latest,
- )}`,
- );
- }
- const result = await clickAssistantHistoryForAssistantContaining(text);
- if (!result.expanded) {
- throw new Error(
- `assistant history 等待后仍未展开: ${text}; latest=${JSON.stringify(result)}`,
- );
- }
- return result;
- }
- export function getToolCallBlockContaining(
- text: string,
- ): Promise<ToolCallBlockSnapshot | null> {
- return getMatchingToolCallBlock({ type: "text", value: text });
- }
- export function getToolCallBlockByToolName(
- toolName: string,
- ): Promise<ToolCallBlockSnapshot | null> {
- return getMatchingToolCallBlock({ type: "toolName", value: toolName });
- }
- export function getToolCallBlockByToolCallId(
- toolCallId: string,
- ): Promise<ToolCallBlockSnapshot | null> {
- return getMatchingToolCallBlock({ type: "toolCallId", value: toolCallId });
- }
- async function waitForToolCallBlock(
- matcher: ToolCallMatcher,
- timeout: number,
- ): Promise<ToolCallBlockSnapshot> {
- let latest: ToolCallDiagnostics | null = null;
- let matchedBlock: ToolCallBlockSnapshot | null = null;
- try {
- await browser.waitUntil(
- async () => {
- latest = await getToolCallDiagnostics(matcher);
- if (latest.matchedBlock?.exists === true) {
- matchedBlock = latest.matchedBlock;
- return true;
- }
- await expandAssistantHistoriesWithContent();
- await expandVisibleToolCallGroups();
- return false;
- },
- {
- timeout,
- timeoutMsg: `没有出现匹配的 tool call block: ${JSON.stringify(matcher)}`,
- },
- );
- } catch {
- latest = await safeGetToolCallDiagnostics(matcher, latest);
- throw new Error(
- `没有出现匹配的 tool call block: ${JSON.stringify(
- matcher,
- )}; diagnostics=${JSON.stringify(latest)}`,
- );
- }
- if (!matchedBlock) {
- latest = await safeGetToolCallDiagnostics(matcher, latest);
- throw new Error(
- `tool call block 等待后仍不存在: ${JSON.stringify(
- matcher,
- )}; diagnostics=${JSON.stringify(latest)}`,
- );
- }
- // 修复原因:tool block 命中后可能立即被折叠进 assistant history。重新查询 DOM
- // 会把已经成功观察到的短生命周期节点误判为不存在,应返回成功轮询捕获的快照。
- return matchedBlock;
- }
- async function getMatchingToolCallBlock(
- matcher: ToolCallMatcher,
- ): Promise<ToolCallBlockSnapshot | null> {
- const diagnostics = await getToolCallDiagnostics(matcher);
- return diagnostics.matchedBlock;
- }
- function findRendererStoreToolCall(
- diagnostics: ToolCallDiagnostics,
- toolCallId: string,
- ) {
- for (const message of diagnostics.rendererStore.messages) {
- const match = message.toolCalls.find(
- (toolCall) =>
- toolCall.toolId === toolCallId ||
- toolCall.toolId?.startsWith(`${toolCallId}:`) === true,
- );
- if (match) return match;
- }
- return null;
- }
- function createToolCallFailure(
- toolCallId: string,
- toolCall: ReturnType<typeof findRendererStoreToolCall>,
- block: ToolCallBlockSnapshot | null,
- ): Error {
- return new Error(
- `toolCallId=${toolCallId} 执行失败; error=${JSON.stringify(
- toolCall?.error,
- )}; ` +
- `rawError=${JSON.stringify(
- toolCall?.rawErrorMessage ?? toolCall?.rawErrorDetail,
- )}; ` +
- `output=${JSON.stringify(toolCall?.output)}; block=${JSON.stringify(
- block,
- )}`,
- );
- }
- function createProviderToolResultFailure(
- result: UpstreamToolResultSnapshot,
- ): Error {
- return new Error(
- `toolCallId=${result.toolCallId} 执行失败; providerToolResult=${JSON.stringify(
- result.content,
- )}; isError=true`,
- );
- }
- function assertToolResultContains(
- toolCallId: string,
- output: string,
- expectedOutputIncludes: readonly string[],
- ): void {
- const missing = expectedOutputIncludes.filter(
- (value) => !output.includes(value),
- );
- if (missing.length > 0) {
- throw new Error(
- `toolCallId=${toolCallId} 已返回 tool_result,但结果缺少 ${JSON.stringify(
- missing,
- )}; output=${output}`,
- );
- }
- }
- async function safeGetToolCallDiagnostics(
- matcher: ToolCallMatcher,
- fallback: ToolCallDiagnostics | null,
- ): Promise<ToolCallDiagnostics | null> {
- try {
- return await getToolCallDiagnostics(matcher);
- } catch {
- return fallback;
- }
- }
- function clickAssistantHistoryForAssistantContaining(
- text: string,
- ): Promise<AssistantHistoryOpenSnapshot> {
- return browser.execute(
- (
- assistantMessagePrefix,
- historyTriggerPrefix,
- historyContentPrefix,
- expectedText,
- ) => {
- const normalizeText = (value: string) =>
- value.replace(/\u00a0/g, " ").trim();
- const assistantMessages = Array.from(
- document.querySelectorAll<HTMLElement>(
- `[data-testid^="${assistantMessagePrefix}-"]`,
- ),
- );
- const assistantMessage = assistantMessages.find((message) =>
- normalizeText(message.innerText).includes(expectedText),
- );
- if (!assistantMessage) {
- return {
- assistantText: assistantMessages
- .map((message) => normalizeText(message.innerText))
- .join("\n---\n"),
- contentExists: false,
- contentOpen: null,
- expanded: false,
- reason: "assistant-not-found",
- triggerTestId: null,
- };
- }
- const trigger = assistantMessage.querySelector<HTMLElement>(
- `[data-testid^="${historyTriggerPrefix}-"]`,
- );
- if (!trigger) {
- return {
- assistantText: normalizeText(assistantMessage.innerText),
- contentExists: false,
- contentOpen: null,
- expanded: false,
- reason: "history-trigger-not-found",
- triggerTestId: null,
- };
- }
- const stateKey = trigger.getAttribute("data-history-state-key");
- const content =
- stateKey !== null
- ? document.querySelector<HTMLElement>(
- `[data-testid^="${historyContentPrefix}-"][data-history-state-key="${stateKey}"]`,
- )
- : null;
- const expanded =
- trigger.getAttribute("aria-expanded") === "true" ||
- trigger.getAttribute("data-history-open") === "true";
- if (!expanded) {
- trigger.click();
- }
- return {
- assistantText: normalizeText(assistantMessage.innerText),
- contentExists: Boolean(content),
- contentOpen: content?.getAttribute("data-history-open") ?? null,
- expanded,
- reason: expanded ? null : "clicked-history-trigger",
- triggerTestId: trigger.getAttribute("data-testid"),
- };
- },
- TID_CHAT_ASSISTANT_MESSAGE,
- TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
- TID_CHAT_ASSISTANT_HISTORY_CONTENT,
- text,
- );
- }
- async function safeClickAssistantHistoryForAssistantContaining(
- text: string,
- fallback: AssistantHistoryOpenSnapshot | null,
- ): Promise<AssistantHistoryOpenSnapshot | null> {
- try {
- return await clickAssistantHistoryForAssistantContaining(text);
- } catch {
- return fallback;
- }
- }
|