plugin-extension-session-approvals.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. // PLM-EXT-P3E:插件回答审批、提问与切换权限模式(docs/plugins/extension-host.md §17.12)。
  2. // 隔离 HOME:
  3. // - 纯 JS fixture 扩展 e2e-ext-approvals(test/e2e/fixtures/fs/plugins/plugin-extension-approvals/)经 plugins.dirs
  4. // 加载,清单声明 sessions.write;预先写进 grants.json 的是本阶段以前的旧格式记录(没有 consentRevision),
  5. // 开头先验证它回到待授权、经真实授权对话框重新授权后才可用(§17.12「已有授权要重新确认」)。它在输入框状态栏
  6. // 有一个命令:每次点击读一次用例写的步骤文件,按顺序执行 ctx.sessions.* 操作,或订阅 / 退订交互,结果写日志。
  7. // - 模型用 replay(plugin-extension-session-approvals.json):Write 触发审批、AskUserQuestion 触发提问;最终文本只在
  8. // tool_result 带对应工具 id 时命中,所以回复出现就证明批准、拒绝或答案回到了模型。
  9. // - 后半段把清单改成申请 sessions.fullAccess,经「重新加载扩展」与真实授权对话框授予完全访问。
  10. // 运行时证据:Main 日志(fixture 的 E2E_APPROVALS_*)、Window Host 项目树、磁盘上的文件、审计文件、对话框 DOM、截图。
  11. import { access, cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  12. import { join, normalize, resolve } from "node:path";
  13. import { ServiceChannels } from "@zcode/shared";
  14. import { EXTENSION_SESSION_CONSENT_REVISION } from "@zcode/shared/extension-host";
  15. import {
  16. TID_CONFIRM_DIALOG_CONFIRM,
  17. TID_EXTENSION_GRANT_DIALOG,
  18. TID_SIDE_PANE_EXTENSION_GRANT,
  19. } from "@zcode/shared/test-ids";
  20. import type { ProjectTree } from "@zcode/services";
  21. import { DEFAULT_WORKSPACE, clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  22. import { resolveE2ERuntimeRoot, resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  23. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  24. import {
  25. clickSlot,
  26. createExtensionLog,
  27. openLauncher,
  28. waitForSlot,
  29. writePluginDirsConfig,
  30. } from "#e2e/helpers/extension-host-views";
  31. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  32. import {
  33. approveV4Permission,
  34. prepareV4ConversationE2E,
  35. sendV4Prompt,
  36. waitForV4AssistantMessageContaining,
  37. waitForV4Pane,
  38. waitForV4PermissionDialog,
  39. } from "#e2e/helpers/v4-conversation";
  40. import {
  41. capturePluginManualReview,
  42. requirePluginManualReview,
  43. setPluginPresentation,
  44. } from "#e2e/helpers/plugin-management-lifecycle";
  45. const CASE_ID = "PLM-EXT-P3E";
  46. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  47. const FIXTURE_ROOT = resolve(
  48. process.cwd(),
  49. "test/e2e/fixtures/fs/plugins/plugin-extension-approvals",
  50. );
  51. const PLUGIN = "e2e-ext-approvals";
  52. const PLUGIN_ID = `${PLUGIN}@inline`;
  53. const SLOT_ITEM = `${PLUGIN_ID}/run`;
  54. const PROMPTS = {
  55. outside: "E2E_P3E_OUTSIDE: a session the user started outside the plugin project.",
  56. allow: "E2E_P3E_ALLOW: write the allow file.",
  57. deny: "E2E_P3E_DENY: write the deny file.",
  58. ask: "E2E_P3E_ASK: ask me a question.",
  59. host: "E2E_P3E_HOST: write the host file.",
  60. mode: "E2E_P3E_MODE: reply with the mode marker.",
  61. yolo: "E2E_P3E_YOLO: reply with the yolo marker.",
  62. full: "E2E_P3E_FULL: write the full access file.",
  63. } as const;
  64. const QUESTION = "E2E_P3E_ASK_QUESTION: which answer?";
  65. const ANSWER = "E2E_P3E_ANSWER_B";
  66. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd();
  67. interface Op {
  68. name: string;
  69. input?: Record<string, unknown>;
  70. }
  71. interface OpResult {
  72. ok?: Record<string, unknown> & {
  73. status?: string;
  74. creation?: string;
  75. session?: { sessionId: string; workspacePath: string; project?: { projectId: string } };
  76. };
  77. error?: string;
  78. }
  79. interface InteractionLine {
  80. id: string;
  81. kind: string;
  82. options: string[];
  83. }
  84. interface InteractionsEvent {
  85. session: string;
  86. mode: string;
  87. interactions: InteractionLine[];
  88. }
  89. const evidence: Record<string, unknown> = {};
  90. const screenshots: string[] = [];
  91. const log = createExtensionLog();
  92. let seq = 0;
  93. function fixturesDir(): string {
  94. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-approvals");
  95. }
  96. function extensionsDataPath(...parts: string[]): string {
  97. return join(resolveE2EStorageRoot(), "v2", "extensions", ...parts);
  98. }
  99. function outputPath(name: string): string {
  100. return join(resolveE2ERuntimeRoot(), "plugin-extension-approvals", name);
  101. }
  102. const exists = (path: string) =>
  103. access(path).then(
  104. () => true,
  105. () => false,
  106. );
  107. async function writeManifestGrants(grants: string[]): Promise<void> {
  108. const path = join(fixturesDir(), PLUGIN, ".zcode-plugin", "plugin.json");
  109. const manifest = JSON.parse(await readFile(path, "utf8")) as {
  110. extension: { grants: string[] };
  111. };
  112. manifest.extension.grants = grants;
  113. await writeFile(path, JSON.stringify(manifest, null, 2));
  114. }
  115. async function seedPlugin(): Promise<void> {
  116. const target = fixturesDir();
  117. await mkdir(target, { recursive: true });
  118. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  119. await writePluginDirsConfig([join(target, PLUGIN)], [PLUGIN_ID]);
  120. await mkdir(extensionsDataPath(), { recursive: true });
  121. await writeFile(
  122. extensionsDataPath("grants.json"),
  123. JSON.stringify({
  124. version: 1,
  125. plugins: {
  126. // 旧格式(P3e 以前):没有 consentRevision,按 1 处理,要重新确认。
  127. [PLUGIN_ID]: {
  128. grants: ["sessions.write"],
  129. consentedVersion: "1.0.0",
  130. consentedAt: Date.now(),
  131. },
  132. },
  133. }),
  134. );
  135. await mkdir(join(resolveE2ERuntimeRoot(), "plugin-extension-approvals"), { recursive: true });
  136. }
  137. async function waitForLogAfter(
  138. from: number,
  139. predicate: (line: string) => boolean,
  140. message: string,
  141. timeout = 60000,
  142. ): Promise<string> {
  143. let found = "";
  144. await browser.waitUntil(
  145. async () => {
  146. found = (await log.lines()).slice(from).find(predicate) ?? "";
  147. return Boolean(found);
  148. },
  149. { timeout, interval: 300, timeoutMsg: message },
  150. );
  151. return found;
  152. }
  153. /** 写步骤文件,点状态栏命令,等这一步执行完;结果按序号返回。 */
  154. async function runStep(label: string, ops: Op[]): Promise<OpResult[]> {
  155. seq += 1;
  156. const current = seq;
  157. await writeFile(
  158. join(fixturesDir(), "e2e-ext-approvals-step.json"),
  159. JSON.stringify({ seq: current, ops }),
  160. );
  161. const from = (await log.lines()).length;
  162. await waitForSlot(SLOT_ITEM, (slot) => slot.text.includes("E2E approvals"), "the run slot");
  163. await clickSlot(SLOT_ITEM);
  164. await waitForLogAfter(
  165. from,
  166. (line) => line.includes(`E2E_APPROVALS_DONE seq=${current}`),
  167. `${label}: the extension should finish step ${current}`,
  168. 120000,
  169. );
  170. const results: OpResult[] = [];
  171. for (const line of (await log.lines()).slice(from)) {
  172. const match = new RegExp(`E2E_APPROVALS_RESULT seq=${current} index=(\\d+) `).exec(line);
  173. if (!match) continue;
  174. const ok = /\bok=(.*)$/.exec(line)?.[1];
  175. const error = /\berror=(\S+)/.exec(line)?.[1];
  176. results[Number(match[1])] = {
  177. ...(ok !== undefined ? { ok: JSON.parse(ok) as OpResult["ok"] } : {}),
  178. ...(error ? { error } : {}),
  179. };
  180. }
  181. evidence[`step-${current}-${label}`] = results;
  182. return results;
  183. }
  184. function parseEvent(line: string): InteractionsEvent | null {
  185. const match = /E2E_APPROVALS_EVENT session=(\S+) mode=(\S+) interactions=(.*)$/.exec(line);
  186. if (!match) return null;
  187. return {
  188. session: match[1]!,
  189. mode: match[2]!,
  190. interactions: JSON.parse(match[3]!) as InteractionLine[],
  191. };
  192. }
  193. /** 等 from 行之后、这个会话满足条件的交互事件。 */
  194. async function waitForEvent(
  195. from: number,
  196. sessionId: string,
  197. predicate: (event: InteractionsEvent) => boolean,
  198. message: string,
  199. timeout = 60000,
  200. ): Promise<InteractionsEvent> {
  201. let event: InteractionsEvent | null = null;
  202. await browser.waitUntil(
  203. async () => {
  204. for (const line of (await log.lines()).slice(from)) {
  205. const parsed = parseEvent(line);
  206. if (parsed?.session === sessionId && predicate(parsed)) {
  207. event = parsed;
  208. return true;
  209. }
  210. }
  211. return false;
  212. },
  213. { timeout, interval: 300, timeoutMsg: message },
  214. );
  215. return event!;
  216. }
  217. function optionId(interaction: InteractionLine, kind: string): string {
  218. const option = interaction.options.find((entry) => entry.startsWith(`${kind}:`));
  219. if (!option) throw new Error(`the interaction has no ${kind} option: ${interaction.options}`);
  220. return option.slice(kind.length + 1);
  221. }
  222. function createdSession(result: OpResult | undefined, label: string) {
  223. if (!result?.ok) throw new Error(`${label} failed: ${result?.error ?? "no result"}`);
  224. expect(result.ok).toMatchObject({ creation: "created" });
  225. return result.ok.session!;
  226. }
  227. async function hasHostPermissionDialog(): Promise<boolean> {
  228. return waitForV4PermissionDialog(500)
  229. .then(() => true)
  230. .catch(() => false);
  231. }
  232. /** 插件建一个会话、订阅它的交互、在桌面打开它,返回会话 id 与订阅开始时的日志位置。 */
  233. async function createWatchedSession(label: string, prompt: string, mode?: string) {
  234. const created = await runStep(`${label}-create`, [
  235. { name: "createSession", input: { prompt, ...(mode ? { mode } : {}) } },
  236. ]);
  237. const session = createdSession(created[0], `${label}: createSession`);
  238. const from = (await log.lines()).length;
  239. const watched = await runStep(`${label}-watch`, [
  240. { name: "watch", input: { sessionId: session.sessionId } },
  241. { name: "openSession", input: { sessionId: session.sessionId } },
  242. ]);
  243. expect(watched[1]?.ok).toMatchObject({ status: "opened" });
  244. await waitForV4Pane(
  245. (snapshot) => snapshot.sessionId === session.sessionId,
  246. `${label}: the desktop should open the plugin session`,
  247. 30000,
  248. );
  249. return { session, from };
  250. }
  251. async function readAudit(): Promise<Array<Record<string, unknown>>> {
  252. const dir = extensionsDataPath("audit");
  253. const names = (await readdir(dir).catch(() => [] as string[])).filter((name) =>
  254. name.endsWith(".jsonl"),
  255. );
  256. let text = "";
  257. for (const name of names.sort()) text += await readFile(join(dir, name), "utf8");
  258. return text
  259. .split("\n")
  260. .filter(Boolean)
  261. .map((line) => JSON.parse(line) as Record<string, unknown>);
  262. }
  263. async function runReloadFromCommandCenter(): Promise<void> {
  264. await $('[data-testid="sidebar-search-open"]').click();
  265. const input = $('[role="dialog"] [cmdk-input]');
  266. await input.waitForDisplayed({ timeout: 10000 });
  267. await input.setValue(">重新加载扩展");
  268. await browser.waitUntil(
  269. async () =>
  270. browser.execute(() => {
  271. const item = Array.from(
  272. document.querySelectorAll<HTMLElement>('[role="dialog"] [cmdk-item]'),
  273. ).find((element) => /重新加载扩展|Reload extensions/.test(element.textContent ?? ""));
  274. if (!item) return false;
  275. item.click();
  276. return true;
  277. }),
  278. { timeout: 10000, timeoutMsg: "command center should list 重新加载扩展" },
  279. );
  280. }
  281. function grantRowSelector(): string {
  282. return `[data-testid="${TID_SIDE_PANE_EXTENSION_GRANT}"][data-side-pane-open-tab-item="extension-grant:${PLUGIN_ID}"]`;
  283. }
  284. async function readDialog(): Promise<string | null> {
  285. return browser.execute((id) => {
  286. const dialog = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  287. return dialog ? (dialog.innerText ?? "") : null;
  288. }, TID_EXTENSION_GRANT_DIALOG);
  289. }
  290. /** 启动页「需要授权」行 → 授权对话框;返回对话框文字。 */
  291. async function openGrantDialog(): Promise<string> {
  292. await openLauncher();
  293. await browser.waitUntil(async () => $(grantRowSelector()).isDisplayed(), {
  294. timeout: 60000,
  295. interval: 300,
  296. timeoutMsg: "the launcher should show the needs-consent row",
  297. });
  298. await browser.execute((selector) => {
  299. const row = document.querySelector<HTMLElement>(selector);
  300. row?.scrollIntoView({ block: "center" });
  301. row?.click();
  302. }, grantRowSelector());
  303. let text: string | null = null;
  304. await browser.waitUntil(
  305. async () => {
  306. text = await readDialog();
  307. return Boolean(text);
  308. },
  309. { timeout: 15000, interval: 200, timeoutMsg: "the grant row should open the consent dialog" },
  310. );
  311. return text!;
  312. }
  313. /** 点授权对话框的确认,等它关闭。 */
  314. async function confirmGrantDialog(): Promise<void> {
  315. await browser.execute(
  316. (id, confirmTestId) => {
  317. document
  318. .querySelector<HTMLElement>(`[data-testid="${id}"] [data-testid="${confirmTestId}"]`)
  319. ?.click();
  320. },
  321. TID_EXTENSION_GRANT_DIALOG,
  322. TID_CONFIRM_DIALOG_CONFIRM,
  323. );
  324. await browser.waitUntil(async () => (await readDialog()) === null, {
  325. timeout: 15000,
  326. timeoutMsg: "the consent dialog should close after granting",
  327. });
  328. }
  329. async function readGrantRecord(): Promise<Record<string, unknown> | undefined> {
  330. const text = await readFile(extensionsDataPath("grants.json"), "utf8").catch(() => null);
  331. if (!text) return undefined;
  332. const file = JSON.parse(text) as { plugins?: Record<string, Record<string, unknown>> };
  333. return file.plugins?.[PLUGIN_ID];
  334. }
  335. describe("PLM-EXT-P3E 插件回答审批、提问与切换权限模式", () => {
  336. after(async () => {
  337. evidence.screenshots = screenshots;
  338. await writeFile(
  339. join(artifacts, "plm-ext-p3e-evidence.json"),
  340. JSON.stringify(evidence, null, 2),
  341. ).catch(() => undefined);
  342. await clearAppData();
  343. });
  344. it("插件项目里的会话:批准、拒绝、回答提问、切换模式;完全访问要申请并授权;项目外的会话 forbidden", async function () {
  345. this.timeout(1200000);
  346. requirePluginManualReview();
  347. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  348. await seedPlugin();
  349. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  350. afterElectronProcessExit: async () => {
  351. await log.mark();
  352. },
  353. });
  354. await prepareV4ConversationE2E();
  355. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  356. const activated = await log.waitFor(
  357. (line) => line.includes(`E2E_APPROVALS_ACTIVATED plugin=${PLUGIN_ID}`),
  358. "the approvals fixture should activate",
  359. 90000,
  360. );
  361. const dataPath = JSON.parse(/dataPath=(".*")$/.exec(activated)![1]!) as string;
  362. evidence.dataPath = dataPath;
  363. await installHandoffRpcProbe();
  364. // (0) 旧授权记录(没有 consentRevision):会话能力报 not-granted,启动页显示「需要授权」;对话框写着新增的三项能力,
  365. // 重新授权后记录写入当前 revision,之后的步骤(项目外 forbidden、批准、拒绝……)证明授权已生效。
  366. const stale = await runStep("stale-grant", [
  367. { name: "setPermissionMode", input: { sessionId: "missing", mode: "guarded" } },
  368. ]);
  369. expect(stale[0]?.error).toBe("not-granted");
  370. const reconsent = await openGrantDialog();
  371. evidence.reconsentDialog = reconsent;
  372. expect(reconsent).toContain(`允许「${PLUGIN}」读取和操作会话?`);
  373. expect(reconsent).toContain(
  374. "插件项目里的会话:插件还能替你批准或拒绝工具调用、回答 Agent 的提问、切换权限模式。",
  375. );
  376. expect(reconsent).not.toContain("完全访问:");
  377. screenshots.push(await capturePluginManualReview(CASE_ID, "reconsent-dialog-zh-CN-zai-light"));
  378. await confirmGrantDialog();
  379. await browser.waitUntil(
  380. async () => (await readGrantRecord())?.consentRevision === EXTENSION_SESSION_CONSENT_REVISION,
  381. { timeout: 15000, timeoutMsg: "re-granting should write the current consent revision" },
  382. );
  383. evidence.reconsentRecord = await readGrantRecord();
  384. await browser.waitUntil(async () => !(await $(grantRowSelector()).isExisting()), {
  385. timeout: 15000,
  386. timeoutMsg: "the needs-consent row should disappear after re-granting",
  387. });
  388. // (a) 用户在主界面建的会话(不在插件项目里):订阅、回答、切换都 forbidden。
  389. await sendV4Prompt(PROMPTS.outside);
  390. const outside = await waitForV4Pane(
  391. (snapshot) =>
  392. Boolean(snapshot.sessionId && snapshot.sessionId !== "draft") &&
  393. snapshot.timelineText.includes("E2E_P3E_OUTSIDE_DONE"),
  394. "the user's own session should reply",
  395. 60000,
  396. );
  397. const outsideId = outside.sessionId!;
  398. const outsideFrom = (await log.lines()).length;
  399. const outsideStep = await runStep("outside", [
  400. { name: "watch", input: { sessionId: outsideId } },
  401. {
  402. name: "resolveInteraction",
  403. input: { sessionId: outsideId, interactionId: "missing", answer: { optionId: "allow" } },
  404. },
  405. { name: "setPermissionMode", input: { sessionId: outsideId, mode: "guarded" } },
  406. ]);
  407. expect(outsideStep[1]?.error).toBe("forbidden");
  408. expect(outsideStep[2]?.error).toBe("forbidden");
  409. evidence.outsideWatchError = await waitForLogAfter(
  410. outsideFrom,
  411. (line) => line.includes(`E2E_APPROVALS_WATCH_ERROR session=${outsideId}`),
  412. "watching a session outside the plugin project should end with an error",
  413. );
  414. expect(String(evidence.outsideWatchError)).toContain("error=forbidden");
  415. // (b) 批准一次:宿主审批面板与插件看到同一个交互;插件回答后面板消失,工具执行(文件写出)。
  416. const allow = await createWatchedSession("allow", PROMPTS.allow);
  417. const allowEvent = await waitForEvent(
  418. allow.from,
  419. allow.session.sessionId,
  420. (event) => event.interactions.some((entry) => entry.kind === "permission"),
  421. "the plugin should see the Write approval",
  422. );
  423. expect(allowEvent.mode).toBe("build");
  424. const allowInteraction = allowEvent.interactions[0]!;
  425. evidence.allowInteraction = allowInteraction;
  426. await waitForV4PermissionDialog();
  427. // 行镜像里的工具行状态(宿主行为,以前只由 PLM-JARVIS-2 断言):等审批时是 pendingApproval。
  428. const allowRowsFrom = (await log.lines()).length;
  429. await runStep("allow-rows", [
  430. { name: "watchRows", input: { sessionId: allow.session.sessionId } },
  431. ]);
  432. const pendingRows = await waitForLogAfter(
  433. allowRowsFrom,
  434. (line) =>
  435. line.includes(`E2E_APPROVALS_ROWS session=${allow.session.sessionId} `) &&
  436. /tools=(\S*,)?Write:pendingApproval\b/.test(line),
  437. "the rows mirror should show the Write tool row waiting for approval",
  438. );
  439. evidence.allowRowsPending = pendingRows;
  440. screenshots.push(await capturePluginManualReview(CASE_ID, "host-panel-before-zh-CN-zai-light"));
  441. const allowAnswer = await runStep("allow-answer", [
  442. {
  443. name: "resolveInteraction",
  444. input: {
  445. sessionId: allow.session.sessionId,
  446. interactionId: allowInteraction.id,
  447. answer: { optionId: optionId(allowInteraction, "allowOnce") },
  448. },
  449. },
  450. ]);
  451. expect(allowAnswer[0]?.ok).toEqual({ status: "accepted" });
  452. await waitForEvent(
  453. allow.from,
  454. allow.session.sessionId,
  455. (event) => event.interactions.length === 0,
  456. "the approval should disappear after the plugin answered",
  457. );
  458. await browser.waitUntil(async () => !(await hasHostPermissionDialog()), {
  459. timeout: 30000,
  460. interval: 300,
  461. timeoutMsg: "the host permission panel should disappear after the plugin answered",
  462. });
  463. await waitForV4AssistantMessageContaining("E2E_P3E_ALLOW_DONE", 90000);
  464. expect(await exists(outputPath("allow.txt"))).toBe(true);
  465. // 批准后工具执行完:同一个工具行变成 success。
  466. evidence.allowRowsDone = await waitForLogAfter(
  467. allowRowsFrom,
  468. (line) =>
  469. line.includes(`E2E_APPROVALS_ROWS session=${allow.session.sessionId} `) &&
  470. /tools=(\S*,)?Write:success\b/.test(line),
  471. "the rows mirror should show the Write tool row succeeded",
  472. );
  473. await runStep("allow-unwatch-rows", [
  474. { name: "unwatchRows", input: { sessionId: allow.session.sessionId } },
  475. ]);
  476. // (c) 拒绝:工具不执行(文件没有写出),模型收到拒绝结果。
  477. const deny = await createWatchedSession("deny", PROMPTS.deny);
  478. const denyEvent = await waitForEvent(
  479. deny.from,
  480. deny.session.sessionId,
  481. (event) => event.interactions.some((entry) => entry.kind === "permission"),
  482. "the plugin should see the second Write approval",
  483. );
  484. const denyInteraction = denyEvent.interactions[0]!;
  485. const denied = await runStep("deny-answer", [
  486. {
  487. name: "resolveInteraction",
  488. input: {
  489. sessionId: deny.session.sessionId,
  490. interactionId: denyInteraction.id,
  491. answer: { optionId: optionId(denyInteraction, "deny") },
  492. },
  493. },
  494. ]);
  495. expect(denied[0]?.ok).toEqual({ status: "accepted" });
  496. await waitForV4AssistantMessageContaining("E2E_P3E_DENY_DONE", 90000);
  497. expect(await exists(outputPath("deny.txt"))).toBe(false);
  498. // (d) 回答 AskUserQuestion:答案进了下一次请求(最终夹具要求请求体里有答案)。
  499. const ask = await createWatchedSession("ask", PROMPTS.ask);
  500. const askEvent = await waitForEvent(
  501. ask.from,
  502. ask.session.sessionId,
  503. (event) => event.interactions.some((entry) => entry.kind === "userInput"),
  504. "the plugin should see the AskUserQuestion interaction",
  505. );
  506. const askInteraction = askEvent.interactions[0]!;
  507. // 原由 PLM-JARVIS-2 断言:插件看到的提问带模型给的选项。
  508. expect(askInteraction.options).toEqual([
  509. `question:${QUESTION}`,
  510. "choice:E2E_P3E_ANSWER_A",
  511. `choice:${ANSWER}`,
  512. ]);
  513. const answered = await runStep("ask-answer", [
  514. {
  515. name: "resolveInteraction",
  516. input: {
  517. sessionId: ask.session.sessionId,
  518. interactionId: askInteraction.id,
  519. // 与宿主的回答同一种形状(ElicitationDialog 的 content:answers 按问题原文,answer_<序号>,单题时 answer)。
  520. answer: {
  521. action: "accept",
  522. content: { answers: { [QUESTION]: ANSWER }, answer_0: ANSWER, answer: ANSWER },
  523. },
  524. },
  525. },
  526. ]);
  527. expect(answered[0]?.ok).toEqual({ status: "accepted" });
  528. await waitForV4AssistantMessageContaining("E2E_P3E_ASK_GOT_B", 90000);
  529. // (e) 宿主先回答:插件之后用同一个交互回答得到 stale,不发命令。
  530. const host = await createWatchedSession("host", PROMPTS.host);
  531. const hostEvent = await waitForEvent(
  532. host.from,
  533. host.session.sessionId,
  534. (event) => event.interactions.some((entry) => entry.kind === "permission"),
  535. "the plugin should see the host-answered approval",
  536. );
  537. await approveV4Permission();
  538. await waitForEvent(
  539. host.from,
  540. host.session.sessionId,
  541. (event) => event.interactions.length === 0,
  542. "the approval should disappear after the host answered",
  543. );
  544. const late = await runStep("host-late-answer", [
  545. {
  546. name: "resolveInteraction",
  547. input: {
  548. sessionId: host.session.sessionId,
  549. interactionId: hostEvent.interactions[0]!.id,
  550. answer: { optionId: optionId(hostEvent.interactions[0]!, "allowOnce") },
  551. },
  552. },
  553. ]);
  554. expect(late[0]?.ok).toEqual({ status: "stale" });
  555. await waitForV4AssistantMessageContaining("E2E_P3E_HOST_DONE", 90000);
  556. // (f) 切换权限模式;没有申请完全访问时 yolo 一律 not-declared。
  557. const mode = await createWatchedSession("mode", PROMPTS.mode);
  558. // 修复原因(PLM-EXT-P3E 首跑偶发「看不到 guarded」):已提交的输入按提交时的模式开跑,轮开始时 CLI 再应用一次
  559. // (turn.ts「session_persistence」→ applySubmissionExecutionState)。createSession 的首条输入按 build 提交,
  560. // 首轮开始前切到 guarded,轮一开始就被改回 build;两次变化落在同一帧时插件只看到最终的 build。
  561. // 这是 CLI 的现有语义(宿主界面相同),所以等首轮做完再切换;首轮就要别的模式用 createSession.mode。
  562. await waitForV4AssistantMessageContaining("E2E_P3E_MODE_DONE", 90000);
  563. await waitForEvent(
  564. mode.from,
  565. mode.session.sessionId,
  566. (event) => event.mode === "build",
  567. "the plugin should see the initial mode",
  568. );
  569. const switched = await runStep("mode-switch", [
  570. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "guarded" } },
  571. ]);
  572. expect(switched[0]?.ok).toEqual({ status: "accepted" });
  573. await waitForEvent(
  574. mode.from,
  575. mode.session.sessionId,
  576. (event) => event.mode === "guarded",
  577. "the plugin should see the guarded mode",
  578. );
  579. const refused = await runStep("mode-refused", [
  580. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "guarded" } },
  581. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "yolo" } },
  582. { name: "createSession", input: { prompt: PROMPTS.yolo, mode: "yolo" } },
  583. ]);
  584. expect(refused[0]?.ok).toEqual({ status: "unchanged" });
  585. expect(refused[1]?.error).toBe("not-declared");
  586. expect(refused[2]?.error).toBe("not-declared");
  587. // (g) 清单申请 sessions.fullAccess:重新加载后回到「需要授权」,授权对话框单独写完全访问一行;授权后 yolo 可用。
  588. await writeManifestGrants(["sessions.fullAccess"]);
  589. const reloadFrom = (await log.lines()).length;
  590. await runReloadFromCommandCenter();
  591. await waitForLogAfter(
  592. reloadFrom,
  593. (line) => line.includes(`E2E_APPROVALS_ACTIVATED plugin=${PLUGIN_ID}`),
  594. "the extension should activate again after reloading",
  595. 90000,
  596. );
  597. const notGranted = await runStep("full-not-granted", [
  598. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "yolo" } },
  599. ]);
  600. expect(notGranted[0]?.error).toBe("not-granted");
  601. const dialog = await openGrantDialog();
  602. evidence.fullAccessDialog = dialog;
  603. expect(dialog).toContain(`允许「${PLUGIN}」读取和操作会话?`);
  604. expect(dialog).toContain("插件项目里的会话:插件还能替你批准或拒绝工具调用");
  605. expect(dialog).toContain("完全访问:插件可以把它项目里的会话切到完全访问");
  606. screenshots.push(
  607. await capturePluginManualReview(CASE_ID, "full-access-dialog-zh-CN-zai-light"),
  608. );
  609. await confirmGrantDialog();
  610. const grantedFrom = (await log.lines()).length;
  611. const granted = await runStep("full-granted", [
  612. { name: "watch", input: { sessionId: mode.session.sessionId } },
  613. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "yolo" } },
  614. { name: "createSession", input: { prompt: PROMPTS.yolo, mode: "yolo" } },
  615. ]);
  616. expect(granted[1]?.ok).toEqual({ status: "accepted" });
  617. await waitForEvent(
  618. grantedFrom,
  619. mode.session.sessionId,
  620. (event) => event.mode === "yolo",
  621. "the plugin should see full access after the grant",
  622. );
  623. const yoloSession = createdSession(granted[2], "createSession with mode yolo");
  624. const yoloFrom = (await log.lines()).length;
  625. await runStep("yolo-watch", [{ name: "watch", input: { sessionId: yoloSession.sessionId } }]);
  626. await waitForEvent(
  627. yoloFrom,
  628. yoloSession.sessionId,
  629. (event) => event.mode === "yolo",
  630. "a session created with mode yolo should start in full access",
  631. );
  632. // 原由 PLM-JARVIS-2 断言:完全访问之后能切回 build,插件看到 build。
  633. const backFrom = (await log.lines()).length;
  634. const back = await runStep("mode-back", [
  635. { name: "setPermissionMode", input: { sessionId: mode.session.sessionId, mode: "build" } },
  636. ]);
  637. expect(back[0]?.ok).toEqual({ status: "accepted" });
  638. await waitForEvent(
  639. backFrom,
  640. mode.session.sessionId,
  641. (event) => event.mode === "build",
  642. "the plugin should see build again after leaving full access",
  643. );
  644. // (h) 选「允许并切到完全访问」:模式变成 yolo,工具执行。
  645. const full = await createWatchedSession("full", PROMPTS.full);
  646. const fullEvent = await waitForEvent(
  647. full.from,
  648. full.session.sessionId,
  649. (event) =>
  650. event.interactions.some((entry) =>
  651. entry.options.some((option) => option.startsWith("fullAccess:")),
  652. ),
  653. "the approval should offer full access",
  654. );
  655. const fullInteraction = fullEvent.interactions[0]!;
  656. const fullAnswer = await runStep("full-answer", [
  657. {
  658. name: "resolveInteraction",
  659. input: {
  660. sessionId: full.session.sessionId,
  661. interactionId: fullInteraction.id,
  662. answer: { optionId: optionId(fullInteraction, "fullAccess") },
  663. },
  664. },
  665. ]);
  666. expect(fullAnswer[0]?.ok).toEqual({ status: "accepted" });
  667. await waitForEvent(
  668. full.from,
  669. full.session.sessionId,
  670. (event) => event.mode === "yolo" && event.interactions.length === 0,
  671. "answering with full access should switch the session to yolo",
  672. );
  673. await waitForV4AssistantMessageContaining("E2E_P3E_FULL_DONE", 90000);
  674. expect(await exists(outputPath("full.txt"))).toBe(true);
  675. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  676. screenshots.push(await capturePluginManualReview(CASE_ID, "after-full-access-en-US-zai-dark"));
  677. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  678. // (i) 插件会话都在插件项目里;插件只看到 permission 与 userInput 两种交互。
  679. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{}]);
  680. const workspace = normalize(join(dataPath, "workspace"));
  681. const projectIds = new Set(
  682. tree.projects
  683. .filter((project) => project.roots.some((root) => normalize(root.rootPath) === workspace))
  684. .map((project) => project.id),
  685. );
  686. for (const session of [allow, deny, ask, host, mode, full].map((entry) => entry.session))
  687. expect(projectIds.has(session.project!.projectId)).toBe(true);
  688. const kinds = new Set(
  689. (await log.lines())
  690. .map(parseEvent)
  691. .flatMap((event) => event?.interactions.map((entry) => entry.kind) ?? []),
  692. );
  693. evidence.interactionKinds = [...kinds];
  694. expect([...kinds].every((kind) => kind === "permission" || kind === "userInput")).toBe(true);
  695. // (j) 审计:每次回答、切换一行,有种类与选择,没有问题、答案与提示词。
  696. const audit = (await readAudit()).filter((row) => row.pluginId === PLUGIN_ID);
  697. const answers = audit.filter((row) => row.capability === "sessions.resolveInteraction");
  698. const switches = audit.filter((row) => row.capability === "sessions.setPermissionMode");
  699. evidence.auditAnswers = answers;
  700. evidence.auditSwitches = switches;
  701. expect(answers.map((row) => row.choice)).toEqual(
  702. expect.arrayContaining(["allowOnce", "deny", "answer", "fullAccess"]),
  703. );
  704. expect(answers.find((row) => row.choice === "answer")?.interactionKind).toBe("userInput");
  705. expect(answers.some((row) => row.errorCode === "result.stale")).toBe(true);
  706. expect(switches.some((row) => row.mode === "guarded" && row.outcome === "ok")).toBe(true);
  707. expect(switches.some((row) => row.errorCode === "not-declared")).toBe(true);
  708. expect(switches.some((row) => row.mode === "yolo" && row.outcome === "ok")).toBe(true);
  709. const auditText = JSON.stringify(audit);
  710. for (const secret of [QUESTION, ANSWER, PROMPTS.allow, PROMPTS.ask])
  711. expect(auditText).not.toContain(secret);
  712. });
  713. });