v4-conversation.ts 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833
  1. /* eslint-disable max-lines -- v4 conversation e2e helper 集中承载 pane/composer/queue/分屏等全部定位与断言原语,拆分会让 spec 的导入面漂移。 */
  2. // v4 竖切(protocol-v4)conversation e2e helper。
  3. // 与旧 conversation-session.ts 的区别:所有定位走 TID_V4_* 常量(testid contract v2,
  4. // 带 paneId 维度),状态断言读 v4 pane 的 data-* 投影属性,不再依赖旧 ChatView DOM。
  5. // 旧 helper 的登录/工作区/provider 部分继续复用(desktop-app.ts / upstream-provider.ts)。
  6. import {
  7. TID_CHAT_MODE_SELECT_ITEM,
  8. TID_CHAT_MODE_SELECT_TRIGGER,
  9. TID_CHAT_SUMMARY_PANEL,
  10. TID_CHAT_MODEL_SELECT_GROUP,
  11. TID_CHAT_MODEL_SELECT_ITEM,
  12. TID_CHAT_MODEL_SELECT_TRIGGER,
  13. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  14. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  15. TID_PROMPT_SUGGESTION_OPTION,
  16. TID_PROMPT_SUGGESTION_PANEL,
  17. TID_LOGIN_API_KEY_CONTINUE_BUTTON,
  18. TID_LOGIN_API_KEY_INPUT,
  19. TID_LOGIN_USE_API_KEY_BUTTON,
  20. TID_TASK_ITEM,
  21. TID_TASK_NEW_BUTTON,
  22. TID_V4_AUTODRAIN_TOGGLE,
  23. TID_V4_ATTACHMENT,
  24. TID_V4_BACKGROUND_WORK_ITEM,
  25. TID_V4_COMPOSER,
  26. TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER,
  27. TID_V4_COMPOSER_CLEAR_QUEUE_SEND,
  28. TID_V4_COMPOSER_INPUT,
  29. TID_V4_COMPOSER_KEEP_QUEUE_SEND,
  30. TID_V4_COMPOSER_SEND,
  31. TID_V4_DELETE_SESSION,
  32. TID_V4_EDIT,
  33. TID_V4_EDIT_INPUT,
  34. TID_V4_EDIT_REWIND_WORKSPACE,
  35. TID_V4_EDIT_SUBMIT,
  36. TID_V4_EDIT_WORKSPACE_CONFLICT_CONVERSATION_ONLY,
  37. TID_V4_EDIT_WORKSPACE_CONFLICT_DIALOG,
  38. TID_V4_FOLLOWUP_TOGGLE,
  39. TID_V4_MODEL_CONFIG,
  40. TID_V4_PAUSED_QUEUE_SEND_DIALOG,
  41. TID_V4_PANE_SHELL,
  42. TID_V4_QUEUE,
  43. TID_V4_QUEUE_ITEM,
  44. TID_V4_QUEUE_PAUSED_BANNER,
  45. TID_V4_QUEUE_RESUME,
  46. TID_V4_RENAME_INPUT,
  47. TID_V4_RENAME_SUBMIT,
  48. TID_V4_ROW,
  49. TID_V4_ROW_ATTACHMENTS,
  50. TID_V4_SESSION_PANE,
  51. TID_V4_SESSION_TITLE,
  52. TID_V4_SPLIT_CLOSE,
  53. TID_V4_SPLIT_DOWN,
  54. TID_V4_SPLIT_DIVIDER,
  55. TID_V4_SPLIT_OPEN,
  56. TID_V4_TASK_OPEN_IN_SPLIT,
  57. TID_V4_STOP,
  58. TID_V4_TIMELINE,
  59. TID_V4_TIMELINE_BOTTOM,
  60. TID_V4_TURN_NAVIGATOR,
  61. TID_V4_TURN_NAVIGATOR_ITEM,
  62. TID_V4_TURN_NAVIGATOR_TOOLTIP,
  63. encodeCustomModelValue,
  64. testId,
  65. } from "@zcode/shared";
  66. import {
  67. clickTestIdByDom,
  68. dispatchMouseDownByExactTestId,
  69. setInputValueByTestIdDom,
  70. waitForDefaultWorkspaceReady,
  71. } from "./desktop-app.js";
  72. import {
  73. ensureUpstreamProviderForE2E,
  74. selectUpstreamModel,
  75. selectUpstreamThoughtLevel,
  76. } from "./upstream-provider.js";
  77. import { readV4ChatRootSnapshotInBrowser } from "./conversation-session-chat-root-snapshot-script.js";
  78. import { getTaskStoreSnapshot as readTaskStoreSnapshotForDiagnostics } from "./conversation-session-store.js";
  79. import { sel } from "./selectors.js";
  80. import { skipOccupationOnboardingIfPresent } from "./occupation-onboarding.js";
  81. export const LOGIN_API_KEY = "e2e-login-api-key";
  82. export const E2E_REPLY_TOKEN = "upstream-e2e-ok";
  83. interface PrepareV4ConversationE2EOptions {
  84. resetDraftBeforeProvider?: boolean;
  85. skipProvider?: boolean;
  86. }
  87. /** 单 pane 竖切固定 paneId(V4ChatPane 写死 workspace-main)。 */
  88. export const V4_MAIN_PANE_ID = "workspace-main";
  89. export interface V4PaneSnapshot {
  90. /** data-session-id;draft 表示未绑定 CLI session。 */
  91. sessionId: string | null;
  92. initialDraftProvider: string;
  93. initialDraftModel: string;
  94. /** stop 按钮是否存在(= projection.control.canStop)。 */
  95. canStop: boolean;
  96. /** timeline 全部行文本(虚拟滚动下为当前渲染窗口内的行)。 */
  97. timelineText: string;
  98. rowCount: number;
  99. }
  100. export interface V4CompactMarkerSnapshot {
  101. origin: string | null;
  102. rowId: number | null;
  103. status: string | null;
  104. text: string;
  105. }
  106. export interface V4ConversationStateSnapshot {
  107. activeInputId: string | null;
  108. modelSwitchPending: boolean;
  109. queueCount: number;
  110. runtimeStatus: string | null;
  111. sessionId: string | null;
  112. state: string | null;
  113. stopRequested: boolean;
  114. targetId: string | null;
  115. targetObjective: string | null;
  116. targetStatus: string | null;
  117. taskId: string | null;
  118. }
  119. export interface V4MessageSnapshot {
  120. id: string | null;
  121. role: "assistant" | "user";
  122. text: string;
  123. }
  124. export async function prepareV4ConversationE2E(options: PrepareV4ConversationE2EOptions = {}) {
  125. await ensureV4ShellReady();
  126. if (options.resetDraftBeforeProvider) {
  127. // 修复原因:正式用例若停留在旧 active session,provider 初始化可能把默认模型
  128. // 写回旧 session;先切到 v4 空草稿,保持旧 helper 的隔离语义但不再依赖 legacy DOM。
  129. await startNewV4Draft();
  130. }
  131. if (!options.skipProvider) {
  132. await ensureUpstreamProviderForE2E({ skipToolbarSelection: true });
  133. }
  134. await startNewV4Draft();
  135. if (!options.skipProvider) {
  136. // 新 Composer 会保留已经初始化的空选择。仅写 Recent 不能覆盖这个草稿;
  137. // 测试准备必须像用户一样选择目标模型和档位,不能依赖旧初始化副作用。
  138. await selectUpstreamModel();
  139. await selectUpstreamThoughtLevel();
  140. }
  141. }
  142. async function ensureV4ShellReady() {
  143. try {
  144. // 新隔离 profile 的职业引导会遮住工作区,先复用真实 UI 跳过流程。
  145. await skipOccupationOnboardingIfPresent();
  146. await waitForDefaultWorkspaceReady(30000);
  147. return;
  148. } catch (error) {
  149. if (!(await hasApiKeyLoginButton())) {
  150. throw error;
  151. }
  152. await loginWithApiKey();
  153. await skipOccupationOnboardingIfPresent();
  154. await waitForDefaultWorkspaceReady(30000);
  155. }
  156. }
  157. async function hasApiKeyLoginButton() {
  158. const exists = await browser
  159. .execute(
  160. (currentTestId) => Boolean(document.querySelector(`[data-testid="${currentTestId}"]`)),
  161. TID_LOGIN_USE_API_KEY_BUTTON,
  162. )
  163. .catch(() => false);
  164. return Boolean(exists);
  165. }
  166. export async function loginWithApiKey() {
  167. await clickTestIdByDom(TID_LOGIN_USE_API_KEY_BUTTON, {
  168. timeout: 30000,
  169. timeoutMsg: "欢迎页没有出现 API Key 登录入口",
  170. });
  171. await setInputValueByTestIdDom(TID_LOGIN_API_KEY_INPUT, LOGIN_API_KEY, {
  172. timeout: 15000,
  173. timeoutMsg: "API Key 登录输入框没有出现",
  174. });
  175. await browser.waitUntil(
  176. async () =>
  177. browser.execute((continueButtonTestId) => {
  178. const button = document.querySelector<HTMLElement>(
  179. `[data-testid="${continueButtonTestId}"]`,
  180. );
  181. return button instanceof HTMLButtonElement && !button.disabled;
  182. }, TID_LOGIN_API_KEY_CONTINUE_BUTTON),
  183. {
  184. timeout: 15000,
  185. timeoutMsg: "API Key 登录继续按钮没有变为可用",
  186. },
  187. );
  188. await clickTestIdByDom(TID_LOGIN_API_KEY_CONTINUE_BUTTON, {
  189. timeout: 15000,
  190. timeoutMsg: "API Key 登录继续按钮没有出现或不可点击",
  191. });
  192. }
  193. /** 新建草稿:点侧栏新任务按钮,等 v4 pane 回到 draft 态。 */
  194. export async function startNewV4Draft() {
  195. await clickTestIdByDom(TID_TASK_NEW_BUTTON, {
  196. timeout: 15000,
  197. timeoutMsg: "侧栏新任务按钮没有出现或不可点击",
  198. });
  199. await waitForV4Pane(
  200. (snapshot) => snapshot.sessionId === "draft",
  201. "新建任务后 v4 pane 没有回到 draft 态",
  202. );
  203. }
  204. export function getV4PaneSnapshot(paneId: string = V4_MAIN_PANE_ID): Promise<V4PaneSnapshot> {
  205. return browser.execute(
  206. (paneTestId, stopTestId, timelineTestId, rowPrefix) => {
  207. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  208. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  209. return {
  210. sessionId: pane?.getAttribute("data-session-id") ?? null,
  211. initialDraftProvider: pane?.getAttribute("data-initial-draft-provider") ?? "",
  212. initialDraftModel: pane?.getAttribute("data-initial-draft-model") ?? "",
  213. canStop: Boolean(pane?.querySelector(`[data-testid="${stopTestId}"]`)),
  214. timelineText: (timeline?.innerText ?? "").replace(/ /g, " "),
  215. rowCount: pane?.querySelectorAll(`[data-testid^="${rowPrefix}-"]`).length ?? 0,
  216. };
  217. },
  218. testId(TID_V4_SESSION_PANE, paneId),
  219. TID_V4_STOP,
  220. TID_V4_TIMELINE,
  221. TID_V4_ROW,
  222. );
  223. }
  224. export async function waitForV4Pane(
  225. predicate: (snapshot: V4PaneSnapshot) => boolean,
  226. timeoutMsg: string,
  227. timeout = 30000,
  228. paneId: string = V4_MAIN_PANE_ID,
  229. ) {
  230. let latest: V4PaneSnapshot | null = null;
  231. try {
  232. await browser.waitUntil(
  233. async () => {
  234. latest = await getV4PaneSnapshot(paneId);
  235. return predicate(latest);
  236. },
  237. { timeout, timeoutMsg },
  238. );
  239. } catch (error) {
  240. latest = await getV4PaneSnapshot(paneId);
  241. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  242. cause: error,
  243. });
  244. }
  245. // 原因:会话切换时 pane 可能短暂经过 draft。waitUntil 已命中目标快照后若再读一次 DOM,
  246. // 调用方拿到的可能反而是下一帧过渡态,造成“条件通过但返回值不满足条件”的假失败。
  247. return latest ?? getV4PaneSnapshot(paneId);
  248. }
  249. export async function waitForV4ConversationState(
  250. predicate: (snapshot: V4ConversationStateSnapshot) => boolean,
  251. timeoutMsg: string,
  252. timeout = 30000,
  253. ) {
  254. let latest: V4ConversationStateSnapshot | null = null;
  255. try {
  256. await browser.waitUntil(
  257. async () => {
  258. latest = await getV4ConversationState();
  259. return predicate(latest);
  260. },
  261. { timeout, timeoutMsg },
  262. );
  263. } catch (error) {
  264. latest = await getV4ConversationState();
  265. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  266. cause: error,
  267. });
  268. }
  269. // 修复原因:命中 predicate 后再次读取会跨过 running/completed 瞬时边界,
  270. // 让调用方拿到与 waitUntil 判定不一致的状态。
  271. return latest ?? getV4ConversationState();
  272. }
  273. export async function getV4ConversationState(): Promise<V4ConversationStateSnapshot> {
  274. const browserSnapshot = await browser.execute(
  275. readV4ChatRootSnapshotInBrowser,
  276. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  277. TID_V4_QUEUE_ITEM,
  278. TID_V4_STOP,
  279. );
  280. if (browserSnapshot.bridgeError) {
  281. throw new Error(
  282. `无法读取 V4 conversation workspace: ${browserSnapshot.bridgeError}; ` +
  283. `workspaceKey=${browserSnapshot.workspaceKey}; paneSessionId=${browserSnapshot.paneSessionId}`,
  284. );
  285. }
  286. if (!browserSnapshot.taskId) {
  287. return {
  288. activeInputId: null,
  289. modelSwitchPending: browserSnapshot.modelSwitchPending,
  290. queueCount: browserSnapshot.queueCount,
  291. runtimeStatus: browserSnapshot.runtimeStatus,
  292. sessionId: null,
  293. state: browserSnapshot.runtimeStatus === "streaming" ? "streaming" : "idle",
  294. stopRequested: false,
  295. targetId: null,
  296. targetObjective: null,
  297. targetStatus: null,
  298. taskId: null,
  299. };
  300. }
  301. const taskStore = await readTaskStoreSnapshotForDiagnostics(
  302. browserSnapshot.taskId,
  303. browserSnapshot.workspaceKey ?? undefined,
  304. );
  305. if (!taskStore.workspaceKey) {
  306. throw new Error(
  307. `无法读取 V4 conversation task: ${taskStore.error}; ` +
  308. `workspaceKey=${browserSnapshot.workspaceKey}; taskId=${browserSnapshot.taskId}`,
  309. );
  310. }
  311. const goalProjection = await browser.execute(
  312. (paneTestId, panelTestId) => {
  313. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  314. const panel = pane?.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  315. if (!panel) return null;
  316. return {
  317. objective: panel.getAttribute("data-goal-objective"),
  318. status: panel.getAttribute("data-goal-status"),
  319. };
  320. },
  321. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  322. TID_CHAT_SUMMARY_PANEL,
  323. );
  324. const hasBlockingGoalWork =
  325. goalProjection?.status === "active" || goalProjection?.status === "verifying";
  326. const effectiveRuntimeStatus =
  327. browserSnapshot.runtimeStatus === "streaming" ? "streaming" : taskStore.runtimeStatus;
  328. return {
  329. activeInputId: taskStore.activeInputId,
  330. modelSwitchPending: browserSnapshot.modelSwitchPending,
  331. queueCount: browserSnapshot.queueCount,
  332. runtimeStatus: effectiveRuntimeStatus,
  333. sessionId: browserSnapshot.taskId,
  334. state: effectiveRuntimeStatus === "streaming" || hasBlockingGoalWork ? "streaming" : "idle",
  335. stopRequested: taskStore.stopRequested,
  336. targetId: taskStore.taskMeta?.targetId ?? null,
  337. targetObjective: goalProjection?.objective ?? taskStore.taskMeta?.targetObjective ?? null,
  338. targetStatus: goalProjection?.status ?? taskStore.taskMeta?.targetStatus ?? null,
  339. taskId: browserSnapshot.taskId,
  340. };
  341. }
  342. /**
  343. * v4 composer 输入(M5 起为 Lexical contenteditable):写入走
  344. * setInputValueByTestIdDom 的 __zcodeLexicalInputE2E bridge 分支(驱动真实 editor state)。
  345. */
  346. export async function sendV4Prompt(prompt: string) {
  347. await setV4ComposerText(prompt);
  348. const mainPaneTestId = testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID);
  349. try {
  350. await browser.waitUntil(
  351. async () =>
  352. browser.execute(
  353. (paneTestId, sendButtonTestId) => {
  354. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  355. const button = pane?.querySelector<HTMLButtonElement>(
  356. `[data-testid="${sendButtonTestId}"]`,
  357. );
  358. return Boolean(button && !button.disabled);
  359. },
  360. mainPaneTestId,
  361. TID_V4_COMPOSER_SEND,
  362. ),
  363. {
  364. timeout: 30000,
  365. timeoutMsg: "v4 发送按钮没有变为可用",
  366. },
  367. );
  368. } catch (error) {
  369. // 修复原因:会话切换竞态发生时,单独的“按钮 disabled”无法区分 projection connecting、
  370. // 上一轮仍在运行或 composer 未写入;把失败瞬间的 DOM 状态带回日志,避免继续靠猜测修复。
  371. const diagnostics = await browser.execute(
  372. (paneTestId, inputTestId, sendTestId, stopTestId) => {
  373. const panes = Array.from(
  374. document.querySelectorAll<HTMLElement>(`[data-testid^="${paneTestId}"]`),
  375. );
  376. const active = document.activeElement as HTMLElement | null;
  377. return {
  378. activeTestId: active?.getAttribute("data-testid") ?? null,
  379. panes: panes.map((pane) => {
  380. const input = pane.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  381. const send = pane.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  382. return {
  383. paneTestId: pane.getAttribute("data-testid"),
  384. sessionId: pane.getAttribute("data-session-id"),
  385. inputText: input?.innerText ?? input?.textContent ?? null,
  386. sendDisabled: send?.disabled ?? null,
  387. sendTitle: send?.getAttribute("title") ?? null,
  388. canStop: Boolean(pane.querySelector(`[data-testid="${stopTestId}"]`)),
  389. };
  390. }),
  391. };
  392. },
  393. TID_V4_SESSION_PANE,
  394. TID_V4_COMPOSER_INPUT,
  395. TID_V4_COMPOSER_SEND,
  396. TID_V4_STOP,
  397. );
  398. throw new Error(`v4 发送按钮没有变为可用; diagnostics=${JSON.stringify(diagnostics)}`, {
  399. cause: error,
  400. });
  401. }
  402. const submitResult = await browser.execute(
  403. (paneTestId, sendButtonTestId) => {
  404. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  405. const button = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendButtonTestId}"]`);
  406. if (!pane) return { submitted: false, reason: "pane-missing" };
  407. if (!button) return { submitted: false, reason: "button-missing" };
  408. if (button.disabled) return { submitted: false, reason: "button-disabled" };
  409. const form = button.closest("form");
  410. if (!form) {
  411. button.click();
  412. return { submitted: true, method: "click-fallback" };
  413. }
  414. let submitEventSeen = false;
  415. const onSubmit = () => {
  416. submitEventSeen = true;
  417. };
  418. form.addEventListener("submit", onSubmit, { capture: true, once: true });
  419. form.requestSubmit(button);
  420. return {
  421. submitted: submitEventSeen,
  422. method: "request-submit",
  423. reason: submitEventSeen ? undefined : "submit-event-not-seen",
  424. };
  425. },
  426. mainPaneTestId,
  427. TID_V4_COMPOSER_SEND,
  428. );
  429. if (!submitResult.submitted) {
  430. throw new Error(`v4 composer 没有派发 submit 事件: ${JSON.stringify(submitResult)}`);
  431. }
  432. }
  433. /**
  434. * 发送普通 prompt 并等待 renderer 明确接受:主 pane composer 清空且真实 user row 出现。
  435. * 不重试 submit,避免首发已进入 Host、但慢渲染尚未投影时重复发送同一条消息。
  436. */
  437. export async function sendV4PromptAndWaitAccepted(
  438. prompt: string,
  439. userMessageMarker: string,
  440. timeoutMsg: string,
  441. timeout = 60_000,
  442. ) {
  443. await sendV4Prompt(prompt);
  444. let latest: {
  445. composerText: string | null;
  446. paneExists: boolean;
  447. sendDisabled: boolean | null;
  448. sessionId: string | null;
  449. userMessageSeen: boolean;
  450. } | null = null;
  451. const readAcceptance = () =>
  452. browser.execute(
  453. (paneTestId, inputTestId, sendTestId, timelineTestId, marker) => {
  454. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  455. const input = pane?.querySelector<
  456. HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } }
  457. >(`[data-testid="${inputTestId}"]`);
  458. const send = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  459. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  460. const userMessageSeen = Array.from(
  461. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  462. ).some(
  463. (row) =>
  464. row.classList.contains("group/user-row") &&
  465. (row.innerText || row.textContent || "").includes(marker),
  466. );
  467. return {
  468. composerText: input?.__zcodeLexicalInputE2E?.getText() ?? null,
  469. paneExists: Boolean(pane),
  470. sendDisabled: send?.disabled ?? null,
  471. sessionId: pane?.getAttribute("data-session-id") ?? null,
  472. userMessageSeen,
  473. };
  474. },
  475. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  476. TID_V4_COMPOSER_INPUT,
  477. TID_V4_COMPOSER_SEND,
  478. TID_V4_TIMELINE,
  479. userMessageMarker,
  480. );
  481. try {
  482. await browser.waitUntil(
  483. async () => {
  484. latest = await readAcceptance();
  485. return latest.composerText === "" && latest.userMessageSeen;
  486. },
  487. { timeout, timeoutMsg },
  488. );
  489. } catch (error) {
  490. latest = await readAcceptance().catch(() => latest);
  491. const state = await getV4ConversationState().catch((stateError) => ({
  492. error: stateError instanceof Error ? stateError.message : String(stateError),
  493. }));
  494. throw new Error(
  495. `${timeoutMsg}; acceptance=${JSON.stringify(latest)}; state=${JSON.stringify(state)}`,
  496. { cause: error },
  497. );
  498. }
  499. }
  500. /** 只写入 v4 composer,不触发发送。 */
  501. export async function setV4ComposerText(text: string) {
  502. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, text, {
  503. timeout: 15000,
  504. timeoutMsg: "v4 composer 输入框没有出现或不可输入",
  505. });
  506. }
  507. export async function waitForV4ComposerText(expected: string, timeoutMsg: string, timeout = 10000) {
  508. await browser.waitUntil(async () => (await getV4ComposerText()) === expected, {
  509. timeout,
  510. timeoutMsg,
  511. });
  512. }
  513. /** 点击 v4 composer 发送按钮(输入已由调用方写入,如 slash 命令)。 */
  514. export async function clickV4Send() {
  515. await browser.waitUntil(
  516. async () =>
  517. browser.execute((sendButtonTestId) => {
  518. const button = document.querySelector<HTMLButtonElement>(
  519. `[data-testid="${sendButtonTestId}"]`,
  520. );
  521. return Boolean(button && !button.disabled);
  522. }, TID_V4_COMPOSER_SEND),
  523. {
  524. timeout: 30000,
  525. timeoutMsg: "v4 发送按钮没有变为可用",
  526. },
  527. );
  528. await clickTestIdByDom(TID_V4_COMPOSER_SEND, {
  529. timeout: 15000,
  530. timeoutMsg: "v4 发送按钮没有出现或不可点击",
  531. });
  532. }
  533. export async function waitForV4TimelineContaining(text: string, timeout = 60000) {
  534. await waitForV4Pane(
  535. (snapshot) => snapshot.timelineText.includes(text),
  536. `v4 timeline 中没有出现: ${text}`,
  537. timeout,
  538. );
  539. }
  540. /**
  541. * 只等待当前 V4 pane 的 assistant 正文,避免用户 prompt 中的同名 marker
  542. * 抢先满足完成屏障。formal case 不应为此回退到 legacy conversation helper。
  543. */
  544. export async function waitForV4AssistantMessageContaining(
  545. text: string,
  546. timeout = 90000,
  547. paneId: string = V4_MAIN_PANE_ID,
  548. ) {
  549. let latestAssistantMessages: string[] = [];
  550. const readAssistantMessages = () =>
  551. browser.execute(
  552. (paneTestId, timelineTestId) => {
  553. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  554. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  555. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  556. .filter((row) => row.classList.contains("group/assistant-row"))
  557. .map((row) => row.innerText.replace(/\u00a0/g, " ").trim());
  558. },
  559. testId(TID_V4_SESSION_PANE, paneId),
  560. TID_V4_TIMELINE,
  561. );
  562. try {
  563. await browser.waitUntil(
  564. async () => {
  565. latestAssistantMessages = await readAssistantMessages();
  566. return latestAssistantMessages.some((message) => message.includes(text));
  567. },
  568. {
  569. timeout,
  570. timeoutMsg: `v4 assistant 消息中没有出现: ${text}`,
  571. },
  572. );
  573. } catch (error) {
  574. latestAssistantMessages = await readAssistantMessages().catch(() => latestAssistantMessages);
  575. throw new Error(
  576. `v4 assistant 消息中没有出现: ${text}; latest=${JSON.stringify(latestAssistantMessages)}`,
  577. { cause: error },
  578. );
  579. }
  580. }
  581. export function getV4Messages(role?: "assistant" | "user"): Promise<V4MessageSnapshot[]> {
  582. return browser.execute(
  583. (paneTestId, timelineTestId, selectedRole) => {
  584. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  585. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  586. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  587. .map((element) => {
  588. const currentRole = element.classList.contains("group/user-row")
  589. ? "user"
  590. : element.classList.contains("group/assistant-row")
  591. ? "assistant"
  592. : null;
  593. return {
  594. id: element.getAttribute("data-row-id"),
  595. role: currentRole,
  596. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  597. };
  598. })
  599. .filter(
  600. (message): message is V4MessageSnapshot =>
  601. message.role !== null && (!selectedRole || message.role === selectedRole),
  602. );
  603. },
  604. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  605. TID_V4_TIMELINE,
  606. role,
  607. );
  608. }
  609. export async function waitForV4UserMessageContaining(text: string) {
  610. let latestMessages: V4MessageSnapshot[] = [];
  611. try {
  612. await browser.waitUntil(
  613. async () => {
  614. latestMessages = await getV4Messages("user");
  615. return latestMessages.some((message) => message.text.includes(text));
  616. },
  617. {
  618. timeout: 60000,
  619. timeoutMsg: `v4 user 消息中没有出现: ${text}`,
  620. },
  621. );
  622. } catch (error) {
  623. const [state, composer, queue] = await Promise.all([
  624. getV4ConversationState().catch((stateError) => ({
  625. error: stateError instanceof Error ? stateError.message : String(stateError),
  626. })),
  627. getV4ComposerText().catch((composerError) =>
  628. composerError instanceof Error ? composerError.message : String(composerError),
  629. ),
  630. getV4QueueItems().catch((queueError) => [
  631. {
  632. queueItemId: "<queue-read-error>",
  633. text: queueError instanceof Error ? queueError.message : String(queueError),
  634. },
  635. ]),
  636. ]);
  637. throw new Error(
  638. `v4 user 消息中没有出现: ${text}; latestMessages=${JSON.stringify(latestMessages)}; state=${JSON.stringify(state)}; queue=${JSON.stringify(queue)}; composer=${JSON.stringify(composer)}`,
  639. { cause: error },
  640. );
  641. }
  642. }
  643. export async function assertVisibleV4UserMessagesNotContaining(text: string) {
  644. const messages = await getV4Messages("user");
  645. expect(messages.map((message) => message.text).join("\n")).not.toContain(text);
  646. }
  647. export async function clickV4Stop() {
  648. await clickTestIdByDom(TID_V4_STOP, {
  649. timeout: 30000,
  650. timeoutMsg: "v4 stop 按钮没有出现或不可点击",
  651. });
  652. }
  653. /** 点击第一个可见的 fork 按钮(完成态 assistant 行),返回是否点到。 */
  654. export async function clickFirstV4Fork() {
  655. const buttons = await browser.$$('[data-testid^="v4-fork-"]');
  656. for (const button of buttons) {
  657. await moveV4ForkRowIntoHoverState(button);
  658. if (!(await button.isDisplayed()) || !(await button.isEnabled())) {
  659. continue;
  660. }
  661. // Bug 根因:直接在 renderer 里调用 HTMLElement.click() 会绕过 WebDriver 的
  662. // 用户交互路径;Radix/React 组合控件在长批次中可能只更新视觉层而未提交 fork。
  663. // 使用 WebDriver 原生 click,保留同一个按钮和断言语义,确保触发真实 pointer/click 事件。
  664. await button.click();
  665. return true;
  666. }
  667. return false;
  668. }
  669. export async function waitForV4Fork(timeout = 60000) {
  670. await browser.waitUntil(
  671. async () => {
  672. const buttons = await browser.$$('[data-testid^="v4-fork-"]');
  673. for (const button of buttons) {
  674. await moveV4ForkRowIntoHoverState(button);
  675. if ((await button.isDisplayed()) && (await button.isEnabled())) {
  676. return true;
  677. }
  678. }
  679. return false;
  680. },
  681. { timeout, timeoutMsg: "v4 fork 按钮没有出现(assistant 行未完成?)" },
  682. );
  683. }
  684. async function moveV4ForkRowIntoHoverState(button: WebdriverIO.Element): Promise<void> {
  685. const rowTestId = await browser.execute(
  686. (element) => element.closest<HTMLElement>("[data-row-id]")?.dataset.rowId ?? null,
  687. button,
  688. );
  689. const row = rowTestId ? await browser.$(`[data-row-id="${rowTestId}"]`) : await button.$("..");
  690. // Bug 根因:assistant action toolbar 默认由 group-hover 隐藏,旧 helper 只检查 DOM
  691. // 存在就直接点隐藏按钮;长列表中该 click 不会触发真实 fork。先把所属 turn 移入
  692. // hover 状态,再用可见且 enabled 的按钮完成同一用户操作,不改变 case 证明。
  693. await row.moveTo();
  694. }
  695. /** 点击第一个可见的 edit 按钮(user 行),返回是否点到。 */
  696. export async function clickFirstV4Edit() {
  697. return browser.execute(() => {
  698. const btn = document.querySelector<HTMLButtonElement>('[data-testid^="v4-edit-"]');
  699. btn?.click();
  700. return Boolean(btn);
  701. });
  702. }
  703. export async function waitForV4Edit(timeout = 60000) {
  704. await browser.waitUntil(
  705. async () =>
  706. browser.execute((editPrefix) => {
  707. const exactPattern = new RegExp(`^${editPrefix}-\\d+$`);
  708. return Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).some(
  709. (candidate) => exactPattern.test(candidate.dataset.testid ?? ""),
  710. );
  711. }, TID_V4_EDIT),
  712. { timeout, timeoutMsg: "v4 edit 按钮没有出现(user 行未完成?)" },
  713. );
  714. }
  715. /** 读取 v4 queue 面板当前项数与文本。 */
  716. export function getV4QueueItems(): Promise<Array<{ queueItemId: string; text: string }>> {
  717. return browser.execute(() =>
  718. Array.from(document.querySelectorAll<HTMLElement>('li[data-testid^="v4-queue-item-"]'))
  719. // 修复原因:删除/编辑/立即发送按钮以及行内输入都共享
  720. // `v4-queue-item-*` 前缀和 data-queue-item-id;只按前缀会把一个 item
  721. // 统计成 4~5 个,误报 projection 没有显示 queue。列表项元素是唯一权威行。
  722. .filter((el) => el.hasAttribute("data-queue-item-id"))
  723. .map((el) => ({
  724. queueItemId: el.getAttribute("data-queue-item-id") ?? "",
  725. text: (el.innerText || "").replace(/ /g, " ").trim(),
  726. })),
  727. );
  728. }
  729. /** 读取 queue.autoDrain 权威 DOM 投影,供 fault/恢复 case 证明错误后不会自动消费。 */
  730. export function getV4QueueAutoDrain(): Promise<boolean | null> {
  731. return browser.execute((queueTestId) => {
  732. const queue = document.querySelector<HTMLElement>(`[data-testid="${queueTestId}"]`);
  733. const value = queue?.getAttribute("data-queue-auto-drain");
  734. return value === null || value === undefined ? null : value === "true";
  735. }, TID_V4_QUEUE);
  736. }
  737. export async function waitForV4QueueCount(expected: number, timeout = 30000) {
  738. await browser.waitUntil(async () => (await getV4QueueItems()).length === expected, {
  739. timeout,
  740. timeoutMsg: `v4 queue 项数没有达到 ${expected}`,
  741. });
  742. }
  743. /** 点击某 queue 项的删除按钮(按 queueItemId)。 */
  744. export async function clickV4QueueItemDelete(queueItemId: string) {
  745. return browser.execute((id) => {
  746. const btn = document.querySelector<HTMLButtonElement>(
  747. `[data-testid="v4-queue-item-delete-${id}"]`,
  748. );
  749. btn?.click();
  750. return Boolean(btn);
  751. }, queueItemId);
  752. }
  753. /** 点击某 queue 项的编辑按钮(按 queueItemId,撤回到 composer)。 */
  754. export async function clickV4QueueItemEdit(queueItemId: string, clickCount = 1) {
  755. return browser.execute(
  756. (id, count) => {
  757. const btn = document.querySelector<HTMLButtonElement>(
  758. `[data-testid="v4-queue-item-edit-${id}"]`,
  759. );
  760. for (let index = 0; index < count; index += 1) {
  761. btn?.click();
  762. }
  763. return Boolean(btn);
  764. },
  765. queueItemId,
  766. clickCount,
  767. );
  768. }
  769. /** 点击某 queue 项的立即发送按钮(按 queueItemId)。 */
  770. export async function clickV4QueueItemSendNow(queueItemId: string) {
  771. return browser.execute((id) => {
  772. const btn = document.querySelector<HTMLButtonElement>(
  773. `[data-testid="v4-queue-item-send-now-${id}"]`,
  774. );
  775. btn?.click();
  776. return Boolean(btn);
  777. }, queueItemId);
  778. }
  779. // ── 暂停队列发送确认与恢复(B06/B07/B14/B15/C08)──
  780. // 原因:旧 E2E 把 clear/keep 当作 composer 的两颗替代发送按钮;产品交互改成
  781. // 正常发送按钮先打开 modal 后,必须显式走“发送 → 等 modal → 选择”,否则测试会
  782. // 把只打开弹窗误判成消息已经提交。
  783. /** 暂停队列发送确认 modal 与两个操作按钮是否同时存在。 */
  784. export function hasV4PausedQueueSendDialog(): Promise<boolean> {
  785. return browser.execute(
  786. (dialogTestId, clearTestId, keepTestId) =>
  787. Boolean(
  788. document.querySelector(`[data-testid="${dialogTestId}"]`) &&
  789. document.querySelector(`[data-testid="${clearTestId}"]`) &&
  790. document.querySelector(`[data-testid="${keepTestId}"]`),
  791. ),
  792. TID_V4_PAUSED_QUEUE_SEND_DIALOG,
  793. TID_V4_COMPOSER_CLEAR_QUEUE_SEND,
  794. TID_V4_COMPOSER_KEEP_QUEUE_SEND,
  795. );
  796. }
  797. /** 等待正常发送按钮提交后出现暂停队列确认 modal。 */
  798. export async function waitForV4PausedQueueSendDialog(timeout = 30000) {
  799. await browser.waitUntil(async () => hasV4PausedQueueSendDialog(), {
  800. timeout,
  801. timeoutMsg: "暂停队列发送确认 modal 没有出现(清空/发送按钮缺失)",
  802. });
  803. }
  804. /** 通过正常发送按钮打开 modal,再选择“保留队列并发送”。 */
  805. export async function sendV4PausedQueueKeep(prompt: string) {
  806. await sendV4Prompt(prompt);
  807. await waitForV4PausedQueueSendDialog();
  808. await clickTestIdByDom(TID_V4_COMPOSER_KEEP_QUEUE_SEND, {
  809. timeout: 15000,
  810. timeoutMsg: "暂停队列确认 modal 的“发送消息”按钮没有出现或不可点击",
  811. });
  812. }
  813. /** 通过正常发送按钮打开 modal,再选择“清空队列并发送”。 */
  814. export async function sendV4PausedQueueClear(prompt: string) {
  815. await sendV4Prompt(prompt);
  816. await waitForV4PausedQueueSendDialog();
  817. await clickTestIdByDom(TID_V4_COMPOSER_CLEAR_QUEUE_SEND, {
  818. timeout: 15000,
  819. timeoutMsg: "暂停队列确认 modal 的“清空队列”按钮没有出现或不可点击",
  820. });
  821. }
  822. /** 暂停提示条与“继续”按钮是否同时存在。 */
  823. export function hasV4PausedQueueBanner(): Promise<boolean> {
  824. return browser.execute(
  825. (bannerTestId, resumeTestId) =>
  826. Boolean(
  827. document.querySelector(`[data-testid="${bannerTestId}"]`) &&
  828. document.querySelector(`[data-testid="${resumeTestId}"]`),
  829. ),
  830. TID_V4_QUEUE_PAUSED_BANNER,
  831. TID_V4_QUEUE_RESUME,
  832. );
  833. }
  834. export async function waitForV4PausedQueueBanner(timeout = 30000) {
  835. await browser.waitUntil(async () => hasV4PausedQueueBanner(), {
  836. timeout,
  837. timeoutMsg: "暂停队列提示条或“继续”按钮没有出现",
  838. });
  839. }
  840. /** 点击暂停队列提示条的“继续”,恢复 CLI FIFO 自动消费。 */
  841. export async function clickV4PausedQueueResume() {
  842. await waitForV4PausedQueueBanner();
  843. await clickTestIdByDom(TID_V4_QUEUE_RESUME, {
  844. timeout: 15000,
  845. timeoutMsg: "暂停队列提示条的“继续”按钮没有出现或不可点击",
  846. });
  847. }
  848. /** 读取后台工作面板项(workId + status)。 */
  849. export function getV4BackgroundWorks(): Promise<Array<{ workId: string; status: string | null }>> {
  850. return browser.execute((itemPrefix) => {
  851. return Array.from(
  852. document.querySelectorAll<HTMLElement>(`[data-testid^="${itemPrefix}-"]`),
  853. ).map((el) => ({
  854. workId: el.getAttribute("data-work-id") ?? "",
  855. status: el.getAttribute("data-work-status"),
  856. }));
  857. }, TID_V4_BACKGROUND_WORK_ITEM);
  858. }
  859. /** 读取 Composer 当前 session 的后台任务计数与响应式展示形态;无入口返回 null。 */
  860. export function getV4ComposerBackgroundWorkCounts(): Promise<{
  861. bashCount: number;
  862. workflowCount: number;
  863. subagentCount: number;
  864. totalCount: number;
  865. /** 入口点击的落点(docs/dynamic-workflow/presentation.md):"panel" | "workflow-run"。 */
  866. openTarget: string;
  867. typedVisible: boolean;
  868. compactVisible: boolean;
  869. } | null> {
  870. return browser.execute((triggerTestId) => {
  871. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  872. if (!trigger) return null;
  873. const isVisible = (layout: string) => {
  874. const element = trigger.querySelector<HTMLElement>(
  875. `[data-composer-background-layout="${layout}"]`,
  876. );
  877. return Boolean(element && getComputedStyle(element).display !== "none");
  878. };
  879. return {
  880. bashCount: Number(trigger.dataset.backgroundBashCount ?? "0"),
  881. workflowCount: Number(trigger.dataset.backgroundWorkflowCount ?? "0"),
  882. subagentCount: Number(trigger.dataset.backgroundSubagentCount ?? "0"),
  883. totalCount: Number(trigger.dataset.backgroundTotalCount ?? "0"),
  884. openTarget: trigger.dataset.backgroundOpenTarget ?? "panel",
  885. typedVisible: isVisible("typed"),
  886. compactVisible: isVisible("compact"),
  887. };
  888. }, TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER);
  889. }
  890. /** Electron driver 不实现 WebDriver window/rect;通过主进程 BrowserWindow 调整 viewport。 */
  891. export async function setV4ElectronWindowSize(width: number, height: number) {
  892. const resized = await browser.electron.execute(
  893. (electron, nextWidth, nextHeight) => {
  894. const window = electron.BrowserWindow.getAllWindows().find(
  895. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  896. );
  897. if (!window) return false;
  898. const bounds = window.getBounds();
  899. window.setBounds({ ...bounds, width: nextWidth, height: nextHeight });
  900. window.focus();
  901. return true;
  902. },
  903. width,
  904. height,
  905. );
  906. if (!resized) {
  907. throw new Error("没有找到可调整尺寸的 Electron 窗口");
  908. }
  909. await browser.waitUntil(
  910. async () =>
  911. browser.execute(
  912. (expectedWidth, expectedHeight) =>
  913. Math.abs(window.innerWidth - expectedWidth) < 80 &&
  914. Math.abs(window.innerHeight - expectedHeight) < 120,
  915. width,
  916. height,
  917. ),
  918. { timeout: 10000, timeoutMsg: `Electron 窗口尺寸没有收敛到 ${width}x${height}` },
  919. );
  920. }
  921. /** 从 Composer 单一入口展开 Status panel,并直达所有非空后台类型区块。 */
  922. export async function openV4ComposerRunningBackgroundWorks(timeout = 30000) {
  923. await clickTestIdByDom(TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER, {
  924. timeout,
  925. timeoutMsg: "Composer 后台任务入口没有出现或不可点击",
  926. });
  927. await browser.waitUntil(
  928. async () =>
  929. browser.execute(
  930. (panelTestId, itemPrefix) => {
  931. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  932. const terminalCount = Number(panel?.dataset.runningTerminalCount ?? "0");
  933. const agentCount = Number(panel?.dataset.runningAgentCount ?? "0");
  934. const terminalTrigger = panel?.querySelector<HTMLElement>(
  935. '[data-status-section-trigger="terminal"]',
  936. );
  937. const agentTrigger = panel?.querySelector<HTMLElement>(
  938. '[data-status-section-trigger="agent"]',
  939. );
  940. return Boolean(
  941. panel?.dataset.state === "expanded" &&
  942. (terminalCount === 0 || terminalTrigger?.getAttribute("aria-expanded") === "true") &&
  943. (agentCount === 0 || agentTrigger?.getAttribute("aria-expanded") === "true") &&
  944. panel.querySelector(`[data-testid^="${itemPrefix}-"]`),
  945. );
  946. },
  947. TID_CHAT_SUMMARY_PANEL,
  948. TID_V4_BACKGROUND_WORK_ITEM,
  949. ),
  950. { timeout, timeoutMsg: "Composer 入口没有直达展开的终端/智能体明细" },
  951. );
  952. }
  953. /** 展开统一 status panel 的非空后台类型区块;定位只依赖结构化属性,不依赖中英文。 */
  954. export async function openV4RunningBackgroundWorks(timeout = 30000) {
  955. await browser.waitUntil(
  956. async () =>
  957. browser.execute(
  958. (panelTestId, itemPrefix) => {
  959. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  960. if (!panel || Number(panel.dataset.runningBackgroundCount ?? "0") < 1) {
  961. return false;
  962. }
  963. if (panel.dataset.state === "collapsed") {
  964. panel.querySelector<HTMLButtonElement>("button")?.click();
  965. return false;
  966. }
  967. const sections = [
  968. {
  969. count: Number(panel.dataset.runningTerminalCount ?? "0"),
  970. name: "terminal",
  971. },
  972. {
  973. count: Number(panel.dataset.runningAgentCount ?? "0"),
  974. name: "agent",
  975. },
  976. ];
  977. let allOpen = true;
  978. for (const section of sections) {
  979. if (section.count === 0) continue;
  980. const trigger = panel.querySelector<HTMLButtonElement>(
  981. `[data-status-section-trigger="${section.name}"]`,
  982. );
  983. if (!trigger) return false;
  984. if (trigger.getAttribute("aria-expanded") !== "true") {
  985. trigger.click();
  986. allOpen = false;
  987. }
  988. }
  989. return allOpen && Boolean(panel.querySelector(`[data-testid^="${itemPrefix}-"]`));
  990. },
  991. TID_CHAT_SUMMARY_PANEL,
  992. TID_V4_BACKGROUND_WORK_ITEM,
  993. ),
  994. { timeout, timeoutMsg: "status panel 没有展开终端/智能体 background work" },
  995. );
  996. }
  997. export function getLatestV4CommandAck(type: string): Promise<{
  998. type: string;
  999. status: string;
  1000. reasonCode?: string;
  1001. } | null> {
  1002. return browser.execute((commandType) => {
  1003. const entries =
  1004. (
  1005. window as Window & {
  1006. __zcodeV4CommandAcksE2E?: Array<{
  1007. type: string;
  1008. status: string;
  1009. reasonCode?: string;
  1010. }>;
  1011. }
  1012. ).__zcodeV4CommandAcksE2E ?? [];
  1013. return [...entries].reverse().find((entry) => entry.type === commandType) ?? null;
  1014. }, type);
  1015. }
  1016. /** 等待指定 v4 command 的结构化 ACK,避免业务断言把 command 卡住误报成模型无回复。 */
  1017. export async function waitForLatestV4CommandAck(type: string, timeout = 30000) {
  1018. let latest: Awaited<ReturnType<typeof getLatestV4CommandAck>> = null;
  1019. await browser.waitUntil(
  1020. async () => {
  1021. latest = await getLatestV4CommandAck(type);
  1022. return latest !== null;
  1023. },
  1024. { timeout, timeoutMsg: `v4 command 没有返回 ACK: ${type}` },
  1025. );
  1026. return latest!;
  1027. }
  1028. /** 点击某后台工作的取消按钮(cancelBackgroundWork 命令,按 workId)。 */
  1029. export async function clickV4BackgroundWorkCancel(workId: string) {
  1030. return browser.execute((id) => {
  1031. const btn = document.querySelector<HTMLButtonElement>(
  1032. `[data-testid="v4-background-work-cancel-${id}"]`,
  1033. );
  1034. btn?.click();
  1035. return Boolean(btn);
  1036. }, workId);
  1037. }
  1038. /** 点击会话删除按钮(deleteSession 命令)。 */
  1039. export async function clickV4DeleteSession() {
  1040. return clickTestIdByDom(TID_V4_DELETE_SESSION, {
  1041. timeout: 15000,
  1042. timeoutMsg: "v4 删除按钮没有出现",
  1043. });
  1044. }
  1045. /** 读取 Composer 当前 mode/模型选择显示。 */
  1046. export function getV4ModelConfig(): Promise<{
  1047. mode: string | null;
  1048. provider: string | null;
  1049. model: string | null;
  1050. source: string | null;
  1051. thought: string | null;
  1052. }> {
  1053. return browser.execute((modelTestId) => {
  1054. const el = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  1055. return {
  1056. mode: el?.getAttribute("data-mode") ?? null,
  1057. provider: el?.getAttribute("data-provider") ?? null,
  1058. model: el?.getAttribute("data-model") ?? null,
  1059. source: el?.getAttribute("data-source") ?? null,
  1060. thought: el?.getAttribute("data-thought") ?? null,
  1061. };
  1062. }, TID_V4_MODEL_CONFIG);
  1063. }
  1064. /** 等待当前 Composer 已从持久 Draft 完成 mode/模型选择初始化。 */
  1065. export async function waitForV4ComposerSelectionReady(timeout = 30_000) {
  1066. let latest = await getV4ModelConfig();
  1067. await browser.waitUntil(
  1068. async () => {
  1069. latest = await getV4ModelConfig();
  1070. return (
  1071. latest.source === "composer" &&
  1072. Boolean(latest.mode?.trim()) &&
  1073. Boolean(latest.provider?.trim()) &&
  1074. Boolean(latest.model?.trim())
  1075. );
  1076. },
  1077. {
  1078. timeout,
  1079. timeoutMsg: `v4 Composer 选择没有就绪: ${JSON.stringify(latest)}`,
  1080. },
  1081. );
  1082. }
  1083. /** 读取 draft 当前模型及其思考档位;V4 投影优先,legacy 目录仅作水合前 fallback。 */
  1084. export function getV4DraftThoughtState(workspacePath: string): Promise<{
  1085. current: string | null;
  1086. model: string | null;
  1087. values: string[];
  1088. }> {
  1089. return browser.execute(
  1090. (path, modelTestId) => {
  1091. const e2eWindow = window as Window & {
  1092. __zcodeSessionStoreE2E?: {
  1093. getState: () => {
  1094. getWorkspaceState?: (workspacePath: string) => {
  1095. configOptions?: Array<{
  1096. category?: string;
  1097. currentValue?: unknown;
  1098. options?: Array<{ value: string }>;
  1099. }>;
  1100. };
  1101. };
  1102. };
  1103. };
  1104. const options =
  1105. e2eWindow.__zcodeSessionStoreE2E?.getState().getWorkspaceState?.(path).configOptions ?? [];
  1106. const model = options.find((option) => option.category === "model");
  1107. const thought = options.find((option) => option.category === "thought_level");
  1108. const v4Config = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  1109. const v4ThoughtLevels = (v4Config?.dataset.thoughtLevels ?? "")
  1110. .split(",")
  1111. .map((value) => value.trim())
  1112. .filter(Boolean);
  1113. return {
  1114. current:
  1115. v4Config?.dataset.thought?.trim() ||
  1116. (typeof thought?.currentValue === "string" ? thought.currentValue : null),
  1117. model:
  1118. v4Config?.dataset.model?.trim() ||
  1119. (typeof model?.currentValue === "string" ? model.currentValue : null),
  1120. values:
  1121. v4ThoughtLevels.length > 0
  1122. ? v4ThoughtLevels
  1123. : (thought?.options?.map((option) => option.value) ?? []),
  1124. };
  1125. },
  1126. workspacePath,
  1127. TID_V4_MODEL_CONFIG,
  1128. );
  1129. }
  1130. /**
  1131. * 通过 composer 工具条切换模型 + 思考深度(switchModelConfig 命令)。
  1132. * M5:调试表单(provider/model/thought 文本框 + 应用)已被真实模型选择器替换——
  1133. * helper 适配为驱动 ModelConfigSelect(含 provider 分组二级菜单)与思考深度选择器,
  1134. * spec 的断言语义不变(config 投影更新为目标值)。
  1135. */
  1136. export async function switchV4Model(provider: string, model: string, thought: string) {
  1137. // 1) 模型:打开菜单 → (必要时展开 provider 分组子菜单)→ 点目标模型项。
  1138. const modelItemTestId = testId(
  1139. TID_CHAT_MODEL_SELECT_ITEM,
  1140. encodeCustomModelValue(provider, model),
  1141. );
  1142. const providerGroupTestIds = [
  1143. testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${provider}`),
  1144. ];
  1145. // 模型菜单是受控 DropdownMenu(pointerdown 打开),element.click() 不触发;
  1146. // 与旧 upstream helper 同口径用 WebDriver 真实点击。
  1147. const modelTrigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  1148. await modelTrigger.waitForClickable({ timeout: 30000 });
  1149. await modelTrigger.click();
  1150. await browser.waitUntil(
  1151. async () =>
  1152. browser.execute(
  1153. (itemTestId, groupTestIds) => {
  1154. const item = document.querySelector<HTMLElement>(`[data-testid="${itemTestId}"]`);
  1155. if (item) {
  1156. item.click();
  1157. return true;
  1158. }
  1159. // 自定义 provider 模型在二级菜单:先触发分组展开(hover + click 双保险)。
  1160. const group = groupTestIds
  1161. .map((groupTestId) =>
  1162. document.querySelector<HTMLElement>(`[data-testid="${groupTestId}"]`),
  1163. )
  1164. .find((candidate): candidate is HTMLElement => Boolean(candidate));
  1165. if (group) {
  1166. group.focus();
  1167. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  1168. group.dispatchEvent(
  1169. new MouseEvent(eventName, {
  1170. bubbles: true,
  1171. cancelable: true,
  1172. view: window,
  1173. }),
  1174. );
  1175. }
  1176. group.click();
  1177. }
  1178. return false;
  1179. },
  1180. modelItemTestId,
  1181. providerGroupTestIds,
  1182. ),
  1183. {
  1184. timeout: 45000,
  1185. timeoutMsg: `v4 模型选择器没有出现目标模型项: ${provider}/${model}`,
  1186. },
  1187. );
  1188. // 模型 config 投影落定后再切思考深度:thought 命令的 provider/model 参数取自
  1189. // 最新投影,模型切换未回流前切 thought 会被 UI 跳过(config-empty 防御)。
  1190. await browser.waitUntil(async () => (await getV4ModelConfig()).model === model, {
  1191. timeout: 30000,
  1192. timeoutMsg: `模型切换后 config.model 投影没有更新为 ${model}`,
  1193. });
  1194. // 无 reasoning metadata 的 custom provider 不渲染 thought selector。协议类 E2E
  1195. // 传空值表示只切模型,不能把不存在的思考深度控件当作模型切换失败。
  1196. if (!thought) {
  1197. return;
  1198. }
  1199. // 2) 思考深度:Radix Select 的 item 在真实 pointer 事件上确认(element.click() 无效),
  1200. // trigger/item 都用 WebDriver 真实点击。
  1201. await selectRadixOption(
  1202. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  1203. testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thought),
  1204. `v4 思考深度选择器没有出现目标档位: ${thought}`,
  1205. );
  1206. }
  1207. /** Radix Select 通用驱动:真实点击 trigger 展开,item 需要完整 pointer 手势才会确认。 */
  1208. async function selectRadixOption(triggerTestId: string, itemTestId: string, timeoutMsg: string) {
  1209. const trigger = $(sel(triggerTestId));
  1210. await trigger.waitForClickable({ timeout: 30000 });
  1211. await trigger.click();
  1212. const item = $(sel(itemTestId));
  1213. try {
  1214. await item.waitForClickable({ timeout: 15000 });
  1215. } catch (error) {
  1216. throw new Error(timeoutMsg, { cause: error });
  1217. }
  1218. // Radix SelectItem 的确认:mouse 手势要求 trusted pointer 链路(合成事件被手势
  1219. // 判定忽略),键盘路径(item 聚焦 + Enter,SELECTION_KEYS)是自动化下最稳的确认方式。
  1220. const confirmResult = await browser.execute((currentTestId) => {
  1221. const element = document.querySelector<HTMLElement>(`[data-testid="${currentTestId}"]`);
  1222. if (!element) {
  1223. return {
  1224. ok: false,
  1225. reason: "item-missing",
  1226. testIds: Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  1227. .map((el) => el.dataset.testid ?? "")
  1228. .filter((id) => id.includes("select"))
  1229. .slice(0, 40),
  1230. };
  1231. }
  1232. element.focus();
  1233. const focused = document.activeElement === element;
  1234. element.dispatchEvent(
  1235. new KeyboardEvent("keydown", {
  1236. key: "Enter",
  1237. bubbles: true,
  1238. cancelable: true,
  1239. }),
  1240. );
  1241. return { ok: true, focused };
  1242. }, itemTestId);
  1243. if (!confirmResult || confirmResult.ok !== true) {
  1244. throw new Error(`${timeoutMsg}(item 确认阶段异常: ${JSON.stringify(confirmResult)})`);
  1245. }
  1246. // 选择生效 ⇔ SelectContent 卸载(item 消失);未关闭说明确认未生效,抛诊断。
  1247. await browser
  1248. .waitUntil(
  1249. async () =>
  1250. browser.execute(
  1251. (currentTestId) => !document.querySelector(`[data-testid="${currentTestId}"]`),
  1252. itemTestId,
  1253. ),
  1254. { timeout: 5000 },
  1255. )
  1256. .catch(() => {
  1257. throw new Error(`${timeoutMsg}(item 确认后菜单未关闭——选择未生效)`);
  1258. });
  1259. }
  1260. /** 读取 goal 横幅(data-goal-status / data-goal-objective 投影属性);无目标返回 null。 */
  1261. export function getV4GoalProjection(): Promise<{
  1262. status: string | null;
  1263. objective: string | null;
  1264. } | null> {
  1265. return browser.execute(
  1266. (paneTestId, paneId, panelTestId) => {
  1267. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}-${paneId}"]`);
  1268. const el = pane?.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  1269. if (!el) return null;
  1270. return {
  1271. status: el.getAttribute("data-goal-status"),
  1272. objective: el.getAttribute("data-goal-objective"),
  1273. };
  1274. },
  1275. TID_V4_SESSION_PANE,
  1276. V4_MAIN_PANE_ID,
  1277. TID_CHAT_SUMMARY_PANEL,
  1278. );
  1279. }
  1280. /** 打开 latest user query 行内编辑并填入新文本,但不提交。 */
  1281. export async function beginFirstV4UserQueryEdit(newText: string) {
  1282. let rowId: string | null = null;
  1283. let lastClickedRowId: string | null = null;
  1284. let lastClickedAt = 0;
  1285. await browser.waitUntil(
  1286. async () => {
  1287. const state = await browser.execute(
  1288. (editPrefix, editInputPrefix) => {
  1289. const actionPattern = new RegExp(`^${editPrefix}-(\\d+)$`);
  1290. const inputPattern = new RegExp(`^${editInputPrefix}-(\\d+)$`);
  1291. const testIds = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"));
  1292. const input = testIds
  1293. .filter((candidate) => inputPattern.test(candidate.dataset.testid ?? ""))
  1294. .at(-1);
  1295. if (input) {
  1296. return {
  1297. inputRowId: inputPattern.exec(input.dataset.testid ?? "")?.[1] ?? null,
  1298. actionRowId: null,
  1299. };
  1300. }
  1301. const action = testIds
  1302. .filter((candidate) => actionPattern.test(candidate.dataset.testid ?? ""))
  1303. .at(-1);
  1304. return {
  1305. inputRowId: null,
  1306. actionRowId: actionPattern.exec(action?.dataset.testid ?? "")?.[1] ?? null,
  1307. };
  1308. },
  1309. TID_V4_EDIT,
  1310. TID_V4_EDIT_INPUT,
  1311. );
  1312. if (state.inputRowId) {
  1313. rowId = state.inputRowId;
  1314. return true;
  1315. }
  1316. if (!state.actionRowId) return false;
  1317. const now = Date.now();
  1318. if (lastClickedRowId !== state.actionRowId || now - lastClickedAt >= 500) {
  1319. lastClickedRowId = state.actionRowId;
  1320. lastClickedAt = now;
  1321. await clickTestIdByDom(testId(TID_V4_EDIT, state.actionRowId), {
  1322. timeout: 2000,
  1323. timeoutMsg: `v4 行内编辑按钮在 projection 收口时消失: rowId=${state.actionRowId}`,
  1324. }).catch(() => undefined);
  1325. }
  1326. return false;
  1327. },
  1328. {
  1329. timeout: 15000,
  1330. timeoutMsg: "v4 latest user edit action 出现后没有进入稳定行内编辑态",
  1331. interval: 100,
  1332. },
  1333. );
  1334. if (!rowId) {
  1335. throw new Error("v4 latest user edit action 没有出现");
  1336. }
  1337. // Bug 根因:compact success 会先投影成功 marker,再清理 active work;这两帧之间
  1338. // 旧 edit action 可能短暂可见后被 canEdit 收口撤下。单次 DOM click 会把刚打开的
  1339. // 本地 editing 状态随 onEdit 消失一起关闭。等待稳定 input,并在 action 恢复后重试。
  1340. await setInputValueByTestIdDom(testId(TID_V4_EDIT_INPUT, rowId), newText, {
  1341. timeout: 15000,
  1342. timeoutMsg: `v4 行内编辑输入框没有出现: rowId=${rowId}`,
  1343. });
  1344. return rowId;
  1345. }
  1346. /** 按真实行内编辑交互提交 latest user query,主 composer 草稿不参与。 */
  1347. export async function editFirstV4UserQuery(newText: string) {
  1348. const rowId = await beginFirstV4UserQueryEdit(newText);
  1349. await clickTestIdByDom(testId(TID_V4_EDIT_SUBMIT, rowId), {
  1350. timeout: 15000,
  1351. timeoutMsg: `v4 行内编辑提交按钮没有出现: rowId=${rowId}`,
  1352. });
  1353. return rowId;
  1354. }
  1355. /** 提交行内编辑的“对话 + 文件重置”路径。 */
  1356. export async function clickV4EditWorkspaceReset(rowId: string) {
  1357. await clickTestIdByDom(testId(TID_V4_EDIT_REWIND_WORKSPACE, rowId), {
  1358. timeout: 15000,
  1359. timeoutMsg: `v4 对话 + 文件重置按钮没有出现或不可点击: rowId=${rowId}`,
  1360. });
  1361. }
  1362. export async function waitForV4EditWorkspaceConflict(timeout = 30000) {
  1363. await browser.waitUntil(
  1364. async () =>
  1365. browser.execute(
  1366. (testIdValue) => Boolean(document.querySelector(`[data-testid="${testIdValue}"]`)),
  1367. TID_V4_EDIT_WORKSPACE_CONFLICT_DIALOG,
  1368. ),
  1369. { timeout, timeoutMsg: "v4 edit 文件冲突弹窗没有出现" },
  1370. );
  1371. }
  1372. export async function clickV4EditConflictConversationOnly() {
  1373. await clickTestIdByDom(TID_V4_EDIT_WORKSPACE_CONFLICT_CONVERSATION_ONLY, {
  1374. timeout: 15000,
  1375. timeoutMsg: "v4 edit 冲突弹窗没有出现仅重置对话按钮",
  1376. });
  1377. }
  1378. /** 读取结构化 compact marker;状态与来源只读 data-*,不依赖本地化 label。 */
  1379. export function getV4CompactMarkers(
  1380. paneId: string = V4_MAIN_PANE_ID,
  1381. ): Promise<V4CompactMarkerSnapshot[]> {
  1382. return browser.execute(
  1383. (paneTestId, rowPrefix) => {
  1384. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  1385. return Array.from(
  1386. pane?.querySelectorAll<HTMLElement>(
  1387. `[data-testid^="${rowPrefix}-"][data-row-kind="timelineMarker"][data-marker-type="compact"]`,
  1388. ) ?? [],
  1389. ).map((row) => {
  1390. const rowId = row.dataset.rowId ? Number(row.dataset.rowId) : Number.NaN;
  1391. return {
  1392. origin: row.dataset.origin ?? null,
  1393. rowId: Number.isFinite(rowId) ? rowId : null,
  1394. status: row.dataset.status ?? null,
  1395. text: row.innerText.trim(),
  1396. };
  1397. });
  1398. },
  1399. testId(TID_V4_SESSION_PANE, paneId),
  1400. TID_V4_ROW,
  1401. );
  1402. }
  1403. /** 等待结构化 compact marker;不读取本地化 label。 */
  1404. export async function waitForV4CompactMarker(
  1405. expected: { status: string; origin: "manual" | "auto" },
  1406. timeout = 90000,
  1407. ) {
  1408. await browser.waitUntil(
  1409. async () =>
  1410. (await getV4CompactMarkers()).some(
  1411. (marker) => marker.status === expected.status && marker.origin === expected.origin,
  1412. ),
  1413. {
  1414. timeout,
  1415. timeoutMsg: `v4 compact marker 未达到 ${expected.origin}/${expected.status}`,
  1416. },
  1417. );
  1418. }
  1419. /** 读取会话标题显示(data-title 投影属性)。 */
  1420. export function getV4SessionTitle(): Promise<string | null> {
  1421. return browser.execute((titleTestId) => {
  1422. const el = document.querySelector<HTMLElement>(`[data-testid="${titleTestId}"]`);
  1423. return el?.getAttribute("data-title") ?? null;
  1424. }, TID_V4_SESSION_TITLE);
  1425. }
  1426. /** 在 header 重命名输入框写入标题并点提交(renameSession 命令)。 */
  1427. export async function renameV4Session(title: string) {
  1428. await setInputValueByTestIdDom(TID_V4_RENAME_INPUT, title, {
  1429. timeout: 15000,
  1430. timeoutMsg: "v4 重命名输入框没有出现",
  1431. });
  1432. await clickTestIdByDom(TID_V4_RENAME_SUBMIT, {
  1433. timeout: 15000,
  1434. timeoutMsg: "v4 重命名提交按钮没有出现",
  1435. });
  1436. }
  1437. /** 读取输入控制条:autoDrain(data-auto-drain)与 followupMode(data-followup-mode)。 */
  1438. export function getV4InputControlState(): Promise<{
  1439. autoDrain: string | null;
  1440. followupMode: string | null;
  1441. }> {
  1442. return browser.execute(
  1443. (autoDrainTestId, followupTestId) => {
  1444. const autoBtn = document.querySelector<HTMLElement>(`[data-testid="${autoDrainTestId}"]`);
  1445. const followupBtn = document.querySelector<HTMLElement>(`[data-testid="${followupTestId}"]`);
  1446. return {
  1447. autoDrain: autoBtn?.getAttribute("data-auto-drain") ?? null,
  1448. followupMode: followupBtn?.getAttribute("data-followup-mode") ?? null,
  1449. };
  1450. },
  1451. TID_V4_AUTODRAIN_TOGGLE,
  1452. TID_V4_FOLLOWUP_TOGGLE,
  1453. );
  1454. }
  1455. /** 点击 autoDrain 开关(setAutoDrain 命令)。 */
  1456. export async function clickV4AutoDrainToggle() {
  1457. return clickTestIdByDom(TID_V4_AUTODRAIN_TOGGLE, {
  1458. timeout: 15000,
  1459. timeoutMsg: "v4 autoDrain 开关没有出现",
  1460. });
  1461. }
  1462. /** 点击 followupMode 开关(setFollowupMode 命令)。 */
  1463. export async function clickV4FollowupToggle() {
  1464. return clickTestIdByDom(TID_V4_FOLLOWUP_TOGGLE, {
  1465. timeout: 15000,
  1466. timeoutMsg: "v4 followupMode 开关没有出现",
  1467. });
  1468. }
  1469. /** 拖拽某 queue 项到目标 queue 项上(按 queueItemId)。 */
  1470. export async function dragV4QueueItemOnto(sourceQueueItemId: string, targetQueueItemId: string) {
  1471. const positions = (await browser.execute(
  1472. (sourceId, targetId) => {
  1473. const dragHandle = Array.from(
  1474. document.querySelectorAll<HTMLElement>('[data-v4-queue-drag-handle="true"]'),
  1475. ).find((el) => el.getAttribute("data-queue-item-id") === sourceId);
  1476. const targetItem = Array.from(
  1477. document.querySelectorAll<HTMLElement>("li[data-queue-item-id]"),
  1478. ).find((el) => el.getAttribute("data-queue-item-id") === targetId);
  1479. if (!dragHandle || !targetItem) {
  1480. return {
  1481. ok: false,
  1482. reason: "missing-element",
  1483. hasDragHandle: Boolean(dragHandle),
  1484. hasTargetItem: Boolean(targetItem),
  1485. };
  1486. }
  1487. const dragRect = dragHandle.getBoundingClientRect();
  1488. const targetRect = targetItem.getBoundingClientRect();
  1489. return {
  1490. ok: true,
  1491. startX: Math.round(dragRect.left + dragRect.width / 2),
  1492. startY: Math.round(dragRect.top + dragRect.height / 2),
  1493. endX: Math.round(targetRect.left + targetRect.width / 2),
  1494. endY: Math.round(targetRect.top + targetRect.height / 2),
  1495. };
  1496. },
  1497. sourceQueueItemId,
  1498. targetQueueItemId,
  1499. )) as
  1500. | { ok: true; startX: number; startY: number; endX: number; endY: number }
  1501. | {
  1502. ok: false;
  1503. reason: string;
  1504. hasDragHandle: boolean;
  1505. hasTargetItem: boolean;
  1506. };
  1507. if (!positions.ok) {
  1508. throw new Error(`v4 队列项拖拽元素不存在: ${JSON.stringify(positions)}`);
  1509. }
  1510. await browser.performActions([
  1511. {
  1512. id: "v4-queue-drag-pointer",
  1513. type: "pointer",
  1514. parameters: { pointerType: "mouse" },
  1515. actions: [
  1516. {
  1517. type: "pointerMove",
  1518. duration: 0,
  1519. x: positions.startX,
  1520. y: positions.startY,
  1521. },
  1522. { type: "pointerDown", button: 0 },
  1523. { type: "pause", duration: 80 },
  1524. {
  1525. type: "pointerMove",
  1526. duration: 120,
  1527. x: positions.startX,
  1528. y: positions.startY - 10,
  1529. },
  1530. {
  1531. type: "pointerMove",
  1532. duration: 260,
  1533. x: positions.endX,
  1534. y: positions.endY,
  1535. },
  1536. { type: "pointerUp", button: 0 },
  1537. ],
  1538. },
  1539. ]);
  1540. await browser.releaseActions();
  1541. // 修复原因:dnd-kit 会屏蔽拖拽结束后的紧随 click,E2E 用空白 click 消耗这次屏蔽,
  1542. // 避免后续按钮点击被误吞。
  1543. await browser.execute(() => {
  1544. document.body.dispatchEvent(
  1545. new MouseEvent("click", {
  1546. bubbles: true,
  1547. cancelable: true,
  1548. view: window,
  1549. }),
  1550. );
  1551. });
  1552. await browser.pause(50);
  1553. }
  1554. // ── M5④ 虚拟滚动:timeline 滚动状态读写 ──
  1555. // 虚拟化后 DOM 只有挂载的 turn units;raw 行数分别走 timeline 容器的
  1556. // data-window-row-count(rows.window)与 data-total-row-count(rows.totalCount),
  1557. // 避免把 mounted unit、logical unit 与持久 raw row 三种计量单位混用。
  1558. export interface V4TimelineScrollState {
  1559. scrollTop: number;
  1560. scrollHeight: number;
  1561. clientHeight: number;
  1562. /** raw projection window 行数。 */
  1563. windowRowCount: number;
  1564. /** turn-level logical render unit 数。 */
  1565. renderUnitCount: number;
  1566. /** 全序行数(data-total-row-count)。 */
  1567. totalRowCount: number;
  1568. /** 底部跟随态(data-following:"true" | "false")。 */
  1569. following: string | null;
  1570. /** 实际挂载到 DOM 的 turn unit 数(虚拟化窗口 + overscan)。 */
  1571. mountedRenderUnitCount: number;
  1572. /** 「回到底部」按钮是否出现。 */
  1573. hasBackToBottom: boolean;
  1574. }
  1575. export function getV4TimelineScrollState(): Promise<V4TimelineScrollState> {
  1576. return browser.execute(
  1577. (timelineTestId, bottomTestId) => {
  1578. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1579. return {
  1580. scrollTop: timeline?.scrollTop ?? 0,
  1581. scrollHeight: timeline?.scrollHeight ?? 0,
  1582. clientHeight: timeline?.clientHeight ?? 0,
  1583. windowRowCount: Number(timeline?.getAttribute("data-window-row-count") ?? 0),
  1584. renderUnitCount: Number(timeline?.getAttribute("data-render-unit-count") ?? 0),
  1585. totalRowCount: Number(timeline?.getAttribute("data-total-row-count") ?? 0),
  1586. following: timeline?.getAttribute("data-following") ?? null,
  1587. mountedRenderUnitCount:
  1588. timeline?.querySelectorAll('[data-v4-turn-unit="true"]').length ?? 0,
  1589. hasBackToBottom: Boolean(document.querySelector(`[data-testid="${bottomTestId}"]`)),
  1590. };
  1591. },
  1592. TID_V4_TIMELINE,
  1593. TID_V4_TIMELINE_BOTTOM,
  1594. );
  1595. }
  1596. /**
  1597. * 把 timeline 滚到顶(scrollTop=0,触发原生 scroll 事件 → 解除底部跟随),
  1598. * 并等虚拟化窗口对齐到新滚动位置后才返回。
  1599. *
  1600. * bugfix(虚拟化语义):scrollTop 赋值后 scroll 事件要到下一渲染帧才派发,
  1601. * virtualizer 收到事件才重渲染顶端行——期间 DOM 仍是旧的底部窗口
  1602. * (实测:scrollTop=0 后旧行 58..72 还挂在视口下方 3272px 处),此时视口里没有
  1603. * 任何行。CDP execute 往返快于一帧,调用方紧接着的 DOM 采样会读到过期窗口。
  1604. * 这里等「有行真正落进视口」(虚拟窗口已对齐当前滚动位置)再返回。
  1605. * 注意不能等 scrollTop 停在 0:到顶会触发 loadOlder,prepend 锚定会立刻把
  1606. * scrollTop 平移到保持阅读位置的新值(这正是被测语义),0 只是瞬态。
  1607. */
  1608. export async function scrollV4TimelineToTop() {
  1609. await browser.execute((timelineTestId) => {
  1610. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1611. if (!timeline) return;
  1612. // 修复原因:ConversationTimeline 会先用 wheel/touch/key 记录真实用户意图,
  1613. // 仅写 scrollTop 的脚本滚动可能被布局保护窗口归类为虚拟化校正,继续保持底部跟随。
  1614. timeline.dispatchEvent(
  1615. new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -600 }),
  1616. );
  1617. timeline.scrollTop = 0;
  1618. timeline.dispatchEvent(new Event("scroll"));
  1619. }, TID_V4_TIMELINE);
  1620. await browser.waitUntil(
  1621. async () =>
  1622. browser.execute(
  1623. (timelineTestId, rowPrefix) => {
  1624. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1625. if (!timeline) return false;
  1626. const timelineTop = timeline.getBoundingClientRect().top;
  1627. const viewportHeight = timeline.clientHeight;
  1628. return Array.from(
  1629. timeline.querySelectorAll<HTMLElement>(`[data-testid^="${rowPrefix}-"]`),
  1630. ).some((row) => {
  1631. const rect = row.getBoundingClientRect();
  1632. return rect.bottom - timelineTop > 0 && rect.top - timelineTop < viewportHeight;
  1633. });
  1634. },
  1635. TID_V4_TIMELINE,
  1636. TID_V4_ROW,
  1637. ),
  1638. {
  1639. timeout: 15000,
  1640. timeoutMsg: "scrollTop=0 后虚拟化窗口没有对齐到滚动位置(视口内始终没有行)",
  1641. },
  1642. );
  1643. }
  1644. /** 点「回到底部」按钮(恢复跟随并贴底)。 */
  1645. export async function clickV4TimelineBackToBottom() {
  1646. return clickTestIdByDom(TID_V4_TIMELINE_BOTTOM, {
  1647. timeout: 15000,
  1648. timeoutMsg: "v4 回到底部按钮没有出现",
  1649. });
  1650. }
  1651. // ── TN:v4 对话轮次导航 minimap ──
  1652. export interface V4TurnNavigatorState {
  1653. centerOffsetPx: number;
  1654. composerLeftGutterPx: number;
  1655. exists: boolean;
  1656. firstItemLeftOffsetPx: number;
  1657. visible: boolean;
  1658. itemCount: number;
  1659. paneWidthPx: number;
  1660. items: Array<{
  1661. active: boolean;
  1662. height: number;
  1663. left: number;
  1664. testId: string;
  1665. top: number;
  1666. turnId: string | null;
  1667. unitIndex: number | null;
  1668. visualColorTone: string | null;
  1669. visualScale: number | null;
  1670. visualTone: string | null;
  1671. }>;
  1672. }
  1673. export function getV4TurnNavigatorState(): Promise<V4TurnNavigatorState> {
  1674. return browser.execute(
  1675. (navigatorTestId, itemPrefix, timelineTestId, composerTestId, sessionPaneTestId) => {
  1676. const pane = document.querySelector<HTMLElement>(`[data-testid="${sessionPaneTestId}"]`);
  1677. const scope: Document | HTMLElement = pane ?? document;
  1678. const navigator = scope.querySelector<HTMLElement>(`[data-testid="${navigatorTestId}"]`);
  1679. const timeline = scope.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1680. const composer = scope.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`);
  1681. const style = navigator ? window.getComputedStyle(navigator) : null;
  1682. const rect = navigator?.getBoundingClientRect();
  1683. const timelineRect = timeline?.getBoundingClientRect();
  1684. const composerRect = composer?.getBoundingClientRect();
  1685. const paneRect = pane?.getBoundingClientRect();
  1686. const items = Array.from(
  1687. navigator?.querySelectorAll<HTMLElement>(`[data-testid^="${itemPrefix}-"]`) ?? [],
  1688. ).map((el) => {
  1689. const itemRect = el.getBoundingClientRect();
  1690. return {
  1691. active: el.getAttribute("data-active") === "true",
  1692. height: itemRect.height,
  1693. left: itemRect.left,
  1694. testId: el.dataset.testid ?? "",
  1695. top: itemRect.top,
  1696. turnId: el.getAttribute("data-turn-id"),
  1697. unitIndex:
  1698. el.getAttribute("data-unit-index") === null
  1699. ? null
  1700. : Number(el.getAttribute("data-unit-index")),
  1701. visualColorTone: el.getAttribute("data-visual-color-tone"),
  1702. visualScale:
  1703. el.getAttribute("data-visual-scale") === null
  1704. ? null
  1705. : Number(el.getAttribute("data-visual-scale")),
  1706. visualTone: el.getAttribute("data-visual-tone"),
  1707. };
  1708. });
  1709. const firstItemLeftOffsetPx =
  1710. items[0] && timelineRect ? items[0].left - timelineRect.left : Number.NaN;
  1711. const firstItem = items[0];
  1712. const lastItem = items.at(-1);
  1713. const stackCenter =
  1714. firstItem && lastItem ? (firstItem.top + lastItem.top + lastItem.height) / 2 : Number.NaN;
  1715. const timelineCenter = timelineRect ? timelineRect.top + timelineRect.height / 2 : Number.NaN;
  1716. return {
  1717. centerOffsetPx: stackCenter - timelineCenter,
  1718. composerLeftGutterPx:
  1719. composerRect && timelineRect ? composerRect.left - timelineRect.left : Number.NaN,
  1720. exists: Boolean(navigator),
  1721. firstItemLeftOffsetPx,
  1722. visible: Boolean(
  1723. navigator &&
  1724. style &&
  1725. rect &&
  1726. style.display !== "none" &&
  1727. style.visibility !== "hidden" &&
  1728. rect.width > 0 &&
  1729. rect.height > 0,
  1730. ),
  1731. itemCount: items.length,
  1732. items,
  1733. paneWidthPx: paneRect?.width ?? Number.NaN,
  1734. };
  1735. },
  1736. TID_V4_TURN_NAVIGATOR,
  1737. TID_V4_TURN_NAVIGATOR_ITEM,
  1738. TID_V4_TIMELINE,
  1739. TID_V4_COMPOSER,
  1740. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  1741. );
  1742. }
  1743. export async function waitForV4TurnNavigator(
  1744. predicate: (state: V4TurnNavigatorState) => boolean,
  1745. timeoutMsg: string,
  1746. timeout = 30000,
  1747. ) {
  1748. let latest: V4TurnNavigatorState | null = null;
  1749. try {
  1750. await browser.waitUntil(
  1751. async () => {
  1752. latest = await getV4TurnNavigatorState();
  1753. return predicate(latest);
  1754. },
  1755. { timeout, timeoutMsg },
  1756. );
  1757. } catch (error) {
  1758. latest = await getV4TurnNavigatorState();
  1759. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  1760. cause: error,
  1761. });
  1762. }
  1763. return getV4TurnNavigatorState();
  1764. }
  1765. async function getV4TurnNavigatorItemTestIdByIndex(index: number) {
  1766. const state = await getV4TurnNavigatorState();
  1767. const item = state.items[index];
  1768. if (!item) {
  1769. throw new Error(
  1770. `v4 turn navigator item 不存在: index=${index}; latest=${JSON.stringify(state)}`,
  1771. );
  1772. }
  1773. return item.testId;
  1774. }
  1775. export async function hoverV4TurnNavigatorItemByIndex(index: number) {
  1776. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1777. const item = $(sel(itemTestId));
  1778. await item.waitForDisplayed({ timeout: 15000 });
  1779. await item.moveTo();
  1780. return itemTestId;
  1781. }
  1782. export async function focusV4TurnNavigatorItemByIndex(index: number) {
  1783. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1784. await browser.execute((currentTestId) => {
  1785. document.querySelector<HTMLElement>(`[data-testid="${currentTestId}"]`)?.focus();
  1786. }, itemTestId);
  1787. return itemTestId;
  1788. }
  1789. export async function clickV4TurnNavigatorItemByIndex(index: number) {
  1790. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1791. await browser.execute((currentTestId) => {
  1792. document.querySelector<HTMLButtonElement>(`[data-testid="${currentTestId}"]`)?.click();
  1793. }, itemTestId);
  1794. return itemTestId;
  1795. }
  1796. export function getV4TurnNavigatorTooltipText(): Promise<string> {
  1797. return browser.execute((tooltipPrefix) => {
  1798. const tooltip = document.querySelector<HTMLElement>(`[data-testid^="${tooltipPrefix}-"]`);
  1799. return (tooltip?.innerText ?? "").replace(/ /g, " ");
  1800. }, TID_V4_TURN_NAVIGATOR_TOOLTIP);
  1801. }
  1802. export async function waitForV4TurnNavigatorTooltip(
  1803. predicate: (text: string) => boolean,
  1804. timeoutMsg: string,
  1805. timeout = 15000,
  1806. ) {
  1807. let latest = "";
  1808. try {
  1809. await browser.waitUntil(
  1810. async () => {
  1811. latest = await getV4TurnNavigatorTooltipText();
  1812. return predicate(latest);
  1813. },
  1814. { timeout, timeoutMsg },
  1815. );
  1816. } catch (error) {
  1817. latest = await getV4TurnNavigatorTooltipText();
  1818. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  1819. cause: error,
  1820. });
  1821. }
  1822. return getV4TurnNavigatorTooltipText();
  1823. }
  1824. // ── M5⑤ 分屏(Layout/Focus 两层):pane 级定位与焦点断言 ──
  1825. // 分屏后同 testid(composer 输入/发送等)在两个 pane 各有一份,全局 helper 只会
  1826. // 命中 DOM 序第一个(primary)。以下 helper 一律先按 v4-pane-shell-<paneId>
  1827. // 收口作用域再定位,焦点断言读外壳的 data-focused。
  1828. /** 读取当前 focused pane 的 paneId(data-focused="true" 的外壳);无外壳返回 null。 */
  1829. export function getV4FocusedPaneId(): Promise<string | null> {
  1830. return browser.execute((shellPrefix) => {
  1831. const focused = document.querySelector<HTMLElement>(
  1832. `[data-testid^="${shellPrefix}-"][data-focused="true"]`,
  1833. );
  1834. return focused?.getAttribute("data-pane-id") ?? null;
  1835. }, TID_V4_PANE_SHELL);
  1836. }
  1837. /**
  1838. * 首个非 primary pane 的 paneId(分屏二期 paneId 动态分配:pane-1/pane-2/…,
  1839. * 一期固定 "split" 仅存于 v1 持久化迁移形态);无分屏返回 null。
  1840. */
  1841. export function getV4SecondaryPaneId(): Promise<string | null> {
  1842. return browser.execute(
  1843. (shellPrefix, mainPaneId) => {
  1844. const shells = Array.from(
  1845. document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`),
  1846. );
  1847. for (const shell of shells) {
  1848. const paneId = shell.getAttribute("data-pane-id");
  1849. if (paneId && paneId !== mainPaneId) {
  1850. return paneId;
  1851. }
  1852. }
  1853. return null;
  1854. },
  1855. TID_V4_PANE_SHELL,
  1856. V4_MAIN_PANE_ID,
  1857. );
  1858. }
  1859. /** 当前 workbench 中全部 paneId。 */
  1860. export function getV4PaneIds(): Promise<string[]> {
  1861. return browser.execute((shellPrefix) => {
  1862. return Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`))
  1863. .map((shell) => shell.getAttribute("data-pane-id"))
  1864. .filter((paneId): paneId is string => Boolean(paneId));
  1865. }, TID_V4_PANE_SHELL);
  1866. }
  1867. /** 是否存在非 primary pane(分屏布局)。 */
  1868. export async function hasV4SplitPane(): Promise<boolean> {
  1869. return (await getV4SecondaryPaneId()) !== null;
  1870. }
  1871. /** 点击 primary pane header 的「向右拆分」按钮,等新 pane 出现并返回其 paneId。 */
  1872. export async function openV4SplitPane(): Promise<string> {
  1873. await clickTestIdByDom(TID_V4_SPLIT_OPEN, {
  1874. timeout: 15000,
  1875. timeoutMsg: "v4 拆分按钮没有出现或不可点击",
  1876. });
  1877. let paneId: string | null = null;
  1878. await browser.waitUntil(
  1879. async () => {
  1880. paneId = await getV4SecondaryPaneId();
  1881. return paneId !== null;
  1882. },
  1883. {
  1884. timeout: 15000,
  1885. timeoutMsg: "点击拆分按钮后新 pane 没有出现",
  1886. },
  1887. );
  1888. return paneId as unknown as string;
  1889. }
  1890. /** 在指定 pane 上点击向右/向下拆分按钮,返回本次新增 paneId。 */
  1891. export async function openV4SplitPaneFrom(
  1892. paneId: string,
  1893. direction: "right" | "down" = "right",
  1894. ): Promise<string> {
  1895. const before = new Set(await getV4PaneIds());
  1896. const splitButtonTestId = direction === "down" ? TID_V4_SPLIT_DOWN : TID_V4_SPLIT_OPEN;
  1897. const clicked = await browser.execute(
  1898. (shellTestId, buttonTestId) => {
  1899. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  1900. const button = shell?.querySelector<HTMLButtonElement>(`[data-testid="${buttonTestId}"]`);
  1901. if (!button || button.disabled) return false;
  1902. button.click();
  1903. return true;
  1904. },
  1905. testId(TID_V4_PANE_SHELL, paneId),
  1906. splitButtonTestId,
  1907. );
  1908. if (!clicked) {
  1909. throw new Error(`pane ${paneId} 的 ${direction} 拆分按钮不存在或不可用`);
  1910. }
  1911. let addedPaneId: string | null = null;
  1912. await browser.waitUntil(
  1913. async () => {
  1914. const after = await getV4PaneIds();
  1915. addedPaneId = after.find((id) => !before.has(id)) ?? null;
  1916. return addedPaneId !== null;
  1917. },
  1918. {
  1919. timeout: 15000,
  1920. timeoutMsg: `pane ${paneId} 点击 ${direction} 拆分后没有新增 pane`,
  1921. },
  1922. );
  1923. return addedPaneId as unknown as string;
  1924. }
  1925. /** 点击非 primary pane header 的「关闭窗格」按钮,并等该 pane 外壳消失。 */
  1926. export async function closeV4SplitPane() {
  1927. await clickTestIdByDom(TID_V4_SPLIT_CLOSE, {
  1928. timeout: 15000,
  1929. timeoutMsg: "v4 关闭窗格按钮没有出现或不可点击",
  1930. });
  1931. await browser.waitUntil(async () => !(await hasV4SplitPane()), {
  1932. timeout: 15000,
  1933. timeoutMsg: "点击关闭窗格后 pane 没有消失",
  1934. });
  1935. }
  1936. // ── 布局持久化 / 拖拽调宽 / 侧栏分屏入口 ──
  1937. /** paneLayoutStore 的 localStorage 键(packages/ui paneLayoutStore.PANE_LAYOUT_STORAGE_KEY,分屏二期 v2)。 */
  1938. export const V4_PANE_LAYOUT_STORAGE_KEY = "zcode-v4-pane-layout:v2";
  1939. export const V4_WORKBENCH_GROUP_STORAGE_KEY = "zcode-v4-session-workbench-groups:v1";
  1940. /** v2 持久化载荷形态(与 packages/ui paneLayoutStore PersistedPaneLayoutV2 对偶,e2e 断言/篡改用)。 */
  1941. export interface V4PersistedPaneLayout {
  1942. root: {
  1943. type: string;
  1944. ratio?: number;
  1945. [key: string]: unknown;
  1946. };
  1947. panes: Record<string, { workspaceScope: { workspacePath: string }; sessionId: string | null }>;
  1948. focusedPaneId: string;
  1949. }
  1950. /** promoted 分屏的唯一持久化 owner(与 packages/ui workbenchGroupStore 对偶)。 */
  1951. export interface V4PersistedWorkbenchGroups {
  1952. activeGroupId: string | null;
  1953. groups: Record<
  1954. string,
  1955. {
  1956. root: {
  1957. type: string;
  1958. ratio?: number;
  1959. [key: string]: unknown;
  1960. };
  1961. panes: Record<
  1962. string,
  1963. {
  1964. workspaceScope: { workspacePath: string };
  1965. sessionId: string;
  1966. }
  1967. >;
  1968. focusedPaneId: string;
  1969. }
  1970. >;
  1971. }
  1972. /** 读取当前分屏占比(primary 外壳宽 / 容器宽);无分屏或容器不可测返回 null。 */
  1973. export function getV4SplitRatio(): Promise<number | null> {
  1974. return browser.execute(
  1975. (primaryShellTestId, shellPrefix, mainPaneId) => {
  1976. const primary = document.querySelector<HTMLElement>(`[data-testid="${primaryShellTestId}"]`);
  1977. const hasSecondary = Array.from(
  1978. document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`),
  1979. ).some((shell) => shell.getAttribute("data-pane-id") !== mainPaneId);
  1980. const container = primary?.parentElement;
  1981. if (!primary || !hasSecondary || !container) return null;
  1982. const containerWidth = container.getBoundingClientRect().width;
  1983. if (containerWidth <= 0) return null;
  1984. return primary.getBoundingClientRect().width / containerWidth;
  1985. },
  1986. testId(TID_V4_PANE_SHELL, V4_MAIN_PANE_ID),
  1987. TID_V4_PANE_SHELL,
  1988. V4_MAIN_PANE_ID,
  1989. );
  1990. }
  1991. /**
  1992. * 把分屏分隔条拖到容器宽度的 targetRatio 处(pointer events:down → move → up;
  1993. * 分隔条 pointerup 提交 store → 持久化)。
  1994. */
  1995. export async function dragV4SplitDividerTo(targetRatio: number) {
  1996. const dispatched = await browser.execute(
  1997. (dividerTestId, primaryShellTestId, ratio) => {
  1998. const divider = document.querySelector<HTMLElement>(`[data-testid="${dividerTestId}"]`);
  1999. const container = document.querySelector<HTMLElement>(
  2000. `[data-testid="${primaryShellTestId}"]`,
  2001. )?.parentElement;
  2002. if (!divider || !container) return false;
  2003. const containerRect = container.getBoundingClientRect();
  2004. const dividerRect = divider.getBoundingClientRect();
  2005. const startX = dividerRect.left + dividerRect.width / 2;
  2006. const y = dividerRect.top + dividerRect.height / 2;
  2007. const targetX = containerRect.left + containerRect.width * ratio;
  2008. const base = {
  2009. bubbles: true,
  2010. cancelable: true,
  2011. button: 0,
  2012. pointerId: 1,
  2013. pointerType: "mouse",
  2014. } as const;
  2015. divider.dispatchEvent(
  2016. new PointerEvent("pointerdown", { ...base, clientX: startX, clientY: y }),
  2017. );
  2018. divider.dispatchEvent(
  2019. new PointerEvent("pointermove", {
  2020. ...base,
  2021. clientX: (startX + targetX) / 2,
  2022. clientY: y,
  2023. }),
  2024. );
  2025. divider.dispatchEvent(
  2026. new PointerEvent("pointermove", { ...base, clientX: targetX, clientY: y }),
  2027. );
  2028. divider.dispatchEvent(
  2029. new PointerEvent("pointerup", { ...base, clientX: targetX, clientY: y }),
  2030. );
  2031. return true;
  2032. },
  2033. TID_V4_SPLIT_DIVIDER,
  2034. testId(TID_V4_PANE_SHELL, V4_MAIN_PANE_ID),
  2035. targetRatio,
  2036. );
  2037. if (!dispatched) {
  2038. throw new Error("分屏分隔条不存在,无法拖拽");
  2039. }
  2040. }
  2041. /** 等待实际分屏占比进入 target±tolerance。 */
  2042. export async function waitForV4SplitRatio(target: number, tolerance = 0.03, timeout = 15000) {
  2043. let latest: number | null = null;
  2044. await browser.waitUntil(
  2045. async () => {
  2046. latest = await getV4SplitRatio();
  2047. return latest !== null && Math.abs(latest - target) <= tolerance;
  2048. },
  2049. {
  2050. timeout,
  2051. timeoutMsg: `分屏占比没有达到 ${target}(最近值 ${latest})`,
  2052. },
  2053. );
  2054. }
  2055. /** 右键侧栏会话项 → 上下文菜单「在分屏打开」→ 等新 pane 出现并返回其 paneId(仅桌面 shell)。 */
  2056. export async function openV4SplitFromSidebar(sessionId: string): Promise<string> {
  2057. const before = new Set(await getV4PaneIds());
  2058. await browser.waitUntil(
  2059. async () =>
  2060. browser.execute(
  2061. (itemTestId) => {
  2062. const item = document.querySelector<HTMLElement>(`[data-testid="${itemTestId}"]`);
  2063. if (!item) return false;
  2064. const rect = item.getBoundingClientRect();
  2065. item.dispatchEvent(
  2066. new MouseEvent("contextmenu", {
  2067. bubbles: true,
  2068. cancelable: true,
  2069. button: 2,
  2070. clientX: rect.left + rect.width / 2,
  2071. clientY: rect.top + rect.height / 2,
  2072. }),
  2073. );
  2074. return true;
  2075. },
  2076. testId(TID_TASK_ITEM, sessionId),
  2077. ),
  2078. {
  2079. timeout: 15000,
  2080. timeoutMsg: `侧栏会话项不存在: ${sessionId}`,
  2081. },
  2082. );
  2083. await clickTestIdByDom(TID_V4_TASK_OPEN_IN_SPLIT, {
  2084. timeout: 15000,
  2085. timeoutMsg: "会话项上下文菜单「在分屏打开」没有出现",
  2086. });
  2087. let paneId: string | null = null;
  2088. await browser.waitUntil(
  2089. async () => {
  2090. const after = await getV4PaneIds();
  2091. paneId =
  2092. after.find((candidate) => !before.has(candidate)) ??
  2093. (before.size === 1 ? await getV4SecondaryPaneId() : null);
  2094. return paneId !== null;
  2095. },
  2096. {
  2097. timeout: 15000,
  2098. timeoutMsg: "「在分屏打开」后新 pane 没有出现",
  2099. },
  2100. );
  2101. return paneId as unknown as string;
  2102. }
  2103. /** 点击侧栏会话项并等待 primary pane 绑定到该 session。 */
  2104. export async function selectV4TaskById(sessionId: string, taskListTimeout = 15000) {
  2105. await clickTestIdByDom(testId(TID_TASK_ITEM, sessionId), {
  2106. timeout: taskListTimeout,
  2107. timeoutMsg: `任务列表没有可点击的 v4 task: ${sessionId}`,
  2108. });
  2109. await waitForV4Pane(
  2110. (snapshot) => snapshot.sessionId === sessionId,
  2111. `点击侧栏 task 后 primary pane 没有切到 ${sessionId}`,
  2112. 30000,
  2113. V4_MAIN_PANE_ID,
  2114. );
  2115. }
  2116. /** 对 pane 外壳派发 pointerdown(Focus 层 onPointerDownCapture → focus 该 pane)。 */
  2117. export async function focusV4Pane(paneId: string) {
  2118. const dispatched = await browser.execute(
  2119. (shellTestId) => {
  2120. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2121. if (!shell) return false;
  2122. shell.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true }));
  2123. return true;
  2124. },
  2125. testId(TID_V4_PANE_SHELL, paneId),
  2126. );
  2127. if (!dispatched) {
  2128. throw new Error(`focusV4Pane: pane 外壳不存在: ${paneId}`);
  2129. }
  2130. await browser.waitUntil(async () => (await getV4FocusedPaneId()) === paneId, {
  2131. timeout: 15000,
  2132. timeoutMsg: `pane ${paneId} 没有获得焦点`,
  2133. });
  2134. }
  2135. /** pane 作用域内点 stop(分屏时全局 TID_V4_STOP 会命中 DOM 序第一个 pane)。 */
  2136. export async function clickV4StopInPane(paneId: string) {
  2137. const clicked = await browser.execute(
  2138. (shellTestId, stopTestId) => {
  2139. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2140. const btn = shell?.querySelector<HTMLButtonElement>(`[data-testid="${stopTestId}"]`);
  2141. btn?.click();
  2142. return Boolean(btn);
  2143. },
  2144. testId(TID_V4_PANE_SHELL, paneId),
  2145. TID_V4_STOP,
  2146. );
  2147. if (!clicked) {
  2148. throw new Error(`pane ${paneId} 内没有可点击的 stop 按钮`);
  2149. }
  2150. }
  2151. /** pane 作用域内点分屏 pane 的 session pane snapshot(按 paneId)。 */
  2152. export async function waitForV4PaneById(
  2153. paneId: string,
  2154. predicate: (snapshot: V4PaneSnapshot) => boolean,
  2155. timeoutMsg: string,
  2156. timeout = 30000,
  2157. ) {
  2158. return waitForV4Pane(predicate, timeoutMsg, timeout, paneId);
  2159. }
  2160. /** pane 作用域内写 composer 文本并点发送(同 sendV4Prompt,但按 paneId 收口)。 */
  2161. export async function sendV4PromptInPane(paneId: string, prompt: string) {
  2162. const paneShellTestId = testId(TID_V4_PANE_SHELL, paneId);
  2163. // M5:composer 为 Lexical contenteditable——写入走编辑器挂载的 __zcodeLexicalInputE2E
  2164. // bridge(驱动真实 editor state);bridge.focus() 同时驱动 Focus 层 → composer 归属该 pane。
  2165. await browser.waitUntil(
  2166. async () =>
  2167. browser.execute(
  2168. (shellTestId, inputTestId, nextValue) => {
  2169. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2170. const element = shell?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2171. if (!element) return false;
  2172. const bridge = (
  2173. element as HTMLElement & {
  2174. __zcodeLexicalInputE2E?: {
  2175. focus: () => void;
  2176. getText: () => string;
  2177. setText: (text: string) => void;
  2178. };
  2179. }
  2180. ).__zcodeLexicalInputE2E;
  2181. if (!bridge) return false;
  2182. bridge.focus();
  2183. bridge.setText(nextValue);
  2184. return bridge.getText() === nextValue;
  2185. },
  2186. paneShellTestId,
  2187. TID_V4_COMPOSER_INPUT,
  2188. prompt,
  2189. ),
  2190. {
  2191. timeout: 15000,
  2192. timeoutMsg: `pane ${paneId} 的 composer 输入框没有出现或不可输入`,
  2193. },
  2194. );
  2195. await browser.waitUntil(
  2196. async () =>
  2197. browser.execute(
  2198. (shellTestId, sendTestId) => {
  2199. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2200. const button = shell?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  2201. if (!button || button.disabled) return false;
  2202. button.click();
  2203. return true;
  2204. },
  2205. paneShellTestId,
  2206. TID_V4_COMPOSER_SEND,
  2207. ),
  2208. {
  2209. timeout: 30000,
  2210. timeoutMsg: `pane ${paneId} 的发送按钮没有变为可用`,
  2211. },
  2212. );
  2213. }
  2214. /** 等待 v4 权限弹窗出现(V4InteractionDialogs → PermissionDialog,role=listbox)。 */
  2215. export function hasV4PermissionDialog(): Promise<boolean> {
  2216. return browser.execute(() => {
  2217. const normalize = (value: string | null | undefined) => (value ?? "").replace(/ /g, " ").trim();
  2218. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  2219. (element) => {
  2220. const label = normalize(element.getAttribute("aria-label"));
  2221. return label === "Permission required" || label === "需要权限";
  2222. },
  2223. );
  2224. });
  2225. }
  2226. /** V4 普通 permission 声明 freeText 能力时,底部输入行必须实际挂载。 */
  2227. export function hasV4PermissionFeedbackInput(): Promise<boolean> {
  2228. return browser.execute(() =>
  2229. Boolean(
  2230. document.querySelector(
  2231. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2232. ),
  2233. ),
  2234. );
  2235. }
  2236. export async function waitForV4PermissionDialog(timeout = 60000) {
  2237. await browser.waitUntil(hasV4PermissionDialog, { timeout, timeoutMsg: "v4 权限弹窗没有出现" });
  2238. }
  2239. export interface V4PermissionRuleScope {
  2240. kind: "exact" | "prefix";
  2241. text: string;
  2242. }
  2243. export async function getV4PermissionRuleScopes(): Promise<V4PermissionRuleScope[]> {
  2244. return browser.execute(() => {
  2245. const normalize = (value: string | null | undefined) => (value ?? "").replace(/ /g, " ").trim();
  2246. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2247. (element) => {
  2248. const label = normalize(element.getAttribute("aria-label"));
  2249. return label === "Permission required" || label === "需要权限";
  2250. },
  2251. );
  2252. return Array.from(
  2253. listbox?.querySelectorAll<HTMLElement>("[data-permission-rule-scope]") ?? [],
  2254. ).map((element) => ({
  2255. kind: element.getAttribute("data-permission-rule-scope") === "prefix" ? "prefix" : "exact",
  2256. text: normalize(element.innerText),
  2257. }));
  2258. });
  2259. }
  2260. export interface V4PermissionDockState {
  2261. inDock: boolean;
  2262. composerMounted: boolean;
  2263. composerHidden: boolean;
  2264. interactionBeforeComposer: boolean;
  2265. composerAriaHidden: string | null;
  2266. composerDisplay: string | null;
  2267. }
  2268. async function readV4PermissionDockState(): Promise<V4PermissionDockState> {
  2269. return browser.execute((composerTestId) => {
  2270. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2271. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2272. (el) => {
  2273. const label = normalize(el.getAttribute("aria-label"));
  2274. return label === "Permission required" || label === "需要权限";
  2275. },
  2276. );
  2277. const dock = listbox?.closest<HTMLElement>('[data-v4-composer-dock="true"]') ?? null;
  2278. const composer = dock?.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`) ?? null;
  2279. const composerDisplay = composer ? getComputedStyle(composer).display : null;
  2280. const interactionBeforeComposer = Boolean(
  2281. listbox &&
  2282. composer &&
  2283. listbox.compareDocumentPosition(composer) & Node.DOCUMENT_POSITION_FOLLOWING,
  2284. );
  2285. return {
  2286. inDock: Boolean(dock),
  2287. composerMounted: Boolean(composer),
  2288. composerHidden:
  2289. composer?.getAttribute("aria-hidden") === "true" && composerDisplay === "none",
  2290. interactionBeforeComposer,
  2291. composerAriaHidden: composer?.getAttribute("aria-hidden") ?? null,
  2292. composerDisplay,
  2293. };
  2294. }, TID_V4_COMPOSER);
  2295. }
  2296. /**
  2297. * 等待真实权限弹窗进入 v4 composer dock,并确认阻塞期间 composer 只隐藏不卸载。
  2298. */
  2299. export async function waitForV4PermissionDialogInComposerDock(timeout = 60000) {
  2300. await waitForV4PermissionDialog(timeout);
  2301. await browser.waitUntil(
  2302. async () => {
  2303. const state = await readV4PermissionDockState();
  2304. return (
  2305. state.inDock &&
  2306. state.composerMounted &&
  2307. state.composerHidden &&
  2308. state.interactionBeforeComposer
  2309. );
  2310. },
  2311. { timeout, timeoutMsg: "v4 权限弹窗没有进入 composer dock 或 composer 未正确隐藏" },
  2312. );
  2313. return readV4PermissionDockState();
  2314. }
  2315. /**
  2316. * 批准 v4 权限弹窗的第一个选项(Allow once)。PermissionDialog 首项默认选中,
  2317. * 单击已选中项即确认 onRespond → resolveInteraction 命令。为稳妥点两次
  2318. *(第一次若只是选中,第二次确认)。
  2319. */
  2320. export async function approveV4Permission(feedback?: string) {
  2321. await waitForV4PermissionDialog();
  2322. if (feedback !== undefined) {
  2323. const input = await $(
  2324. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2325. );
  2326. await input.waitForDisplayed({ timeout: 15000 });
  2327. await input.setValue(feedback);
  2328. }
  2329. const confirmFirstOption = () =>
  2330. browser.execute(() => {
  2331. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2332. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2333. (el) => {
  2334. const label = normalize(el.getAttribute("aria-label"));
  2335. return label === "Permission required" || label === "需要权限";
  2336. },
  2337. );
  2338. const option = listbox?.querySelector<HTMLButtonElement>('button[role="option"]');
  2339. option?.click();
  2340. return Boolean(option);
  2341. });
  2342. await confirmFirstOption();
  2343. // 弹窗消失即视为已应答;若首次点击只是选中,再点一次确认。
  2344. const dismissed = await browser
  2345. .waitUntil(
  2346. async () => {
  2347. const stillOpen = await browser.execute(() => {
  2348. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2349. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  2350. (el) => {
  2351. const label = normalize(el.getAttribute("aria-label"));
  2352. return label === "Permission required" || label === "需要权限";
  2353. },
  2354. );
  2355. });
  2356. if (stillOpen) {
  2357. await confirmFirstOption();
  2358. return false;
  2359. }
  2360. return true;
  2361. },
  2362. { timeout: 15000, timeoutMsg: "v4 权限弹窗批准后没有关闭" },
  2363. )
  2364. .then(() => true)
  2365. .catch(() => false);
  2366. return dismissed;
  2367. }
  2368. /** 填写拒绝反馈并确认 Deny,反馈走同一个 resolveInteraction 应答。 */
  2369. export async function denyV4PermissionWithFeedback(feedback: string, submitWithEnter = false) {
  2370. await waitForV4PermissionDialog();
  2371. const input = await $(
  2372. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2373. );
  2374. await input.waitForDisplayed({ timeout: 15000 });
  2375. await input.setValue(feedback);
  2376. // 空白输入行不能提交;普通 Deny 仍可确认且只回传基础拒绝文案。
  2377. if (!feedback.trim() && !submitWithEnter) {
  2378. await browser.execute(() => {
  2379. document
  2380. .querySelector<HTMLButtonElement>('[role="option"][data-permission-option-kind^="reject"]')
  2381. ?.focus();
  2382. });
  2383. }
  2384. await browser.waitUntil(
  2385. () =>
  2386. browser.execute((hasFeedback: boolean) => {
  2387. const selectedDeny = document.querySelector(
  2388. '[role="option"][data-permission-option-kind^="reject"][aria-selected="true"]',
  2389. );
  2390. const input = document.querySelector<HTMLTextAreaElement>(
  2391. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2392. );
  2393. return hasFeedback
  2394. ? !selectedDeny &&
  2395. document.activeElement === input &&
  2396. input?.parentElement?.classList.contains("bg-selected")
  2397. : Boolean(selectedDeny);
  2398. }, Boolean(feedback.trim())),
  2399. { timeout: 5000, timeoutMsg: "权限反馈行与普通 Deny 的独立选择状态不符合预期" },
  2400. );
  2401. if (submitWithEnter) {
  2402. await input.click();
  2403. await browser.keys("Enter");
  2404. }
  2405. const clicked = submitWithEnter
  2406. ? true
  2407. : await browser.execute(() => {
  2408. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2409. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2410. (el) => {
  2411. const label = normalize(el.getAttribute("aria-label"));
  2412. return label === "Permission required" || label === "需要权限";
  2413. },
  2414. );
  2415. // 按稳定的阻塞交互区域定位,避免新增视觉分组后依赖 listbox 的直接父节点。
  2416. const confirmButton = listbox
  2417. ?.closest('[data-v4-composer-dock="true"]')
  2418. ?.querySelector<HTMLButtonElement>(
  2419. 'button[aria-label="Confirm"],button[aria-label="确认"]',
  2420. );
  2421. confirmButton?.click();
  2422. return Boolean(confirmButton);
  2423. });
  2424. if (!clicked) return false;
  2425. return browser
  2426. .waitUntil(async () => !(await hasV4PermissionDialog()), {
  2427. timeout: 15000,
  2428. timeoutMsg: "v4 权限弹窗拒绝后没有关闭",
  2429. })
  2430. .then(() => true)
  2431. .catch(() => false);
  2432. }
  2433. /** 选择携带 CLI suggestion 的项目级始终允许选项。 */
  2434. export async function approveV4PermissionAlways() {
  2435. await waitForV4PermissionDialog();
  2436. const confirmAlwaysOption = () =>
  2437. browser.execute(() => {
  2438. const normalize = (value: string | null | undefined) =>
  2439. (value ?? "").replace(/ /g, " ").trim();
  2440. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2441. (element) => {
  2442. const label = normalize(element.getAttribute("aria-label"));
  2443. return label === "Permission required" || label === "需要权限";
  2444. },
  2445. );
  2446. const option = Array.from(
  2447. listbox?.querySelectorAll<HTMLButtonElement>('button[role="option"]') ?? [],
  2448. ).find((button) => button.dataset.permissionOptionKind === "allowAlways");
  2449. option?.click();
  2450. return Boolean(option);
  2451. });
  2452. if (!(await confirmAlwaysOption())) return false;
  2453. return browser
  2454. .waitUntil(
  2455. async () => {
  2456. const stillOpen = await hasV4PermissionDialog();
  2457. if (stillOpen) {
  2458. await confirmAlwaysOption();
  2459. return false;
  2460. }
  2461. return true;
  2462. },
  2463. { timeout: 15000, timeoutMsg: "v4 项目始终允许后权限弹窗没有关闭" },
  2464. )
  2465. .then(() => true)
  2466. .catch(() => false);
  2467. }
  2468. // ── M5 composer 工具条 / slash 面板 ──
  2469. /** 读取 composer 当前文本(Lexical E2E bridge)。bridge 未挂载返回 null。 */
  2470. export function getV4ComposerText(): Promise<string | null> {
  2471. return browser.execute((inputTestId) => {
  2472. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2473. const bridge = (
  2474. element as (HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } }) | null
  2475. )?.__zcodeLexicalInputE2E;
  2476. return bridge ? bridge.getText() : null;
  2477. }, TID_V4_COMPOSER_INPUT);
  2478. }
  2479. /** composer 本体或其 Lexical 子节点当前是否持有焦点。 */
  2480. export function isV4ComposerFocused(): Promise<boolean> {
  2481. return browser.execute((inputTestId) => {
  2482. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2483. return Boolean(element && document.activeElement && element.contains(document.activeElement));
  2484. }, TID_V4_COMPOSER_INPUT);
  2485. }
  2486. /** 读取 composer 附件卡片的可观察文件名与 ready 状态。 */
  2487. export function getV4ComposerAttachments(): Promise<
  2488. Array<{ text: string; uploadStatus: string | null }>
  2489. > {
  2490. return browser.execute(
  2491. (attachmentPrefix) =>
  2492. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${attachmentPrefix}-"]`))
  2493. .filter((element) => element.hasAttribute("data-upload-status"))
  2494. .map((element) => {
  2495. // Bug 原因:媒体卡片按产品设计只展示缩略图,文件名在 img alt 中;读取
  2496. // innerText 会把 ready 的图片误判成“附件没有进入 ready”。
  2497. const mediaFilename = element.querySelector<HTMLImageElement>("img[alt]")?.alt.trim();
  2498. return {
  2499. text: mediaFilename || (element.innerText || element.textContent || "").trim(),
  2500. uploadStatus: element.getAttribute("data-upload-status"),
  2501. };
  2502. }),
  2503. TID_V4_ATTACHMENT,
  2504. );
  2505. }
  2506. /** slash 候选面板是否出现。 */
  2507. export function hasV4SlashPanel(): Promise<boolean> {
  2508. return browser.execute(
  2509. (panelTestId) => Boolean(document.querySelector(`[data-testid="${panelTestId}"]`)),
  2510. TID_PROMPT_SUGGESTION_PANEL,
  2511. );
  2512. }
  2513. /** 读取 slash 面板当前候选项 id(如 "slash:compact")。 */
  2514. export function getV4SlashOptionIds(): Promise<string[]> {
  2515. return browser.execute((optionPrefix) => {
  2516. return Array.from(
  2517. document.querySelectorAll<HTMLElement>(`[data-testid^="${optionPrefix}-"]`),
  2518. ).map((element) => element.getAttribute("data-option-id") ?? "");
  2519. }, TID_PROMPT_SUGGESTION_OPTION);
  2520. }
  2521. /** 等待 slash 面板出现且包含目标候选项。 */
  2522. export async function waitForV4SlashOption(optionId: string, timeout = 15000) {
  2523. await browser.waitUntil(
  2524. async () => (await hasV4SlashPanel()) && (await getV4SlashOptionIds()).includes(optionId),
  2525. {
  2526. timeout,
  2527. timeoutMsg: `slash 面板没有出现候选项: ${optionId}`,
  2528. },
  2529. );
  2530. }
  2531. /**
  2532. * 点选 slash 候选项。面板选项在 mousedown 上确认(preventDefault 防 blur),
  2533. * element.click() 不派发 mousedown,这里显式 dispatch。
  2534. */
  2535. export async function clickV4SlashOption(optionId: string) {
  2536. const optionTestId = testId(TID_PROMPT_SUGGESTION_OPTION, optionId);
  2537. let dispatched = false;
  2538. await browser.waitUntil(
  2539. async () => {
  2540. // Bug 根因:Windows Skill option id 含反斜杠,动态 CSS selector 无法精确命中;
  2541. // 同时 React 可能在候选加载时重挂载节点,所以定位与 mousedown 必须在一次查询内重试。
  2542. dispatched = await browser.execute(dispatchMouseDownByExactTestId, optionTestId);
  2543. return dispatched;
  2544. },
  2545. {
  2546. timeout: 15000,
  2547. timeoutMsg: `slash 面板候选项不可点击: ${optionId}`,
  2548. },
  2549. );
  2550. return dispatched;
  2551. }
  2552. /** 通过 composer 工具条切换协作模式(switchCollaborationMode 命令)。 */
  2553. export async function switchV4Mode(mode: string) {
  2554. await selectRadixOption(
  2555. TID_CHAT_MODE_SELECT_TRIGGER,
  2556. testId(TID_CHAT_MODE_SELECT_ITEM, mode),
  2557. `v4 模式选择器没有出现目标模式项: ${mode}`,
  2558. );
  2559. }
  2560. /** 读取 config 投影扩展锚点(data-mode / data-usage-*,M5 additive)。 */
  2561. export function getV4ConfigProjection(): Promise<{
  2562. mode: string | null;
  2563. planEnabled: boolean;
  2564. usageUsed: number;
  2565. usageMax: number;
  2566. }> {
  2567. return browser.execute((modelTestId) => {
  2568. const el = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  2569. return {
  2570. mode: el?.getAttribute("data-mode") ?? null,
  2571. usageUsed: Number(el?.getAttribute("data-usage-used") || 0),
  2572. planEnabled: el?.getAttribute("data-plan-enabled") === "true",
  2573. usageMax: Number(el?.getAttribute("data-usage-max") || 0),
  2574. };
  2575. }, TID_V4_MODEL_CONFIG);
  2576. }
  2577. // ── M5 composer mention(@/#/$)/ 附件 ──
  2578. // mention 面板与 slash 面板共用 TID_PROMPT_SUGGESTION_PANEL / _OPTION 契约,
  2579. // 故读取/点选原语与 slash 同源;option-id 前缀区分(file:/session:/skill:)。
  2580. /**
  2581. * 等待 mention 面板出现且含以 prefix 打头的候选项(如 "session:")。
  2582. * 返回首个命中的完整 option-id。
  2583. */
  2584. export async function waitForV4MentionOptionPrefix(
  2585. prefix: string,
  2586. timeout = 15000,
  2587. ): Promise<string> {
  2588. let matched: string | undefined;
  2589. await browser.waitUntil(
  2590. async () => {
  2591. if (!(await hasV4SlashPanel())) return false;
  2592. matched = (await getV4SlashOptionIds()).find((id) => id.startsWith(prefix));
  2593. return Boolean(matched);
  2594. },
  2595. {
  2596. timeout,
  2597. timeoutMsg: `mention 面板没有出现以 "${prefix}" 打头的候选项`,
  2598. },
  2599. );
  2600. return matched as string;
  2601. }
  2602. /** 经真实 paste 事件向 v4 composer 加入一个 File,并走既有 eager upload。 */
  2603. export async function pasteV4ComposerFileAttachment(
  2604. filename = "e2e-pasted.png",
  2605. options: { base64?: string; mimeType?: string; pngBase64?: string } = {},
  2606. ): Promise<string> {
  2607. const pasted = await browser.execute(
  2608. (inputTestId, fileName, explicitBase64, explicitPngBase64, explicitMimeType) => {
  2609. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2610. const editable =
  2611. input?.querySelector<HTMLElement>('[contenteditable="true"]') ??
  2612. (input?.getAttribute("contenteditable") === "true" ? input : null);
  2613. if (!editable) return false;
  2614. // 修复原因:旧 fixture 虽能被 file 识别为 PNG,但 production Jimp 会拒绝其尾部数据;
  2615. // 使用已通过同一解码器验证的 1×1 PNG,避免图片 E2E 在业务读取前退化为占位文本。
  2616. const imageBase64 =
  2617. explicitBase64 ??
  2618. explicitPngBase64 ??
  2619. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4AWMAAQAABQABNtCI3QAAAABJRU5ErkJggg==";
  2620. const binary = atob(imageBase64);
  2621. const bytes = new Uint8Array(binary.length);
  2622. for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
  2623. const file = new File([bytes], fileName, { type: explicitMimeType ?? "image/png" });
  2624. const dataTransfer = new DataTransfer();
  2625. dataTransfer.items.add(file);
  2626. const pasteEvent = new ClipboardEvent("paste", {
  2627. clipboardData: dataTransfer,
  2628. bubbles: true,
  2629. cancelable: true,
  2630. });
  2631. editable.focus();
  2632. editable.dispatchEvent(pasteEvent);
  2633. return true;
  2634. },
  2635. TID_V4_COMPOSER_INPUT,
  2636. filename,
  2637. options.base64,
  2638. options.pngBase64,
  2639. options.mimeType,
  2640. );
  2641. if (!pasted) {
  2642. throw new Error("v4 composer 输入框没有出现,无法派发粘贴事件");
  2643. }
  2644. return filename;
  2645. }
  2646. /** 向 v4 composer 派发图片文件;保留既有 case 的语义化入口。 */
  2647. export function pasteV4ComposerImageAttachment(
  2648. filename = "e2e-pasted.png",
  2649. options: { base64?: string; mimeType?: string; pngBase64?: string } = {},
  2650. ): Promise<string> {
  2651. return pasteV4ComposerFileAttachment(filename, options);
  2652. }
  2653. /** 等待某个 user 行渲染出附件簇,返回文件 pill 文本及媒体缩略图的可访问文件名。 */
  2654. export async function waitForV4RowAttachments(timeout = 60000): Promise<string> {
  2655. let text = "";
  2656. await browser.waitUntil(
  2657. async () => {
  2658. text = await browser.execute((attachmentsPrefix) => {
  2659. const el = document.querySelector<HTMLElement>(`[data-testid^="${attachmentsPrefix}-"]`);
  2660. if (!el) return "";
  2661. // Bug 原因:已发送媒体只有缩略图,文件名由 img alt 承载,不能用 innerText
  2662. // 是否为空来判断附件簇有没有渲染。
  2663. const visibleText = (el.innerText ?? "").trim();
  2664. const mediaFilenames = Array.from(el.querySelectorAll<HTMLImageElement>("img[alt]"))
  2665. .map((image) => image.alt.trim())
  2666. .filter(Boolean);
  2667. return [visibleText, ...mediaFilenames].filter(Boolean).join("\n");
  2668. }, TID_V4_ROW_ATTACHMENTS);
  2669. return text.trim().length > 0;
  2670. },
  2671. { timeout, timeoutMsg: "user 行没有渲染出附件簇(TID_V4_ROW_ATTACHMENTS)" },
  2672. );
  2673. return text;
  2674. }