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

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