conversation-session-background.test.ts 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153
  1. import {
  2. assertIncomingMessage,
  3. assertTaskNotificationContents,
  4. } from "../helpers/incoming-message-evidence.js";
  5. import { execFile } from "node:child_process";
  6. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  7. import {
  8. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  9. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  10. TID_CHAT_BACKGROUND_RESULT_TITLE,
  11. TID_CHAT_LOADING,
  12. TID_CHAT_MESSAGES,
  13. TID_CHAT_USER_MESSAGE,
  14. TID_V4_BACKGROUND_WORK_CANCEL,
  15. TID_V4_SESSION_PANE,
  16. TID_V4_TURN_NAVIGATOR_ITEM,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import { clearAppData, seedSettings } from "../helpers/desktop-app.js";
  20. import {
  21. waitForCompactMarkerStatus,
  22. waitForCompactMarkerStatuses,
  23. } from "../helpers/conversation-session-compact.js";
  24. import {
  25. countUpstreamRequests,
  26. findFirstUpstreamRequestIndex,
  27. getUpstreamRequestEvidence,
  28. getUpstreamRequestRecordCount,
  29. getLatestUpstreamToolResultByToolCallId,
  30. waitForUpstreamRequest,
  31. } from "../helpers/conversation-session-network.js";
  32. import {
  33. clickFirstQueueSendNow,
  34. waitForQueueOrderContaining,
  35. } from "../helpers/conversation-session-queue.js";
  36. import {
  37. listToolCallBlocks,
  38. waitForToolCallBlockByToolCallId,
  39. waitForToolCallBlockByToolName,
  40. } from "../helpers/conversation-session-tool.js";
  41. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  42. import {
  43. assertVisibleV4UserMessagesNotContaining,
  44. clickV4Stop,
  45. getV4ConversationState,
  46. getV4Messages,
  47. getV4PaneSnapshot,
  48. openV4ComposerRunningBackgroundWorks,
  49. prepareV4ConversationE2E,
  50. selectV4TaskById,
  51. sendV4Prompt,
  52. sendV4PromptAndWaitAccepted,
  53. waitForV4AssistantMessageContaining,
  54. waitForV4ComposerText,
  55. waitForV4ConversationState,
  56. waitForV4TimelineContaining,
  57. waitForV4UserMessageContaining,
  58. V4_MAIN_PANE_ID,
  59. } from "../helpers/v4-conversation.js";
  60. import {
  61. ensureToolCrossProductFullAccessMode,
  62. respondToToolCrossProductBlockers,
  63. } from "../helpers/conversation-session-tool-cross-product.js";
  64. import {
  65. beginConversationTelemetryCapture,
  66. checkpointConversationTelemetryCase,
  67. waitForConversationReportDelta,
  68. type ConversationTelemetryReport,
  69. } from "../helpers/conversation-telemetry-parity-capture.js";
  70. const BACKGROUND_E2E_TIMEOUT_MS = 240000;
  71. const BACKGROUND_RUNTIME_ROOT = resolveE2ERuntimePath("conversation-session-background");
  72. const BG14_PREVIEW_RELEASE_FILE = resolveE2ERuntimePath(
  73. "conversation-session-background",
  74. "bg14-preview-release",
  75. );
  76. const BG08_ROOT_PID_FILE = resolveE2ERuntimePath(
  77. "conversation-session-background",
  78. "bg08-root.pid",
  79. );
  80. const BG08_LAUNCHER_PID_FILE = resolveE2ERuntimePath(
  81. "conversation-session-background",
  82. "bg08-launcher.pid",
  83. );
  84. const BG08_WORKER_PID_FILE = resolveE2ERuntimePath(
  85. "conversation-session-background",
  86. "bg08-worker.pid",
  87. );
  88. const BG08_LAUNCHER_SCRIPT_FILE = resolveE2ERuntimePath(
  89. "conversation-session-background",
  90. "bg08-launcher.cjs",
  91. );
  92. const BG08_LAUNCHER_SCRIPT = [
  93. 'const { spawn } = require("node:child_process");',
  94. 'const { writeFileSync } = require("node:fs");',
  95. 'writeFileSync(process.argv[2], String(process.pid) + "\\n");',
  96. 'const worker = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {',
  97. ' stdio: "ignore",',
  98. "});",
  99. 'if (!worker.pid) throw new Error("BG08 worker did not start");',
  100. 'writeFileSync(process.argv[3], String(worker.pid) + "\\n");',
  101. "setInterval(() => {}, 1000);",
  102. ].join("\n");
  103. const BG21_RELEASE_FILE = resolveE2ERuntimePath(
  104. "conversation-session-background",
  105. "bg21-child-tool-release",
  106. );
  107. const BG38_STARTED_FILE = resolveE2ERuntimePath(
  108. "conversation-session-background",
  109. "bg38-bash-started",
  110. );
  111. const BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE = resolveE2ERuntimePath(
  112. "conversation-session-background",
  113. "background-send-now-queue-release",
  114. );
  115. const BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE = resolveE2ERuntimePath(
  116. "conversation-session-background",
  117. "background-child-tool-idle-release",
  118. );
  119. const BACKGROUND_PARENT_ANCHOR_RELEASE_FILE = resolveE2ERuntimePath(
  120. "conversation-session-background",
  121. "background-parent-anchor-release",
  122. );
  123. const BACKGROUND_SWITCH_BACK_RELEASE_FILE = resolveE2ERuntimePath(
  124. "conversation-session-background",
  125. "background-switch-back-release",
  126. );
  127. const BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE = resolveE2ERuntimePath(
  128. "conversation-session-background",
  129. "agent-composition-mixed-foreground-release",
  130. );
  131. interface BackgroundResultPresentationSnapshot {
  132. assistantText: string;
  133. historyContentCount: number;
  134. visibleHistoryContentCount: number;
  135. historyTriggerId: string | null;
  136. historyTriggerCount: number;
  137. historyExpanded: string | null;
  138. titleOutsideHistory: boolean;
  139. navigatorItemCount: number;
  140. title: string;
  141. }
  142. async function getBackgroundResultPresentation(
  143. expectedTitle: string,
  144. ): Promise<BackgroundResultPresentationSnapshot | null> {
  145. return browser.execute(
  146. (titleTestId, historyTriggerTestId, historyContentTestId, navigatorItemTestId, title) => {
  147. const titleNode = Array.from(
  148. document.querySelectorAll<HTMLElement>(`[data-testid^="${titleTestId}-"]`),
  149. ).find((node) => node.textContent?.trim() === title);
  150. const turn = titleNode?.closest<HTMLElement>("[data-turn-key]");
  151. if (!titleNode || !turn) return null;
  152. return {
  153. assistantText: turn.innerText,
  154. historyContentCount: turn.querySelectorAll(`[data-testid^="${historyContentTestId}-"]`)
  155. .length,
  156. visibleHistoryContentCount: Array.from(
  157. turn.querySelectorAll<HTMLElement>(`[data-testid^="${historyContentTestId}-"]`),
  158. ).filter(
  159. (node) =>
  160. node.getBoundingClientRect().height > 0 &&
  161. getComputedStyle(node).visibility !== "hidden",
  162. ).length,
  163. historyTriggerId:
  164. turn
  165. .querySelector(`[data-testid^="${historyTriggerTestId}-"]`)
  166. ?.getAttribute("data-testid") ?? null,
  167. historyTriggerCount: turn.querySelectorAll(`[data-testid^="${historyTriggerTestId}-"]`)
  168. .length,
  169. navigatorItemCount: document.querySelectorAll(`[data-testid^="${navigatorItemTestId}-"]`)
  170. .length,
  171. historyExpanded:
  172. turn
  173. .querySelector(`[data-testid^="${historyTriggerTestId}-"]`)
  174. ?.getAttribute("aria-expanded") ?? null,
  175. titleOutsideHistory: titleNode.closest('[data-slot="collapsible-content"]') === null,
  176. title: titleNode.textContent?.trim() ?? "",
  177. };
  178. },
  179. TID_CHAT_BACKGROUND_RESULT_TITLE,
  180. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  181. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  182. TID_V4_TURN_NAVIGATOR_ITEM,
  183. expectedTitle,
  184. );
  185. }
  186. async function waitForBackgroundResultPresentation(options: {
  187. assistantMarker: string;
  188. expectedTitle: string;
  189. failureLabel: string;
  190. }): Promise<void> {
  191. let snapshot: BackgroundResultPresentationSnapshot | null = null;
  192. await browser.waitUntil(
  193. async () => {
  194. snapshot = await getBackgroundResultPresentation(options.expectedTitle);
  195. return Boolean(
  196. snapshot &&
  197. snapshot.assistantText.includes(options.assistantMarker) &&
  198. snapshot.historyTriggerCount === 1 &&
  199. snapshot.historyExpanded === "false" &&
  200. snapshot.titleOutsideHistory &&
  201. snapshot.visibleHistoryContentCount === 0 &&
  202. snapshot.navigatorItemCount === 0,
  203. );
  204. },
  205. {
  206. timeout: 60000,
  207. timeoutMsg: `${options.failureLabel} 没有显示结构化标题、完成态折叠入口缺失,或被计入 turn navigator`,
  208. },
  209. );
  210. expect(snapshot).toMatchObject({
  211. visibleHistoryContentCount: 0,
  212. historyTriggerCount: 1,
  213. historyExpanded: "false",
  214. titleOutsideHistory: true,
  215. navigatorItemCount: 0,
  216. title: options.expectedTitle,
  217. });
  218. // 必须观察实际过程容器:仅检查触发器状态会漏掉内容仍可见的回归。
  219. const completed = await getBackgroundResultPresentation(options.expectedTitle);
  220. expect(completed?.historyTriggerId).toBeTruthy();
  221. const trigger = await $(`[data-testid="${completed!.historyTriggerId}"]`);
  222. for (const expanded of [true, false]) {
  223. await trigger.click();
  224. await browser.waitUntil(
  225. async () => {
  226. const current = await getBackgroundResultPresentation(options.expectedTitle);
  227. return Boolean(
  228. current &&
  229. current.historyExpanded === String(expanded) &&
  230. current.visibleHistoryContentCount === (expanded ? 1 : 0) &&
  231. (!expanded ||
  232. (current.historyContentCount === 1 &&
  233. current.assistantText.includes("background-history-visible"))) &&
  234. current.titleOutsideHistory &&
  235. current.assistantText.includes(options.assistantMarker),
  236. );
  237. },
  238. {
  239. timeout: 5000,
  240. timeoutMsg: `${options.failureLabel} 过程${expanded ? "展开" : "收起"}后内容可见性或最终结果不符合预期`,
  241. },
  242. );
  243. }
  244. }
  245. describe("会话区 Background Runtime Task E2E", () => {
  246. before(async function () {
  247. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  248. await mkdir(BACKGROUND_RUNTIME_ROOT, { recursive: true });
  249. await writeFile(BG08_LAUNCHER_SCRIPT_FILE, BG08_LAUNCHER_SCRIPT, "utf-8");
  250. await removeBg08PidFiles();
  251. await seedSettings({ messageStreamShowTodos: true });
  252. await prepareV4ConversationE2E();
  253. });
  254. afterEach(async () => {
  255. // BG21 / send-now 的 child Bash 使用文件 barrier;失败收尾也要先释放,
  256. // 避免遗留后台进程。
  257. await Promise.all([
  258. writeFile(BG21_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  259. writeFile(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, "release\n", "utf-8").catch(
  260. () => undefined,
  261. ),
  262. writeFile(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, "release\n", "utf-8").catch(
  263. () => undefined,
  264. ),
  265. writeFile(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  266. writeFile(BACKGROUND_SWITCH_BACK_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  267. ]);
  268. await stopIfBusy();
  269. await cleanupBg08ProcessTree();
  270. await rm(BG21_RELEASE_FILE, { force: true }).catch(() => undefined);
  271. await rm(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, { force: true }).catch(() => undefined);
  272. await rm(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, { force: true }).catch(() => undefined);
  273. await rm(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, { force: true }).catch(() => undefined);
  274. await rm(BACKGROUND_SWITCH_BACK_RELEASE_FILE, { force: true }).catch(() => undefined);
  275. await rm(BG38_STARTED_FILE, { force: true }).catch(() => undefined);
  276. await removeBg08PidFiles();
  277. });
  278. after(async () => {
  279. await browser.electron.restoreAllMocks();
  280. await rm(BACKGROUND_RUNTIME_ROOT, { force: true, recursive: true });
  281. await clearAppData();
  282. });
  283. it("background Agent 完成后通过 task-notification 唤醒父会话且不显示 synthetic user", async function () {
  284. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  285. await startNewBackgroundDraft();
  286. const prompt =
  287. "E2E_BACKGROUND_AGENT: Launch a background agent and summarize only after its notification.";
  288. const requestCountBefore = await getUpstreamRequestRecordCount();
  289. await sendV4PromptAndWaitAccepted(
  290. prompt,
  291. "E2E_BACKGROUND_AGENT",
  292. "background Agent prompt 没有被 composer 接受",
  293. );
  294. await waitForToolCallBlockByToolName("Agent", 60000);
  295. await respondToBackgroundBlockers();
  296. const launchIndex = await waitForFirstRequestIndex(
  297. {
  298. includes: ["E2E_BACKGROUND_AGENT", "Async agent launched successfully"],
  299. },
  300. requestCountBefore,
  301. "background Agent launch tool result 没有进入父模型请求",
  302. );
  303. const notificationIndex = await waitForFirstRequestIndex(
  304. {
  305. includes: ["<task-notification>", "E2E_BACKGROUND_AGENT_CHILD_RESULT"],
  306. },
  307. launchIndex,
  308. "background Agent completion notification 没有进入父模型请求",
  309. );
  310. expect(notificationIndex).toBeGreaterThan(launchIndex);
  311. await waitForV4AssistantMessageContaining("background-agent-notification-consumed-ok");
  312. // Bug 根因:V4 completed turn 会把旧 Agent tool card 收进 timeline history;
  313. // 本 case 的主合同由 notification 请求顺序、独立结果轮和无 synthetic user 共同覆盖,
  314. // 不再重复依赖 legacy card 的瞬时展开状态。
  315. await waitForIdle("background Agent notification 后会话没有回到 idle");
  316. await waitForBackgroundResultPresentation({
  317. assistantMarker: "background-agent-notification-consumed-ok",
  318. expectedTitle: "Check background",
  319. failureLabel: "background Agent 独立结果轮",
  320. });
  321. await assertNoVisibleTaskNotification();
  322. await browser.refresh();
  323. await waitForBackgroundResultPresentation({
  324. assistantMarker: "background-agent-notification-consumed-ok",
  325. expectedTitle: "Check background",
  326. failureLabel: "background Agent 刷新恢复结果轮",
  327. });
  328. });
  329. it("background Bash 完成后复用同一 notification/wake 链路", async function () {
  330. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  331. await startNewBackgroundDraft();
  332. const capture = await beginBackgroundTelemetryCapture();
  333. const prompt =
  334. "E2E_BACKGROUND_BASH: Run a background Bash command and report after notification.";
  335. const requestCountBefore = await getUpstreamRequestRecordCount();
  336. await sendV4Prompt(prompt);
  337. await waitForV4ComposerText("", "background Bash prompt 发送后输入框没有清空");
  338. await waitForV4UserMessageContaining("E2E_BACKGROUND_BASH");
  339. await waitForToolCallBlockByToolName("Bash", 60000);
  340. await respondToBackgroundBlockers();
  341. const launchIndex = await waitForFirstRequestIndex(
  342. {
  343. includes: ["E2E_BACKGROUND_BASH", "Command running in background"],
  344. },
  345. requestCountBefore,
  346. "background Bash launch tool result 没有进入父模型请求",
  347. );
  348. const notificationIndex = await waitForFirstRequestIndex(
  349. {
  350. includes: [
  351. "E2E_BACKGROUND_BASH",
  352. "<task-notification>",
  353. "<tool-use-id>toolu_e2e_background_bash</tool-use-id>",
  354. "<status>completed</status>",
  355. ],
  356. },
  357. launchIndex,
  358. "background Bash completion notification 没有进入父模型请求",
  359. );
  360. expect(notificationIndex).toBeGreaterThan(launchIndex);
  361. await waitForV4AssistantMessageContaining("background-bash-notification-consumed-ok");
  362. const block = await waitForToolCallBlockByToolName("Bash", 30000);
  363. expect(block.status).not.toBe("running");
  364. await waitForIdle("background Bash notification 后会话没有回到 idle");
  365. await waitForBackgroundResultPresentation({
  366. assistantMarker: "background-bash-notification-consumed-ok",
  367. expectedTitle: "Print background marker",
  368. failureLabel: "background Bash 独立结果轮",
  369. });
  370. await assertNoVisibleTaskNotification();
  371. const reports = await waitForConversationReportDelta(capture, {
  372. message_completion: 2,
  373. });
  374. assertMainCompletionAgentCompositions(reports, ["main_only", "main_only"]);
  375. assertMainCompletionMessageSources(reports, ["chat", "background_task"]);
  376. });
  377. it("background task running 时用户普通消息应直接发送而不是进入 queue", async function () {
  378. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  379. await startNewBackgroundDraft();
  380. const launchPrompt =
  381. "E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP: Start a long background Bash command and wait for my next message.";
  382. const requestCountBefore = await getUpstreamRequestRecordCount();
  383. await sendV4Prompt(launchPrompt);
  384. await waitForV4ComposerText("", "background direct user prompt setup 发送后输入框没有清空");
  385. await waitForV4UserMessageContaining("E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP");
  386. await waitForToolCallBlockByToolCallId("toolu_e2e_background_direct_user_prompt_bash", 60000);
  387. await respondToBackgroundBlockers();
  388. const launchIndex = await waitForFirstRequestIndex(
  389. {
  390. includes: ["E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP", "Command running in background"],
  391. },
  392. requestCountBefore,
  393. "background direct user prompt setup 的 Bash launch result 没有进入父模型请求",
  394. );
  395. await waitForV4AssistantMessageContaining("background-direct-user-prompt-launched-ok");
  396. await waitForIdle("background direct user prompt setup 后父会话没有回到 idle");
  397. await waitForBackgroundTaskControlRow(
  398. "bash",
  399. "background direct user prompt bash sleep",
  400. "background direct user prompt Bash 没有出现在统一 background control UI",
  401. );
  402. const directPrompt =
  403. "E2E_BACKGROUND_DIRECT_USER_PROMPT: This message should be sent immediately while the background task is still running. Payload: E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD.";
  404. await sendV4Prompt(directPrompt);
  405. await waitForV4ComposerText("", "background running 时用户新消息发送后输入框没有清空");
  406. await waitForV4UserMessageContaining("E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD");
  407. const directSnapshot = await getV4ConversationState();
  408. expect(directSnapshot.queueCount).toBe(0);
  409. const directPromptIndex = await waitForFirstRequestIndex(
  410. {
  411. includes: [
  412. "E2E_BACKGROUND_DIRECT_USER_PROMPT",
  413. "E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD",
  414. ],
  415. lastUserMessageIncludes: ["E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD"],
  416. },
  417. launchIndex,
  418. "background running 时用户普通消息没有立即进入 provider request",
  419. );
  420. expect(directPromptIndex).toBeGreaterThan(launchIndex);
  421. await waitForV4AssistantMessageContaining("background-direct-user-prompt-received-ok");
  422. await waitForIdle("background running 时用户普通消息响应后会话没有回到 idle");
  423. await waitForBackgroundTaskControlRow(
  424. "bash",
  425. "background direct user prompt bash sleep",
  426. "用户普通消息完成后 background Bash control row 不应消失",
  427. );
  428. await clickStopBackgroundTaskControlRow("bash", "background direct user prompt bash sleep");
  429. const notificationIndex = await waitForFirstRequestIndex(
  430. {
  431. includes: [
  432. "E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP",
  433. "<task-notification>",
  434. "<tool-use-id>toolu_e2e_background_direct_user_prompt_bash</tool-use-id>",
  435. "<status>killed</status>",
  436. ],
  437. lastUserMessageIncludes: ["<task-notification>"],
  438. },
  439. directPromptIndex,
  440. "background direct user prompt Bash stop notification 没有进入父模型请求",
  441. );
  442. expect(notificationIndex).toBeGreaterThan(directPromptIndex);
  443. await waitForV4AssistantMessageContaining("background-direct-user-prompt-bash-stopped-ok");
  444. await waitForNoBackgroundTaskControlRow(
  445. "bash",
  446. "background direct user prompt bash sleep",
  447. "被停止的 background direct user prompt Bash 仍显示为 running",
  448. );
  449. await waitForIdle("background direct user prompt Bash stop notification 后会话没有回到 idle");
  450. await assertNoVisibleTaskNotification();
  451. });
  452. it("background task running 且 main idle 时允许 compact,完成 notification 基于 compact 后上下文继续", async function () {
  453. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  454. await startNewBackgroundDraft();
  455. const prompt =
  456. "E2E_BACKGROUND_COMPACT_AFTER_IDLE: Start a background Bash, then stay idle while I compact the conversation.";
  457. const requestCountBefore = await getUpstreamRequestRecordCount();
  458. await sendV4PromptAndWaitAccepted(
  459. prompt,
  460. "E2E_BACKGROUND_COMPACT_AFTER_IDLE",
  461. "background compact setup prompt 没有被 composer 接受",
  462. );
  463. await waitForToolCallBlockByToolCallId("toolu_e2e_background_compact_after_idle_bash", 60000);
  464. await respondToBackgroundBlockers();
  465. const launchIndex = await waitForFirstRequestIndex(
  466. {
  467. includes: ["E2E_BACKGROUND_COMPACT_AFTER_IDLE", "Command running in background"],
  468. },
  469. requestCountBefore,
  470. "background compact Bash launch tool result 没有进入父模型请求",
  471. );
  472. await waitForV4AssistantMessageContaining("background-compact-launched-ok");
  473. await waitForIdle("background compact setup 后 main 没有回到 idle");
  474. await waitForBackgroundTaskControlRow(
  475. "bash",
  476. "background compact bash sleep",
  477. "background compact Bash 没有出现在统一 background control UI",
  478. );
  479. await sendV4Prompt("/compact");
  480. await waitForV4ComposerText("", "background running 时 /compact 发送后输入框没有清空");
  481. // Bug 根因:V4 compact row 会原位从 running 更新成 success,快速 replay 下
  482. // started 可能在 WDIO 首次轮询前就收口;completed 同样能证明命令已被 admission。
  483. const compactMarker = await waitForCompactMarkerStatuses(["started", "completed"], "manual");
  484. expect(compactMarker.inputId).toBeTruthy();
  485. if (compactMarker.status !== "completed") {
  486. await waitForCompactMarkerStatus("completed", "manual", compactMarker.inputId);
  487. }
  488. const notificationIndex = await waitForFirstRequestIndex(
  489. {
  490. includes: [
  491. "<task-notification>",
  492. "E2E_BACKGROUND_COMPACT_SUMMARY_MARKER",
  493. "toolu_e2e_background_compact_after_idle_bash",
  494. "<status>completed</status>",
  495. ],
  496. lastUserMessageIncludes: ["<task-notification>"],
  497. },
  498. launchIndex,
  499. "background compact 后 completion notification 没有基于 compact 摘要进入父模型请求",
  500. );
  501. expect(notificationIndex).toBeGreaterThan(launchIndex);
  502. await waitForV4AssistantMessageContaining("background-compact-notification-consumed-ok");
  503. await waitForIdle("background compact notification 后会话没有回到 idle");
  504. await assertNoVisibleTaskNotification();
  505. });
  506. it("foreground long-running Bash timeout 后会转为 background,并在完成后从 UI 移除", async function () {
  507. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  508. await startNewBackgroundDraft();
  509. const prompt =
  510. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH: Run an eligible foreground Bash command that should auto-background on timeout, then report after completion.";
  511. const requestCountBefore = await getUpstreamRequestRecordCount();
  512. await sendV4PromptAndWaitAccepted(
  513. prompt,
  514. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH",
  515. "foreground Bash auto-background prompt 没有被 composer 接受",
  516. );
  517. await waitForToolCallBlockByToolCallId("toolu_e2e_background_auto_timeout_bash", 60000);
  518. await respondToBackgroundBlockers();
  519. const launchIndex = await waitForFirstRequestIndex(
  520. {
  521. // 前台 Bash 超时转后台时,结果写明超时并给出后台任务 ID。
  522. includes: ["E2E_BACKGROUND_AUTO_TIMEOUT_BASH", "and was moved to the background (ID:"],
  523. },
  524. requestCountBefore,
  525. "foreground Bash timeout 后没有返回 backgrounded tool result",
  526. );
  527. await waitForBackgroundTaskControlRow(
  528. "bash",
  529. "auto timeout bash sleep",
  530. "auto-background Bash 没有出现在统一 background control UI",
  531. );
  532. const notificationIndex = await waitForFirstRequestIndex(
  533. {
  534. includes: [
  535. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH",
  536. "<task-notification>",
  537. "<tool-use-id>toolu_e2e_background_auto_timeout_bash</tool-use-id>",
  538. "<status>completed</status>",
  539. ],
  540. lastUserMessageIncludes: ["<task-notification>"],
  541. },
  542. launchIndex,
  543. "auto-background Bash completion notification 没有进入父模型请求",
  544. );
  545. expect(notificationIndex).toBeGreaterThan(launchIndex);
  546. await waitForV4AssistantMessageContaining("background-auto-timeout-bash-completed-ok");
  547. await waitForNoBackgroundTaskControlRow(
  548. "bash",
  549. "auto timeout bash sleep",
  550. "自然完成的 auto-background Bash 仍显示为 running",
  551. );
  552. await waitForIdle("auto-background Bash notification 后会话没有回到 idle");
  553. await assertNoVisibleTaskNotification();
  554. });
  555. it("explicit background Bash 越过 input timeout 后仍自然完成且只通知一次", async function () {
  556. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  557. await startNewBackgroundDraft();
  558. const prompt =
  559. "E2E_BG37_EXPLICIT_TIMEOUT: Start an explicit background Bash whose timeout is shorter than its runtime, then report after completion.";
  560. const requestCountBefore = await getUpstreamRequestRecordCount();
  561. await sendV4PromptAndWaitAccepted(
  562. prompt,
  563. "E2E_BG37_EXPLICIT_TIMEOUT",
  564. "BG37 prompt 没有被 composer 接受",
  565. );
  566. await waitForToolCallBlockByToolCallId("toolu_e2e_bg37_explicit_timeout", 60000);
  567. await respondToBackgroundBlockers();
  568. const launchIndex = await waitForFirstRequestIndex(
  569. {
  570. includes: ["E2E_BG37_EXPLICIT_TIMEOUT", "Command running in background"],
  571. },
  572. requestCountBefore,
  573. "BG37 explicit Bash 没有返回 background task ID",
  574. );
  575. const launchResult = await getLatestUpstreamToolResultByToolCallId(
  576. "toolu_e2e_bg37_explicit_timeout",
  577. );
  578. const outputPath = /Output is being written to: (.+?)\. You will be notified/u.exec(
  579. launchResult?.content ?? "",
  580. )?.[1];
  581. expect(outputPath).toBeTruthy();
  582. // 根因回归:后台 launch 成功不能代替实时落盘证据;在 DONE 之前读取同一路径。
  583. const runningOutput = await readFile(outputPath!, "utf8");
  584. expect(runningOutput).toContain("E2E_BG37_STARTED");
  585. expect(runningOutput).not.toContain("E2E_BG37_DONE");
  586. await waitForBackgroundTaskControlRow(
  587. "bash",
  588. "BG37 explicit timeout bash",
  589. "BG37 explicit Bash 没有出现在 background control UI",
  590. );
  591. await browser.pause(100);
  592. await waitForBackgroundTaskControlRow(
  593. "bash",
  594. "BG37 explicit timeout bash",
  595. "BG37 explicit Bash 越过 input timeout 后不应被终止",
  596. );
  597. const notificationIndex = await waitForFirstRequestIndex(
  598. {
  599. includes: [
  600. "E2E_BG37_EXPLICIT_TIMEOUT",
  601. "<task-notification>",
  602. "<tool-use-id>toolu_e2e_bg37_explicit_timeout</tool-use-id>",
  603. "<status>completed</status>",
  604. ],
  605. lastUserMessageIncludes: ["<task-notification>"],
  606. },
  607. launchIndex,
  608. "BG37 explicit Bash completion notification 没有进入父模型请求",
  609. );
  610. await waitForV4AssistantMessageContaining("bg37-explicit-timeout-completed-ok");
  611. expect(
  612. await countUpstreamRequests(
  613. {
  614. includes: [
  615. "<task-notification>",
  616. "<tool-use-id>toolu_e2e_bg37_explicit_timeout</tool-use-id>",
  617. ],
  618. },
  619. { afterIndex: launchIndex },
  620. ),
  621. ).toBe(1);
  622. expect(notificationIndex).toBeGreaterThan(launchIndex);
  623. await waitForNoBackgroundTaskControlRow(
  624. "bash",
  625. "BG37 explicit timeout bash",
  626. "BG37 completed Bash 仍显示为 running",
  627. );
  628. await waitForIdle("BG37 completion notification 后会话没有回到 idle");
  629. const completedOutput = await readFile(outputPath!, "utf8");
  630. expect(completedOutput).toContain("E2E_BG37_STARTED");
  631. expect(completedOutput).toContain("E2E_BG37_DONE");
  632. });
  633. it("explicit Bash commit 后停止 parent turn 不会终止后台进程", async function () {
  634. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  635. await rm(BG38_STARTED_FILE, { force: true }).catch(() => undefined);
  636. await startNewBackgroundDraft();
  637. const prompt =
  638. "E2E_BG38_PARENT_ABORT: Start an explicit background Bash, keep the parent turn running, and let me stop that turn after the task starts.";
  639. const requestCountBefore = await getUpstreamRequestRecordCount();
  640. await sendV4PromptAndWaitAccepted(
  641. prompt,
  642. "E2E_BG38_PARENT_ABORT",
  643. "BG38 prompt 没有被 composer 接受",
  644. );
  645. await waitForToolCallBlockByToolCallId("toolu_e2e_bg38_parent_abort", 60000);
  646. await respondToBackgroundBlockers();
  647. const launchIndex = await waitForFirstRequestIndex(
  648. {
  649. includes: ["E2E_BG38_PARENT_ABORT", "Command running in background"],
  650. },
  651. requestCountBefore,
  652. "BG38 explicit Bash 没有完成 background commit",
  653. );
  654. await waitForBackgroundTaskControlRow(
  655. "bash",
  656. "BG38 parent abort bash",
  657. "BG38 committed Bash 没有出现在 background control UI",
  658. );
  659. let startedMarker = "";
  660. await browser.waitUntil(
  661. async () => {
  662. startedMarker = await readFile(BG38_STARTED_FILE, "utf-8").catch(() => "");
  663. return startedMarker.includes("E2E_BG38_STARTED");
  664. },
  665. {
  666. timeout: 30000,
  667. timeoutMsg: `BG38 Bash 没有写出 started marker; latest=${startedMarker}`,
  668. },
  669. );
  670. await waitForMainLoading("BG38 parent turn 在 stop 前没有保持 running");
  671. await clickV4Stop();
  672. await waitForV4ConversationState(
  673. (snapshot) => snapshot.state !== "streaming",
  674. "BG38 parent turn stop 后没有退出 streaming",
  675. 30000,
  676. );
  677. await waitForBackgroundTaskControlRow(
  678. "bash",
  679. "BG38 parent abort bash",
  680. "BG38 parent turn stop 后后台 control row 不应消失",
  681. );
  682. const notificationIndex = await waitForFirstRequestIndex(
  683. {
  684. includes: [
  685. "E2E_BG38_PARENT_ABORT",
  686. "<task-notification>",
  687. "<tool-use-id>toolu_e2e_bg38_parent_abort</tool-use-id>",
  688. "<status>completed</status>",
  689. "E2E_BG38_DONE",
  690. ],
  691. lastUserMessageIncludes: ["<task-notification>"],
  692. },
  693. launchIndex,
  694. "BG38 parent abort 后 Bash 没有自然完成",
  695. );
  696. await waitForV4AssistantMessageContaining("bg38-parent-abort-background-completed-ok");
  697. expect(
  698. await countUpstreamRequests(
  699. {
  700. includes: [
  701. "<task-notification>",
  702. "<tool-use-id>toolu_e2e_bg38_parent_abort</tool-use-id>",
  703. ],
  704. },
  705. { afterIndex: launchIndex },
  706. ),
  707. ).toBe(1);
  708. expect(notificationIndex).toBeGreaterThan(launchIndex);
  709. await waitForNoBackgroundTaskControlRow(
  710. "bash",
  711. "BG38 parent abort bash",
  712. "BG38 completed Bash 留下 orphan control row",
  713. );
  714. await waitForIdle("BG38 completion notification 后会话没有回到 idle");
  715. });
  716. it("首 token 为 sleep 的 foreground Bash timeout 后不会转 background", async function () {
  717. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  718. await startNewBackgroundDraft();
  719. const prompt =
  720. "E2E_BG39_SLEEP_HARD_TIMEOUT: Run a foreground Bash whose first raw token is sleep with a timeout shorter than its runtime.";
  721. const requestCountBefore = await getUpstreamRequestRecordCount();
  722. await sendV4PromptAndWaitAccepted(
  723. prompt,
  724. "E2E_BG39_SLEEP_HARD_TIMEOUT",
  725. "BG39 prompt 没有被 composer 接受",
  726. );
  727. await waitForToolCallBlockByToolCallId("toolu_e2e_bg39_sleep_timeout", 60000);
  728. await respondToBackgroundBlockers();
  729. const completionIndex = await waitForFirstRequestIndex(
  730. {
  731. includes: [
  732. "E2E_BG39_SLEEP_HARD_TIMEOUT",
  733. "<error>Command was aborted before completion</error>",
  734. ],
  735. excludes: ["Command running in background"],
  736. },
  737. requestCountBefore,
  738. "BG39 sleep Bash 没有返回 foreground timeout 结果",
  739. );
  740. await waitForV4AssistantMessageContaining("bg39-sleep-hard-timeout-ok");
  741. await browser.pause(500);
  742. expect(
  743. await countUpstreamRequests(
  744. {
  745. includes: [
  746. "<task-notification>",
  747. "<tool-use-id>toolu_e2e_bg39_sleep_timeout</tool-use-id>",
  748. ],
  749. },
  750. { afterIndex: completionIndex },
  751. ),
  752. ).toBe(0);
  753. await waitForNoBackgroundTaskControlRow(
  754. "bash",
  755. "BG39 sleep hard timeout",
  756. "BG39 sleep Bash 不应生成 background control row",
  757. );
  758. await waitForIdle("BG39 foreground timeout 后会话没有回到 idle");
  759. });
  760. it("普通 foreground 长 Bash running 过程中仍显示底部 loading", async function () {
  761. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  762. await rm(BG14_PREVIEW_RELEASE_FILE, { force: true });
  763. await startNewBackgroundDraft();
  764. const prompt =
  765. "E2E_FOREGROUND_LONG_BASH_LOADING: Run a normal foreground Bash command long enough to show loading, then report after completion.";
  766. const requestCountBefore = await getUpstreamRequestRecordCount();
  767. await sendV4PromptAndWaitAccepted(
  768. prompt,
  769. "E2E_FOREGROUND_LONG_BASH_LOADING",
  770. "foreground long Bash loading prompt 没有被 composer 接受",
  771. );
  772. await waitForToolCallBlockByToolCallId("toolu_e2e_foreground_long_bash_loading", 60000);
  773. await respondToBackgroundBlockers();
  774. await waitForMainLoading("普通 foreground 长 Bash running 时应显示底部 loading");
  775. try {
  776. const trigger = await $(
  777. '[data-testid="tool-summary-trigger-toolu_e2e_foreground_long_bash_loading"]',
  778. );
  779. if ((await trigger.getAttribute("aria-expanded")) === "true") await trigger.click();
  780. await browser.waitUntil(
  781. async () => !(await $('[data-testid^="bash-output-preview-"]').isExisting()),
  782. { timeout: 5000, timeoutMsg: "收起的 Bash 不应渲染运行输出" },
  783. );
  784. await trigger.click();
  785. await browser.waitUntil(
  786. async () => {
  787. const preview = await $('[data-testid="bash-output-preview-full"]');
  788. return (
  789. (await preview.isDisplayed()) && (await preview.getText()).includes("progress-line-30")
  790. );
  791. },
  792. { timeout: 10000, timeoutMsg: "Bash 展开预览未显示长文本" },
  793. );
  794. const full = await $('[data-testid="bash-output-preview-full"]');
  795. expect(await full.getText()).toContain("progress-line-30");
  796. expect(await full.getText()).toContain("progress-line-120");
  797. // 共享 renderer 保持预览换行,长输出不能使用单行截断样式。
  798. expect(
  799. await browser.execute(() => {
  800. const node = document.querySelector('[data-testid="bash-output-preview-full"]');
  801. return node instanceof HTMLElement && getComputedStyle(node).whiteSpace === "pre-wrap";
  802. }),
  803. ).toBe(true);
  804. } finally {
  805. await writeFile(BG14_PREVIEW_RELEASE_FILE, "release");
  806. }
  807. const completionIndex = await waitForFirstRequestIndex(
  808. {
  809. includes: ["E2E_FOREGROUND_LONG_BASH_LOADING", "<persisted-output>"],
  810. },
  811. requestCountBefore,
  812. "foreground long Bash 完成后的 tool result 没有进入父模型请求",
  813. );
  814. expect(completionIndex).toBeGreaterThan(requestCountBefore);
  815. await waitForV4AssistantMessageContaining("foreground-long-bash-loading-completed-ok");
  816. await waitForIdle("foreground long Bash 完成后会话没有回到 idle");
  817. expect(await $('[data-testid="bash-output-preview-full"]').isExisting()).toBe(false);
  818. // turn 完成后工具进入已折叠的 assistant history;先按产品入口重新展开历史。
  819. await waitForToolCallBlockByToolCallId("toolu_e2e_foreground_long_bash_loading");
  820. const resultTrigger = await $(
  821. '[data-testid="tool-summary-trigger-toolu_e2e_foreground_long_bash_loading"]',
  822. );
  823. if ((await resultTrigger.getAttribute("aria-expanded")) !== "true") await resultTrigger.click();
  824. // 历史展开动画会先挂载节点再显示正文,等待实际输出,前台不再展示文件入口。
  825. const result = await $('[data-testid="bash-result-output"]');
  826. await browser.waitUntil(
  827. async () =>
  828. (await result.isDisplayed()) && (await result.getText()).includes("progress-line-1"),
  829. { timeout: 10000, timeoutMsg: "Bash 终态头部正文未显示" },
  830. );
  831. expect(await $('[data-testid="bash-output-notice"]').isExisting()).toBe(false);
  832. expect(await $('[data-testid="bash-output-file"]').isExisting()).toBe(false);
  833. expect(await result.getText()).not.toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  834. expect(await result.getText()).not.toContain("<persisted-output>");
  835. // provider 保持原有小摘要和完整文件契约,Desktop 仅显示 Bash 的头部正文。
  836. const modelResult = await getLatestUpstreamToolResultByToolCallId(
  837. "toolu_e2e_foreground_long_bash_loading",
  838. );
  839. expect(modelResult?.content).toContain("<persisted-output>");
  840. expect(modelResult?.content).not.toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  841. const outputPath = modelResult?.content.match(/Full output saved to: ([^\n]+)/)?.[1];
  842. if (!outputPath) throw new Error("Bash provider result is missing the retained output path");
  843. const output = await readFile(outputPath, "utf8");
  844. expect(Buffer.byteLength(output)).toBeGreaterThan(30000);
  845. expect(output).toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  846. });
  847. it("background Bash 可以从统一 background control UI 停止", async function () {
  848. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  849. await startNewBackgroundDraft();
  850. const prompt =
  851. "E2E_BACKGROUND_CANCEL_BASH: Start a long background Bash command, wait for it to be stopped, then report the stop notification.";
  852. const requestCountBefore = await getUpstreamRequestRecordCount();
  853. await sendV4PromptAndWaitAccepted(
  854. prompt,
  855. "E2E_BACKGROUND_CANCEL_BASH",
  856. "background Bash cancel prompt 没有被 composer 接受",
  857. );
  858. await waitForToolCallBlockByToolCallId("toolu_e2e_background_cancel_bash", 60000);
  859. await respondToBackgroundBlockers();
  860. const launchIndex = await waitForFirstRequestIndex(
  861. {
  862. includes: ["E2E_BACKGROUND_CANCEL_BASH", "Command running in background"],
  863. },
  864. requestCountBefore,
  865. "background Bash cancel launch tool result 没有进入父模型请求",
  866. );
  867. await openV4ComposerRunningBackgroundWorks();
  868. await waitForBackgroundTaskControlRow(
  869. "bash",
  870. "background cancel bash process tree",
  871. "background Bash 没有出现在统一 background control UI",
  872. );
  873. const [launcherPid, workerPid] = await Promise.all([
  874. waitForRunningPidFile(BG08_LAUNCHER_PID_FILE, "BG08 launcher"),
  875. waitForRunningPidFile(BG08_WORKER_PID_FILE, "BG08 worker"),
  876. ]);
  877. let rootPid: number | null = null;
  878. if (process.platform !== "win32") {
  879. rootPid = await waitForRunningPidFile(BG08_ROOT_PID_FILE, "BG08 root Bash");
  880. const [rootProcessGroupId, launcherProcessGroupId, workerProcessGroupId] = await Promise.all([
  881. readPosixProcessGroupId(rootPid),
  882. readPosixProcessGroupId(launcherPid),
  883. readPosixProcessGroupId(workerPid),
  884. ]);
  885. // Bug 根因:Bash job control 会把 launcher/worker 放入根 shell 之外的 PGID;
  886. // 这里只验证真实构造成功,避免普通同组进程让杀树回归得到假阳性。
  887. expect(launcherProcessGroupId).not.toBe(rootProcessGroupId);
  888. expect(workerProcessGroupId).toBe(launcherProcessGroupId);
  889. }
  890. await clickStopBackgroundTaskControlRow("bash", "background cancel bash process tree");
  891. await waitForV4AssistantMessageContaining("background-cancel-bash-launched-ok");
  892. const notificationIndex = await waitForFirstRequestIndex(
  893. {
  894. includes: [
  895. "E2E_BACKGROUND_CANCEL_BASH",
  896. "<task-notification>",
  897. "<tool-use-id>toolu_e2e_background_cancel_bash</tool-use-id>",
  898. "<status>killed</status>",
  899. ],
  900. lastUserMessageIncludes: ["<task-notification>"],
  901. },
  902. launchIndex,
  903. "background Bash stop notification 没有进入父模型请求",
  904. );
  905. expect(notificationIndex).toBeGreaterThan(launchIndex);
  906. await waitForV4AssistantMessageContaining("background-cancel-bash-stopped-ok");
  907. await waitForNoBackgroundTaskControlRow(
  908. "bash",
  909. "background cancel bash process tree",
  910. "被停止的 background Bash 仍显示为 running",
  911. );
  912. await Promise.all([
  913. rootPid === null ? Promise.resolve() : waitForProcessExit(rootPid, "BG08 root Bash"),
  914. waitForProcessExit(launcherPid, "BG08 launcher"),
  915. waitForProcessExit(workerPid, "BG08 worker"),
  916. ]);
  917. await waitForIdle("background Bash stop notification 后会话没有回到 idle");
  918. await assertNoVisibleTaskNotification();
  919. });
  920. it("background Agent 可以从统一 background control UI 停止", async function () {
  921. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  922. await startNewBackgroundDraft();
  923. const prompt =
  924. "E2E_BACKGROUND_CANCEL_AGENT: Start a long background Agent and stop it from the background control UI.";
  925. const requestCountBefore = await getUpstreamRequestRecordCount();
  926. await sendV4PromptAndWaitAccepted(
  927. prompt,
  928. "E2E_BACKGROUND_CANCEL_AGENT",
  929. "background Agent cancel prompt 没有被 composer 接受",
  930. );
  931. await waitForToolCallBlockByToolCallId("toolu_e2e_background_cancel_agent", 60000);
  932. await respondToBackgroundBlockers();
  933. const launchIndex = await waitForFirstRequestIndex(
  934. {
  935. includes: ["E2E_BACKGROUND_CANCEL_AGENT", "Async agent launched successfully"],
  936. },
  937. requestCountBefore,
  938. "background Agent cancel launch tool result 没有进入父模型请求",
  939. );
  940. await waitForBackgroundTaskControlRow(
  941. "agent",
  942. "E2E background cancel agent",
  943. "background Agent 没有出现在统一 background control UI",
  944. );
  945. await clickStopBackgroundTaskControlRow("agent", "E2E background cancel agent");
  946. await waitForV4AssistantMessageContaining("background-cancel-agent-launched-ok");
  947. const notificationIndex = await waitForFirstRequestIndex(
  948. {
  949. includes: [
  950. "E2E_BACKGROUND_CANCEL_AGENT",
  951. "<task-notification>",
  952. "<tool-use-id>toolu_e2e_background_cancel_agent</tool-use-id>",
  953. // 停止状态词是 killed,summary 写明是用户停止的。
  954. "<status>killed</status>",
  955. "was stopped by user</summary>",
  956. ],
  957. lastUserMessageIncludes: ["<task-notification>"],
  958. },
  959. launchIndex,
  960. "background Agent stop notification 没有进入父模型请求",
  961. );
  962. expect(notificationIndex).toBeGreaterThan(launchIndex);
  963. await waitForV4AssistantMessageContaining("background-cancel-agent-stopped-ok");
  964. await waitForNoBackgroundTaskControlRow(
  965. "agent",
  966. "E2E background cancel agent",
  967. "被停止的 background Agent 仍显示为 running",
  968. );
  969. await waitForIdle("background Agent stop notification 后会话没有回到 idle");
  970. await assertNoVisibleTaskNotification();
  971. });
  972. it("TaskStop tool 停止 background Agent 时复用同一 notification 链路", async function () {
  973. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  974. await startNewBackgroundDraft();
  975. const prompt =
  976. "E2E_BACKGROUND_TASKSTOP_AGENT: Start a background Agent, then use TaskStop on its task id and report after the stop notification.";
  977. const requestCountBefore = await getUpstreamRequestRecordCount();
  978. await sendV4PromptAndWaitAccepted(
  979. prompt,
  980. "E2E_BACKGROUND_TASKSTOP_AGENT",
  981. "TaskStop background Agent prompt 没有被 composer 接受",
  982. );
  983. await waitForToolCallBlockByToolCallId("toolu_e2e_background_taskstop_agent", 60000);
  984. await respondToBackgroundBlockers();
  985. const taskStopIndex = await waitForFirstRequestIndex(
  986. {
  987. includes: [
  988. "E2E_BACKGROUND_TASKSTOP_AGENT",
  989. "Async agent launched successfully",
  990. "agentId: agent_",
  991. "TaskStop",
  992. ],
  993. },
  994. requestCountBefore,
  995. "background Agent launch 后父模型没有调用 TaskStop",
  996. );
  997. const notificationIndex = await waitForFirstRequestIndex(
  998. {
  999. includes: [
  1000. "E2E_BACKGROUND_TASKSTOP_AGENT",
  1001. "Successfully stopped task:",
  1002. "<task-notification>",
  1003. "<tool-use-id>toolu_e2e_background_taskstop_agent</tool-use-id>",
  1004. // 模型用 TaskStop 停止:summary 写明是 ZCode 停止的。
  1005. "<status>killed</status>",
  1006. "was stopped by ZCode</summary>",
  1007. ],
  1008. lastUserMessageIncludes: ["<task-notification>"],
  1009. },
  1010. taskStopIndex,
  1011. "TaskStop 后 background Agent stop notification 没有进入父模型请求",
  1012. );
  1013. expect(notificationIndex).toBeGreaterThan(taskStopIndex);
  1014. await waitForV4AssistantMessageContaining("background-taskstop-agent-stopped-ok");
  1015. await waitForIdle("TaskStop background Agent notification 后会话没有回到 idle");
  1016. await assertNoVisibleTaskNotification();
  1017. });
  1018. it("background notification 会在 active tool-loop 下一轮模型请求前合流", async function () {
  1019. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1020. await startNewBackgroundDraft();
  1021. const prompt =
  1022. "E2E_BACKGROUND_ACTIVE_LOOP_BASH: Start a quick background Bash and keep the tool loop active until it can report completion.";
  1023. const requestCountBefore = await getUpstreamRequestRecordCount();
  1024. await sendV4PromptAndWaitAccepted(
  1025. prompt,
  1026. "E2E_BACKGROUND_ACTIVE_LOOP_BASH",
  1027. "active-loop background Bash prompt 没有被 composer 接受",
  1028. );
  1029. await waitForToolCallBlockByToolCallId("toolu_e2e_background_active_loop_bash_bg", 60000);
  1030. await waitForToolCallBlockByToolCallId("toolu_e2e_background_active_loop_bash_wait", 60000);
  1031. await respondToBackgroundBlockers();
  1032. await respondToBackgroundBlockers();
  1033. const activeLoopIndex = await waitForFirstRequestIndex(
  1034. {
  1035. includes: [
  1036. "E2E_BACKGROUND_ACTIVE_LOOP_BASH",
  1037. "E2E_BACKGROUND_ACTIVE_LOOP_WAIT_DONE",
  1038. "<task-notification>",
  1039. "<tool-use-id>toolu_e2e_background_active_loop_bash_bg</tool-use-id>",
  1040. "<status>completed</status>",
  1041. ],
  1042. lastUserMessageIncludes: ["<task-notification>"],
  1043. },
  1044. requestCountBefore,
  1045. "active-loop 后续模型请求没有同时包含 Bash tool result 和 task-notification",
  1046. );
  1047. expect(activeLoopIndex).toBeGreaterThan(requestCountBefore);
  1048. expect(
  1049. await countUpstreamRequests(
  1050. {
  1051. includes: ["E2E_BACKGROUND_ACTIVE_LOOP_BASH", "toolu_e2e_background_active_loop_bash_bg"],
  1052. lastUserMessageExcludes: ["<task-notification>"],
  1053. },
  1054. { afterIndex: requestCountBefore },
  1055. ),
  1056. ).toBe(0);
  1057. expect(
  1058. await countUpstreamRequests(
  1059. {
  1060. includes: [
  1061. "<task-notification>",
  1062. "<tool-use-id>toolu_e2e_background_active_loop_bash_bg</tool-use-id>",
  1063. ],
  1064. lastUserMessageIncludes: ["<task-notification>"],
  1065. },
  1066. { afterIndex: requestCountBefore },
  1067. ),
  1068. ).toBe(1);
  1069. await waitForV4AssistantMessageContaining("background-active-loop-notification-consumed-ok");
  1070. await waitForIdle("active-loop background notification 后会话没有回到 idle");
  1071. await assertNoVisibleTaskNotification();
  1072. });
  1073. it("goal verifier 会等 background notification 被消费后再验证", async function () {
  1074. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1075. await startNewBackgroundDraft();
  1076. const goal =
  1077. '/goal E2E_BACKGROUND_GOAL: Finish only after consuming the background agent result and then reply with "upstream-e2e-ok".';
  1078. const requestCountBefore = await getUpstreamRequestRecordCount();
  1079. await sendV4Prompt(goal);
  1080. await waitForV4ComposerText("", "background goal /goal 发送后输入框没有清空");
  1081. await waitForV4UserMessageContaining("E2E_BACKGROUND_GOAL");
  1082. await waitForToolCallBlockByToolName("Agent", 60000);
  1083. await respondToBackgroundBlockers();
  1084. const notificationIndex = await waitForFirstRequestIndex(
  1085. {
  1086. includes: ["<task-notification>", "E2E_BACKGROUND_GOAL_CHILD_RESULT"],
  1087. },
  1088. requestCountBefore,
  1089. "goal background Agent completion notification 没有进入父模型请求",
  1090. );
  1091. await waitForV4AssistantMessageContaining("E2E_BACKGROUND_GOAL_NOTIFICATION_CONSUMED");
  1092. const verifierIndex = await waitForFirstRequestIndex(
  1093. {
  1094. includes: ["E2E_BACKGROUND_GOAL", "Verify whether the active session goal"],
  1095. },
  1096. notificationIndex,
  1097. "background notification 后没有触发 goal verifier",
  1098. );
  1099. expect(verifierIndex).toBeGreaterThan(notificationIndex);
  1100. expect(
  1101. await countUpstreamRequests(
  1102. {
  1103. includes: ["E2E_BACKGROUND_GOAL", "Verify whether the active session goal"],
  1104. },
  1105. { beforeIndex: notificationIndex },
  1106. ),
  1107. ).toBe(0);
  1108. await waitForV4ConversationState(
  1109. // Bug 根因:旧聊天根节点把已验证目标投影为 complete,V4 状态面板使用
  1110. // verified 表达同一终态;转正用例必须兼容两套展示契约。
  1111. (snapshot) => snapshot.targetStatus === "complete" || snapshot.targetStatus === "verified",
  1112. "background goal verifier 没有把 target 标记为 complete/verified",
  1113. 90000,
  1114. );
  1115. await assertNoVisibleTaskNotification();
  1116. });
  1117. it("running background Agent 可以通过 SendMessage 收到 steer 消息", async function () {
  1118. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1119. await startNewBackgroundDraft();
  1120. const prompt =
  1121. "E2E_BACKGROUND_SEND_MESSAGE: Launch a background agent, then send it a coordinator message while it is still running.";
  1122. const requestCountBefore = await getUpstreamRequestRecordCount();
  1123. await sendV4Prompt(prompt);
  1124. await waitForV4ComposerText("", "background SendMessage prompt 发送后输入框没有清空");
  1125. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_MESSAGE");
  1126. await waitForToolCallBlockByToolName("Agent", 60000);
  1127. await respondToBackgroundBlockers();
  1128. // child prompt 不写出 payload:child 只收到 message,payload 在 child 请求里只能出现一次。
  1129. const sendMessageIndex = await waitForFirstRequestIndex(
  1130. {
  1131. includes: [
  1132. "E2E_BACKGROUND_SEND_MESSAGE",
  1133. "Async agent launched successfully",
  1134. "agentId: agent_",
  1135. ],
  1136. excludes: ["sent to its active turn"],
  1137. },
  1138. requestCountBefore,
  1139. "background Agent launch 后父模型没有调用 SendMessage",
  1140. );
  1141. const sendMessageResultIndex = await waitForFirstRequestIndex(
  1142. {
  1143. includes: [
  1144. "E2E_BACKGROUND_SEND_MESSAGE",
  1145. "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1146. "sent to its active turn",
  1147. ],
  1148. },
  1149. sendMessageIndex,
  1150. "background Agent SendMessage tool result 没有进入父模型请求",
  1151. );
  1152. const coordinatorQuery = {
  1153. includes: ["E2E_BACKGROUND_SEND_MESSAGE_CHILD_BASH_DONE"],
  1154. lastUserMessageIncludes: [
  1155. "The coordinator sent a message while you were working:",
  1156. "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1157. ],
  1158. };
  1159. // 验收真实 wire;旧 debug 文件同时检查请求和响应且依赖 retention,不是稳定的 provider 合同。
  1160. await waitForFirstRequestIndex(
  1161. coordinatorQuery,
  1162. requestCountBefore - 1,
  1163. "running child 没有收到 coordinator 提示",
  1164. );
  1165. const coordinatorEvidence = await getUpstreamRequestEvidence(coordinatorQuery, {
  1166. afterIndex: requestCountBefore - 1,
  1167. });
  1168. await assertIncomingMessage(coordinatorEvidence[0]!.requestJson, {
  1169. presentation: "coordinator_steer",
  1170. marker: "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1171. role: "user",
  1172. // summary 只用于 UI 预览,child 只收到 message。
  1173. body: "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1174. });
  1175. const notificationIndex = await waitForFirstRequestIndex(
  1176. {
  1177. includes: ["<task-notification>", "E2E_BACKGROUND_SEND_MESSAGE_CHILD_RECEIVED"],
  1178. },
  1179. sendMessageResultIndex,
  1180. "SendMessage 后 background Agent completion notification 没有进入父模型请求",
  1181. );
  1182. expect(sendMessageIndex).toBeGreaterThan(requestCountBefore);
  1183. expect(sendMessageResultIndex).toBeGreaterThan(sendMessageIndex);
  1184. expect(notificationIndex).toBeGreaterThan(sendMessageResultIndex);
  1185. await waitForIdle("background SendMessage notification 后会话没有回到 idle");
  1186. await assertNoVisibleTaskNotification();
  1187. });
  1188. it("foreground subagent 运行 child tool 时 main 仍会显示底部 loading", async function () {
  1189. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1190. await startNewBackgroundDraft();
  1191. const capture = await beginBackgroundTelemetryCapture();
  1192. const prompt =
  1193. "E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS: Launch a foreground agent that runs a visible child Bash tool while the parent conversation is still running.";
  1194. const requestCountBefore = await getUpstreamRequestRecordCount();
  1195. await sendV4Prompt(prompt);
  1196. await waitForV4ComposerText("", "foreground child tool streaming prompt 发送后输入框没有清空");
  1197. await waitForV4UserMessageContaining("E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS");
  1198. await waitForToolCallBlockByToolCallId("toolu_e2e_foreground_child_tool_agent", 60000);
  1199. await respondToBackgroundBlockers();
  1200. // Bug 根因:V4 明确把 child tool history 留在 child conversation topic,
  1201. // 父 timeline 只保留 Agent 事实;main loading 应由前台父 Agent 生命周期维持。
  1202. await waitForMainLoading("foreground subagent 运行 child tool 时应保持 main 底部 loading");
  1203. await assertNoMainToolCallById(
  1204. "toolu_e2e_foreground_child_tool_bash",
  1205. "foreground child Bash 不应被镜像成 main timeline tool row",
  1206. );
  1207. const completionIndex = await waitForFirstRequestIndex(
  1208. {
  1209. includes: [
  1210. "E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS",
  1211. "E2E_FOREGROUND_AGENT_CHILD_TOOL_DONE",
  1212. ],
  1213. },
  1214. requestCountBefore,
  1215. "foreground child tool Agent completion 没有进入父模型请求",
  1216. );
  1217. expect(completionIndex).toBeGreaterThan(requestCountBefore);
  1218. await waitForV4AssistantMessageContaining("foreground-agent-child-tool-streaming-completed-ok");
  1219. await waitForIdle("foreground child tool Agent completion 后会话没有回到 idle");
  1220. const reports = await waitForConversationReportDelta(capture, {
  1221. agent_step: 1,
  1222. message_completion: 1,
  1223. });
  1224. assertMainCompletionAgentCompositions(reports, ["main_plus_fg"]);
  1225. assertMainCompletionMessageSources(reports, ["chat"]);
  1226. });
  1227. it("同一 main turn 同时消费 foreground 和 background subagent 结果", async function () {
  1228. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1229. await startNewBackgroundDraft();
  1230. await rm(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, { force: true });
  1231. const capture = await beginBackgroundTelemetryCapture();
  1232. const prompt =
  1233. "E2E_AGENT_COMPOSITION_MIXED: Launch one foreground Agent and one background Agent, then summarize both results.";
  1234. const requestCountBefore = await getUpstreamRequestRecordCount();
  1235. try {
  1236. await sendV4Prompt(prompt);
  1237. await waitForV4ComposerText("", "mixed agent composition prompt 发送后输入框没有清空");
  1238. await waitForV4UserMessageContaining("E2E_AGENT_COMPOSITION_MIXED");
  1239. await waitForToolCallBlockByToolCallId("toolu_e2e_composition_mixed_foreground", 60000);
  1240. await waitForToolCallBlockByToolCallId("toolu_e2e_composition_mixed_background", 60000);
  1241. await browser.waitUntil(
  1242. async () => {
  1243. const evidence = await getUpstreamRequestEvidence(
  1244. {
  1245. lastUserMessageIncludes: ["E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_CHILD"],
  1246. },
  1247. { afterIndex: requestCountBefore },
  1248. );
  1249. return evidence.some(
  1250. (record) =>
  1251. record.fixtureId === "upstream-agent-composition-mixed-foreground-child" &&
  1252. record.status === "complete",
  1253. );
  1254. },
  1255. {
  1256. timeout: 45000,
  1257. timeoutMsg: "mixed agent composition foreground child 没有进入 Bash barrier",
  1258. },
  1259. );
  1260. await respondToBackgroundBlockers();
  1261. await browser.waitUntil(
  1262. async () => {
  1263. const evidence = await getUpstreamRequestEvidence(
  1264. {
  1265. lastUserMessageIncludes: ["E2E_AGENT_COMPOSITION_MIXED_BACKGROUND_CHILD"],
  1266. },
  1267. { afterIndex: requestCountBefore },
  1268. );
  1269. return evidence.some(
  1270. (record) =>
  1271. record.fixtureId === "upstream-agent-composition-mixed-background-child" &&
  1272. record.status === "complete",
  1273. );
  1274. },
  1275. {
  1276. timeout: 45000,
  1277. timeoutMsg: "mixed agent composition background child 没有完成 provider response",
  1278. },
  1279. );
  1280. await writeFile(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, "release\n", "utf-8");
  1281. const mixedRequestIndex = await waitForFirstRequestIndex(
  1282. {
  1283. includes: [
  1284. "E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_DONE",
  1285. "E2E_AGENT_COMPOSITION_MIXED_BACKGROUND_DONE",
  1286. "<task-notification>",
  1287. ],
  1288. lastUserMessageIncludes: [
  1289. "<task-notification>",
  1290. "E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_DONE",
  1291. ],
  1292. },
  1293. requestCountBefore,
  1294. "mixed agent composition 没有在同一 main request 消费 foreground 和 background 结果",
  1295. );
  1296. expect(mixedRequestIndex).toBeGreaterThan(requestCountBefore);
  1297. await waitForV4AssistantMessageContaining("agent-composition-mixed-completed-ok");
  1298. await waitForIdle("mixed agent composition 收口后会话没有回到 idle");
  1299. const reports = await waitForConversationReportDelta(capture, {
  1300. agent_step: 1,
  1301. message_completion: 1,
  1302. });
  1303. assertMainCompletionAgentCompositions(reports, ["main_plus_fg_bg"]);
  1304. assertMainCompletionMessageSources(reports, ["chat"]);
  1305. } finally {
  1306. await writeFile(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, "release\n", "utf-8").catch(
  1307. () => undefined,
  1308. );
  1309. }
  1310. });
  1311. it("background subagent 的 child tool 只留在 child conversation,idle main 不显示底部 loading", async function () {
  1312. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1313. await startNewBackgroundDraft();
  1314. const capture = await beginBackgroundTelemetryCapture();
  1315. await rm(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, { force: true });
  1316. const prompt =
  1317. "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS: Launch a background agent that runs a visible child Bash tool while the parent conversation is idle.";
  1318. const requestCountBefore = await getUpstreamRequestRecordCount();
  1319. await sendV4Prompt(prompt);
  1320. await waitForV4ComposerText("", "background child tool idle prompt 发送后输入框没有清空");
  1321. await waitForV4UserMessageContaining("E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS");
  1322. await waitForToolCallBlockByToolCallId("toolu_e2e_background_idle_child_tool_agent", 60000);
  1323. await respondToBackgroundBlockers();
  1324. const launchIndex = await waitForFirstRequestIndex(
  1325. {
  1326. includes: [
  1327. "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS",
  1328. "Async agent launched successfully",
  1329. ],
  1330. },
  1331. requestCountBefore,
  1332. "background child tool idle Agent launch tool result 没有进入父模型请求",
  1333. );
  1334. await waitForV4AssistantMessageContaining("background-agent-child-tool-idle-launched-ok");
  1335. await waitForIdle("background child tool idle launch 后父会话没有先回到 idle");
  1336. await waitForBackgroundTaskControlRow(
  1337. "agent",
  1338. "E2E background child tool idle",
  1339. "background child tool idle Agent 没有出现在统一 background control UI",
  1340. );
  1341. await assertNoMainToolCallById(
  1342. "toolu_e2e_background_idle_child_tool_bash",
  1343. "background child Bash 不应被镜像成 main timeline tool row",
  1344. );
  1345. await assertNoMainFakeLoading(
  1346. "background subagent child tool update 不应让 idle main 显示底部 loading",
  1347. );
  1348. await writeFile(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, "release\n", "utf-8");
  1349. const notificationIndex = await waitForFirstRequestIndex(
  1350. {
  1351. includes: ["<task-notification>", "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_DONE"],
  1352. lastUserMessageIncludes: ["<task-notification>"],
  1353. },
  1354. launchIndex,
  1355. "background child tool idle Agent completion notification 没有进入父模型请求",
  1356. );
  1357. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1358. await waitForV4AssistantMessageContaining(
  1359. "background-agent-child-tool-idle-notification-consumed-ok",
  1360. );
  1361. await waitForIdle("background child tool idle notification 后会话没有回到 idle");
  1362. const { eventReport: reports } = await checkpointConversationTelemetryCase(capture, {
  1363. caseId: "BG13-token-identity",
  1364. minimumReportInventory: { agent_step: 1, message_completion: 2 },
  1365. minimumArmsInventory: {},
  1366. proof: ["child Bash + Agent usage owner", "new UUID v7 wake message"],
  1367. });
  1368. assertBackgroundToolStepTelemetry(reports, "toolu_e2e_background_idle_child_tool_bash");
  1369. assertMainCompletionAgentCompositions(reports, ["main_only", "main_plus_bg"]);
  1370. assertMainCompletionMessageSources(reports, ["chat", "background_subagent"]);
  1371. await assertNoVisibleTaskNotification();
  1372. });
  1373. it("background subagent 的 child tool 不污染后续主回复且原 Agent 控制身份稳定", async function () {
  1374. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1375. await startNewBackgroundDraft();
  1376. const capture = await beginBackgroundTelemetryCapture();
  1377. const prompt =
  1378. "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR: Launch a background agent whose child tool update arrives after my next main prompt has completed.";
  1379. const followUpPrompt =
  1380. "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP: This main prompt should complete before the background child Bash update arrives.";
  1381. const requestCountBefore = await getUpstreamRequestRecordCount();
  1382. await rm(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, { force: true });
  1383. await sendV4Prompt(prompt);
  1384. await waitForV4ComposerText("", "background parent anchor prompt 发送后输入框没有清空");
  1385. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR");
  1386. await waitForToolCallBlockByToolCallId("toolu_e2e_background_parent_anchor_agent", 60000);
  1387. await respondToBackgroundBlockers();
  1388. const launchIndex = await waitForFirstRequestIndex(
  1389. {
  1390. includes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR", "Async agent launched successfully"],
  1391. },
  1392. requestCountBefore,
  1393. "background parent anchor Agent launch tool result 没有进入父模型请求",
  1394. );
  1395. await waitForV4AssistantMessageContaining("background-child-tool-parent-anchor-launched-ok");
  1396. await waitForIdle("background parent anchor launch 后父会话没有先回到 idle");
  1397. await waitForBackgroundTaskControlRow(
  1398. "agent",
  1399. "E2E background child tool parent anchor",
  1400. "background parent anchor Agent 没有出现在统一 background control UI",
  1401. );
  1402. await sendV4Prompt(followUpPrompt);
  1403. await waitForV4ComposerText("", "background parent anchor follow-up 发送后输入框没有清空");
  1404. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP");
  1405. const followUpIndex = await waitForFirstRequestIndex(
  1406. {
  1407. includes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP"],
  1408. lastUserMessageIncludes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP"],
  1409. },
  1410. launchIndex,
  1411. "background parent anchor follow-up 没有立即进入 provider request",
  1412. );
  1413. expect(followUpIndex).toBeGreaterThan(launchIndex);
  1414. await waitForV4AssistantMessageContaining(
  1415. "background-child-tool-parent-anchor-main-followup-ok",
  1416. );
  1417. await waitForBackgroundTaskControlRow(
  1418. "agent",
  1419. "E2E background child tool parent anchor",
  1420. "background child tool 到达后原 Agent 控制身份没有保持",
  1421. );
  1422. await assertNoMainToolCallById(
  1423. "toolu_e2e_background_parent_anchor_child_bash",
  1424. "background child Bash 不应污染后续 main timeline",
  1425. );
  1426. await writeFile(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, "release\n", "utf-8");
  1427. await respondToBackgroundBlockers();
  1428. const notificationIndex = await waitForFirstRequestIndex(
  1429. {
  1430. includes: ["<task-notification>", "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_CHILD_DONE"],
  1431. lastUserMessageIncludes: ["<task-notification>"],
  1432. },
  1433. followUpIndex,
  1434. "background parent anchor Agent completion notification 没有进入父模型请求",
  1435. );
  1436. expect(notificationIndex).toBeGreaterThan(followUpIndex);
  1437. await waitForV4AssistantMessageContaining(
  1438. "background-child-tool-parent-anchor-notification-consumed-ok",
  1439. );
  1440. await waitForIdle("background parent anchor notification 后会话没有回到 idle");
  1441. const { eventReport: reports } = await checkpointConversationTelemetryCase(capture, {
  1442. caseId: "BG18-token-identity",
  1443. minimumReportInventory: { agent_step: 1, message_completion: 3 },
  1444. minimumArmsInventory: {},
  1445. proof: [
  1446. "child usage retains original launch identity after follow-up",
  1447. "new UUID v7 wake message",
  1448. ],
  1449. });
  1450. assertBackgroundToolStepTelemetry(reports, "toolu_e2e_background_parent_anchor_child_bash");
  1451. assertMainCompletionAgentCompositions(reports, ["main_only", "main_only", "main_plus_bg"]);
  1452. assertMainCompletionMessageSources(reports, ["chat", "chat", "background_subagent"]);
  1453. await assertNoVisibleTaskNotification();
  1454. });
  1455. it("切换 session 期间完成的 background subagent 切回后应保留父 Agent 描述并收口", async function () {
  1456. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1457. await startNewBackgroundDraft();
  1458. const prompt =
  1459. "E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH: Launch a background agent whose child Bash completes while I am viewing another session.";
  1460. const requestCountBefore = await getUpstreamRequestRecordCount();
  1461. await rm(BG21_RELEASE_FILE, { force: true });
  1462. await sendV4Prompt(prompt);
  1463. await waitForV4ComposerText("", "background session switch prompt 发送后输入框没有清空");
  1464. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH");
  1465. await waitForToolCallBlockByToolCallId("toolu_e2e_background_session_switch_agent", 60000);
  1466. await respondToBackgroundBlockers();
  1467. const launchIndex = await waitForFirstRequestIndex(
  1468. {
  1469. includes: ["E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH", "Async agent launched successfully"],
  1470. },
  1471. requestCountBefore,
  1472. "background session switch Agent launch tool result 没有进入父模型请求",
  1473. );
  1474. await waitForV4AssistantMessageContaining("background-session-switch-launched-ok");
  1475. const sessionSwitchSnapshot = await waitForIdle(
  1476. "background session switch launch 后父会话没有先回到 idle",
  1477. );
  1478. const sourceTaskId = sessionSwitchSnapshot.taskId;
  1479. if (!sourceTaskId) {
  1480. throw new Error(
  1481. `background session switch 缺少 source taskId: ${JSON.stringify(sessionSwitchSnapshot)}`,
  1482. );
  1483. }
  1484. await waitForBackgroundTaskControlRow(
  1485. "agent",
  1486. "E2E background session switch child tool",
  1487. "background session switch Agent 没有出现在统一 background control UI",
  1488. );
  1489. await assertNoMainToolCallById(
  1490. "toolu_e2e_background_session_switch_child_bash",
  1491. "background session switch child Bash 不应进入 main timeline",
  1492. );
  1493. await startNewBackgroundDraft();
  1494. await waitForV4ConversationState(
  1495. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  1496. "background session switch 没有切到新草稿 task",
  1497. 30000,
  1498. );
  1499. await writeFile(BG21_RELEASE_FILE, "release\n", "utf-8");
  1500. const notificationIndex = await waitForFirstRequestIndex(
  1501. {
  1502. includes: ["<task-notification>", "E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH_CHILD_DONE"],
  1503. lastUserMessageIncludes: ["<task-notification>"],
  1504. },
  1505. launchIndex,
  1506. "background session switch Agent completion notification 没有进入父模型请求",
  1507. );
  1508. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1509. await selectV4TaskById(sourceTaskId);
  1510. await waitForV4ConversationState(
  1511. (snapshot) => snapshot.taskId === sourceTaskId,
  1512. "background session switch 切回原 task 后 chat root 没有恢复到原 task",
  1513. 30000,
  1514. );
  1515. await waitForV4AssistantMessageContaining("background-session-switch-notification-consumed-ok");
  1516. await waitForIdle("background session switch notification 后会话没有回到 idle");
  1517. await waitForNoBackgroundTaskControlRow(
  1518. "agent",
  1519. "E2E background session switch child tool",
  1520. "background session switch 切回后父 Agent control 没有收口",
  1521. );
  1522. // Bug 根因:V4 终态 Agent 事实由 timeline/subagent row 承载,不再写回 legacy
  1523. // renderer ToolCallBlock;切回后的收口应验证当前 V4 timeline 与 control 消失。
  1524. await waitForV4TimelineContaining("E2E background session switch child tool", 60000);
  1525. expect((await getV4PaneSnapshot()).timelineText).not.toContain("Unknown");
  1526. await assertNoMainToolCallById(
  1527. "toolu_e2e_background_session_switch_child_bash",
  1528. "background session switch 切回后不应把 child Bash 复活成 main row",
  1529. );
  1530. await assertNoVisibleTaskNotification();
  1531. });
  1532. it("切回 session 时 background subagent 仍 running,后续应继续收口父 Agent 状态", async function () {
  1533. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1534. await startNewBackgroundDraft();
  1535. const prompt =
  1536. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING: Launch a background agent whose child Bash is still running when I switch back.";
  1537. const requestCountBefore = await getUpstreamRequestRecordCount();
  1538. await rm(BACKGROUND_SWITCH_BACK_RELEASE_FILE, { force: true });
  1539. await sendV4Prompt(prompt);
  1540. await waitForV4ComposerText("", "background switch-back-running prompt 发送后输入框没有清空");
  1541. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING");
  1542. await waitForToolCallBlockByToolCallId("toolu_e2e_background_switch_back_running_agent", 60000);
  1543. await respondToBackgroundBlockers();
  1544. const launchIndex = await waitForFirstRequestIndex(
  1545. {
  1546. includes: [
  1547. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING",
  1548. "Async agent launched successfully",
  1549. ],
  1550. },
  1551. requestCountBefore,
  1552. "background switch-back-running Agent launch tool result 没有进入父模型请求",
  1553. );
  1554. await waitForV4AssistantMessageContaining("background-switch-back-running-launched-ok");
  1555. const sourceSnapshot = await waitForIdle(
  1556. "background switch-back-running launch 后父会话没有先回到 idle",
  1557. );
  1558. const sourceTaskId = sourceSnapshot.taskId;
  1559. if (!sourceTaskId) {
  1560. throw new Error(
  1561. `background switch-back-running 缺少 source taskId: ${JSON.stringify(sourceSnapshot)}`,
  1562. );
  1563. }
  1564. await waitForBackgroundTaskControlRow(
  1565. "agent",
  1566. "E2E background switch back running child tool",
  1567. "background switch-back-running Agent 没有出现在统一 background control UI",
  1568. );
  1569. await assertNoMainToolCallById(
  1570. "toolu_e2e_background_switch_back_running_child_bash",
  1571. "background switch-back-running child Bash 不应进入 main timeline",
  1572. );
  1573. await startNewBackgroundDraft();
  1574. await waitForV4ConversationState(
  1575. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  1576. "background switch-back-running 没有切到新草稿 task",
  1577. 30000,
  1578. );
  1579. await selectV4TaskById(sourceTaskId);
  1580. await waitForV4ConversationState(
  1581. (snapshot) => snapshot.taskId === sourceTaskId,
  1582. "background switch-back-running 切回原 task 后 chat root 没有恢复到原 task",
  1583. 30000,
  1584. );
  1585. await waitForBackgroundTaskControlRow(
  1586. "agent",
  1587. "E2E background switch back running child tool",
  1588. "background switch-back-running 切回后父 Agent running control 没有恢复",
  1589. );
  1590. await assertNoMainToolCallById(
  1591. "toolu_e2e_background_switch_back_running_child_bash",
  1592. "background switch-back-running 切回后不应把 child Bash 投影到 main timeline",
  1593. );
  1594. await writeFile(BACKGROUND_SWITCH_BACK_RELEASE_FILE, "release\n", "utf-8");
  1595. const notificationIndex = await waitForFirstRequestIndex(
  1596. {
  1597. includes: [
  1598. "<task-notification>",
  1599. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING_CHILD_DONE",
  1600. ],
  1601. lastUserMessageIncludes: ["<task-notification>"],
  1602. },
  1603. launchIndex,
  1604. "background switch-back-running Agent completion notification 没有进入父模型请求",
  1605. );
  1606. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1607. await waitForV4AssistantMessageContaining(
  1608. "background-switch-back-running-notification-consumed-ok",
  1609. );
  1610. await waitForIdle("background switch-back-running notification 后会话没有回到 idle");
  1611. await waitForNoBackgroundTaskControlRow(
  1612. "agent",
  1613. "E2E background switch back running child tool",
  1614. "background switch-back-running 完成后父 Agent control 没有收口",
  1615. );
  1616. await waitForV4TimelineContaining("E2E background switch back running child tool", 60000);
  1617. expect((await getV4PaneSnapshot()).timelineText).not.toContain("Unknown");
  1618. await assertNoMainToolCallById(
  1619. "toolu_e2e_background_switch_back_running_child_bash",
  1620. "background switch-back-running 完成后不应把 child Bash 复活成 main row",
  1621. );
  1622. await assertNoVisibleTaskNotification();
  1623. });
  1624. it("background-only running 时点击 queued prompt 立即发送不应 stop background task", async function () {
  1625. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1626. await startNewBackgroundDraft();
  1627. const prompt =
  1628. "E2E_BACKGROUND_SEND_NOW_QUEUE: Launch a background agent with a visible child Bash tool, then wait.";
  1629. const queuedPrompt =
  1630. "E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD: This queued prompt should send now without stopping the background agent.";
  1631. const holdPrompt =
  1632. 'E2E_HOLD_STREAM E2E_BACKGROUND_SEND_NOW_QUEUE_HOLD: Reply with exactly "upstream-e2e-ok" and no other text.';
  1633. const requestCountBefore = await getUpstreamRequestRecordCount();
  1634. await sendV4Prompt(prompt);
  1635. await waitForV4ComposerText("", "background send-now queue prompt 发送后输入框没有清空");
  1636. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_NOW_QUEUE");
  1637. await waitForToolCallBlockByToolCallId("toolu_e2e_background_send_now_queue_agent", 60000);
  1638. await respondToBackgroundBlockers();
  1639. const launchIndex = await waitForFirstRequestIndex(
  1640. {
  1641. includes: ["E2E_BACKGROUND_SEND_NOW_QUEUE", "Async agent launched successfully"],
  1642. },
  1643. requestCountBefore,
  1644. "background send-now queue Agent launch tool result 没有进入父模型请求",
  1645. );
  1646. await waitForV4AssistantMessageContaining("background-send-now-queue-launched-ok");
  1647. await waitForIdle("background send-now queue launch 后父会话没有先回到 idle");
  1648. await waitForBackgroundTaskControlRow(
  1649. "agent",
  1650. "E2E background send now queue",
  1651. "background send-now queue Agent 没有保持 running control",
  1652. );
  1653. await assertNoMainToolCallById(
  1654. "toolu_e2e_background_send_now_queue_child_bash",
  1655. "background send-now queue child Bash 不应进入 main timeline",
  1656. );
  1657. await assertNoMainFakeLoading(
  1658. "background send-now queue child tool update 不应让 idle main 显示底部 loading",
  1659. );
  1660. // Bug 根因:旧 case 直接调用已删除的 renderer store enqueue API,构造的是
  1661. // 产品 UI 无法到达的状态。现在先启动可停止的主 turn、真实排队,再 stop 进入
  1662. // idle + paused queue;background Agent 仍 running,随后从队列点击“立即”。
  1663. await sendV4Prompt(holdPrompt);
  1664. await waitForV4ComposerText("", "background send-now hold prompt 发送后输入框没有清空");
  1665. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_NOW_QUEUE_HOLD");
  1666. await waitForV4ConversationState(
  1667. (snapshot) => snapshot.state === "streaming",
  1668. "background send-now hold prompt 没有进入 streaming",
  1669. 30000,
  1670. );
  1671. await sendV4Prompt(queuedPrompt);
  1672. await waitForV4ComposerText("", "background send-now queued prompt 没有清空");
  1673. const queuedBeforeSendNow = await waitForQueueOrderContaining(
  1674. ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1675. "background-only running send-now 点击前没有形成 queued prompt",
  1676. );
  1677. expect(queuedBeforeSendNow[0]?.kind).toBe("text");
  1678. await clickV4Stop();
  1679. await waitForV4ConversationState(
  1680. (snapshot) =>
  1681. snapshot.state !== "streaming" && !snapshot.stopRequested && snapshot.queueCount === 1,
  1682. "background send-now stop 后没有进入 background-only + paused queue",
  1683. 30000,
  1684. );
  1685. await waitForBackgroundTaskControlRow(
  1686. "agent",
  1687. "E2E background send now queue",
  1688. "background send-now stop main turn 后误停了 background Agent",
  1689. );
  1690. const sentNowItem = await clickFirstQueueSendNow();
  1691. expect(sentNowItem.content).toContain("E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD");
  1692. await browser.pause(80);
  1693. const afterClickSnapshot = await getV4ConversationState();
  1694. expect(afterClickSnapshot.stopRequested).toBe(false);
  1695. const queuedPromptIndex = await waitForFirstRequestIndex(
  1696. {
  1697. includes: ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1698. lastUserMessageIncludes: ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1699. },
  1700. launchIndex,
  1701. "background-only running 下 queued prompt 点击立即发送后没有直接进入 provider request",
  1702. );
  1703. expect(queuedPromptIndex).toBeGreaterThan(launchIndex);
  1704. await waitForV4AssistantMessageContaining("background-send-now-queue-received-ok");
  1705. // Bug 根因:固定 sleep 窗口在 25 条全量回放负载下可能先于 UI 断言结束,
  1706. // 让用例偶发看不到 running control。点击“立即”完成后再释放 child,才能
  1707. // 确保测试窗口由交互事件决定,而不是依赖机器速度。
  1708. await writeFile(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, "release\n", "utf-8");
  1709. const notificationIndex = await waitForFirstRequestIndex(
  1710. {
  1711. includes: ["<task-notification>", "E2E_BACKGROUND_SEND_NOW_QUEUE_CHILD_DONE"],
  1712. lastUserMessageIncludes: ["<task-notification>"],
  1713. },
  1714. queuedPromptIndex,
  1715. "background send-now queue Agent completion notification 没有进入父模型请求",
  1716. );
  1717. expect(notificationIndex).toBeGreaterThan(queuedPromptIndex);
  1718. await waitForV4AssistantMessageContaining("background-send-now-queue-notification-consumed-ok");
  1719. await waitForIdle("background send-now queue notification 后会话没有回到 idle");
  1720. await assertNoVisibleTaskNotification();
  1721. });
  1722. it("main turn 启动 background task 后结束时会继续 drain 已有 queue,后续 queued prompt 不丢失", async function () {
  1723. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1724. await startNewBackgroundDraft();
  1725. const backgroundLaunchPrompt =
  1726. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END: Start a background agent, but let me queue follow-up messages while this main turn is still running.";
  1727. const queuedPromptTwo =
  1728. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2: Q2 should queue while the background launch turn is still active.";
  1729. const queuedPromptThree =
  1730. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3: Q3 should queue behind Q2 while the background launch turn is still active.";
  1731. const queuedPromptFour =
  1732. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4: Q4 should queue behind Q3 while the background launch turn is still active.";
  1733. const requestCountBefore = await getUpstreamRequestRecordCount();
  1734. // Bug 根因:capture 的 afterIndex 使用最后一个数组下标;启动前记录数直接传入
  1735. // 会漏掉本轮恰好落在 index=requestCountBefore 的首条请求,导致后续 queue drain
  1736. // 证明在真实请求已完成时仍被报告为未命中。
  1737. const lastRequestIndexBefore = requestCountBefore - 1;
  1738. await sendV4Prompt(backgroundLaunchPrompt);
  1739. await waitForV4ComposerText("", "background queue drain launch prompt 发送后输入框没有清空");
  1740. await waitForV4UserMessageContaining("E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END");
  1741. const backgroundPromptIndex = await waitForFirstRequestIndex(
  1742. {
  1743. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END"],
  1744. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END"],
  1745. },
  1746. lastRequestIndexBefore,
  1747. "background launch prompt 没有进入 provider request",
  1748. );
  1749. await waitForToolCallBlockByToolCallId("toolu_e2e_background_queue_drain_agent", 60000);
  1750. await respondToBackgroundBlockers();
  1751. await waitForBackgroundTaskControlRow(
  1752. "agent",
  1753. "E2E background queue drain agent",
  1754. "background queue drain Agent 没有出现在统一 background control UI",
  1755. );
  1756. await waitForV4ConversationState(
  1757. (snapshot) => snapshot.state === "streaming",
  1758. "background queue drain launch ack delay 期间 main 没有保持 running",
  1759. 30000,
  1760. );
  1761. await sendV4Prompt(queuedPromptTwo);
  1762. await waitForV4ComposerText("", "background queue drain Q2 入队后输入框没有清空");
  1763. await waitForQueueOrderContaining(
  1764. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1765. "background Agent running 且 launch ack 未结束时 Q2 没有进入 queue",
  1766. );
  1767. await sendV4Prompt(queuedPromptThree);
  1768. await waitForV4ComposerText("", "background queue drain Q3 入队后输入框没有清空");
  1769. await waitForQueueOrderContaining(
  1770. [
  1771. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1772. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1773. ],
  1774. "background Agent running 且 launch ack 未结束时 Q2/Q3 queue 顺序不正确",
  1775. );
  1776. await sendV4Prompt(queuedPromptFour);
  1777. await waitForV4ComposerText("", "background queue drain Q4 入队后输入框没有清空");
  1778. await waitForQueueOrderContaining(
  1779. [
  1780. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1781. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1782. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1783. ],
  1784. "background Agent running 且 launch ack 未结束时 Q2/Q3/Q4 queue 顺序不正确",
  1785. );
  1786. await startVisibleUserMessageSampler();
  1787. const launchIndex = await waitForFirstRequestIndex(
  1788. {
  1789. includes: [
  1790. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END",
  1791. "Async agent launched successfully",
  1792. ],
  1793. },
  1794. backgroundPromptIndex,
  1795. "background queue drain Agent launch tool result 没有进入父模型请求",
  1796. );
  1797. expect(launchIndex).toBeGreaterThan(backgroundPromptIndex);
  1798. await waitForV4AssistantMessageContaining("background-queue-drain-launched-ok");
  1799. const secondQueuedIndex = await waitForFirstRequestIndex(
  1800. {
  1801. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1802. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1803. },
  1804. launchIndex,
  1805. "background prompt 完成后 Q2 没有继续 drain",
  1806. );
  1807. expect(secondQueuedIndex).toBeGreaterThan(launchIndex);
  1808. await waitForVisibleUserMessagesContainingAll(
  1809. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1810. "Q2 drain 后应渲染为可见 user message",
  1811. );
  1812. await waitForQueueOrderContaining(
  1813. [
  1814. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1815. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1816. ],
  1817. "Q2 drain 期间 Q3/Q4 应仍留在 queue 中",
  1818. );
  1819. expect(
  1820. await countUpstreamRequests(
  1821. {
  1822. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1823. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1824. },
  1825. { afterIndex: secondQueuedIndex },
  1826. ),
  1827. ).toBe(0);
  1828. await waitForV4AssistantMessageContaining("background-queue-drain-first-ok");
  1829. const thirdQueuedIndex = await waitForFirstRequestIndex(
  1830. {
  1831. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3"],
  1832. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3"],
  1833. },
  1834. secondQueuedIndex,
  1835. "Q2 完成后 Q3 没有继续 drain",
  1836. );
  1837. expect(thirdQueuedIndex).toBeGreaterThan(secondQueuedIndex);
  1838. await waitForVisibleUserMessagesContainingAll(
  1839. [
  1840. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1841. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1842. ],
  1843. "Q3 drain 后 Q2/Q3 应同时保留在可见 user messages 中",
  1844. );
  1845. await waitForQueueOrderContaining(
  1846. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1847. "Q3 drain 期间 Q4 应仍留在 queue 中",
  1848. );
  1849. expect(
  1850. await countUpstreamRequests(
  1851. {
  1852. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1853. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1854. },
  1855. { afterIndex: thirdQueuedIndex },
  1856. ),
  1857. ).toBe(0);
  1858. await waitForV4AssistantMessageContaining("background-queue-drain-second-ok");
  1859. const fourthQueuedIndex = await waitForFirstRequestIndex(
  1860. {
  1861. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1862. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1863. },
  1864. thirdQueuedIndex,
  1865. "Q3 完成后 Q4 没有继续 drain",
  1866. );
  1867. expect(fourthQueuedIndex).toBeGreaterThan(thirdQueuedIndex);
  1868. await waitForVisibleUserMessagesContainingAll(
  1869. [
  1870. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1871. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1872. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1873. ],
  1874. "Q4 drain 后 Q2/Q3/Q4 应同时保留在可见 user messages 中",
  1875. );
  1876. assertVisibleUserMessageMarkersNeverDisappear(await stopVisibleUserMessageSampler(), [
  1877. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1878. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1879. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1880. ]);
  1881. await waitForV4AssistantMessageContaining("background-queue-drain-third-ok");
  1882. const notificationIndex = await waitForFirstRequestIndex(
  1883. {
  1884. includes: ["<task-notification>", "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_CHILD_DONE"],
  1885. lastUserMessageIncludes: ["<task-notification>"],
  1886. },
  1887. fourthQueuedIndex,
  1888. "background queue drain Agent completion notification 没有进入父模型请求",
  1889. );
  1890. expect(notificationIndex).toBeGreaterThan(fourthQueuedIndex);
  1891. await waitForV4AssistantMessageContaining("background-queue-drain-notification-consumed-ok");
  1892. await waitForIdle("background queue drain notification 后会话没有回到 idle");
  1893. await assertNoVisibleTaskNotification();
  1894. });
  1895. it("background subagent 内部 background Bash 完成后只做 child cleanup", async function () {
  1896. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1897. await startNewBackgroundDraft();
  1898. const prompt =
  1899. "E2E_BACKGROUND_NESTED_BASH: Launch a background agent that starts a background Bash command and then finishes.";
  1900. const requestCountBefore = await getUpstreamRequestRecordCount();
  1901. await sendV4Prompt(prompt);
  1902. await waitForV4ComposerText("", "nested background Bash prompt 发送后输入框没有清空");
  1903. await waitForV4UserMessageContaining("E2E_BACKGROUND_NESTED_BASH");
  1904. await waitForToolCallBlockByToolName("Agent", 60000);
  1905. await respondToBackgroundBlockers();
  1906. const launchIndex = await waitForFirstRequestIndex(
  1907. {
  1908. includes: ["E2E_BACKGROUND_NESTED_BASH", "Async agent launched successfully"],
  1909. },
  1910. requestCountBefore,
  1911. "nested background Agent launch tool result 没有进入父模型请求",
  1912. );
  1913. const notificationIndex = await waitForFirstRequestIndex(
  1914. {
  1915. includes: ["<task-notification>", "E2E_BACKGROUND_NESTED_BASH_CHILD_DONE"],
  1916. },
  1917. launchIndex,
  1918. "nested background Agent completion notification 没有进入父模型请求",
  1919. );
  1920. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1921. await waitForV4AssistantMessageContaining("background-nested-bash-notification-consumed-ok");
  1922. await waitForIdle("nested background Agent notification 后会话没有回到 idle");
  1923. await browser.pause(2500);
  1924. // Bug 根因:TaskOutput 的工具 description 本身包含 `<task-notification>`;旧断言扫描
  1925. // 整条 model-io JSONL,会把正常 child 首次请求里的工具 schema 与 Bash tool call ID
  1926. // 拼成一次伪 wake。这里改查 provider 实际请求,并把通知限定在 latest user message;
  1927. // 唯一 Bash tool call ID 与时间边界仍保留,真实的 sealed-child wake 仍会被准确捕获。
  1928. const unexpectedChildWakeCount = await countUpstreamRequests(
  1929. {
  1930. includes: ["toolu_e2e_background_nested_child_bash"],
  1931. lastUserMessageIncludes: ["<task-notification>"],
  1932. },
  1933. { afterIndex: launchIndex },
  1934. );
  1935. if (unexpectedChildWakeCount > 0) {
  1936. throw new Error(
  1937. "sealed child runtime 不应被 nested background Bash completion 重新唤起; " +
  1938. `count=${unexpectedChildWakeCount}`,
  1939. );
  1940. }
  1941. expect(unexpectedChildWakeCount).toBe(0);
  1942. expect(
  1943. await countUpstreamRequests(
  1944. {
  1945. includes: ["<task-notification>", "E2E_BACKGROUND_NESTED_BASH_CHILD_DONE"],
  1946. lastUserMessageIncludes: ["<task-notification>"],
  1947. },
  1948. { afterIndex: requestCountBefore },
  1949. ),
  1950. ).toBe(1);
  1951. await assertNoVisibleTaskNotification();
  1952. });
  1953. it("partial runtime snapshot 不应清掉缺失的 running background control row", async function () {
  1954. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1955. await startNewBackgroundDraft();
  1956. const requestCountBefore = await getUpstreamRequestRecordCount();
  1957. await sendV4Prompt(
  1958. "E2E_BACKGROUND_SNAPSHOT_CONTROL: Start two background Bash tasks. One should finish first while the other keeps running.",
  1959. );
  1960. await waitForV4ComposerText("", "BG23 prompt 发送后输入框没有清空");
  1961. await waitForV4UserMessageContaining("E2E_BACKGROUND_SNAPSHOT_CONTROL");
  1962. await waitForToolCallBlockByToolCallId("toolu_e2e_bg23_bash_one", 60000);
  1963. await waitForToolCallBlockByToolCallId("toolu_e2e_bg23_bash_two", 60000);
  1964. await respondToBackgroundBlockers();
  1965. await respondToBackgroundBlockers();
  1966. const launchIndex = await waitForFirstRequestIndex(
  1967. {
  1968. includes: [
  1969. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  1970. "toolu_e2e_bg23_bash_one",
  1971. "toolu_e2e_bg23_bash_two",
  1972. "Command running in background",
  1973. ],
  1974. },
  1975. requestCountBefore,
  1976. "BG23 两个 background Bash launch result 没有进入父模型请求",
  1977. );
  1978. await waitForV4AssistantMessageContaining("background-snapshot-control-ready-ok");
  1979. await waitForIdle("BG23 setup prompt 后会话没有回到 idle");
  1980. await waitForBackgroundTaskControlRow(
  1981. "bash",
  1982. "E2E BG23 bash one",
  1983. "BG23 初始第一个 Bash background control row 没有显示在右上角面板",
  1984. );
  1985. await waitForBackgroundTaskControlRow(
  1986. "bash",
  1987. "E2E BG23 bash two",
  1988. "BG23 初始第二个 Bash background control row 没有显示在右上角面板",
  1989. );
  1990. const firstNotificationIndex = await waitForFirstRequestIndex(
  1991. {
  1992. includes: [
  1993. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  1994. "<task-notification>",
  1995. "<tool-use-id>toolu_e2e_bg23_bash_one</tool-use-id>",
  1996. "<status>completed</status>",
  1997. ],
  1998. lastUserMessageIncludes: ["<task-notification>"],
  1999. },
  2000. launchIndex,
  2001. "BG23 第一个 background Bash completion notification 没有进入父模型请求",
  2002. );
  2003. expect(firstNotificationIndex).toBeGreaterThan(launchIndex);
  2004. await waitForV4AssistantMessageContaining("background-snapshot-control-first-notification-ok");
  2005. await waitForIdle("BG23 第一个 background Bash notification 后会话没有回到 idle");
  2006. await waitForNoBackgroundTaskControlRow(
  2007. "bash",
  2008. "E2E BG23 bash one",
  2009. "BG23 第一个 terminal Bash row 没有从右上角面板消失",
  2010. );
  2011. await waitForBackgroundTaskControlRow(
  2012. "bash",
  2013. "E2E BG23 bash two",
  2014. "BG23 第一个 Bash 完成后第二个 running Bash row 被错误清掉",
  2015. );
  2016. await clickStopBackgroundTaskControlRow("bash", "E2E BG23 bash two");
  2017. const stopNotificationIndex = await waitForFirstRequestIndex(
  2018. {
  2019. includes: [
  2020. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  2021. "<task-notification>",
  2022. "<tool-use-id>toolu_e2e_bg23_bash_two</tool-use-id>",
  2023. "<status>killed</status>",
  2024. ],
  2025. lastUserMessageIncludes: ["<task-notification>"],
  2026. },
  2027. firstNotificationIndex,
  2028. "BG23 第二个 background Bash stop notification 没有进入父模型请求",
  2029. );
  2030. expect(stopNotificationIndex).toBeGreaterThan(firstNotificationIndex);
  2031. await waitForV4AssistantMessageContaining("background-snapshot-control-second-stopped-ok");
  2032. await waitForIdle("BG23 第二个 background Bash stop notification 后会话没有回到 idle");
  2033. await waitForNoBackgroundTaskControlRow(
  2034. "bash",
  2035. "E2E BG23 bash two",
  2036. "BG23 第二个 Bash stop 后 row 没有从右上角面板消失",
  2037. );
  2038. });
  2039. it("background Agent notification 处理中不应清掉仍 running 的其它 Agent control row", async function () {
  2040. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  2041. await startNewBackgroundDraft();
  2042. const requestCountBefore = await getUpstreamRequestRecordCount();
  2043. await sendV4Prompt(
  2044. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE: Start one long-running background agent and three short-lived background agents. The three short-lived agents should finish before the long-running agent.",
  2045. );
  2046. await waitForV4ComposerText("", "BG24 prompt 发送后输入框没有清空");
  2047. await waitForV4UserMessageContaining("E2E_BACKGROUND_AGENT_CONTROL_PRESERVE");
  2048. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_long_running_agent", 60000);
  2049. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_one_agent", 60000);
  2050. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_two_agent", 60000);
  2051. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_three_agent", 60000);
  2052. await respondToBackgroundBlockers();
  2053. const launchIndex = await waitForFirstRequestIndex(
  2054. {
  2055. includes: [
  2056. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2057. "toolu_e2e_bg24_long_running_agent",
  2058. "toolu_e2e_bg24_short_lived_one_agent",
  2059. "toolu_e2e_bg24_short_lived_two_agent",
  2060. "toolu_e2e_bg24_short_lived_three_agent",
  2061. "Async agent launched successfully",
  2062. ],
  2063. },
  2064. requestCountBefore,
  2065. "BG24 四个 background Agent launch result 没有进入父模型请求",
  2066. );
  2067. await waitForV4AssistantMessageContaining("background-agent-control-preserve-ready-ok");
  2068. const sourceSnapshot = await waitForIdle("BG24 setup prompt 后会话没有回到 idle");
  2069. const sourceTaskId = sourceSnapshot.taskId;
  2070. if (!sourceTaskId) {
  2071. throw new Error(`BG24 setup 后缺少 source taskId: ${JSON.stringify(sourceSnapshot)}`);
  2072. }
  2073. await waitForBackgroundTaskControlRow(
  2074. "agent",
  2075. "E2E BG24 long-running keepalive agent",
  2076. "BG24 初始 long-running Agent background control row 没有显示在右上角面板",
  2077. );
  2078. await waitForBackgroundTaskControlRow(
  2079. "agent",
  2080. "E2E BG24 short-lived three agent",
  2081. "BG24 初始第三个 short-lived Agent background control row 没有显示在右上角面板",
  2082. );
  2083. const firstShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2084. {
  2085. includes: [
  2086. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2087. "<task-notification>",
  2088. "<tool-use-id>toolu_e2e_bg24_short_lived_one_agent</tool-use-id>",
  2089. "<status>completed</status>",
  2090. "E2E_BG24_SHORT_LIVED_ONE_CHILD_DONE",
  2091. ],
  2092. lastUserMessageIncludes: ["<task-notification>"],
  2093. },
  2094. launchIndex,
  2095. "BG24 第一个 short-lived background Agent completion notification 没有进入父模型请求",
  2096. );
  2097. expect(firstShortLivedNotificationIndex).toBeGreaterThan(launchIndex);
  2098. await waitForV4AssistantMessageContaining(
  2099. "background-agent-control-preserve-short-lived-one-notification-ok",
  2100. );
  2101. await waitForBackgroundTaskControlRow(
  2102. "agent",
  2103. "E2E BG24 long-running keepalive agent",
  2104. "BG24 第一个 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2105. );
  2106. await startBackgroundTaskControlPresenceProbe(
  2107. "agent",
  2108. "E2E BG24 long-running keepalive agent",
  2109. sourceTaskId,
  2110. );
  2111. const secondShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2112. {
  2113. includes: [
  2114. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2115. "<task-notification>",
  2116. "<tool-use-id>toolu_e2e_bg24_short_lived_two_agent</tool-use-id>",
  2117. "<status>completed</status>",
  2118. "E2E_BG24_SHORT_LIVED_TWO_CHILD_DONE",
  2119. ],
  2120. lastUserMessageIncludes: ["<task-notification>"],
  2121. },
  2122. firstShortLivedNotificationIndex,
  2123. "BG24 第二个 short-lived background Agent completion notification 没有进入父模型请求",
  2124. );
  2125. expect(secondShortLivedNotificationIndex).toBeGreaterThan(firstShortLivedNotificationIndex);
  2126. await startNewBackgroundDraft();
  2127. await waitForV4ConversationState(
  2128. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  2129. "BG24 第二个 notification 处理中没有切到新草稿 task",
  2130. 30000,
  2131. );
  2132. await selectV4TaskById(sourceTaskId);
  2133. await waitForV4ConversationState(
  2134. (snapshot) => snapshot.taskId === sourceTaskId,
  2135. "BG24 第二个 notification 处理中切回原 task 后 chat root 没有恢复",
  2136. 30000,
  2137. );
  2138. await waitForBackgroundTaskControlRow(
  2139. "agent",
  2140. "E2E BG24 long-running keepalive agent",
  2141. "BG24 第二个 notification 处理中切回原 task 后 long-running running Agent row 没有恢复",
  2142. );
  2143. await waitForV4AssistantMessageContaining(
  2144. "background-agent-control-preserve-short-lived-two-notification-ok",
  2145. );
  2146. await waitForBackgroundTaskControlRow(
  2147. "agent",
  2148. "E2E BG24 long-running keepalive agent",
  2149. "BG24 第二个 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2150. );
  2151. const thirdShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2152. {
  2153. includes: [
  2154. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2155. "<task-notification>",
  2156. "<tool-use-id>toolu_e2e_bg24_short_lived_three_agent</tool-use-id>",
  2157. "<status>completed</status>",
  2158. "E2E_BG24_SHORT_LIVED_THREE_CHILD_DONE",
  2159. ],
  2160. lastUserMessageIncludes: ["<task-notification>"],
  2161. },
  2162. secondShortLivedNotificationIndex,
  2163. "BG24 第三个 short-lived background Agent completion notification 没有进入父模型请求",
  2164. );
  2165. expect(thirdShortLivedNotificationIndex).toBeGreaterThan(secondShortLivedNotificationIndex);
  2166. const afterTodoIndex = await waitForFirstRequestIndex(
  2167. {
  2168. includes: [
  2169. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2170. "toolu_e2e_bg24_todo_write",
  2171. "E2E_BG24_TODO_UPDATED",
  2172. ],
  2173. },
  2174. thirdShortLivedNotificationIndex,
  2175. "BG24 short-lived notification 中的 TodoWrite tool result 没有进入后续父模型请求",
  2176. );
  2177. expect(afterTodoIndex).toBeGreaterThan(thirdShortLivedNotificationIndex);
  2178. await waitForV4AssistantMessageContaining(
  2179. "background-agent-control-preserve-short-lived-notification-ok",
  2180. );
  2181. await waitForIdle("BG24 short-lived Agent notification 后会话没有回到 idle");
  2182. const presenceProbe = await stopBackgroundTaskControlPresenceProbe();
  2183. expect(presenceProbe.observedPresent).toBe(true);
  2184. expect(presenceProbe.missingTransitions).toEqual([]);
  2185. await waitForNoBackgroundTaskControlRow(
  2186. "agent",
  2187. "E2E BG24 short-lived three agent",
  2188. "BG24 已完成的第三个 short-lived Agent row 没有从右上角面板消失",
  2189. );
  2190. await waitForBackgroundTaskControlRow(
  2191. "agent",
  2192. "E2E BG24 long-running keepalive agent",
  2193. "BG24 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2194. );
  2195. await clickStopBackgroundTaskControlRow("agent", "E2E BG24 long-running keepalive agent");
  2196. const stopNotificationIndex = await waitForFirstRequestIndex(
  2197. {
  2198. includes: [
  2199. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2200. "<task-notification>",
  2201. "<tool-use-id>toolu_e2e_bg24_long_running_agent</tool-use-id>",
  2202. "<status>killed</status>",
  2203. "was stopped by user</summary>",
  2204. ],
  2205. lastUserMessageIncludes: ["<task-notification>"],
  2206. },
  2207. thirdShortLivedNotificationIndex,
  2208. "BG24 long-running background Agent stop notification 没有进入父模型请求",
  2209. );
  2210. expect(stopNotificationIndex).toBeGreaterThan(thirdShortLivedNotificationIndex);
  2211. await waitForV4AssistantMessageContaining(
  2212. "background-agent-control-preserve-long-running-stopped-ok",
  2213. );
  2214. await waitForIdle("BG24 long-running Agent stop notification 后会话没有回到 idle");
  2215. await waitForNoBackgroundTaskControlRow(
  2216. "agent",
  2217. "E2E BG24 long-running keepalive agent",
  2218. "BG24 stop 后 long-running Agent row 没有从右上角面板消失",
  2219. );
  2220. });
  2221. });
  2222. async function waitForFirstRequestIndex(
  2223. query: Parameters<typeof waitForUpstreamRequest>[0],
  2224. afterIndex: number,
  2225. timeoutMsg: string,
  2226. ) {
  2227. await waitForUpstreamRequest(query, timeoutMsg, 45000, { afterIndex });
  2228. const index = await findFirstUpstreamRequestIndex(query, { afterIndex });
  2229. if (index === null) {
  2230. throw new Error(`${timeoutMsg}; request disappeared after wait`);
  2231. }
  2232. if (
  2233. query.includes?.includes("<task-notification>") ||
  2234. query.lastUserMessageIncludes?.includes("<task-notification>")
  2235. ) {
  2236. const records = await getUpstreamRequestEvidence(query, {
  2237. afterIndex: index - 1,
  2238. beforeIndex: index + 1,
  2239. });
  2240. await assertTaskNotificationContents(records[0]!.requestJson, `background-request-${index}`);
  2241. }
  2242. return index;
  2243. }
  2244. async function waitForRunningPidFile(path: string, label: string): Promise<number> {
  2245. let recordedPid: number | null = null;
  2246. await browser.waitUntil(
  2247. async () => {
  2248. recordedPid = await readRecordedPid(path);
  2249. return recordedPid !== null && isProcessAlive(recordedPid);
  2250. },
  2251. {
  2252. timeout: 30000,
  2253. timeoutMsg: `${label} 没有写入 fresh PID marker 或进程未保持运行`,
  2254. },
  2255. );
  2256. return recordedPid!;
  2257. }
  2258. async function readRecordedPid(path: string): Promise<number | null> {
  2259. const raw = await readFile(path, "utf-8").catch(() => "");
  2260. const pid = Number(raw.trim());
  2261. return Number.isInteger(pid) && pid > 1 ? pid : null;
  2262. }
  2263. function isProcessAlive(pid: number): boolean {
  2264. try {
  2265. process.kill(pid, 0);
  2266. return true;
  2267. } catch (error) {
  2268. return (error as NodeJS.ErrnoException).code === "EPERM";
  2269. }
  2270. }
  2271. async function readPosixProcessGroupId(pid: number): Promise<number> {
  2272. const stdout = await new Promise<string>((resolve, reject) => {
  2273. execFile("ps", ["-o", "pgid=", "-p", String(pid)], (error, output) => {
  2274. if (error) {
  2275. reject(error);
  2276. return;
  2277. }
  2278. resolve(output);
  2279. });
  2280. });
  2281. const processGroupId = Number(stdout.trim());
  2282. if (!Number.isInteger(processGroupId) || processGroupId <= 1) {
  2283. throw new Error(`无法读取 PID ${pid} 的 POSIX PGID: ${JSON.stringify(stdout)}`);
  2284. }
  2285. return processGroupId;
  2286. }
  2287. async function waitForProcessExit(pid: number, label: string): Promise<void> {
  2288. await browser.waitUntil(() => !isProcessAlive(pid), {
  2289. timeout: 15000,
  2290. timeoutMsg: `${label} PID ${pid} 在 background stop 收口后仍存活`,
  2291. });
  2292. }
  2293. async function cleanupBg08ProcessTree(): Promise<void> {
  2294. const processFiles = [BG08_WORKER_PID_FILE, BG08_LAUNCHER_PID_FILE];
  2295. if (process.platform !== "win32") {
  2296. processFiles.push(BG08_ROOT_PID_FILE);
  2297. }
  2298. for (const path of processFiles) {
  2299. const pid = await readRecordedPid(path);
  2300. if (pid === null || !isProcessAlive(pid)) continue;
  2301. try {
  2302. process.kill(pid, "SIGKILL");
  2303. } catch {
  2304. // 测试收尾与进程自然退出存在竞争,已退出即视为完成。
  2305. }
  2306. }
  2307. }
  2308. async function removeBg08PidFiles(): Promise<void> {
  2309. await Promise.all(
  2310. [BG08_ROOT_PID_FILE, BG08_LAUNCHER_PID_FILE, BG08_WORKER_PID_FILE].map((path) =>
  2311. rm(path, { force: true }).catch(() => undefined),
  2312. ),
  2313. );
  2314. }
  2315. async function waitForVisibleUserMessagesContainingAll(
  2316. markers: readonly string[],
  2317. timeoutMsg: string,
  2318. ) {
  2319. let latestMessages: Awaited<ReturnType<typeof getV4Messages>> = [];
  2320. await browser.waitUntil(
  2321. async () => {
  2322. latestMessages = await getV4Messages("user");
  2323. return markers.every((marker) =>
  2324. latestMessages.some((message) => message.text.includes(marker)),
  2325. );
  2326. },
  2327. {
  2328. timeout: 60000,
  2329. timeoutMsg: `${timeoutMsg}; visibleUserMessages=${JSON.stringify(
  2330. latestMessages.map((message) => ({
  2331. id: message.id,
  2332. text: message.text.slice(0, 200),
  2333. })),
  2334. )}`,
  2335. },
  2336. );
  2337. }
  2338. type VisibleUserMessageSample = {
  2339. at: number;
  2340. messages: Array<{
  2341. id: string | null;
  2342. text: string;
  2343. }>;
  2344. };
  2345. async function startVisibleUserMessageSampler() {
  2346. await browser.execute(
  2347. (messagesTestId: string, userMessagePrefix: string) => {
  2348. type SamplerState = {
  2349. intervalId: ReturnType<typeof setInterval>;
  2350. samples: VisibleUserMessageSample[];
  2351. };
  2352. const sampleWindow = window as typeof window & {
  2353. __zcodeBg17UserMessageSampler?: SamplerState;
  2354. };
  2355. if (sampleWindow.__zcodeBg17UserMessageSampler) {
  2356. clearInterval(sampleWindow.__zcodeBg17UserMessageSampler.intervalId);
  2357. }
  2358. const collect = () => {
  2359. const root = document.querySelector<HTMLElement>(`[data-testid="${messagesTestId}"]`);
  2360. const messages = Array.from(
  2361. root?.querySelectorAll<HTMLElement>(`[data-testid^="${userMessagePrefix}-"]`) ?? [],
  2362. ).map((element) => ({
  2363. id: element.getAttribute("data-message-id"),
  2364. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  2365. }));
  2366. sampleWindow.__zcodeBg17UserMessageSampler?.samples.push({
  2367. at: Date.now(),
  2368. messages,
  2369. });
  2370. };
  2371. sampleWindow.__zcodeBg17UserMessageSampler = {
  2372. intervalId: setInterval(collect, 50),
  2373. samples: [],
  2374. };
  2375. collect();
  2376. },
  2377. TID_CHAT_MESSAGES,
  2378. TID_CHAT_USER_MESSAGE,
  2379. );
  2380. }
  2381. async function stopVisibleUserMessageSampler() {
  2382. return await browser.execute(() => {
  2383. const sampleWindow = window as typeof window & {
  2384. __zcodeBg17UserMessageSampler?: {
  2385. intervalId: ReturnType<typeof setInterval>;
  2386. samples: VisibleUserMessageSample[];
  2387. };
  2388. };
  2389. const sampler = sampleWindow.__zcodeBg17UserMessageSampler;
  2390. if (!sampler) {
  2391. return [] satisfies VisibleUserMessageSample[];
  2392. }
  2393. clearInterval(sampler.intervalId);
  2394. delete sampleWindow.__zcodeBg17UserMessageSampler;
  2395. return sampler.samples;
  2396. });
  2397. }
  2398. function assertVisibleUserMessageMarkersNeverDisappear(
  2399. samples: readonly VisibleUserMessageSample[],
  2400. markers: readonly string[],
  2401. ) {
  2402. const seen = new Set<string>();
  2403. const violations: Array<{
  2404. marker: string;
  2405. sampleIndex: number;
  2406. at: number;
  2407. messages: VisibleUserMessageSample["messages"];
  2408. }> = [];
  2409. for (const [sampleIndex, sample] of samples.entries()) {
  2410. const presentMarkers = new Set(
  2411. markers.filter((marker) => sample.messages.some((message) => message.text.includes(marker))),
  2412. );
  2413. for (const marker of presentMarkers) {
  2414. seen.add(marker);
  2415. }
  2416. for (const marker of seen) {
  2417. if (!presentMarkers.has(marker)) {
  2418. violations.push({
  2419. marker,
  2420. sampleIndex,
  2421. at: sample.at,
  2422. messages: sample.messages,
  2423. });
  2424. }
  2425. }
  2426. }
  2427. expect(violations).toEqual([]);
  2428. }
  2429. async function waitForIdle(timeoutMsg: string) {
  2430. return waitForV4ConversationState(
  2431. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  2432. timeoutMsg,
  2433. 90000,
  2434. );
  2435. }
  2436. async function assertNoVisibleTaskNotification() {
  2437. await assertVisibleV4UserMessagesNotContaining("<task-notification>");
  2438. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_AGENT_CHILD_RESULT");
  2439. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_GOAL_CHILD_RESULT");
  2440. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_SEND_MESSAGE_CHILD_RECEIVED");
  2441. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_DONE");
  2442. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_COMPACT_AFTER_IDLE_DONE");
  2443. await assertVisibleV4UserMessagesNotContaining(
  2444. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_CHILD_DONE",
  2445. );
  2446. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_NESTED_BASH_CHILD_DONE");
  2447. }
  2448. async function assertNoMainFakeLoading(timeoutMsg: string) {
  2449. await browser.pause(600);
  2450. const [snapshot, loadingTexts] = await Promise.all([
  2451. getV4ConversationState(),
  2452. getVisibleChatLoadingTexts(),
  2453. ]);
  2454. if (snapshot.state === "streaming" || loadingTexts.length > 0) {
  2455. throw new Error(
  2456. `${timeoutMsg}; state=${JSON.stringify(snapshot)}; loading=${JSON.stringify(loadingTexts)}`,
  2457. );
  2458. }
  2459. }
  2460. async function waitForMainLoading(timeoutMsg: string) {
  2461. let latestSnapshot = await getV4ConversationState();
  2462. let latestLoadingTexts: string[] = [];
  2463. await browser.waitUntil(
  2464. async () => {
  2465. latestSnapshot = await getV4ConversationState();
  2466. latestLoadingTexts = await getVisibleChatLoadingTexts();
  2467. // Bugfix: Windows Electron 下 foreground Bash 有时只暴露 chat root streaming 状态,
  2468. // 不稳定渲染旧的底部 loading 节点;这里验证主会话没有退成 background-only idle 即可。
  2469. return latestSnapshot.state === "streaming";
  2470. },
  2471. {
  2472. interval: 100,
  2473. timeout: 5000,
  2474. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(
  2475. latestSnapshot,
  2476. )}; loading=${JSON.stringify(latestLoadingTexts)}`,
  2477. },
  2478. );
  2479. }
  2480. async function getVisibleChatLoadingTexts(): Promise<string[]> {
  2481. return browser.execute((chatLoadingTestId) => {
  2482. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2483. const isElementVisible = (element: HTMLElement) =>
  2484. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2485. return Array.from(
  2486. document.querySelectorAll<HTMLElement>(`[data-testid="${chatLoadingTestId}"]`),
  2487. )
  2488. .filter(isElementVisible)
  2489. .map((element) => element.innerText.replace(/\u00a0/g, " ").trim());
  2490. }, TID_CHAT_LOADING);
  2491. }
  2492. async function assertNoMainToolCallById(toolCallId: string, failureMessage: string) {
  2493. const blocks = await listToolCallBlocks();
  2494. const mirrored = blocks.filter((block) => block.toolCallId?.includes(toolCallId));
  2495. if (mirrored.length > 0) {
  2496. throw new Error(`${failureMessage}; mirrored=${JSON.stringify(mirrored)}`);
  2497. }
  2498. }
  2499. async function beginBackgroundTelemetryCapture() {
  2500. // 跨 case 复用采集器会混入中间用例的 completion,失败后游标也可能只推进一半。
  2501. // 每条 case 从空 HTTP 调用记录和 ARMS 缓冲开始,保留精确数量断言。
  2502. const capture = await beginConversationTelemetryCapture();
  2503. await capture.telemetryFetch.mockClear();
  2504. return capture;
  2505. }
  2506. async function startNewBackgroundDraft() {
  2507. // Bash fixture 的相对路径属于夹具项目;全局新建会切到另一个 cwd,读不到 PID/释放文件。
  2508. // 初始空草稿直接复用,避免准备步骤重复新建;已有任务仍走同一项目的新建入口。
  2509. await prepareV4ConversationE2E({ skipProvider: true });
  2510. // Bug 根因:suite 只在 before 设置 yolo,新草稿恢复默认 build 后 child Bash 会停在审批。
  2511. // 生命周期用例在每次 draft admission 前固定前置;权限代理仍由独立 interaction spec 验证。
  2512. await ensureToolCrossProductFullAccessMode();
  2513. }
  2514. async function respondToBackgroundBlockers() {
  2515. // Full access 前置条件下正常路径没有 blocker;只做一次兼容探测,不能再固定等待
  2516. // 3 秒,否则 4 秒 child Bash 会在 UI running 断言前结束,掩盖真实生命周期窗口。
  2517. await respondToToolCrossProductBlockers();
  2518. }
  2519. type BackgroundTaskControlKind = "agent" | "bash";
  2520. interface BackgroundTaskControlRowSnapshot {
  2521. buttonDisabled: boolean;
  2522. kind: string | null;
  2523. text: string;
  2524. visible: boolean;
  2525. }
  2526. interface BackgroundTaskProjectionSnapshot {
  2527. projectionSeq: string | null;
  2528. runningSubagentIds: string | null;
  2529. runningSubagentWorkIds: string | null;
  2530. sessionId: string | null;
  2531. }
  2532. async function waitForBackgroundTaskControlRow(
  2533. kind: BackgroundTaskControlKind,
  2534. textIncludes: string,
  2535. timeoutMsg: string,
  2536. ) {
  2537. let latest: BackgroundTaskControlRowSnapshot[] = [];
  2538. let projection: BackgroundTaskProjectionSnapshot | null = null;
  2539. await browser.waitUntil(
  2540. async () => {
  2541. try {
  2542. await openV4ComposerRunningBackgroundWorks();
  2543. } catch (error) {
  2544. projection = await getBackgroundTaskProjectionSnapshot();
  2545. throw new Error(
  2546. `${error instanceof Error ? error.message : String(error)}; projection=${JSON.stringify(projection)}`,
  2547. { cause: error },
  2548. );
  2549. }
  2550. latest = await getBackgroundTaskControlRows({ visibleOnly: false });
  2551. return latest.some(
  2552. (row) => row.visible && row.kind === kind && row.text.includes(textIncludes),
  2553. );
  2554. },
  2555. {
  2556. interval: 250,
  2557. timeout: 30000,
  2558. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}; projection=${JSON.stringify(projection)}`,
  2559. },
  2560. );
  2561. }
  2562. async function getBackgroundTaskProjectionSnapshot(): Promise<BackgroundTaskProjectionSnapshot> {
  2563. return browser.execute(
  2564. (paneTestId) => {
  2565. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  2566. return {
  2567. projectionSeq: pane?.getAttribute("data-projection-seq") ?? null,
  2568. runningSubagentIds: pane?.getAttribute("data-running-subagent-ids") ?? null,
  2569. runningSubagentWorkIds: pane?.getAttribute("data-running-subagent-work-ids") ?? null,
  2570. sessionId: pane?.getAttribute("data-session-id") ?? null,
  2571. };
  2572. },
  2573. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  2574. );
  2575. }
  2576. async function waitForNoBackgroundTaskControlRow(
  2577. kind: BackgroundTaskControlKind,
  2578. textIncludes: string,
  2579. timeoutMsg: string,
  2580. ) {
  2581. let latest: BackgroundTaskControlRowSnapshot[] = [];
  2582. await browser.waitUntil(
  2583. async () => {
  2584. latest = await getBackgroundTaskControlRows({ visibleOnly: false });
  2585. return !latest.some((row) => row.kind === kind && row.text.includes(textIncludes));
  2586. },
  2587. {
  2588. interval: 250,
  2589. timeout: 30000,
  2590. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}`,
  2591. },
  2592. );
  2593. }
  2594. interface BackgroundTaskControlPresenceProbeResult {
  2595. missingTransitions: Array<{
  2596. atMs: number;
  2597. panelState: string | null;
  2598. rows: string[];
  2599. storeJobs: string[];
  2600. }>;
  2601. observedPresent: boolean;
  2602. }
  2603. async function startBackgroundTaskControlPresenceProbe(
  2604. kind: BackgroundTaskControlKind,
  2605. textIncludes: string,
  2606. taskId: string,
  2607. ) {
  2608. await openV4ComposerRunningBackgroundWorks();
  2609. await browser.execute(
  2610. (expectedKind, expectedText, expectedTaskId, v4SessionPanePrefix) => {
  2611. const probeKey = "__zcodeBackgroundTaskControlPresenceProbe";
  2612. const probeWindow = window as typeof window & {
  2613. __zcodeBackgroundTaskControlPresenceProbe?: {
  2614. intervalId: number;
  2615. missingTransitions: Array<{
  2616. atMs: number;
  2617. panelState: string | null;
  2618. rows: string[];
  2619. storeJobs: string[];
  2620. }>;
  2621. hasLeftTask: boolean;
  2622. hasReturnedToTask: boolean;
  2623. observedPresent: boolean;
  2624. startedAt: number;
  2625. wasPresent: boolean | null;
  2626. };
  2627. };
  2628. const existing = probeWindow[probeKey];
  2629. if (existing) {
  2630. window.clearInterval(existing.intervalId);
  2631. }
  2632. const state: NonNullable<(typeof probeWindow)[typeof probeKey]> = {
  2633. intervalId: 0,
  2634. missingTransitions: [],
  2635. hasLeftTask: false,
  2636. hasReturnedToTask: false,
  2637. observedPresent: false,
  2638. startedAt: performance.now(),
  2639. wasPresent: null,
  2640. };
  2641. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2642. const isElementVisible = (element: HTMLElement) =>
  2643. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2644. const sample = () => {
  2645. const legacyTaskId = document
  2646. .querySelector<HTMLElement>('[data-testid="chat-view"]')
  2647. ?.getAttribute("data-task-id");
  2648. const v4SessionId = document
  2649. .querySelector<HTMLElement>(`[data-testid="${v4SessionPanePrefix}-workspace-main"]`)
  2650. ?.getAttribute("data-session-id");
  2651. // Bug 根因:V4 无 legacy chat-view;presence probe 需要从主 pane
  2652. // 读取 session id,否则切回目标 task 后仍会被误判成“尚未返回”。
  2653. const activeTaskId =
  2654. legacyTaskId || (v4SessionId && v4SessionId !== "draft" ? v4SessionId : null);
  2655. if (activeTaskId !== expectedTaskId) {
  2656. state.hasLeftTask = true;
  2657. state.wasPresent = null;
  2658. return;
  2659. }
  2660. if (state.hasLeftTask) {
  2661. state.hasReturnedToTask = true;
  2662. }
  2663. const rows = Array.from(
  2664. document.querySelectorAll<HTMLElement>("[data-background-task-kind]"),
  2665. );
  2666. const present = rows.some(
  2667. (row) =>
  2668. row.getAttribute("data-background-task-kind") === expectedKind &&
  2669. row.innerText.includes(expectedText) &&
  2670. isElementVisible(row),
  2671. );
  2672. state.observedPresent ||= present;
  2673. if (state.hasReturnedToTask && state.wasPresent === true && !present) {
  2674. const store = (
  2675. window as typeof window & {
  2676. __zcodeSessionStoreE2E?: {
  2677. getState: () => {
  2678. workspaces: Record<
  2679. string,
  2680. {
  2681. taskRuntimeByTaskId?: Record<
  2682. string,
  2683. {
  2684. backgroundTaskControls?: Array<{
  2685. jobId: string;
  2686. status: string;
  2687. title?: string;
  2688. }>;
  2689. }
  2690. >;
  2691. }
  2692. >;
  2693. };
  2694. };
  2695. }
  2696. ).__zcodeSessionStoreE2E;
  2697. const taskRuntime = Object.values(store?.getState().workspaces ?? {})
  2698. .map((workspace) => workspace.taskRuntimeByTaskId?.[expectedTaskId])
  2699. .find(Boolean);
  2700. state.missingTransitions.push({
  2701. atMs: Math.round(performance.now() - state.startedAt),
  2702. panelState:
  2703. document
  2704. .querySelector<HTMLElement>('[data-testid="chat-summary-panel"]')
  2705. ?.getAttribute("data-state") ?? null,
  2706. rows: rows.map((row) => row.innerText.replace(/\u00a0/g, " ").trim()),
  2707. storeJobs: (taskRuntime?.backgroundTaskControls ?? []).map(
  2708. (job) => `${job.jobId}:${job.status}:${job.title ?? ""}`,
  2709. ),
  2710. });
  2711. }
  2712. state.wasPresent = present;
  2713. };
  2714. sample();
  2715. state.intervalId = window.setInterval(sample, 16);
  2716. probeWindow[probeKey] = state;
  2717. },
  2718. kind,
  2719. textIncludes,
  2720. taskId,
  2721. TID_V4_SESSION_PANE,
  2722. );
  2723. }
  2724. async function stopBackgroundTaskControlPresenceProbe(): Promise<BackgroundTaskControlPresenceProbeResult> {
  2725. return browser.execute(() => {
  2726. const probeKey = "__zcodeBackgroundTaskControlPresenceProbe";
  2727. const probeWindow = window as typeof window & {
  2728. __zcodeBackgroundTaskControlPresenceProbe?: {
  2729. intervalId: number;
  2730. missingTransitions: BackgroundTaskControlPresenceProbeResult["missingTransitions"];
  2731. observedPresent: boolean;
  2732. };
  2733. };
  2734. const state = probeWindow[probeKey];
  2735. if (!state) {
  2736. return { missingTransitions: [], observedPresent: false };
  2737. }
  2738. window.clearInterval(state.intervalId);
  2739. delete probeWindow[probeKey];
  2740. return {
  2741. missingTransitions: state.missingTransitions,
  2742. observedPresent: state.observedPresent,
  2743. };
  2744. });
  2745. }
  2746. async function clickStopBackgroundTaskControlRow(
  2747. kind: BackgroundTaskControlKind,
  2748. textIncludes: string,
  2749. ) {
  2750. let latest:
  2751. | { clicked: true; rows: [] }
  2752. | { clicked: false; rows: BackgroundTaskControlRowSnapshot[] } = {
  2753. clicked: false,
  2754. rows: [],
  2755. };
  2756. await browser.waitUntil(
  2757. async () => {
  2758. await openV4ComposerRunningBackgroundWorks();
  2759. latest = await browser.execute(
  2760. (expectedKind, expectedText, cancelButtonPrefix) => {
  2761. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2762. const isElementVisible = (element: HTMLElement) =>
  2763. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2764. const rows = Array.from(
  2765. document.querySelectorAll<HTMLElement>("[data-background-task-kind]"),
  2766. );
  2767. const row = rows.find(
  2768. (candidate) =>
  2769. isElementVisible(candidate) &&
  2770. candidate.getAttribute("data-background-task-kind") === expectedKind &&
  2771. candidate.innerText.includes(expectedText),
  2772. );
  2773. // Bug 根因:V4 Agent 行的第一个 button 是透明的 child session 下钻入口,
  2774. // 旧 helper 会误点详情而没有发出 stop。取消动作必须按专用 test id 定位。
  2775. const button = row?.querySelector<HTMLButtonElement>(
  2776. `[data-testid^="${cancelButtonPrefix}-"]`,
  2777. );
  2778. if (!row || !button || button.disabled || !isElementVisible(button)) {
  2779. return {
  2780. clicked: false,
  2781. rows: rows.map((candidate) => ({
  2782. buttonDisabled:
  2783. candidate.querySelector<HTMLButtonElement>("button")?.disabled ?? false,
  2784. kind: candidate.getAttribute("data-background-task-kind"),
  2785. text: candidate.innerText.replace(/\u00a0/g, " ").trim(),
  2786. visible: isElementVisible(candidate),
  2787. })),
  2788. };
  2789. }
  2790. button.click();
  2791. return { clicked: true, rows: [] };
  2792. },
  2793. kind,
  2794. textIncludes,
  2795. TID_V4_BACKGROUND_WORK_CANCEL,
  2796. );
  2797. return latest.clicked;
  2798. },
  2799. {
  2800. interval: 250,
  2801. timeout: 30000,
  2802. timeoutMsg: `没有点击到 background control stop button: ${JSON.stringify(latest)}`,
  2803. },
  2804. );
  2805. }
  2806. async function getBackgroundTaskControlRows({
  2807. visibleOnly,
  2808. }: {
  2809. visibleOnly: boolean;
  2810. }): Promise<BackgroundTaskControlRowSnapshot[]> {
  2811. return browser.execute((filterVisible) => {
  2812. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2813. const isElementVisible = (element: HTMLElement) =>
  2814. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2815. return Array.from(document.querySelectorAll<HTMLElement>("[data-background-task-kind]"))
  2816. .map((row) => ({
  2817. buttonDisabled: row.querySelector<HTMLButtonElement>("button")?.disabled ?? false,
  2818. kind: row.getAttribute("data-background-task-kind"),
  2819. text: row.innerText.replace(/\u00a0/g, " ").trim(),
  2820. visible: isElementVisible(row),
  2821. }))
  2822. .filter((row) => !filterVisible || row.visible);
  2823. }, visibleOnly);
  2824. }
  2825. async function stopIfBusy() {
  2826. const snapshot = await getV4ConversationState().catch(() => null);
  2827. if (snapshot?.state !== "streaming" || snapshot.stopRequested) {
  2828. return;
  2829. }
  2830. await browser.keys(["Escape"]).catch(() => undefined);
  2831. await waitForV4ConversationState(
  2832. (candidate) => candidate.state !== "streaming" || candidate.stopRequested,
  2833. "background E2E 收尾时没有停止当前运行",
  2834. 30000,
  2835. ).catch(() => undefined);
  2836. }
  2837. function assertBackgroundToolStepTelemetry(
  2838. reports: ConversationTelemetryReport[],
  2839. childToolCallId: string,
  2840. ): void {
  2841. const backgroundSteps = reports.filter(
  2842. (report) =>
  2843. report.element_name === "agent_step" &&
  2844. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_role ===
  2845. "background subagent",
  2846. );
  2847. expect(backgroundSteps).toHaveLength(2);
  2848. const detail = backgroundSteps[0]?.event_extra_detail as Record<string, unknown> | undefined;
  2849. expect(detail).toMatchObject({
  2850. agent_role: "background subagent",
  2851. step_type: "tool_call",
  2852. status: "success",
  2853. tool_name: "Bash",
  2854. loop_index: "1",
  2855. token_usage_scope: "",
  2856. total_tokens: "0",
  2857. });
  2858. expect(typeof detail?.agent_id).toBe("string");
  2859. expect(String(detail?.agent_id)).not.toHaveLength(0);
  2860. expect(typeof detail?.model_name).toBe("string");
  2861. expect(detail?.model_name).not.toBe("");
  2862. expect(typeof detail?.model_provider).toBe("string");
  2863. expect(detail?.model_provider).not.toBe("");
  2864. expect(typeof detail?.provider_name).toBe("string");
  2865. expect(detail?.provider_name).not.toBe("");
  2866. expect(typeof backgroundSteps[0]?.message_id).toBe("string");
  2867. expect(backgroundSteps[0]?.message_id).not.toBe("");
  2868. expect(typeof backgroundSteps[0]?.talk_id).toBe("string");
  2869. expect(backgroundSteps[0]?.talk_id).not.toBe("");
  2870. expect(String(detail?.tool_call_id)).toBe(
  2871. `tool_subagent_${String(detail?.agent_id)}_${childToolCallId}`,
  2872. );
  2873. // 两个 fixture child 请求各 input=128,tool_use output=16、最终 text output=12。
  2874. // usage 只出现在收口 Agent step,不能复制到 child Bash,也不能串到后续 main turn。
  2875. const aggregate = backgroundSteps[1]!;
  2876. const aggregateDetail = aggregate.event_extra_detail as Record<string, unknown>;
  2877. expect(aggregateDetail).toMatchObject({
  2878. agent_role: "background subagent",
  2879. agent_id: detail?.agent_id,
  2880. step_type: "tool_call",
  2881. tool_name: "Agent",
  2882. status: "success",
  2883. loop_index: "2",
  2884. token_usage_scope: "subagent_requests",
  2885. model_request_count: "2",
  2886. input_tokens: "256",
  2887. output_tokens: "28",
  2888. total_tokens: "284",
  2889. model_name: detail?.model_name,
  2890. model_provider: detail?.model_provider,
  2891. provider_name: detail?.provider_name,
  2892. });
  2893. expect(aggregateDetail.tool_call_id).toBe(
  2894. `tool_subagent_${String(detail?.agent_id)}_${String(aggregateDetail.parent_tool_call_id)}`,
  2895. );
  2896. const completions = reports.filter((report) => report.element_name === "message_completion");
  2897. expect(aggregate.message_id).toBe(completions[0]?.message_id);
  2898. expect(aggregate.message_id).toBe(backgroundSteps[0]?.message_id);
  2899. expect(reports.indexOf(aggregate)).toBeGreaterThan(reports.indexOf(completions[0]!));
  2900. for (const completion of completions) {
  2901. expect(completion.message_id).toMatch(
  2902. /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
  2903. );
  2904. expect(
  2905. reports.filter(
  2906. (report) =>
  2907. report.element_name === "agent_step" &&
  2908. report.message_id === completion.message_id &&
  2909. !(report.event_extra_detail as Record<string, unknown>)?.agent_role,
  2910. ).length,
  2911. ).toBeGreaterThan(0);
  2912. }
  2913. expect(
  2914. reports.filter(
  2915. (report) =>
  2916. report.element_name === "message_completion" &&
  2917. ["child_session_id", "parent_tool_call_id"].some((key) =>
  2918. Object.hasOwn(
  2919. (report.event_extra_detail as Record<string, unknown> | undefined) ?? {},
  2920. key,
  2921. ),
  2922. ),
  2923. ),
  2924. ).toHaveLength(0);
  2925. }
  2926. function assertMainCompletionAgentCompositions(
  2927. reports: ConversationTelemetryReport[],
  2928. expectedCompositions: string[],
  2929. ): void {
  2930. const completions = reports.filter((report) => report.element_name === "message_completion");
  2931. expect(completions).toHaveLength(expectedCompositions.length);
  2932. expect(
  2933. completions.map(
  2934. (report) =>
  2935. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_composition,
  2936. ),
  2937. ).toEqual(expectedCompositions);
  2938. const messageIds = completions.map((report) => String(report.message_id ?? ""));
  2939. expect(messageIds.every((messageId) => messageId.length > 0)).toBe(true);
  2940. expect(new Set(messageIds).size).toBe(messageIds.length);
  2941. }
  2942. function assertMainCompletionMessageSources(
  2943. reports: ConversationTelemetryReport[],
  2944. expectedSources: string[],
  2945. ): void {
  2946. const completions = reports.filter((report) => report.element_name === "message_completion");
  2947. expect(completions).toHaveLength(expectedSources.length);
  2948. expect(
  2949. completions.map(
  2950. (report) =>
  2951. (report.event_extra_detail as Record<string, unknown> | undefined)?.message_source,
  2952. ),
  2953. ).toEqual(expectedSources);
  2954. }