conversation-session-background.test.ts 124 KB

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