verify-provision-entry.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /** 授权的独立验收账号全链路;凭据与截图只保存在本机临时目录。 */
  2. import fs from 'node:fs';
  3. import os from 'node:os';
  4. import path from 'node:path';
  5. import assert from 'node:assert/strict';
  6. import { chromium } from 'playwright';
  7. const dir = process.env.FMODE_E2E_DIR || path.join(os.tmpdir(), 'fmode-app-1127-e2e');
  8. const accountPath = path.join(dir, 'account.json');
  9. const account = JSON.parse(fs.readFileSync(accountPath, 'utf8'));
  10. const base = process.env.FMODE_E2E_URL || 'http://127.0.0.1:4200';
  11. const stage = process.argv.find(a => a.startsWith('--stage='))?.slice(8) || 'start';
  12. const executablePath = [
  13. 'C:/Program Files/Google/Chrome/Application/chrome.exe',
  14. 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
  15. ].find(p => fs.existsSync(p));
  16. const browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) });
  17. const errors = [];
  18. const output = value => console.log(JSON.stringify(value));
  19. const statePath = path.join(dir, 'browser-state.json');
  20. async function context(mobile = false, restore = true) {
  21. const c = await browser.newContext({
  22. viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 960 },
  23. isMobile: mobile, hasTouch: mobile,
  24. ...(restore && fs.existsSync(statePath) ? { storageState: statePath } : {}),
  25. });
  26. const page = await c.newPage();
  27. page.setDefaultTimeout(30000);
  28. page.on('pageerror', e => errors.push(e.message));
  29. return { c, page };
  30. }
  31. async function login(page, mobile = false) {
  32. await page.goto(base + '/login', { waitUntil: 'domcontentloaded' });
  33. await page.getByRole('button', { name: mobile ? '使用账号密码登录' : '账号登录', exact: true }).click();
  34. await page.locator('input[placeholder="请输入账号"]').fill(account.username);
  35. await page.locator('input[placeholder="请输入密码"]').fill(account.password);
  36. if (mobile) {
  37. const agreement = page.locator('input[type="checkbox"]');
  38. if (await agreement.count()) await agreement.first().check({ force: true });
  39. }
  40. await page.getByRole('button', { name: /^登\s*录$/ }).click();
  41. }
  42. async function chatThroughUi() {
  43. assert.ok(account.agentId, 'Missing isolated test agent');
  44. const { c, page } = await context();
  45. const canonical = 'agent-node-app-' + account.agentId.toLowerCase();
  46. const existing = process.argv.includes('--existing');
  47. let marker = '验收成功-' + Date.now();
  48. let prompt = '请只回复这段文字:' + marker;
  49. if (!existing) {
  50. await page.goto(base + '/desktop/chat/' + canonical + '/new', { waitUntil: 'domcontentloaded' });
  51. const area = page.locator('textarea').first();
  52. await area.waitFor({ state: 'visible', timeout: 60000 });
  53. await page.waitForFunction(() => { const el = document.querySelector('textarea'); return el && !el.disabled; }, undefined, { timeout: 60000 });
  54. await area.fill(prompt);
  55. await page.locator('button.send').click();
  56. }
  57. const cfg = JSON.parse(fs.readFileSync(new URL('../.claude/dev-login.json', import.meta.url), 'utf8'));
  58. const env = fs.readFileSync(new URL('../src/environments/environment.base.ts', import.meta.url), 'utf8');
  59. const parseBase = env.match(/parseServer:\s*'([^']+)'/)[1];
  60. const appId = env.match(/parseAppId:\s*'([^']+)'/)[1];
  61. const u = new URL(parseBase + '/classes/FmodeMatrixBinding');
  62. u.searchParams.set('where', JSON.stringify({
  63. userPointer: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical, status: 'active',
  64. }));
  65. const response = await fetch(u, { headers: { 'X-Parse-Application-Id': appId, 'X-Parse-Master-Key': cfg.masterKey } });
  66. const binding = (await response.json()).results?.[0];
  67. assert.ok(binding?.roomId, 'No owned binding');
  68. // App 一房间一会话;绑定房间只用于初始接入,不能误拿它验收新对话。
  69. const threadsUrl = new URL(parseBase + '/classes/FmodeChatThread');
  70. threadsUrl.searchParams.set('where', JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical }));
  71. threadsUrl.searchParams.set('order', '-createdAt');
  72. const threadsRes = await fetch(threadsUrl, { headers: { 'X-Parse-Application-Id': appId, 'X-Parse-Master-Key': cfg.masterKey } });
  73. const threads = (await threadsRes.json()).results || [];
  74. const thread = threads.find(t => !t.isDeleted && (existing ? /验收成功-\d+/.test(t.lastPreview || '') : t.lastPreview?.includes(marker)));
  75. assert.ok(thread?.roomId, 'Actual UI session room was not persisted');
  76. if (existing) {
  77. marker = thread.lastPreview.match(/验收成功-\d+/)[0];
  78. prompt = thread.lastPreview;
  79. }
  80. let proof;
  81. for (let i = 0; i < 60; i++) {
  82. const r = await fetch(binding.homeserver + '/_matrix/client/v3/rooms/' + encodeURIComponent(thread.roomId) + '/messages?dir=b&limit=100', {
  83. headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(15000),
  84. });
  85. const events = (await r.json()).chunk || [];
  86. const sent = events.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(prompt));
  87. const reply = events.find(e => e.sender === binding.agentMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
  88. const targets = [sent?.event_id, sent?.content?.['m.relates_to']?.event_id, reply?.event_id].filter(Boolean);
  89. const done = events.find(e => e.sender === binding.agentMxId && e.type === 'm.reaction' &&
  90. e.content?.['m.relates_to']?.key === '✅' && targets.includes(e.content['m.relates_to'].event_id));
  91. if (sent && reply && done) {
  92. proof = { sentEventId: sent.event_id, replyEventId: reply.event_id, completionEventId: done.event_id, agentId: canonical };
  93. break;
  94. }
  95. await new Promise(resolve => setTimeout(resolve, 3000));
  96. }
  97. assert.ok(proof, 'Actual UI send did not produce an authenticated target reply and completion');
  98. fs.writeFileSync(path.join(dir, 'chat-proof.json'), JSON.stringify(proof, null, 2));
  99. await page.goto(base + '/desktop/chat/' + canonical + '/' + encodeURIComponent(thread.threadRoot), { waitUntil: 'domcontentloaded' });
  100. await page.getByText(marker, { exact: true }).first().waitFor({ state: 'visible', timeout: 60000 });
  101. await page.screenshot({ path: path.join(dir, '07-real-chat.png'), fullPage: true });
  102. output({ check: 'real-ui-chat-roundtrip', ...proof, pass: true });
  103. await c.close();
  104. const mobile = await context(true);
  105. await mobile.page.goto(base, { waitUntil: 'domcontentloaded' });
  106. await mobile.page.waitForURL(/\/mobile\/messages/, { timeout: 60000 });
  107. await mobile.page.locator('button.m-row').first().waitFor({ state: 'visible', timeout: 60000 });
  108. await mobile.page.screenshot({ path: path.join(dir, '06-mobile-reopen.png'), fullPage: true });
  109. await mobile.page.locator('button.m-row').first().click();
  110. await mobile.page.getByText(marker, { exact: true }).first().waitFor({ state: 'visible', timeout: 60000 });
  111. await mobile.page.screenshot({ path: path.join(dir, '08-mobile-real-chat.png'), fullPage: true });
  112. output({ check: 'mobile-existing-chat-readback', pass: true });
  113. await mobile.c.close();
  114. }
  115. try {
  116. if (stage === 'chat') {
  117. await chatThroughUi();
  118. } else if (stage === 'start') {
  119. assert.ok(!account.jobId, 'This account already has an acceptance job; resume it instead of creating another.');
  120. const { c, page } = await context(false, false);
  121. await login(page);
  122. await page.waitForURL(/\/plans(?:\?|$)/, { timeout: 60000 });
  123. await page.screenshot({ path: path.join(dir, '01-new-user-plans.png'), fullPage: true });
  124. output({ check: 'new-user-login', url: page.url(), pass: true });
  125. const advanced = page.locator('article.plan-card').filter({ has: page.getByRole('heading', { name: '进阶版', exact: true }) });
  126. await advanced.getByRole('button', { name: '立即开通', exact: true }).click();
  127. await page.waitForURL(/\/provision\?jobId=/, { timeout: 90000 });
  128. account.jobId = new URL(page.url()).searchParams.get('jobId');
  129. fs.writeFileSync(accountPath, JSON.stringify(account, null, 2));
  130. await c.storageState({ path: statePath });
  131. await page.screenshot({ path: path.join(dir, '02-provisioning.png'), fullPage: true });
  132. output({ check: 'start-provision-through-ui', jobId: account.jobId, pass: true });
  133. await c.close();
  134. } else {
  135. assert.ok(account.jobId, 'No verified start-stage job');
  136. const { c, page } = await context();
  137. await page.goto(base + '/provision?jobId=' + encodeURIComponent(account.jobId), { waitUntil: 'domcontentloaded' });
  138. if (process.argv.includes('--refresh-running')) {
  139. await page.waitForTimeout(1500);
  140. await page.reload({ waitUntil: 'domcontentloaded' });
  141. assert.equal(new URL(page.url()).searchParams.get('jobId'), account.jobId);
  142. await page.screenshot({ path: path.join(dir, '02-provisioning-refreshed.png'), fullPage: true });
  143. output({ check: 'refresh-preserves-provision-job', jobId: account.jobId, pass: true });
  144. }
  145. const ticker = setInterval(() => output({ check: 'waiting-for-real-readiness', jobId: account.jobId }), 30000);
  146. try {
  147. await page.getByRole('button', { name: '进入应用', exact: true }).waitFor({ state: 'visible', timeout: 12 * 60 * 1000 });
  148. } finally { clearInterval(ticker); }
  149. await page.screenshot({ path: path.join(dir, '03-ready.png'), fullPage: true });
  150. await page.getByRole('button', { name: '进入应用', exact: true }).click();
  151. await page.waitForURL(/\/desktop\/chat(?:[/?]|$)/, { timeout: 60000 });
  152. await page.screenshot({ path: path.join(dir, '04-entered-app.png'), fullPage: true });
  153. output({ check: 'ready-enter-app', url: page.url(), pass: true });
  154. await page.reload({ waitUntil: 'domcontentloaded' });
  155. await page.waitForURL(/\/desktop\/chat(?:[/?]|$)/, { timeout: 60000 });
  156. output({ check: 'desktop-refresh', pass: true });
  157. await c.storageState({ path: statePath });
  158. await c.close();
  159. for (const mobile of [false, true]) {
  160. const reopened = await context(mobile);
  161. await reopened.page.goto(base, { waitUntil: 'domcontentloaded' });
  162. await reopened.page.waitForURL(mobile ? /\/mobile\/messages/ : /\/desktop\/chat/, { timeout: 60000 });
  163. await reopened.page.screenshot({ path: path.join(dir, mobile ? '06-mobile-reopen.png' : '05-desktop-reopen.png'), fullPage: true });
  164. output({ check: mobile ? 'mobile-reopen' : 'desktop-reopen', url: reopened.page.url(), pass: true });
  165. await reopened.c.close();
  166. }
  167. const freshLogin = await context(false, false);
  168. await login(freshLogin.page);
  169. await freshLogin.page.waitForURL(/\/desktop\/chat/, { timeout: 60000 });
  170. output({ check: 'fresh-password-login-after-provision', pass: true });
  171. await freshLogin.c.close();
  172. }
  173. assert.deepEqual(errors, [], 'Browser page errors');
  174. output({ stage, pageErrors: errors, evidenceDirectory: dir, success: true });
  175. } finally {
  176. await browser.close();
  177. }