conversation-session-local-config-runtime-usage.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import {
  4. TID_MCP_SERVER_ROW,
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_SETTINGS_PAGE,
  7. TID_SETTINGS_SECTION_NAV,
  8. TID_SUBAGENT_ROW,
  9. TID_TASK_SETTINGS_BUTTON,
  10. TID_V4_SESSION_PANE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. DEFAULT_WORKSPACE,
  17. getE2EAppDataPaths,
  18. pinE2ELocale,
  19. waitForTestIdByDom,
  20. } from "#e2e/helpers/desktop-app";
  21. import {
  22. refreshSeededOpenAIProvidersThroughSettings,
  23. seedCustomOpenAIChatCompletionsProvider,
  24. } from "#e2e/helpers/custom-openai-provider";
  25. import {
  26. addMarketplaceSourceThroughAgent,
  27. clickPluginControl,
  28. createPluginLifecycleFixture,
  29. installPluginThroughUi,
  30. openPluginCard,
  31. openPluginSettings,
  32. PLUGIN_LIFECYCLE_ID,
  33. PLUGIN_LIFECYCLE_MCP_TOOL_NAME,
  34. PLUGIN_LIFECYCLE_RUNTIME_MARKER,
  35. waitUntilPluginOverview,
  36. } from "#e2e/helpers/plugin-management-lifecycle";
  37. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  38. import {
  39. selectUpstreamProviderModelById,
  40. selectUpstreamThoughtLevelValue,
  41. } from "#e2e/helpers/upstream-provider";
  42. import {
  43. countUpstreamRequests,
  44. getLatestUpstreamToolResultByToolCallId,
  45. getUpstreamRequestEvidence,
  46. getUpstreamRequestRecordCount,
  47. getUpstreamRequestToolNames,
  48. waitForUpstreamRequest,
  49. type UpstreamToolResultSnapshot,
  50. } from "#e2e/helpers/conversation-session-network";
  51. import { hasAssistantReplyForUserTurn } from "#e2e/helpers/conversation-turn-evidence";
  52. import {
  53. approveV4Permission,
  54. clickV4Stop,
  55. getV4ConversationState,
  56. getV4Messages,
  57. getV4SlashOptionIds,
  58. hasV4PermissionDialog,
  59. prepareV4ConversationE2E,
  60. selectV4TaskById,
  61. sendV4PromptAndWaitAccepted,
  62. setV4ComposerText,
  63. V4_MAIN_PANE_ID,
  64. waitForV4ConversationState,
  65. } from "#e2e/helpers/v4-conversation";
  66. // DSYNC-18:本机配置变更在本机会话中的生效时机,作为 DSYNC-17(远端推送)的对照。
  67. // 每个分类单独打开一个新建任务页(预热会话建好),再按本机真实途径新建该分类:
  68. // 子智能体、MCP、钩子、命令走设置页;技能和 inline 插件没有设置页新建入口,直接写文件;
  69. // marketplace 插件走插件商店安装(商店主视图会卸掉会话面板,所以不测预热草稿)。
  70. // 然后分别在该页、推送前已有的 task A 发探针;最后新建 task C 实际调用各工具。只记录事实,
  71. // 期望由用户确认后再改为断言;task C 的可用性与 DSYNC-17-03 相同,作为断言。
  72. const CASE_MARKER = "E2E_DSYNC_18_LOCAL_RUNTIME";
  73. const TITLE_REQUEST = "Generate a concise title";
  74. const MODEL_ID = "e2e-dsync-18-model";
  75. const PROVIDER_ID = "e2e-dsync-18-provider";
  76. const PROVIDER_NAME = "DSYNC 18 local";
  77. const SKILL_NAME = "e2e-dsync-18-skill";
  78. const SKILL_DESC = "E2E_DSYNC_18_SKILL_DESC";
  79. const SKILL_BODY = "E2E_DSYNC_18_SKILL_BODY";
  80. const AGENT_NAME = "e2e-dsync-18-agent";
  81. const AGENT_DESC = "E2E_DSYNC_18_AGENT_DESC";
  82. const AGENT_BODY = "E2E_DSYNC_18_AGENT_BODY";
  83. const AGENT_DONE = "E2E_DSYNC_18_AGENT_DONE";
  84. const COMMAND_NAME = "e2e-dsync-18-cmd";
  85. const COMMAND_BODY = "E2E_DSYNC_18_COMMAND_BODY";
  86. const MCP_SERVER = "e2e-dsync-18-mcp";
  87. const MCP_TOOL = `mcp__${MCP_SERVER}__marker`;
  88. const MCP_RESULT = "E2E_DSYNC_18_MCP_RESULT";
  89. const INLINE_PLUGIN = "e2e-dsync-18-inline";
  90. const INLINE_TOOL = `mcp__plugin_${INLINE_PLUGIN}_rt__marker`;
  91. const INLINE_RESULT = "E2E_DSYNC_18_INLINE_RESULT";
  92. const MARKET_RESULT = `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_1.0.0`;
  93. // 钩子在 workspace 目录(钩子的 cwd)追加标记行,不写 stdout:stdout 会进入上下文。
  94. const HOOK_MARK = "E2E_DSYNC_18_HOOK";
  95. const HOOK_LOG = join(DEFAULT_WORKSPACE, ".e2e-dsync-18-hooks.log");
  96. const HOOK_FORM = '[data-testid="hooks-form"]';
  97. const SCOPE_TRIGGER = '[data-plugin-scope-trigger="true"]';
  98. const artifactDir = resolve(
  99. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/dsync-18-local-runtime",
  100. "dsync-18",
  101. );
  102. interface StageFacts {
  103. skillListed: boolean;
  104. subagentListed: boolean;
  105. mcpTool: boolean;
  106. inlinePluginTool: boolean;
  107. marketplacePluginTool: boolean;
  108. hookFired: boolean;
  109. }
  110. interface RunOutcome {
  111. exposed: boolean;
  112. timedOut: boolean;
  113. result: UpstreamToolResultSnapshot | null;
  114. }
  115. interface LocalCliConfig {
  116. [key: string]: unknown;
  117. plugins?: { [key: string]: unknown; dirs?: string[]; enabledPlugins?: Record<string, boolean> };
  118. }
  119. /** 依赖为零的 stdio MCP 服务器脚本。 */
  120. function mcpServerScript(serverName: string, result: string): string {
  121. return [
  122. 'const rl = require("node:readline").createInterface({ input: process.stdin });',
  123. 'const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");',
  124. 'rl.on("line", (line) => {',
  125. " let request;",
  126. " try { request = JSON.parse(line); } catch { return; }",
  127. ` if (request.method === "initialize") return send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: ${JSON.stringify(serverName)}, version: "1.0.0" } } });`,
  128. ' if (request.method === "tools/list") return send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "marker", description: "Return the data sync runtime marker", inputSchema: { type: "object", properties: {} } }] } });',
  129. ` if (request.method === "tools/call") return send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: ${JSON.stringify(result)} }] } });`,
  130. ' if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });',
  131. "});",
  132. ].join("\n");
  133. }
  134. async function writeText(path: string, content: string): Promise<void> {
  135. await mkdir(join(path, ".."), { recursive: true });
  136. await writeFile(path, content);
  137. }
  138. async function countHookLines(): Promise<number> {
  139. const text = await readFile(HOOK_LOG, "utf-8").catch(() => "");
  140. return text.split("\n").filter((line) => line.includes(HOOK_MARK)).length;
  141. }
  142. /** 本轮首个模型请求(排除标题请求):请求体文本与工具名。 */
  143. async function readTurnRequest(lastUserMarker: string, afterIndex: number) {
  144. const query = { lastUserMessageIncludes: [lastUserMarker], excludes: [TITLE_REQUEST] };
  145. const [request] = await getUpstreamRequestEvidence(query, { afterIndex });
  146. if (!request) throw new Error(`${CASE_MARKER}: 没有找到 ${lastUserMarker} 的模型请求`);
  147. return {
  148. body: JSON.stringify(request.requestJson),
  149. tools: await getUpstreamRequestToolNames(query),
  150. };
  151. }
  152. function factsFromRequest(
  153. request: { body: string; tools: string[] },
  154. hookFired: boolean,
  155. ): StageFacts {
  156. return {
  157. skillListed: request.body.includes(SKILL_DESC),
  158. subagentListed: request.body.includes(AGENT_DESC),
  159. mcpTool: request.tools.includes(MCP_TOOL),
  160. inlinePluginTool: request.tools.includes(INLINE_TOOL),
  161. marketplacePluginTool: request.tools.includes(PLUGIN_LIFECYCLE_MCP_TOOL_NAME),
  162. hookFired,
  163. };
  164. }
  165. async function waitForTurnReply(userMarker: string, reply: string): Promise<string> {
  166. await browser.waitUntil(
  167. async () => hasAssistantReplyForUserTurn(await getV4Messages(), userMarker, reply),
  168. { timeout: 120_000, timeoutMsg: `${CASE_MARKER}: ${userMarker} 没有收到回复 ${reply}` },
  169. );
  170. const state = await waitForV4ConversationState(
  171. (snapshot) =>
  172. Boolean(snapshot.taskId && snapshot.taskId !== "draft") &&
  173. snapshot.state === "idle" &&
  174. snapshot.queueCount === 0,
  175. `${CASE_MARKER}: ${userMarker} 完成后没有回到 idle`,
  176. 120_000,
  177. );
  178. return state.taskId!;
  179. }
  180. /** 探针轮次:只回复固定文本,返回本轮模型请求里可见的新建内容与钩子是否执行。 */
  181. async function sendProbe(label: string) {
  182. const prompt = `${CASE_MARKER}_PROBE_${label}`;
  183. const reply = `DSYNC_18_PROBE_${label}_REPLY`;
  184. const hookBefore = await countHookLines();
  185. const start = await getUpstreamRequestRecordCount();
  186. await sendV4PromptAndWaitAccepted(
  187. `${prompt}: 只回复 ${reply}`,
  188. prompt,
  189. `${CASE_MARKER}: 探针 ${label} 没有被接受`,
  190. );
  191. await waitForUpstreamRequest(
  192. { lastUserMessageIncludes: [`${prompt}:`] },
  193. `${CASE_MARKER}: 探针 ${label} 没有到达回放`,
  194. 120_000,
  195. { afterIndex: start - 1 },
  196. );
  197. const taskId = await waitForTurnReply(prompt, reply);
  198. const request = await readTurnRequest(`${prompt}:`, start - 1);
  199. return { taskId, facts: factsFromRequest(request, (await countHookLines()) > hookBefore) };
  200. }
  201. /** 命令轮次:CLI 展开 /命令 时,本轮请求含命令正文与参数。 */
  202. async function sendCommandProbe(label: string): Promise<boolean> {
  203. const args = `E2E_DSYNC_18_CMD_${label}`;
  204. const start = await getUpstreamRequestRecordCount();
  205. await sendV4PromptAndWaitAccepted(
  206. `/${COMMAND_NAME} ${args}`,
  207. args,
  208. `${CASE_MARKER}: 命令 ${label} 没有被接受`,
  209. );
  210. await waitForUpstreamRequest(
  211. { lastUserMessageIncludes: [args] },
  212. `${CASE_MARKER}: 命令 ${label} 没有到达回放`,
  213. 120_000,
  214. { afterIndex: start - 1 },
  215. );
  216. await waitForTurnReply(args, `DSYNC_18_CMD_${label}_REPLY`);
  217. return (await readTurnRequest(args, start - 1)).body.includes(`${COMMAND_BODY} ${args}`);
  218. }
  219. /** 输入框的 / 菜单里是否有该命令(只读界面,不发送)。 */
  220. async function isCommandInSlashMenu(): Promise<boolean> {
  221. await setV4ComposerText(`/${COMMAND_NAME}`);
  222. const found = await browser
  223. .waitUntil(async () => (await getV4SlashOptionIds()).some((id) => id.includes(COMMAND_NAME)), {
  224. timeout: 10_000,
  225. interval: 500,
  226. })
  227. .then(
  228. () => true,
  229. () => false,
  230. );
  231. await setV4ComposerText("");
  232. return found;
  233. }
  234. /** 执行轮次:回放在工具暴露时调用工具,否则回复 NOT_EXPOSED;卡住时停止本轮并继续。 */
  235. async function runTool(key: string, instruction: string): Promise<RunOutcome> {
  236. // 带冒号:RUN_AGENT 是 RUN_AGENT_EXISTING 的前缀。
  237. const prompt = `${CASE_MARKER}_RUN_${key}:`;
  238. const done = `DSYNC_18_RUN_${key}_DONE`;
  239. const notExposed = `DSYNC_18_RUN_${key}_NOT_EXPOSED`;
  240. const toolCallId = `call_dsync18_${key.toLowerCase()}`;
  241. await sendV4PromptAndWaitAccepted(
  242. `${prompt} ${instruction}`,
  243. prompt,
  244. `${CASE_MARKER}: ${key} 执行轮次没有被接受`,
  245. );
  246. let reply: string | null = null;
  247. const settled = await browser
  248. .waitUntil(
  249. async () => {
  250. if (await hasV4PermissionDialog()) await approveV4Permission();
  251. const messages = await getV4Messages();
  252. reply =
  253. [done, notExposed].find((text) => hasAssistantReplyForUserTurn(messages, prompt, text)) ??
  254. null;
  255. return reply !== null;
  256. },
  257. { timeout: 120_000 },
  258. )
  259. .then(
  260. () => true,
  261. () => false,
  262. );
  263. if (!settled) {
  264. if ((await getV4ConversationState()).state === "streaming") await clickV4Stop();
  265. await waitForV4ConversationState(
  266. (snapshot) => snapshot.state === "idle",
  267. `${CASE_MARKER}: ${key} 停止后没有回到 idle`,
  268. 120_000,
  269. );
  270. return {
  271. exposed: true,
  272. timedOut: true,
  273. result: await getLatestUpstreamToolResultByToolCallId(toolCallId),
  274. };
  275. }
  276. await waitForTurnReply(prompt, reply!);
  277. return {
  278. exposed: reply === done,
  279. timedOut: false,
  280. result: await getLatestUpstreamToolResultByToolCallId(toolCallId),
  281. };
  282. }
  283. async function readMainPaneSessionId(): Promise<string | null> {
  284. return await browser.execute(
  285. (paneTestId) =>
  286. document.querySelector(`[data-testid="${paneTestId}"]`)?.getAttribute("data-session-id") ??
  287. null,
  288. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  289. );
  290. }
  291. /** 在本机项目里打开新建任务页并选好模型:预热会话在这一步建好。 */
  292. async function openLocalDraft(): Promise<void> {
  293. await startDraftFromProject(DEFAULT_WORKSPACE);
  294. await selectUpstreamProviderModelById(MODEL_ID, {
  295. includePlainModelFallback: false,
  296. providerId: PROVIDER_ID,
  297. providerName: PROVIDER_NAME,
  298. });
  299. await selectUpstreamThoughtLevelValue("disabled");
  300. expect(await readMainPaneSessionId()).toBe("draft");
  301. }
  302. // ── 设置页操作(与 DSYNC-15 的写法相同:按可见元素操作,React 受控组件用原生 setter)──
  303. async function openSettingsSection(section: string): Promise<void> {
  304. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  305. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  306. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, section), {
  307. timeout: 30_000,
  308. timeoutMsg: `${CASE_MARKER}: 设置页没有 ${section} 分区`,
  309. });
  310. // 本机项目的 tab 下默认是「本机 · 用户」。
  311. await browser.waitUntil(
  312. () =>
  313. browser.execute(
  314. (selector) =>
  315. Array.from(document.querySelectorAll<HTMLElement>(selector)).find(
  316. (element) => element.getClientRects().length > 0,
  317. )?.dataset.pluginScopeKey === "user",
  318. SCOPE_TRIGGER,
  319. ),
  320. { timeout: 60_000, timeoutMsg: `${CASE_MARKER}: ${section} 页没有默认选中「本机 · 用户」` },
  321. );
  322. }
  323. async function closeSettings(): Promise<void> {
  324. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 30_000 });
  325. await browser.waitUntil(
  326. async () => !(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed()),
  327. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 设置页没有关闭` },
  328. );
  329. }
  330. /** 点击第一个可见、可用、文案或 aria-label 匹配的按钮。 */
  331. async function clickVisibleButton(labels: readonly string[], timeoutMsg: string): Promise<void> {
  332. await browser.waitUntil(
  333. () =>
  334. browser.execute((expected) => {
  335. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  336. (element) =>
  337. element.getClientRects().length > 0 &&
  338. !element.disabled &&
  339. (expected.includes(element.getAttribute("aria-label") ?? "") ||
  340. expected.includes(element.innerText.trim()) ||
  341. expected.includes(element.dataset.settingsCreateAction ?? "")),
  342. );
  343. button?.click();
  344. return Boolean(button);
  345. }, labels),
  346. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: ${timeoutMsg}` },
  347. );
  348. }
  349. async function fillByPlaceholder(placeholder: string, value: string): Promise<void> {
  350. const filled = await browser.execute(
  351. (expected, nextValue) => {
  352. const field = Array.from(
  353. document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea"),
  354. ).find((element) => element.placeholder === expected && element.getClientRects().length > 0);
  355. if (!field) return false;
  356. const prototype =
  357. field instanceof HTMLTextAreaElement
  358. ? HTMLTextAreaElement.prototype
  359. : HTMLInputElement.prototype;
  360. Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(field, nextValue);
  361. field.dispatchEvent(new Event("input", { bubbles: true }));
  362. return true;
  363. },
  364. placeholder,
  365. value,
  366. );
  367. if (!filled) throw new Error(`${CASE_MARKER}: 表单没有输入框 ${placeholder}`);
  368. }
  369. /** 提交含指定输入框的表单,并等表单关闭。 */
  370. async function submitFormOf(placeholder: string): Promise<void> {
  371. await browser.waitUntil(
  372. () =>
  373. browser.execute((expected) => {
  374. const field = Array.from(
  375. document.querySelectorAll<HTMLInputElement>("input, textarea"),
  376. ).find((element) => element.placeholder === expected);
  377. const form = field?.closest("form");
  378. const submit = form?.querySelector<HTMLButtonElement>('button[type="submit"]');
  379. if (!form || !submit || submit.disabled) return false;
  380. form.requestSubmit(submit);
  381. return true;
  382. }, placeholder),
  383. { timeout: 15_000, interval: 300, timeoutMsg: `${CASE_MARKER}: 表单 ${placeholder} 不能保存` },
  384. );
  385. await browser.waitUntil(
  386. () =>
  387. browser.execute(
  388. (expected) =>
  389. !Array.from(document.querySelectorAll<HTMLInputElement>("input")).some(
  390. (element) => element.placeholder === expected,
  391. ),
  392. placeholder,
  393. ),
  394. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 保存后表单 ${placeholder} 没有关闭` },
  395. );
  396. }
  397. async function createSubagentInSettings(): Promise<void> {
  398. await openSettingsSection("subagents");
  399. await clickVisibleButton(["新建", "New"], "子智能体页没有可用的「新建」按钮");
  400. await fillByPlaceholder("code-reviewer", AGENT_NAME);
  401. await fillByPlaceholder("展示给模型的简短说明", `${AGENT_DESC} local runtime subagent`);
  402. await fillByPlaceholder(
  403. "描述这个子智能体的角色、边界和规则...",
  404. `${AGENT_BODY} Reply exactly as the task asks.`,
  405. );
  406. await submitFormOf("code-reviewer");
  407. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, AGENT_NAME), { timeout: 30_000 });
  408. await closeSettings();
  409. }
  410. async function createMcpInSettings(serverPath: string): Promise<void> {
  411. await openSettingsSection("mcp");
  412. await clickVisibleButton(
  413. ["settings.mcp.create.open", "新建 MCP 服务器"],
  414. "MCP 页没有可用的「新建 MCP 服务器」",
  415. );
  416. await fillByPlaceholder("my-mcp-server", MCP_SERVER);
  417. await fillByPlaceholder("npx", "node");
  418. await fillByPlaceholder("-y @modelcontextprotocol/server-memory", serverPath);
  419. await clickVisibleButton(["保存"], "MCP 表单没有「保存」");
  420. await waitForTestIdByDom(testId(TID_MCP_SERVER_ROW, MCP_SERVER), { timeout: 30_000 });
  421. await closeSettings();
  422. }
  423. /** 设置页新建一条 UserPromptSubmit 的 process 钩子,在 workspace 目录追加标记行。 */
  424. async function createHookInSettings(): Promise<void> {
  425. const hookPath = join(DEFAULT_WORKSPACE, ".e2e-dsync-18-hook.cjs");
  426. // Bug 原因:Windows 没有 /bin/sh;用同一个 Node 脚本验证钩子,避免平台 shell 差异。
  427. await writeText(
  428. hookPath,
  429. 'require("node:fs/promises").appendFile(process.argv[2], process.argv[3] + "\\n");\n',
  430. );
  431. await openSettingsSection("hooks");
  432. await browser.waitUntil(
  433. () =>
  434. browser.execute(() => {
  435. const button = Array.from(
  436. document.querySelectorAll<HTMLButtonElement>(
  437. '[data-settings-create-action="settings.hooks.add"]',
  438. ),
  439. ).find((element) => element.getClientRects().length > 0 && !element.disabled);
  440. button?.click();
  441. return Boolean(button);
  442. }),
  443. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 没有可用的「新建钩子」` },
  444. );
  445. await $(HOOK_FORM).waitForDisplayed({ timeout: 15_000 });
  446. await $("#hook-event").click();
  447. await $('[role="option"]*=UserPromptSubmit').click();
  448. await browser.waitUntil(
  449. async () => ((await $("#hook-event").getText()) ?? "").includes("UserPromptSubmit"),
  450. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 钩子事件没有选中 UserPromptSubmit` },
  451. );
  452. for (const [id, value] of [
  453. ["command", process.execPath],
  454. ["args", [hookPath, HOOK_LOG, HOOK_MARK].join("\n")],
  455. ] as const) {
  456. const filled = await browser.execute(
  457. (selector, fieldId, nextValue) => {
  458. const field = document
  459. .querySelector<HTMLElement>(selector)
  460. ?.querySelector<HTMLInputElement | HTMLTextAreaElement>(`#${fieldId}`);
  461. if (!field) return false;
  462. const prototype =
  463. field instanceof HTMLTextAreaElement
  464. ? HTMLTextAreaElement.prototype
  465. : HTMLInputElement.prototype;
  466. Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(field, nextValue);
  467. field.dispatchEvent(new Event("input", { bubbles: true }));
  468. return true;
  469. },
  470. HOOK_FORM,
  471. id,
  472. value,
  473. );
  474. if (!filled) throw new Error(`${CASE_MARKER}: 钩子表单没有输入框 #${id}`);
  475. }
  476. await browser.waitUntil(
  477. () =>
  478. browser.execute((selector) => {
  479. const button = Array.from(
  480. document
  481. .querySelector<HTMLElement>(selector)
  482. ?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  483. ).find((item) => /^(保存|Save)$/iu.test(item.innerText.trim()) && !item.disabled);
  484. button?.click();
  485. return Boolean(button);
  486. }, HOOK_FORM),
  487. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 钩子表单没有可用的保存按钮` },
  488. );
  489. await browser.waitUntil(async () => !(await $(HOOK_FORM).isExisting()), {
  490. timeout: 30_000,
  491. timeoutMsg: `${CASE_MARKER}: 保存后钩子表单没有关闭`,
  492. });
  493. await closeSettings();
  494. }
  495. async function createCommandInSettings(): Promise<void> {
  496. await openSettingsSection("commands");
  497. await clickVisibleButton(["新建", "New"], "命令页没有可用的「新建」按钮");
  498. await fillByPlaceholder("my-command", COMMAND_NAME);
  499. await fillByPlaceholder("在命令选择器中显示的简短描述", "local runtime command");
  500. await fillByPlaceholder("填写调用该命令时发送的提示词...", `${COMMAND_BODY} $ARGUMENTS`);
  501. await submitFormOf("my-command");
  502. await closeSettings();
  503. }
  504. /** 技能没有设置页新建入口(「新建」是开一个让 Agent 写文件的任务),直接写文件。 */
  505. async function writeSkillFile(homeDir: string): Promise<void> {
  506. await writeText(
  507. join(homeDir, ".zcode", "skills", SKILL_NAME, "SKILL.md"),
  508. `---\nname: ${SKILL_NAME}\ndescription: ${SKILL_DESC} local runtime skill\n---\n\n${SKILL_BODY}\n`,
  509. );
  510. }
  511. /** inline 插件没有设置页添加入口,写插件目录并登记到 config.json 的 plugins.dirs。 */
  512. async function writeInlinePlugin(homeDir: string): Promise<void> {
  513. const dir = join(homeDir, ".zcode", "plugins", INLINE_PLUGIN);
  514. await writeText(
  515. join(dir, ".zcode-plugin", "plugin.json"),
  516. `${JSON.stringify(
  517. {
  518. name: INLINE_PLUGIN,
  519. version: "1.0.0",
  520. description: "local runtime inline plugin",
  521. mcpServers: {
  522. rt: { type: "stdio", command: "node", args: ["${ZCODE_PLUGIN_ROOT}/server.cjs"] },
  523. },
  524. },
  525. null,
  526. 2,
  527. )}\n`,
  528. );
  529. await writeText(join(dir, "server.cjs"), `${mcpServerScript(INLINE_PLUGIN, INLINE_RESULT)}\n`);
  530. const configPath = join(homeDir, ".zcode", "cli", "config.json");
  531. const config = await readFile(configPath, "utf-8")
  532. .then((text) => JSON.parse(text) as LocalCliConfig)
  533. .catch((): LocalCliConfig => ({}));
  534. const plugins = config.plugins ?? {};
  535. await writeText(
  536. configPath,
  537. `${JSON.stringify(
  538. {
  539. ...config,
  540. plugins: {
  541. ...plugins,
  542. dirs: [...(plugins.dirs ?? []), dir],
  543. enabledPlugins: { ...plugins.enabledPlugins, [`${INLINE_PLUGIN}@inline`]: true },
  544. },
  545. },
  546. null,
  547. 2,
  548. )}\n`,
  549. );
  550. }
  551. describe(`${CASE_MARKER}: 本机配置变更在本机会话中的生效时机`, () => {
  552. let taskAId = "";
  553. const facts: Record<string, unknown> = {};
  554. const record = (key: string, value: unknown) => {
  555. facts[key] = value;
  556. process.stdout.write(`[${CASE_MARKER}] ${key} ${JSON.stringify(value)}\n`);
  557. };
  558. /** 推送前已打开的新建任务页:变更后在该页发送;再到 task A 续发。 */
  559. async function measureStage(
  560. label: string,
  561. change: () => Promise<void>,
  562. options: { secondDraftTurn?: boolean } = {},
  563. ): Promise<void> {
  564. await openLocalDraft();
  565. await change();
  566. expect(await readMainPaneSessionId()).toBe("draft");
  567. const draft = await sendProbe(`DRAFT_${label}`);
  568. await selectV4TaskById(taskAId, 30_000);
  569. const existing = await sendProbe(`EXISTING_${label}`);
  570. expect(existing.taskId).toBe(taskAId);
  571. // 子智能体:Host 缓存靠文件监听更新,写入后约 1–1.5 秒才生效(awaitWriteFinish 1000ms)。
  572. // 回到草稿生成的 task 再发一轮,区分「空窗内看不到」与「这个会话一直看不到」。
  573. let draftSecondTurn: StageFacts | undefined;
  574. if (options.secondDraftTurn) {
  575. await selectV4TaskById(draft.taskId, 30_000);
  576. draftSecondTurn = (await sendProbe(`DRAFT_${label}_2`)).facts;
  577. }
  578. record(label, { draft: draft.facts, existing: existing.facts, draftSecondTurn });
  579. }
  580. after(async () => {
  581. await mkdir(artifactDir, { recursive: true });
  582. await writeFile(join(artifactDir, "runtime-usage.json"), `${JSON.stringify(facts, null, 2)}\n`);
  583. await rm(HOOK_LOG, { force: true });
  584. await browser.electron.restoreAllMocks();
  585. await clearAppData();
  586. });
  587. it("DSYNC-18-01 本机逐类新建配置:记录推送前打开的新建任务页与已有 task 的可见内容", async function () {
  588. this.timeout(40 * 60_000);
  589. const { homeDir } = getE2EAppDataPaths();
  590. await rm(HOOK_LOG, { force: true });
  591. await prepareV4ConversationE2E({ skipProvider: true });
  592. // 表单按中文 placeholder 定位;英文 Runner 会在创建配置前失败,须先固定并等待界面语言。
  593. await pinE2ELocale("zh-CN");
  594. await seedCustomOpenAIChatCompletionsProvider({
  595. modelId: MODEL_ID,
  596. providerId: PROVIDER_ID,
  597. providerName: PROVIDER_NAME,
  598. });
  599. await refreshSeededOpenAIProvidersThroughSettings([PROVIDER_NAME], {
  600. workspacePath: DEFAULT_WORKSPACE,
  601. });
  602. const marketplace = await createPluginLifecycleFixture("1.0.0");
  603. await addMarketplaceSourceThroughAgent(marketplace.marketplaceRoot);
  604. const mcpServerPath = join(homeDir, "e2e-dsync-18", "mcp-server.cjs");
  605. await writeText(mcpServerPath, `${mcpServerScript(MCP_SERVER, MCP_RESULT)}\n`);
  606. await openLocalDraft();
  607. const firstPrompt = `${CASE_MARKER}_A_FIRST_PROMPT`;
  608. const start = await getUpstreamRequestRecordCount();
  609. await sendV4PromptAndWaitAccepted(
  610. `${firstPrompt}: 只回复 DSYNC_18_LOCAL_RUNTIME_REPLY`,
  611. firstPrompt,
  612. `${CASE_MARKER}: task A 首发没有被接受`,
  613. );
  614. taskAId = await waitForTurnReply(firstPrompt, "DSYNC_18_LOCAL_RUNTIME_REPLY");
  615. const control = factsFromRequest(
  616. await readTurnRequest(firstPrompt, start - 1),
  617. (await countHookLines()) > 0,
  618. );
  619. record("control", control);
  620. expect(Object.values(control).some(Boolean)).toBe(false);
  621. await measureStage("SUBAGENT", createSubagentInSettings, { secondDraftTurn: true });
  622. await measureStage("MCP", () => createMcpInSettings(mcpServerPath));
  623. await measureStage("HOOK", createHookInSettings);
  624. // 命令:在推送前打开的新建任务页直接发 /命令;再到 task A 发。
  625. await openLocalDraft();
  626. await createCommandInSettings();
  627. expect(await readMainPaneSessionId()).toBe("draft");
  628. const slashMenuAfterSave = await isCommandInSlashMenu();
  629. const draftCommand = await sendCommandProbe("DRAFT");
  630. await selectV4TaskById(taskAId, 30_000);
  631. record("COMMAND", {
  632. slashMenuAfterSave,
  633. draftExpanded: draftCommand,
  634. existingExpanded: await sendCommandProbe("EXISTING"),
  635. });
  636. await measureStage("SKILL", () => writeSkillFile(homeDir));
  637. await measureStage("INLINE", () => writeInlinePlugin(homeDir));
  638. // marketplace 插件:插件商店主视图会卸掉会话面板(预热会话随之丢弃),只测已有 task。
  639. await waitUntilPluginOverview(
  640. (overview) => overview.availablePlugins.some((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID),
  641. `${CASE_MARKER}: 本地目录 marketplace 的插件没有出现在可用列表`,
  642. 60_000,
  643. );
  644. await openPluginSettings();
  645. // 本地目录添加的 marketplace 在商店的「个人」分段。
  646. await clickPluginControl("plugin-store-segment-personal");
  647. await openPluginCard(PLUGIN_LIFECYCLE_ID);
  648. await installPluginThroughUi(PLUGIN_LIFECYCLE_ID);
  649. await selectV4TaskById(taskAId, 30_000);
  650. record("MARKET", { existing: (await sendProbe("EXISTING_MARKET")).facts });
  651. });
  652. it("DSYNC-18-02 已有 task:按名字调用 Skill,调用新建的子智能体", async function () {
  653. this.timeout(10 * 60_000);
  654. await selectV4TaskById(taskAId, 30_000);
  655. const skill = await runTool(
  656. "SKILL_EXISTING",
  657. `调用 Skill 工具加载 ${SKILL_NAME},然后只回复 DSYNC_18_RUN_SKILL_EXISTING_DONE`,
  658. );
  659. const agent = await runTool(
  660. "AGENT_EXISTING",
  661. `用 Agent 工具运行子智能体 ${AGENT_NAME},然后只回复 DSYNC_18_RUN_AGENT_EXISTING_DONE`,
  662. );
  663. record("existingRuns", {
  664. skill: { ...skill, result: null, bodyReturned: skill.result?.content.includes(SKILL_BODY) },
  665. agent,
  666. });
  667. });
  668. it("DSYNC-18-03 变更后新建 task:各类内容都可见并真正执行,钩子执行,命令展开", async function () {
  669. this.timeout(20 * 60_000);
  670. await openLocalDraft();
  671. const fresh = await sendProbe("NEW");
  672. record("newTask", fresh.facts);
  673. expect(fresh.facts).toEqual({
  674. skillListed: true,
  675. subagentListed: true,
  676. mcpTool: true,
  677. inlinePluginTool: true,
  678. marketplacePluginTool: true,
  679. hookFired: true,
  680. });
  681. expect(await sendCommandProbe("NEW")).toBe(true);
  682. const mcp = await runTool("MCP", `调用 ${MCP_TOOL} 一次,然后只回复 DSYNC_18_RUN_MCP_DONE`);
  683. const inline = await runTool(
  684. "INLINE",
  685. `调用 ${INLINE_TOOL} 一次,然后只回复 DSYNC_18_RUN_INLINE_DONE`,
  686. );
  687. const market = await runTool(
  688. "MARKET",
  689. `调用 ${PLUGIN_LIFECYCLE_MCP_TOOL_NAME} 一次,然后只回复 DSYNC_18_RUN_MARKET_DONE`,
  690. );
  691. const skill = await runTool(
  692. "SKILL_NEW",
  693. `调用 Skill 工具加载 ${SKILL_NAME},然后只回复 DSYNC_18_RUN_SKILL_NEW_DONE`,
  694. );
  695. const agent = await runTool(
  696. "AGENT",
  697. `用 Agent 工具运行子智能体 ${AGENT_NAME},然后只回复 DSYNC_18_RUN_AGENT_DONE`,
  698. );
  699. const subagentRequests = await countUpstreamRequests({ includes: [AGENT_BODY] });
  700. record("newTaskRuns", { mcp, inline, market, skill, agent, subagentRequests });
  701. for (const run of [mcp, inline, market, skill, agent]) {
  702. expect(run.timedOut).toBe(false);
  703. expect(run.exposed).toBe(true);
  704. expect(run.result?.isError).toBe(false);
  705. }
  706. expect(mcp.result?.content.trim()).toBe(MCP_RESULT);
  707. expect(inline.result?.content.trim()).toBe(INLINE_RESULT);
  708. expect(market.result?.content.trim()).toBe(MARKET_RESULT);
  709. expect(skill.result?.content).toContain(SKILL_BODY);
  710. expect(agent.result?.content).toContain(AGENT_DONE);
  711. expect(subagentRequests).toBeGreaterThan(0);
  712. });
  713. });