plugin-extension-sessions-write.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // PLM-EXT-P3C:扩展经 ctx.sessions.* 写会话(docs/plugins/extension-host.md §17.3、§17.8、§17.10 第 3 步、
  2. // §18.1 H10)。
  3. // 隔离 HOME:
  4. // - 纯 JS fixture 扩展 e2e-ext-writes(test/e2e/fixtures/fs/plugins/plugin-extension-writes/)经 plugins.dirs
  5. // 加载,清单声明 sessions.write;授权记录预先写进隔离 HOME 的 grants.json(授权流程由 PLM-EXT-P3A 覆盖)。
  6. // 它在输入框状态栏有一个命令:每次点击读一次用例写的步骤文件,按顺序执行 ctx.sessions.* 操作,结果写日志。
  7. // - 模型用 replay(plugin-extension-sessions-write.json):创建、发送、换模型(只在请求体是 deepseek-v4-pro 时命中)
  8. // 与中断(受控流闸门)各一个夹具。
  9. // - 手机:wdio 的远控夹具起本地 Web 前端与假 relay(web-remote-control-auth-gate-fixture.ts 登记了本 spec)。
  10. // 运行时证据:Main 日志(fixture 的 E2E_WRITES_*)、Window Host 项目树、审计文件、桌面与手机的 DOM、截图。
  11. import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  12. import { join, resolve } from "node:path";
  13. import { chromium, type Browser, type Page } from "playwright-core";
  14. import { ServiceChannels } from "@zcode/shared";
  15. import { EXTENSION_SESSION_CONSENT_REVISION } from "@zcode/shared/extension-host";
  16. import type { ProjectTask, ProjectTree } from "@zcode/services";
  17. import {
  18. TID_EXTENSION_PERMISSIONS,
  19. TID_EXTENSION_PERMISSIONS_ACTION,
  20. TID_SETTINGS_BACK_BUTTON,
  21. TID_SETTINGS_PAGE,
  22. TID_TASK_ITEM,
  23. TID_V4_SESSION_PANE,
  24. testId,
  25. } from "@zcode/shared/test-ids";
  26. import {
  27. DEFAULT_WORKSPACE,
  28. clearAppData,
  29. clickTestIdByDom,
  30. getE2EAppDataPaths,
  31. } from "#e2e/helpers/desktop-app";
  32. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  33. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  34. import {
  35. clickSlot,
  36. createExtensionLog,
  37. waitForSlot,
  38. writePluginDirsConfig,
  39. } from "#e2e/helpers/extension-host-views";
  40. import { waitForControlledReplay } from "#e2e/helpers/controlled-replay";
  41. import {
  42. callHandoffHost,
  43. installHandoffRpcProbe,
  44. restoreHandoffProbes,
  45. } from "#e2e/helpers/remote-project-handoff-probe";
  46. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  47. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  48. import {
  49. UPSTREAM_PROVIDER_ID,
  50. UPSTREAM_SECONDARY_MODEL,
  51. ensureUpstreamModelForE2E,
  52. } from "#e2e/helpers/upstream-provider";
  53. import {
  54. prepareV4ConversationE2E,
  55. waitForV4AssistantMessageContaining,
  56. waitForV4Pane,
  57. } from "#e2e/helpers/v4-conversation";
  58. import {
  59. capturePluginManualReview,
  60. openInstalledPluginSettingsDetail,
  61. openPluginManagementSettings,
  62. requirePluginManualReview,
  63. setPluginPresentation,
  64. } from "#e2e/helpers/plugin-management-lifecycle";
  65. const CASE_ID = "PLM-EXT-P3C";
  66. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  67. const FIXTURE_ROOT = resolve(process.cwd(), "test/e2e/fixtures/fs/plugins/plugin-extension-writes");
  68. const PLUGIN = "e2e-ext-writes";
  69. const PLUGIN_ID = `${PLUGIN}@inline`;
  70. const SLOT_ITEM = `${PLUGIN_ID}/run`;
  71. const CREATE_PROMPT = "E2E_P3C_CREATE: reply with the create marker.";
  72. const SEND_PROMPT = "E2E_P3C_SEND: reply with the send marker.";
  73. const MODEL_PROMPT = "E2E_P3C_MODEL: reply with the model marker.";
  74. const INTERRUPT_PROMPT = "E2E_P3C_INTERRUPT: start a long reply.";
  75. const STREAM_PROMPT = "E2E_P3C_STREAM: reply in several parts.";
  76. const STREAM_REPLY =
  77. "E2E_P3C_STREAM_PART_1 E2E_P3C_STREAM_PART_2 E2E_P3C_STREAM_PART_3 E2E_P3C_STREAM_DONE";
  78. const FAIL_PROMPT = "E2E_P3C_FAIL: this request fails.";
  79. const AFTER_DELETE_PROMPT = "E2E_P3C_AFTER_DELETE: the task is gone.";
  80. const FORGED_TEXT = "E2E_P3C_FORGED";
  81. const RENAMED = "E2E P3C 已改名";
  82. const CREATE_REQUEST_ID = "e2e-p3c-create";
  83. const SEND_REQUEST_ID = "e2e-p3c-send";
  84. const LABEL_SELECTOR = '[data-v4-user-input-source-kind="extension"]';
  85. const LABELS = { "zh-CN": `来自插件 ${PLUGIN}`, "en-US": `From plugin ${PLUGIN}` } as const;
  86. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd();
  87. interface SessionRef {
  88. kind: "app";
  89. sourceServerId: string;
  90. workspacePath: string;
  91. sessionId: string;
  92. workspaceIdentity?: string;
  93. project?: { kind: "app"; sourceServerId: string; projectId: string };
  94. }
  95. interface Op {
  96. name: string;
  97. input: Record<string, unknown>;
  98. subscribeRows?: boolean;
  99. /** 结果一有会话就持续订阅它的行,每个事件写一行 E2E_WRITES_WATCH。 */
  100. watchRows?: boolean;
  101. }
  102. interface OpResult {
  103. ok?: Record<string, unknown> & {
  104. session?: SessionRef;
  105. operation?: { commandId: string };
  106. requestId?: string;
  107. };
  108. error?: string;
  109. rows?: string;
  110. }
  111. const evidence: Record<string, unknown> = {};
  112. const screenshots: string[] = [];
  113. const log = createExtensionLog();
  114. let seq = 0;
  115. function fixturesDir(): string {
  116. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-writes");
  117. }
  118. function extensionsDataPath(...parts: string[]): string {
  119. return join(resolveE2EStorageRoot(), "v2", "extensions", ...parts);
  120. }
  121. /** fixture 插件进 plugins.dirs 并启用;授权记录预先写好(授权流程由 PLM-EXT-P3A 覆盖)。 */
  122. async function seedPlugin(): Promise<void> {
  123. const target = fixturesDir();
  124. await mkdir(target, { recursive: true });
  125. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  126. await writePluginDirsConfig([join(target, PLUGIN)], [PLUGIN_ID]);
  127. await mkdir(extensionsDataPath(), { recursive: true });
  128. await writeFile(
  129. extensionsDataPath("grants.json"),
  130. JSON.stringify({
  131. version: 1,
  132. plugins: {
  133. [PLUGIN_ID]: {
  134. grants: ["sessions.write"],
  135. consentedVersion: "1.0.0",
  136. consentedAt: Date.now(),
  137. // 当前的会话档位含义(§17.12):没有这个字段的旧记录要重新确认,迁移由 PLM-EXT-P3E 覆盖。
  138. consentRevision: EXTENSION_SESSION_CONSENT_REVISION,
  139. },
  140. },
  141. }),
  142. );
  143. }
  144. async function waitForLogAfter(
  145. from: number,
  146. predicate: (line: string) => boolean,
  147. message: string,
  148. timeout = 60000,
  149. ): Promise<string> {
  150. let found = "";
  151. await browser.waitUntil(
  152. async () => {
  153. found = (await log.lines()).slice(from).find(predicate) ?? "";
  154. return Boolean(found);
  155. },
  156. { timeout, interval: 300, timeoutMsg: message },
  157. );
  158. return found;
  159. }
  160. /** 写步骤文件,点状态栏命令,等这一步执行完,按操作序号返回结果(日志里的 JSON 与错误码)。 */
  161. async function runStep(label: string, ops: Op[]): Promise<OpResult[]> {
  162. seq += 1;
  163. const current = seq;
  164. await writeFile(
  165. join(fixturesDir(), "e2e-ext-writes-step.json"),
  166. JSON.stringify({ seq: current, ops }),
  167. );
  168. const from = (await log.lines()).length;
  169. await waitForSlot(SLOT_ITEM, (slot) => slot.text.includes("E2E writes"), "the run slot");
  170. await clickSlot(SLOT_ITEM);
  171. await waitForLogAfter(
  172. from,
  173. (line) => line.includes(`E2E_WRITES_DONE seq=${current}`),
  174. `${label}: the extension should finish step ${current}`,
  175. 120000,
  176. );
  177. const lines = (await log.lines()).slice(from);
  178. const results = ops.map((_op, index): OpResult => {
  179. const marker = `E2E_WRITES_RESULT seq=${current} index=${index} `;
  180. const line = lines.find((entry) => entry.includes(marker)) ?? "";
  181. const rows = lines.find((entry) =>
  182. entry.includes(`E2E_WRITES_ROWS seq=${current} index=${index} `),
  183. );
  184. const ok = /\bok=(.*)$/.exec(line)?.[1];
  185. const error = /\berror=(\S+)/.exec(line)?.[1];
  186. return {
  187. ...(ok !== undefined ? { ok: JSON.parse(ok) as OpResult["ok"] } : {}),
  188. ...(error ? { error } : {}),
  189. ...(rows ? { rows: rows.slice(rows.indexOf("session=")) } : {}),
  190. };
  191. });
  192. evidence[`step-${current}-${label}`] = results;
  193. return results;
  194. }
  195. async function readTask(id: string): Promise<ProjectTask> {
  196. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{}]);
  197. const task = tree.tasks.find((value) => value.taskId === id);
  198. if (!task) throw new Error(`the product task is absent: ${id}`);
  199. return task;
  200. }
  201. async function readLabels(): Promise<string[]> {
  202. return browser.execute(
  203. (selector) =>
  204. Array.from(document.querySelectorAll<HTMLElement>(selector)).map(
  205. (element) => element.innerText ?? "",
  206. ),
  207. LABEL_SELECTOR,
  208. );
  209. }
  210. async function waitForLabels(count: number, message: string): Promise<string[]> {
  211. let labels: string[] = [];
  212. await browser.waitUntil(
  213. async () => {
  214. labels = await readLabels();
  215. return labels.length === count;
  216. },
  217. { timeout: 30000, interval: 300, timeoutMsg: message },
  218. );
  219. return labels;
  220. }
  221. async function capture(label: string): Promise<void> {
  222. screenshots.push(await capturePluginManualReview(CASE_ID, label));
  223. }
  224. interface PermissionsUi {
  225. text: string;
  226. actions: Array<{ capability: string; outcome: string }>;
  227. }
  228. async function readPermissions(): Promise<PermissionsUi | null> {
  229. return browser.execute(
  230. (sectionTestId, actionTestId, id) => {
  231. const section = document.querySelector<HTMLElement>(
  232. `[data-testid="${sectionTestId}"][data-plugin-id="${id}"]`,
  233. );
  234. if (!section) return null;
  235. return {
  236. text: section.innerText ?? "",
  237. actions: Array.from(
  238. section.querySelectorAll<HTMLElement>(`[data-testid="${actionTestId}"]`),
  239. ).map((row) => ({
  240. capability: row.dataset.capability ?? "",
  241. outcome: row.dataset.outcome ?? "",
  242. })),
  243. };
  244. },
  245. TID_EXTENSION_PERMISSIONS,
  246. TID_EXTENSION_PERMISSIONS_ACTION,
  247. PLUGIN_ID,
  248. );
  249. }
  250. /** 从插件详情页回到工作区:详情页的返回先回到插件列表,再返回才离开设置页。 */
  251. async function leaveSettings(): Promise<void> {
  252. await browser.waitUntil(
  253. async () => {
  254. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting())) return true;
  255. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 5000 }).catch(() => undefined);
  256. return false;
  257. },
  258. { timeout: 30000, interval: 500, timeoutMsg: "the settings page should close" },
  259. );
  260. }
  261. async function readAudit(): Promise<{ text: string; lines: Array<Record<string, unknown>> }> {
  262. const dir = extensionsDataPath("audit");
  263. const names = (await readdir(dir).catch(() => [] as string[])).filter((name) =>
  264. name.endsWith(".jsonl"),
  265. );
  266. let text = "";
  267. for (const name of names.sort()) text += await readFile(join(dir, name), "utf8");
  268. return {
  269. text,
  270. lines: text
  271. .split("\n")
  272. .filter(Boolean)
  273. .map((line) => JSON.parse(line) as Record<string, unknown>),
  274. };
  275. }
  276. describe("PLM-EXT-P3C 扩展经 ctx.sessions.* 写会话", () => {
  277. let sessionId = "";
  278. let mobile: Browser | undefined;
  279. let page: Page | undefined;
  280. after(async () => {
  281. evidence.screenshots = screenshots;
  282. await writeFile(
  283. join(artifacts, "plm-ext-p3c-evidence.json"),
  284. JSON.stringify(evidence, null, 2),
  285. ).catch(() => undefined);
  286. await page
  287. ?.screenshot({ path: join(artifacts, "plm-ext-p3c-mobile-last.png") })
  288. .catch(() => {});
  289. await mobile?.close();
  290. await restoreHandoffProbes().catch(() => undefined);
  291. await clearAppData();
  292. });
  293. it("新建、立即订阅、幂等重试、换模型、中断、整理与打开;来源标识、审计与拒绝伪造来源", async function () {
  294. this.timeout(900000);
  295. requirePluginManualReview();
  296. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  297. await seedPlugin();
  298. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  299. afterElectronProcessExit: async () => {
  300. await log.mark();
  301. },
  302. });
  303. await prepareV4ConversationE2E();
  304. // H10 的目标模型:与默认模型同一个 provider,回放夹具按请求体里的模型名区分。
  305. await ensureUpstreamModelForE2E(UPSTREAM_SECONDARY_MODEL);
  306. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  307. evidence.activated = await log.waitFor(
  308. (line) => line.includes(`E2E_WRITES_ACTIVATED plugin=${PLUGIN_ID}`),
  309. "the write fixture should activate",
  310. 90000,
  311. );
  312. // (a) 默认工作区的项目。
  313. const [projects] = await runStep("projects", [
  314. { name: "listProjects", input: { query: "ZCodeProject" } },
  315. ]);
  316. const project = (
  317. projects!.ok as { projects: Array<{ project: NonNullable<SessionRef["project"]> }> }
  318. ).projects[0]!.project;
  319. expect(project.projectId).toBeTruthy();
  320. // (b) 新建会话,结果一到立即订阅行(新建后立即订阅的时序);同一个 requestId 再建一次,得到同一个会话。
  321. const [created, createdAgain] = await runStep("create", [
  322. {
  323. name: "createSession",
  324. input: { project, prompt: CREATE_PROMPT, requestId: CREATE_REQUEST_ID },
  325. subscribeRows: true,
  326. },
  327. {
  328. name: "createSession",
  329. input: { project, prompt: CREATE_PROMPT, requestId: CREATE_REQUEST_ID },
  330. },
  331. ]);
  332. expect(created!.ok).toMatchObject({
  333. requestId: CREATE_REQUEST_ID,
  334. creation: "created",
  335. firstInput: "accepted",
  336. });
  337. sessionId = created!.ok!.session!.sessionId;
  338. expect(created!.ok!.session!.project?.projectId).toBe(project.projectId);
  339. expect(createdAgain!.ok?.session?.sessionId).toBe(sessionId);
  340. // 新建后立即订阅:第一个事件必须是 reset,不能是 unavailable。
  341. expect(created!.rows).toMatch(/kind=reset/);
  342. // (c) 打开会话:桌面切到它;用户行显示「来自插件 e2e-ext-writes」,回复来自回放夹具。
  343. const [opened] = await runStep("open", [{ name: "openSession", input: { sessionId } }]);
  344. expect(opened!.ok).toMatchObject({ status: "opened" });
  345. await waitForV4Pane(
  346. (snapshot) => snapshot.sessionId === sessionId,
  347. "the desktop should open the plugin session",
  348. 30000,
  349. );
  350. await waitForV4AssistantMessageContaining("E2E_P3C_CREATE_DONE", 90000);
  351. expect(await waitForLabels(1, "the first user row should carry the plugin label")).toEqual([
  352. LABELS["zh-CN"],
  353. ]);
  354. await installHandoffRpcProbe();
  355. const createdTask = await readTask(sessionId);
  356. evidence.createdTask = { projectId: createdTask.projectId, title: createdTask.title };
  357. expect(createdTask.projectId).toBe(project.projectId);
  358. // (d) 同一个 requestId 发两次:同一个命令,只出现一条消息。
  359. const [sent, sentAgain] = await runStep("send", [
  360. {
  361. name: "sendToSession",
  362. input: { sessionId, prompt: SEND_PROMPT, requestId: SEND_REQUEST_ID },
  363. },
  364. {
  365. name: "sendToSession",
  366. input: { sessionId, prompt: SEND_PROMPT, requestId: SEND_REQUEST_ID },
  367. },
  368. ]);
  369. expect(sent!.ok).toMatchObject({ requestId: SEND_REQUEST_ID, admission: "accepted" });
  370. expect(sentAgain!.ok?.operation?.commandId).toBe(sent!.ok?.operation?.commandId);
  371. await waitForV4AssistantMessageContaining("E2E_P3C_SEND_DONE", 90000);
  372. await waitForLabels(2, "a retried send should add exactly one user row");
  373. // (e) H10:带 model 发送;只有请求体里的模型是 deepseek-v4-pro 时回放夹具才命中。requestId 由扩展进程补。
  374. const [modeled] = await runStep("model", [
  375. {
  376. name: "sendToSession",
  377. // 用 providerId/modelId:第一次运行只给 modelId 时报 invalid-input(唯一匹配失败),带上 provider 就是唯一的。
  378. input: {
  379. sessionId,
  380. prompt: MODEL_PROMPT,
  381. model: `${UPSTREAM_PROVIDER_ID}/${UPSTREAM_SECONDARY_MODEL}`,
  382. },
  383. },
  384. ]);
  385. expect(modeled!.ok).toMatchObject({ admission: "accepted" });
  386. expect(modeled!.ok?.requestId).toMatch(/^[0-9a-f-]{36}$/);
  387. await waitForV4AssistantMessageContaining("E2E_P3C_MODEL_DONE", 90000);
  388. await waitForLabels(3, "the model send should add one user row");
  389. // (f) 中断:受控流停在闸门上,读 executionId,再中断。
  390. const [running] = await runStep("interrupt-send", [
  391. { name: "sendToSession", input: { sessionId, prompt: INTERRUPT_PROMPT } },
  392. ]);
  393. expect(running!.ok).toMatchObject({ admission: "accepted" });
  394. await waitForControlledReplay("p3c-interrupt-target");
  395. const [summary] = await runStep("summary", [
  396. { name: "readSession", input: { sessionId, view: "summary" } },
  397. ]);
  398. const executionId = (summary!.ok as { summary: { executionId?: string; status: string } })
  399. .summary.executionId;
  400. expect(executionId).toBeTruthy();
  401. const [interrupted] = await runStep("interrupt", [
  402. { name: "interruptSession", input: { sessionId, expectedExecutionId: executionId } },
  403. ]);
  404. expect(interrupted!.ok).toMatchObject({ status: "applied" });
  405. await waitForV4Pane(
  406. (snapshot) => snapshot.sessionId === sessionId && !snapshot.canStop,
  407. "the interrupted turn should stop",
  408. 60000,
  409. );
  410. // (g) 整理:改名、置顶、归档再取消归档、打开。
  411. const organized = await runStep("organize", [
  412. { name: "renameSession", input: { sessionId, title: RENAMED } },
  413. { name: "setSessionPinned", input: { sessionId, pinned: true } },
  414. { name: "setSessionArchived", input: { sessionId, archived: true } },
  415. { name: "setSessionArchived", input: { sessionId, archived: false } },
  416. { name: "openSession", input: { sessionId } },
  417. ]);
  418. expect(organized.slice(0, 4).map((result) => result.ok?.status)).toEqual([
  419. "applied",
  420. "applied",
  421. "applied",
  422. "applied",
  423. ]);
  424. expect(organized[4]!.ok).toMatchObject({ status: "opened" });
  425. await browser.waitUntil(
  426. async () => {
  427. const task = await readTask(sessionId);
  428. return task.title === RENAMED && task.pinned === true && task.archived === false;
  429. },
  430. { timeout: 30000, timeoutMsg: "rename, pin and unarchive should be durable" },
  431. );
  432. evidence.organizedTask = await readTask(sessionId).then(({ title, pinned, archived }) => ({
  433. title,
  434. pinned,
  435. archived,
  436. }));
  437. // (h) 渲染进程伪造 extension 来源:Host 的连接作用域拒绝,会话里不多出消息。
  438. evidence.forged = await callHandoffHost(
  439. ServiceChannels.ZCodeAgent,
  440. "sendConversationCommandV4",
  441. [
  442. {
  443. workspacePath: DEFAULT_WORKSPACE,
  444. envelope: {
  445. commandId: `e2e-p3c-forged-${Date.now()}`,
  446. clientId: "e2e-p3c-forged",
  447. sessionId,
  448. type: "sendText",
  449. payload: { text: FORGED_TEXT, source: { kind: "extension", pluginId: PLUGIN_ID } },
  450. issuedAt: Date.now(),
  451. },
  452. },
  453. ],
  454. ).then(
  455. () => "accepted",
  456. (error: unknown) => (error instanceof Error ? error.message : String(error)),
  457. );
  458. expect(String(evidence.forged)).toContain("fault.command.extensionSourceUntrusted");
  459. // (g) 里先归档、再取消归档、再打开,侧栏的归档清理可能在「打开」之前把会话撤出窗格,
  460. // 打开后窗格重新载入,载入完成前一行都没有,所以等到恰好 4 条,不只读一次。
  461. // 伪造的消息如果被收下会变成 5 条,照样失败。
  462. // 清理落在「打开」之后、窗格停在新草稿上,是侧栏用过期快照清理的产品问题,已在 useProjectTree 修复
  463. // (读取期间已打开的任务跳过清理),这里等不来 4 条就是回归。
  464. await waitForLabels(4, "the forged send should not add a user row");
  465. // (i) 桌面截图:四条用户行都带标识(中文浅色、英文深色)。
  466. await capture("labels-zh-CN-zai-light");
  467. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  468. await browser.waitUntil(
  469. async () => (await readLabels()).every((label) => label === LABELS["en-US"]),
  470. { timeout: 15000, timeoutMsg: "the labels should switch to English" },
  471. );
  472. await capture("labels-en-US-zai-dark");
  473. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  474. // (j) 插件详情页「最近操作」:最近 10 行里有整理、打开与中断;全部成功。
  475. await openPluginManagementSettings();
  476. await openInstalledPluginSettingsDetail(PLUGIN_ID);
  477. let permissions: PermissionsUi | null = null;
  478. await browser.waitUntil(
  479. async () => {
  480. permissions = await readPermissions();
  481. const capabilities = permissions?.actions.map((action) => action.capability) ?? [];
  482. return [
  483. "sessions.openSession",
  484. "sessions.setSessionArchived",
  485. "sessions.setSessionPinned",
  486. "sessions.renameSession",
  487. "sessions.interruptSession",
  488. ].every((capability) => capabilities.includes(capability));
  489. },
  490. { timeout: 30000, interval: 300, timeoutMsg: "recent actions should list the writes" },
  491. );
  492. evidence.permissions = permissions;
  493. const permissionsUi = permissions as PermissionsUi | null;
  494. expect(permissionsUi!.actions.every((action) => action.outcome === "ok")).toBe(true);
  495. expect(permissionsUi!.text).toContain("重命名会话");
  496. await capture("recent-actions-zh-CN-zai-light");
  497. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  498. await browser.waitUntil(
  499. async () => ((await readPermissions())?.text ?? "").includes("Renamed a session"),
  500. { timeout: 15000, timeoutMsg: "recent actions should switch to English" },
  501. );
  502. await capture("recent-actions-en-US-zai-dark");
  503. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  504. await leaveSettings();
  505. // (k) 审计:每个写动作一行,带 requestId、目标与提示词长度;不含提示词正文。
  506. const audit = await readAudit();
  507. const writes = audit.lines.filter((line) => String(line.capability).startsWith("sessions."));
  508. evidence.audit = writes;
  509. expect(writes.length).toBeGreaterThanOrEqual(13);
  510. const createRow = writes.find(
  511. (line) =>
  512. line.capability === "sessions.createSession" && line.requestId === CREATE_REQUEST_ID,
  513. );
  514. expect(createRow).toMatchObject({
  515. grant: "sessions.write",
  516. outcome: "ok",
  517. promptChars: CREATE_PROMPT.length,
  518. target: { sessionId, projectId: project.projectId },
  519. });
  520. expect(
  521. writes.find(
  522. (line) =>
  523. line.capability === "sessions.sendToSession" && line.requestId === SEND_REQUEST_ID,
  524. ),
  525. ).toMatchObject({ commandId: sent!.ok?.operation?.commandId, promptChars: SEND_PROMPT.length });
  526. for (const marker of ["E2E_P3C_CREATE", "E2E_P3C_SEND", "E2E_P3C_MODEL", RENAMED])
  527. expect(audit.text).not.toContain(marker);
  528. // (m)–(o) 行镜像的增量、本轮失败与删除后的信号。宿主行为,以前只由示例插件用例 PLM-JARVIS-1、2 断言。
  529. // (m) 流式期间:回复分四段到达(夹具 p3c-stream,间隔 1.5 秒),扩展的行订阅在本轮 running 时
  530. // 逐段收到 rows 增量,助手文字的字数递增;结束后是 completedSuccess 与完整的回复。
  531. const streamFrom = (await log.lines()).length;
  532. const [streamed] = await runStep("stream", [
  533. { name: "createSession", input: { project, prompt: STREAM_PROMPT }, watchRows: true },
  534. ]);
  535. const streamId = streamed!.ok!.session!.sessionId;
  536. const streamDone = await waitForLogAfter(
  537. streamFrom,
  538. (line) =>
  539. line.includes(`E2E_WRITES_WATCH session=${streamId} `) &&
  540. line.includes("turns=completedSuccess"),
  541. "the streamed turn should complete in the rows mirror",
  542. 90000,
  543. );
  544. const watchLines = (await log.lines())
  545. .slice(streamFrom)
  546. .filter((line) => line.includes(`E2E_WRITES_WATCH session=${streamId} `));
  547. evidence.streamWatch = watchLines;
  548. expect(Number(/replyChars=(\d+)/.exec(streamDone)?.[1])).toBe(STREAM_REPLY.length);
  549. const runningChars = watchLines
  550. .filter((line) => line.includes(" kind=rows ") && line.includes("turns=running "))
  551. .map((line) => Number(/replyChars=(\d+)/.exec(line)?.[1]))
  552. .filter((chars) => chars > 0);
  553. const distinctChars = [...new Set(runningChars)];
  554. evidence.streamRunningChars = distinctChars;
  555. expect(distinctChars.length).toBeGreaterThanOrEqual(2);
  556. expect(distinctChars).toEqual([...distinctChars].sort((a, b) => a - b));
  557. expect(distinctChars.at(-1)!).toBeLessThan(STREAM_REPLY.length);
  558. // (n) 本轮失败:服务商返回 400(夹具 p3c-fail),扩展经行镜像看到这一轮的 turnHeader 是 failed。
  559. const failFrom = (await log.lines()).length;
  560. const [failedCreate] = await runStep("fail", [
  561. { name: "createSession", input: { project, prompt: FAIL_PROMPT }, watchRows: true },
  562. ]);
  563. const failId = failedCreate!.ok!.session!.sessionId;
  564. evidence.failedTurn = await waitForLogAfter(
  565. failFrom,
  566. (line) =>
  567. line.includes(`E2E_WRITES_WATCH session=${failId} `) && line.includes("turns=failed "),
  568. "the extension should see the failed turn in the rows mirror",
  569. 90000,
  570. );
  571. // (o) 宿主删除任务(与侧栏「删除」同一条路径):之后 sendToSession 报 forbidden(项目树里找不到它);
  572. // 已开着的行订阅不结束(会话仍在 CLI 里)。§18.3「大脑被删的信号」记的就是这个行为。
  573. const failTask = await readTask(failId);
  574. await callHandoffHost(ServiceChannels.ZCodeTask, "deleteTask", [
  575. {
  576. taskId: failId,
  577. workspacePath: failTask.workspacePath,
  578. ...(failTask.workspaceIdentity ? { workspaceIdentity: failTask.workspaceIdentity } : {}),
  579. },
  580. ]);
  581. const [sentAfterDelete] = await runStep("send-after-delete", [
  582. { name: "sendToSession", input: { sessionId: failId, prompt: AFTER_DELETE_PROMPT } },
  583. ]);
  584. evidence.sendAfterDelete = sentAfterDelete;
  585. expect(sentAfterDelete!.error).toBe("forbidden");
  586. const endedAfterDelete = (await log.lines())
  587. .slice(failFrom)
  588. .filter((line) => line.includes(`E2E_WRITES_WATCH session=${failId} ended=`));
  589. evidence.watchEndedAfterDelete = endedAfterDelete;
  590. expect(endedAfterDelete).toEqual([]);
  591. await runStep("unwatch", [
  592. { name: "unwatchRows", input: { sessionId: streamId } },
  593. { name: "unwatchRows", input: { sessionId: failId } },
  594. ]);
  595. });
  596. it("手机远控显示同样的「来自插件」标识", async function () {
  597. this.timeout(300000);
  598. requirePluginManualReview();
  599. expect(sessionId).toBeTruthy();
  600. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  601. if (!endpoint) throw new Error("the mobile Web fixture is not configured for this spec");
  602. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  603. mobile = await chromium.launch({
  604. ...(process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE
  605. ? { executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE }
  606. : { channel: "chrome" }),
  607. headless: true,
  608. });
  609. const context = await mobile.newContext({
  610. viewport: { width: 390, height: 844 },
  611. isMobile: true,
  612. hasTouch: true,
  613. locale: "zh-CN",
  614. });
  615. await seedMobileFixtureLogin(context);
  616. page = await context.newPage();
  617. await openMobilePairingPage(page, pairingUrl, {
  618. artifactDir: artifacts,
  619. caseMarker: "P3C",
  620. phase: "pairing",
  621. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  622. });
  623. await showMobileTaskHome(page);
  624. for (const toggle of await page.getByTestId("virtual-project-toggle").all()) {
  625. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  626. }
  627. await page.getByTestId(testId(TID_TASK_ITEM, sessionId)).first().click();
  628. await page
  629. .locator(`[data-testid^="${TID_V4_SESSION_PANE}-"][data-session-id="${sessionId}"]`)
  630. .waitFor();
  631. await page.locator(LABEL_SELECTOR).first().waitFor();
  632. const mobileLabels = await page.locator(LABEL_SELECTOR).allTextContents();
  633. evidence.mobileLabels = mobileLabels;
  634. expect(mobileLabels).toEqual([
  635. LABELS["zh-CN"],
  636. LABELS["zh-CN"],
  637. LABELS["zh-CN"],
  638. LABELS["zh-CN"],
  639. ]);
  640. const layout = await page.evaluate(() => ({
  641. width: window.innerWidth,
  642. overflow: document.documentElement.scrollWidth > window.innerWidth,
  643. }));
  644. expect(layout).toEqual({ width: 390, overflow: false });
  645. const shot = join(artifacts, "plm-ext-p3c-mobile-labels-zh-CN-light.png");
  646. await page.screenshot({ path: shot });
  647. screenshots.push(shot);
  648. });
  649. });