conversation-session-remote-data-sync-builtin-subagent-runtime.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_SETTINGS_BACK_BUTTON,
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_TASK_SETTINGS_BUTTON,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { seedCustomOpenAIChatCompletionsProvider } from "#e2e/helpers/custom-openai-provider-store";
  11. import { refreshSeededOpenAIProvidersThroughSettings } from "#e2e/helpers/custom-openai-provider";
  12. import {
  13. clearAppData,
  14. clickTestIdByDom,
  15. getE2EAppDataPaths,
  16. waitForTestIdByDom,
  17. } from "#e2e/helpers/desktop-app";
  18. import {
  19. execInRemoteContainer,
  20. readRemoteContainerFile,
  21. readRemoteDockerContainer,
  22. } from "#e2e/helpers/remote-docker-target";
  23. import {
  24. getUpstreamRequestEvidence,
  25. getUpstreamRequestRecordCount,
  26. } from "#e2e/helpers/conversation-session-network";
  27. import { hasAssistantReplyForUserTurn } from "#e2e/helpers/conversation-turn-evidence";
  28. import {
  29. connectSSHWorkspaceAndSendFirstTurn,
  30. prepareSSHLifecycle,
  31. SSH_LIFECYCLE_MODEL_ID,
  32. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  33. type SSHLifecycleProvider,
  34. } from "#e2e/helpers/ssh-remote-lifecycle";
  35. import { prepareSSHConnectionPage } from "#e2e/helpers/ssh-remote-p0";
  36. import {
  37. approveV4Permission,
  38. getV4Messages,
  39. hasV4PermissionDialog,
  40. sendV4PromptAndWaitAccepted,
  41. waitForV4ConversationState,
  42. } from "#e2e/helpers/v4-conversation";
  43. // DSYNC-09-05:推送内置 Explore 的模型覆盖后,远端已有 task 的下一轮 Explore 子请求使用推送的模型
  44. // (docs/remote/data-sync.md「子智能体」,票 20)。模型请求经 SSH 反向隧道回到本机回放,
  45. // 子请求的 model 字段就是远端 Agent 实际选用的模型。
  46. const CASE_MARKER = "E2E_DSYNC_09_BUILTIN_RUNTIME";
  47. const ALT_MODEL_ID = "e2e-dsync-09-alt-model";
  48. const REMOTE_STATE_FILE = "/home/dev/.zcode/v2/agents-state.json";
  49. const EXPLORE_KEY = "built-in:built-in:explore";
  50. // 远端 Core 的子智能体监听在文件稳定 1000ms 后读取、再合并 300ms 才发布快照(docs/subagent-runtime-refresh.md)。
  51. const SUBAGENT_PUBLISH_WINDOW_MS = 3_000;
  52. async function readRowStatus(key: string): Promise<string | null> {
  53. return await browser.execute(
  54. (rowTestId) =>
  55. document.querySelector<HTMLElement>(`[data-testid="${rowTestId}"]`)?.dataset.syncStatus ??
  56. null,
  57. `remote-sync-row-${key}`,
  58. );
  59. }
  60. async function waitForRowStatus(key: string, status: string, timeoutMsg: string): Promise<void> {
  61. await browser.waitUntil(async () => (await readRowStatus(key)) === status, {
  62. timeout: 60_000,
  63. timeoutMsg: `${CASE_MARKER}: ${timeoutMsg}`,
  64. });
  65. }
  66. /** 设置 → 数据同步 → 唯一在线设备 → 打开同步弹窗。 */
  67. async function openDataSyncDialog(): Promise<void> {
  68. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  69. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  70. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "dataSync"), {
  71. timeout: 30_000,
  72. timeoutMsg: `${CASE_MARKER}: 设置页没有数据同步分区`,
  73. });
  74. await waitForTestIdByDom("remote-sync-device-list", {
  75. timeout: 60_000,
  76. timeoutMsg: `${CASE_MARKER}: 数据同步页没有在线设备`,
  77. });
  78. await clickTestIdByDom("remote-sync-device-action");
  79. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  80. }
  81. /** 关闭同步弹窗和设置页,回到打开设置前的 task。 */
  82. async function closeDataSyncDialogAndSettings(): Promise<void> {
  83. // 关闭按钮只在概览页底栏。
  84. await clickTestIdByDom("remote-sync-tab-overview", { timeout: 30_000 });
  85. await clickTestIdByDom("remote-sync-close", { timeout: 30_000 });
  86. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 30_000 });
  87. await browser.waitUntil(
  88. async () => !(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed()),
  89. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 设置页没有关闭` },
  90. );
  91. }
  92. /** 在当前 task 里让模型调用 Explore,返回这一轮 Explore 子请求使用的模型。 */
  93. async function runExplore(key: string): Promise<Array<string | null>> {
  94. const prompt = `${CASE_MARKER}_RUN_${key}`;
  95. const done = `DSYNC_09_RUN_${key}_DONE`;
  96. const start = await getUpstreamRequestRecordCount();
  97. await sendV4PromptAndWaitAccepted(
  98. `${prompt}: 用 Agent 工具运行 Explore,然后只回复 ${done}`,
  99. prompt,
  100. `${CASE_MARKER}: ${key} 没有被接受`,
  101. );
  102. await browser.waitUntil(
  103. async () => {
  104. if (await hasV4PermissionDialog()) await approveV4Permission();
  105. return hasAssistantReplyForUserTurn(await getV4Messages(), prompt, done);
  106. },
  107. { timeout: SSH_LIFECYCLE_TURN_TIMEOUT_MS, timeoutMsg: `${CASE_MARKER}: ${key} 没有最终回复` },
  108. );
  109. await waitForV4ConversationState(
  110. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  111. `${CASE_MARKER}: ${key} 没有回到 idle`,
  112. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  113. );
  114. const childRequests = await getUpstreamRequestEvidence(
  115. { lastUserMessageIncludes: [`E2E_EXPLORE_PROBE_${key}`] },
  116. { afterIndex: start - 1 },
  117. );
  118. return childRequests.map(
  119. (request) => (request.requestJson as { model?: string } | null)?.model ?? null,
  120. );
  121. }
  122. describe(`${CASE_MARKER}: 推送内置子智能体模型覆盖后远端生效`, () => {
  123. let provider: SSHLifecycleProvider | null = null;
  124. after(async () => {
  125. await provider?.tunnel.close().catch(() => undefined);
  126. provider = null;
  127. await browser.electron.restoreAllMocks();
  128. await clearAppData();
  129. });
  130. it("DSYNC-09-05 推送 Explore 模型覆盖后,远端已有 task 的下一轮 Explore 使用推送的模型", async function () {
  131. this.timeout(30 * 60_000);
  132. await prepareSSHConnectionPage(CASE_MARKER);
  133. const prepared = await prepareSSHLifecycle(CASE_MARKER);
  134. provider = prepared.provider;
  135. const container = readRemoteDockerContainer(CASE_MARKER);
  136. // 第二个本机 Personal Provider:连接时随 Provisioning 下发到远端,作为 Explore 覆盖的目标。
  137. const alt = await seedCustomOpenAIChatCompletionsProvider({
  138. baseURL: provider.tunnel.baseURL,
  139. modelId: ALT_MODEL_ID,
  140. providerId: `e2e-dsync-09-alt-${Date.now()}`,
  141. providerName: `DSYNC 09 alt ${Date.now()}`,
  142. });
  143. await refreshSeededOpenAIProvidersThroughSettings([alt.name]);
  144. await connectSSHWorkspaceAndSendFirstTurn({
  145. caseMarker: CASE_MARKER,
  146. config: prepared.config,
  147. label: "A",
  148. provider,
  149. workspacePath: prepared.config.workspacePaths[0],
  150. });
  151. // 推送前:远端没有覆盖,Explore 继承父会话模型。
  152. await execInRemoteContainer(container, ["rm", "-f", REMOTE_STATE_FILE]);
  153. await browser.pause(SUBAGENT_PUBLISH_WINDOW_MS);
  154. expect(await runExplore("BEFORE")).toEqual([SSH_LIFECYCLE_MODEL_ID]);
  155. // 本机给 Explore 选 alt 模型(e2e 模型只有 disabled 一个推理档位),经数据同步弹窗推送。
  156. const exploreOverride = {
  157. providerId: alt.id,
  158. modelId: ALT_MODEL_ID,
  159. options: { reasoningLevel: "disabled" },
  160. };
  161. const localStateDir = join(getE2EAppDataPaths().homeDir, ".zcode", "v2");
  162. await mkdir(localStateDir, { recursive: true });
  163. await writeFile(
  164. join(localStateDir, "agents-state.json"),
  165. `${JSON.stringify(
  166. {
  167. disabledAgentIds: [],
  168. builtInModelSelectionOverrides: { Explore: exploreOverride },
  169. pluginAgentModelSelectionOverrides: {},
  170. },
  171. null,
  172. 2,
  173. )}\n`,
  174. );
  175. await openDataSyncDialog();
  176. await clickTestIdByDom("remote-sync-tab-subagents", { timeout: 60_000 });
  177. await waitForRowStatus(EXPLORE_KEY, "push", "Explore 覆盖没有显示为「推送」");
  178. await clickTestIdByDom("remote-sync-push", {
  179. timeout: 30_000,
  180. timeoutMsg: `${CASE_MARKER}: 推送子智能体按钮不可用`,
  181. });
  182. await waitForRowStatus(EXPLORE_KEY, "synced", "推送后 Explore 覆盖没有变为「已同步」");
  183. const pushedAt = Date.now();
  184. const remoteState = JSON.parse(await readRemoteContainerFile(container, REMOTE_STATE_FILE)) as {
  185. builtInModelSelectionOverrides?: unknown;
  186. };
  187. expect(remoteState.builtInModelSelectionOverrides).toEqual({ Explore: exploreOverride });
  188. // 回到推送前已有的 task A,不重开项目、不重启远端 Agent:下一轮 Explore 用推送的模型。
  189. await closeDataSyncDialogAndSettings();
  190. await browser.pause(Math.max(0, SUBAGENT_PUBLISH_WINDOW_MS - (Date.now() - pushedAt)));
  191. expect(await runExplore("AFTER")).toEqual([ALT_MODEL_ID]);
  192. });
  193. });