product-request.spec.ts (58649B)
1 import { test, expect, type Page } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { svelte } from '@sveltejs/vite-plugin-svelte'; 4 import { fileURLToPath } from 'node:url'; 5 import { once } from 'node:events'; 6 import { WebSocketServer } from 'ws'; 7 import { finalizeEvent, getPublicKey } from 'applesauce-core/helpers'; 8 import { createStaticHarness } from '../integration/harness/static.ts'; 9 import type * as Fixture from './harness/product-request.ts'; 10 11 declare global { 12 interface Window { 13 cr007PendingSend?: Promise<unknown>; 14 cr007DelayPrivateClose?: boolean; 15 cr007DelayedCloses?: (() => void)[]; 16 hcp107: typeof Fixture; 17 hcp107Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>; 18 hcp108SendClock: { 19 samples: { milliseconds: number; phase: string; stack?: string }[]; 20 locks: { captured: number; callback: number; granted: boolean }[]; 21 transactions: string[]; 22 restore(): void; 23 }; 24 hcp126HeldClock: { 25 samples: { 26 milliseconds: number; 27 actualMilliseconds: number; 28 stack?: string; 29 }[]; 30 restore(): void; 31 }; 32 } 33 } 34 let server: Awaited<ReturnType<typeof createStaticHarness>>; 35 let sockets: WebSocketServer, endpoint: string, bundle: string; 36 let missingOwn = false; 37 let holdPrivateAck = false; 38 let listingStatus: 'active' | 'sold' | 'withdrawn' = 'active'; 39 let sellerInbox: 40 | 'normal' 41 | 'missing' 42 | 'unsupported' 43 | 'unapproved' 44 | 'malformed' 45 | 'partial' = 'normal'; 46 let incompleteListing = false; 47 let holdListingHead = false; 48 let headUpdates: (() => void)[] = [], 49 deletionUpdates: (() => void)[] = []; 50 let holdOwnEose = false, 51 holdPeerEose = false; 52 let waitingEose: (() => void)[] = []; 53 let events: { 54 origin: string; 55 event: { 56 kind: number; 57 id: string; 58 pubkey: string; 59 content: string; 60 tags: string[][]; 61 }; 62 }[] = []; 63 const sellerSecret = new Uint8Array(32).fill(84); 64 const ownerSecret = new Uint8Array(32).fill(83); 65 const peer = getPublicKey(sellerSecret), 66 owner = getPublicKey(ownerSecret); 67 let ownPreference: ReturnType<typeof finalizeEvent> | undefined; 68 function preference(secret: Uint8Array, origin: string) { 69 return finalizeEvent( 70 { 71 kind: 10050, 72 created_at: 1700000060, 73 tags: [['relay', origin]], 74 content: '' 75 }, 76 secret 77 ); 78 } 79 test.beforeAll(async () => { 80 server = await createStaticHarness(); 81 sockets = new WebSocketServer({ 82 host: '127.0.0.1', 83 port: 0, 84 maxPayload: 65536 85 }); 86 await once(sockets, 'listening'); 87 const address = sockets.address(); 88 if (!address || typeof address === 'string') throw Error('no loopback'); 89 endpoint = 'ws://127.0.0.1:' + address.port; 90 sockets.on('connection', (socket, request) => { 91 const origin = 92 new URL(request.url ?? '/', endpoint).searchParams.get('source') ?? ''; 93 socket.on('message', (bytes) => { 94 const raw = Buffer.isBuffer(bytes) 95 ? bytes 96 : Array.isArray(bytes) 97 ? Buffer.concat(bytes) 98 : Buffer.from(bytes); 99 const frame = JSON.parse(raw.toString()) as unknown[]; 100 if (frame[0] === 'EVENT') { 101 const event = frame[1] as (typeof events)[number]['event']; 102 events.push({ origin, event }); 103 if (event.kind === 10050) 104 ownPreference = event as ReturnType<typeof finalizeEvent>; 105 if (!holdPrivateAck || event.kind !== 1059) 106 socket.send( 107 JSON.stringify(['OK', event.id, true, 'controlled acceptance']) 108 ); 109 return; 110 } 111 if (frame[0] !== 'REQ') return; 112 const filters = frame.slice(2) as { 113 kinds?: number[]; 114 authors?: string[]; 115 }[]; 116 for (const filter of filters) { 117 if (filter.kinds?.includes(30402)) { 118 const event = finalizeEvent( 119 { 120 kind: 30402, 121 created_at: 1700000060, 122 content: 'Independently signed carrots', 123 tags: [ 124 ['d', 'carrots'], 125 ['title', 'Verified carrots'], 126 ['summary', 'Actual signed listing'], 127 ['published_at', '1700000000'], 128 ['location', 'Victoria'], 129 ['price', '3.5', 'CAD'], 130 ['radroots:price_unit', 'lb'], 131 ['status', listingStatus === 'sold' ? 'sold' : 'active'] 132 ] 133 }, 134 sellerSecret 135 ); 136 socket.send(JSON.stringify(['EVENT', frame[1], event])); 137 headUpdates.push(() => { 138 if (socket.readyState === 1) 139 socket.send( 140 JSON.stringify([ 141 'EVENT', 142 frame[1], 143 finalizeEvent( 144 { 145 ...event, 146 created_at: 1700000080, 147 tags: event.tags.map((tag) => 148 tag[0] === 'status' 149 ? [ 150 'status', 151 listingStatus === 'sold' ? 'sold' : 'active' 152 ] 153 : tag 154 ) 155 }, 156 sellerSecret 157 ) 158 ]) 159 ); 160 }); 161 } 162 if (filter.kinds?.includes(5)) 163 deletionUpdates.push(() => { 164 if (socket.readyState === 1) 165 socket.send( 166 JSON.stringify([ 167 'EVENT', 168 frame[1], 169 finalizeEvent( 170 { 171 kind: 5, 172 created_at: 1700000090, 173 tags: [['a', '30402:' + peer + ':carrots']], 174 content: '' 175 }, 176 sellerSecret 177 ) 178 ]) 179 ); 180 }); 181 if (filter.kinds?.includes(5) && listingStatus === 'withdrawn') 182 socket.send( 183 JSON.stringify([ 184 'EVENT', 185 frame[1], 186 finalizeEvent( 187 { 188 kind: 5, 189 created_at: 1700000070, 190 tags: [['a', '30402:' + peer + ':carrots']], 191 content: '' 192 }, 193 sellerSecret 194 ) 195 ]) 196 ); 197 if (filter.kinds?.includes(10050)) { 198 if (filter.authors?.includes(peer) && sellerInbox !== 'missing') 199 socket.send( 200 JSON.stringify([ 201 'EVENT', 202 frame[1], 203 sellerInbox === 'normal' || sellerInbox === 'partial' 204 ? preference(sellerSecret, 'wss://peer.example.org') 205 : finalizeEvent( 206 { 207 kind: 10050, 208 created_at: 1700000060, 209 content: '', 210 tags: 211 sellerInbox === 'unapproved' 212 ? [['relay', 'wss://unapproved.example.org']] 213 : sellerInbox === 'unsupported' 214 ? [['relay', 'https://unsupported.example.org']] 215 : [['relay']] 216 }, 217 sellerSecret 218 ) 219 ]) 220 ); 221 if (filter.authors?.includes(owner) && (!missingOwn || ownPreference)) 222 socket.send( 223 JSON.stringify([ 224 'EVENT', 225 frame[1], 226 ownPreference ?? 227 preference(ownerSecret, 'wss://archive.example.org') 228 ]) 229 ); 230 } 231 } 232 if ( 233 (holdListingHead && 234 filters.some((filter) => filter.kinds?.includes(30402))) || 235 (incompleteListing && 236 filters.some((filter) => filter.kinds?.includes(5))) || 237 filters.some( 238 (filter) => 239 filter.kinds?.includes(10050) && 240 ((holdOwnEose && filter.authors?.includes(owner)) || 241 ((holdPeerEose || sellerInbox === 'partial') && 242 filter.authors?.includes(peer))) 243 ) 244 ) 245 waitingEose.push(() => { 246 if (socket.readyState === 1) 247 socket.send(JSON.stringify(['EOSE', frame[1]])); 248 }); 249 else socket.send(JSON.stringify(['EOSE', frame[1]])); 250 }); 251 }); 252 const result = await build({ 253 configFile: false, 254 logLevel: 'silent', 255 plugins: [svelte({ configFile: false })], 256 resolve: { 257 conditions: ['browser'], 258 alias: { 259 '$app/navigation': fileURLToPath( 260 new URL('./harness/product-request.ts', import.meta.url) 261 ) 262 } 263 }, 264 build: { 265 write: false, 266 minify: false, 267 lib: { 268 entry: fileURLToPath( 269 new URL('./harness/product-request.ts', import.meta.url) 270 ), 271 name: 'hcp107', 272 formats: ['iife'] 273 } 274 } 275 }); 276 const output = Array.isArray(result) ? result[0] : result; 277 if (!('output' in output)) throw Error('no bundle'); 278 const chunks = output.output.filter((row) => row.type === 'chunk'); 279 expect(chunks).toHaveLength(1); 280 bundle = chunks[0].code; 281 }); 282 test.afterAll(async () => { 283 for (const socket of sockets.clients) socket.terminate(); 284 await new Promise<void>((resolve) => sockets.close(() => resolve())); 285 await server.close(); 286 }); 287 test.beforeEach(async ({ page }) => { 288 events = []; 289 missingOwn = false; 290 holdPrivateAck = false; 291 listingStatus = 'active'; 292 sellerInbox = 'normal'; 293 incompleteListing = false; 294 holdListingHead = false; 295 headUpdates = []; 296 deletionUpdates = []; 297 ownPreference = undefined; 298 holdOwnEose = false; 299 holdPeerEose = false; 300 waitingEose = []; 301 await page.addInitScript( 302 ({ endpoint }) => { 303 const Native = window.WebSocket; 304 window.WebSocket = class extends Native { 305 constructor(url: string | URL, protocols?: string | string[]) { 306 const origin = new URL(String(url)).origin; 307 if ( 308 ![ 309 'wss://discovery.example.org', 310 'wss://archive.example.org', 311 'wss://peer.example.org' 312 ].includes(origin) 313 ) 314 throw Error('unapproved destination'); 315 super(endpoint + '/?source=' + encodeURIComponent(origin), protocols); 316 this.cr007Private = origin !== 'wss://discovery.example.org'; 317 } 318 readonly cr007Private: boolean; 319 override close(code?: number, reason?: string) { 320 if (this.cr007Private && window.cr007DelayPrivateClose) 321 (window.cr007DelayedCloses ??= []).push(() => 322 super.close(code, reason) 323 ); 324 else super.close(code, reason); 325 } 326 }; 327 }, 328 { endpoint } 329 ); 330 await page.goto(server.url + '/search'); 331 await page.addScriptTag({ content: bundle }); 332 }); 333 test.afterEach(async ({ page }) => { 334 if (!page.isClosed()) 335 await page.evaluate(() => { 336 window.cr007DelayPrivateClose = false; 337 for (const release of window.cr007DelayedCloses ?? []) release(); 338 return window.hcp107Fixture?.close(); 339 }); 340 }); 341 const panel = (page: Page) => page.locator('[data-request-fixture]'); 342 const editor = (page: Page) => 343 panel(page).getByRole('textbox', { name: 'Your message', exact: true }); 344 for (const status of ['sold', 'withdrawn'] as const) 345 test(`HCP108 known ${status} food has no new enquiry and remains readable`, async ({ 346 page 347 }) => { 348 listingStatus = status; 349 await page.evaluate(async () => { 350 window.hcp107Fixture = await window.hcp107.renderFixture(); 351 }); 352 await expect 353 .poll(() => 354 page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) 355 ) 356 .toBe(status); 357 await expect( 358 panel(page).getByRole('button', { name: 'Message seller', exact: true }) 359 ).toHaveCount(0); 360 expect( 361 await page.evaluate( 362 () => window.hcp107Fixture.viewSnapshot().reference.pubkey 363 ) 364 ).toBe(peer); 365 expect( 366 await page.evaluate(() => window.hcp107Fixture.message()) 367 ).toBeUndefined(); 368 await noPrivate(page); 369 }); 370 371 for (const crossSecond of [false, true]) 372 test( 373 crossSecond 374 ? 'CR003 original product request reserves across a real owner second boundary' 375 : 'HCP108 incomplete active terms need explicit original acknowledgement and retain signed citations', 376 async ({ page }) => { 377 incompleteListing = true; 378 await page.evaluate(async () => { 379 window.hcp107Fixture = await window.hcp107.renderFixture(); 380 }); 381 await expect 382 .poll(() => 383 page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) 384 ) 385 .toBe('active'); 386 await expect( 387 panel(page).getByRole('button', { name: 'Message seller', exact: true }) 388 ).toBeDisabled(); 389 expect( 390 await page.evaluate(() => 391 window.hcp107Fixture.captureUncertain(undefined) 392 ) 393 ).toBe(false); 394 await panel(page) 395 .getByRole('button', { 396 name: 'I understand the listing status is uncertain', 397 exact: true 398 }) 399 .click(); 400 await panel(page) 401 .getByRole('button', { name: 'Message seller', exact: true }) 402 .click(); 403 await expect(editor(page)).toBeVisible(); 404 const observed = await page.evaluate(() => ({ 405 product: window.hcp107Fixture.product(), 406 view: window.hcp107Fixture.viewSnapshot(), 407 message: window.hcp107Fixture.message() 408 })); 409 expect(observed.product?.eventId).toBe(observed.view.eventId); 410 expect(observed.message?.tags).toEqual([['p', peer]]); 411 expect(observed.message?.content).toContain( 412 'nostr:' + observed.product?.nevent 413 ); 414 await noPrivate(page); 415 if (crossSecond) 416 await editor(page).fill('HC_TEST_ONLY_unsent_boundary_request'); 417 await unlock(page); 418 const before = await page.evaluate(async () => ({ 419 native: await window.hcp107Fixture.native(), 420 counts: window.hcp107Fixture.counts(), 421 text: window.hcp107Fixture.text() 422 })); 423 await page.evaluate((crossSecond) => { 424 const original = Date.now; 425 let phase = 'send'; 426 let crossed = false; 427 const samples: { 428 milliseconds: number; 429 phase: string; 430 stack?: string; 431 }[] = []; 432 const locks: { 433 captured: number; 434 callback: number; 435 granted: boolean; 436 }[] = []; 437 const transactions: string[] = []; 438 const manager = navigator.locks; 439 const descriptor = Object.getOwnPropertyDescriptor(manager, 'request'); 440 const request = Reflect.get(manager, 'request'); 441 const owner = window.hcp107Fixture.owner; 442 manager.request = (...args: unknown[]) => { 443 const forwarded = args.slice(); 444 const at = args.length - 1; 445 const callback = args[at] as (lock: Lock | null) => unknown; 446 const options = 447 args.length === 3 ? (args[1] as LockOptions) : undefined; 448 forwarded[at] = async (lock: Lock | null) => { 449 if ( 450 lock && 451 options?.ifAvailable && 452 args[0] === 'harvestcircle:owner:' + owner && 453 !crossed 454 ) { 455 crossed = true; 456 const captured = samples.at(-1)!.milliseconds; 457 if (crossSecond) 458 await new Promise<void>((resolve) => { 459 function afterBoundary() { 460 if ( 461 Math.floor(original() / 1000) === 462 Math.floor(captured / 1000) 463 ) { 464 window.setTimeout(afterBoundary, 1); 465 return; 466 } 467 resolve(); 468 } 469 window.setTimeout( 470 afterBoundary, 471 Math.max( 472 1, 473 (Math.floor(captured / 1000) + 1) * 1000 - original() + 1 474 ) 475 ); 476 }); 477 locks.push({ captured, callback: original(), granted: true }); 478 phase = 'owner_reservation'; 479 try { 480 return await callback(lock); 481 } finally { 482 phase = 'send'; 483 } 484 } 485 return callback(lock); 486 }; 487 return Reflect.apply(request, manager, forwarded) as Promise<unknown>; 488 }; 489 const prototype = IDBDatabase.prototype; 490 const transactionDescriptor = Object.getOwnPropertyDescriptor( 491 prototype, 492 'transaction' 493 )!; 494 const transaction = Reflect.get(prototype, 'transaction'); 495 prototype.transaction = function ( 496 this: IDBDatabase, 497 ...args: Parameters<IDBDatabase['transaction']> 498 ) { 499 const tx: IDBTransaction = Reflect.apply(transaction, this, args); 500 if ( 501 tx.mode === 'readwrite' && 502 tx.objectStoreNames.contains('private_sends') 503 ) 504 for (const outcome of ['abort', 'complete']) 505 tx.addEventListener(outcome, () => transactions.push(outcome)); 506 return tx; 507 } as typeof prototype.transaction; 508 Date.now = () => { 509 const milliseconds = original(); 510 if (samples.length < 128) 511 samples.push({ 512 milliseconds, 513 phase, 514 stack: new Error().stack?.split('\n').slice(0, 5).join('\n') 515 }); 516 return milliseconds; 517 }; 518 window.hcp108SendClock = { 519 samples, 520 locks, 521 transactions, 522 restore: () => { 523 Date.now = original; 524 if (descriptor) 525 Object.defineProperty(manager, 'request', descriptor); 526 else Reflect.deleteProperty(manager, 'request'); 527 Object.defineProperty( 528 prototype, 529 'transaction', 530 transactionDescriptor 531 ); 532 } 533 }; 534 }, crossSecond); 535 try { 536 await panel(page) 537 .getByRole('button', { name: 'Send request', exact: true }) 538 .click(); 539 await expect 540 .poll(() => 541 page.evaluate(() => window.hcp107Fixture.snapshot()?.busy) 542 ) 543 .toBe(false); 544 const terminal = await page.evaluate(() => { 545 window.hcp108SendClock.restore(); 546 return { 547 snapshot: window.hcp107Fixture.snapshot(), 548 counts: window.hcp107Fixture.counts(), 549 samples: window.hcp108SendClock.samples, 550 locks: window.hcp108SendClock.locks, 551 transactions: window.hcp108SendClock.transactions 552 }; 553 }); 554 console.log( 555 JSON.stringify({ 556 fixture: 'CR003_REAL_CLOCK_PRODUCT_REQUEST_DIAGNOSTIC', 557 terminal 558 }) 559 ); 560 if (crossSecond) { 561 expect(terminal.locks).toHaveLength(1); 562 expect(Math.floor(terminal.locks[0].callback / 1000)).toBeGreaterThan( 563 Math.floor(terminal.locks[0].captured / 1000) 564 ); 565 expect(terminal.transactions.length).toBeGreaterThan(0); 566 expect( 567 terminal.transactions.every((outcome) => outcome === 'complete') 568 ).toBe(true); 569 } 570 expect(terminal.snapshot?.state).toBe('completed'); 571 expect(terminal.counts).toMatchObject({ 572 signs: before.counts.signs + 2, 573 encrypts: before.counts.encrypts + 2 574 }); 575 await expect 576 .poll(() => events.filter((row) => row.event.kind === 1059).length) 577 .toBe(2); 578 expect( 579 events 580 .filter((row) => row.event.kind === 1059) 581 .map((row) => row.origin) 582 .sort() 583 ).toEqual(['wss://archive.example.org', 'wss://peer.example.org']); 584 await expect 585 .poll(() => 586 page.evaluate(() => window.hcp107Fixture.snapshot()?.state) 587 ) 588 .toBe('completed'); 589 } finally { 590 await page.evaluate(() => window.hcp108SendClock.restore()); 591 } 592 } 593 ); 594 595 test('HCP108 connecting as the verified publisher shows Manage and keeps unsent memory without self enquiry', async ({ 596 page 597 }) => { 598 await ready(page); 599 await editor(page).fill( 600 'Keep this guest text after discovering my own listing' 601 ); 602 await page.evaluate(() => window.hcp107Fixture.mode('changed_key')); 603 await panel(page) 604 .getByRole('button', { name: 'Connect extension', exact: true }) 605 .click(); 606 await expect( 607 panel(page).getByRole('link', { name: 'Manage listing', exact: true }) 608 ).toBeVisible(); 609 await expect( 610 panel(page).getByRole('button', { name: 'Send request', exact: true }) 611 ).toBeDisabled(); 612 await expect(editor(page)).toHaveValue( 613 'Keep this guest text after discovering my own listing' 614 ); 615 await noPrivate(page); 616 }); 617 618 for (const status of [ 619 'missing', 620 'unsupported', 621 'malformed', 622 'partial' 623 ] as const) 624 test(`HCP108 ${status} seller inbox cannot guess a send destination`, async ({ 625 page 626 }) => { 627 sellerInbox = status; 628 await ready(page); 629 await unlock(page); 630 await panel(page) 631 .getByRole('button', { name: 'Send request', exact: true }) 632 .click(); 633 if (status === 'partial') { 634 await expect 635 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) 636 .toBe('checking'); 637 await page.evaluate(() => window.hcp107Fixture.advance()); 638 } 639 await expect(panel(page)).toContainText( 640 status === 'missing' 641 ? 'In-app messaging is not available for this seller in this prototype.' 642 : status === 'unsupported' || status === 'malformed' 643 ? 'The seller inbox configuration is unsupported in this prototype.' 644 : 'The seller inbox could not be confirmed from the sources checked.' 645 ); 646 await expect( 647 panel(page).getByRole('button', { name: 'Send request', exact: true }) 648 ).toBeDisabled(); 649 await expect(editor(page)).toBeVisible(); 650 expect( 651 await page.evaluate(() => window.hcp107Fixture.viewSnapshot().food?.title) 652 ).toBe('Verified carrots'); 653 await noPrivate(page); 654 }); 655 async function ready(page: Page, qualified = true) { 656 await page.evaluate(async (qualified) => { 657 window.hcp107Fixture = await window.hcp107.renderFixture(qualified); 658 }, qualified); 659 await expect 660 .poll(() => 661 page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) 662 ) 663 .toBe('active'); 664 await panel(page) 665 .getByRole('button', { name: 'Message seller', exact: true }) 666 .click(); 667 await expect(editor(page)).toBeVisible(); 668 } 669 test('HCP108 a signed but unapproved seller inbox is unavailable without guessed routing', async ({ 670 page 671 }) => { 672 sellerInbox = 'unapproved'; 673 await ready(page); 674 await unlock(page); 675 await panel(page) 676 .getByRole('button', { name: 'Send request', exact: true }) 677 .click(); 678 await expect 679 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) 680 .toBe('needs_action'); 681 expect( 682 await page.evaluate(() => window.hcp107Fixture.snapshot()?.copy) 683 ).toContain( 684 'The seller inbox configuration is unsupported in this prototype.' 685 ); 686 await noPrivate(page); 687 }); 688 async function uncertain(page: Page) { 689 incompleteListing = true; 690 holdListingHead = true; 691 await page.evaluate(async () => { 692 window.hcp107Fixture = await window.hcp107.renderFixture(); 693 }); 694 await expect 695 .poll(() => 696 page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) 697 ) 698 .toBe('active'); 699 await panel(page) 700 .getByRole('button', { 701 name: 'I understand the listing status is uncertain', 702 exact: true 703 }) 704 .click(); 705 await panel(page) 706 .getByRole('button', { name: 'Message seller', exact: true }) 707 .click(); 708 await expect(editor(page)).toBeVisible(); 709 } 710 test('HCP108 copied consent and genuine consent from another original view cannot acknowledge uncertain terms', async ({ 711 page 712 }) => { 713 await uncertain(page); 714 await page.evaluate(() => window.hcp107Fixture.createOtherView()); 715 await expect 716 .poll(() => 717 page.evaluate(() => window.hcp107Fixture.otherViewSnapshot()?.outcome) 718 ) 719 .toBe('active'); 720 expect( 721 await page.evaluate(() => window.hcp107Fixture.consentCases()) 722 ).toEqual({ 723 genuine: true, 724 current: true, 725 copied: false, 726 other: false, 727 otherControl: true, 728 unreviewed: false 729 }); 730 await noPrivate(page); 731 }); 732 for (const change of ['coverage', 'close'] as const) 733 test(`HCP108 original ${change} transition revokes genuine uncertainty consent`, async ({ 734 page 735 }) => { 736 await uncertain(page); 737 expect( 738 (await page.evaluate(() => window.hcp107Fixture.consentCases())).current 739 ).toBe(true); 740 await editor(page).fill('uncertainty-memory-marker'); 741 if (change === 'coverage') 742 await page.evaluate(() => window.hcp107Fixture.advance()); 743 else await page.evaluate(() => window.hcp107Fixture.closeView()); 744 expect( 745 await page.evaluate(() => window.hcp107Fixture.consentCurrent()) 746 ).toBe(false); 747 expect( 748 await page.evaluate(() => window.hcp107Fixture.message()) 749 ).toBeUndefined(); 750 if (change === 'coverage') 751 expect( 752 await page.evaluate(() => window.hcp107Fixture.product()?.text) 753 ).toBe('uncertainty-memory-marker'); 754 else 755 expect( 756 await page.evaluate(() => window.hcp107Fixture.product()) 757 ).toBeUndefined(); 758 await noPrivate(page); 759 }); 760 for (const change of ['sold', 'withdrawn', 'version'] as const) 761 test(`HCP108 a real newer ${change} observation revokes request consent while preserving unsent text`, async ({ 762 page 763 }) => { 764 await uncertain(page); 765 expect( 766 (await page.evaluate(() => window.hcp107Fixture.consentCases())).current 767 ).toBe(true); 768 await editor(page).fill('changed-listing-memory-marker'); 769 const before = await page.evaluate( 770 () => window.hcp107Fixture.product()?.eventId 771 ); 772 if (change === 'withdrawn') { 773 listingStatus = 'withdrawn'; 774 for (const update of deletionUpdates) update(); 775 } else { 776 listingStatus = change === 'sold' ? 'sold' : 'active'; 777 for (const update of headUpdates) update(); 778 } 779 if (change === 'version') 780 await expect 781 .poll(() => 782 page.evaluate(() => window.hcp107Fixture.viewSnapshot().eventId) 783 ) 784 .not.toBe(before); 785 else 786 await expect 787 .poll(() => 788 page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) 789 ) 790 .toBe(change); 791 expect( 792 await page.evaluate(() => window.hcp107Fixture.consentCurrent()) 793 ).toBe(false); 794 expect( 795 await page.evaluate(() => window.hcp107Fixture.product()?.text) 796 ).toBe('changed-listing-memory-marker'); 797 expect( 798 await page.evaluate(() => window.hcp107Fixture.message()) 799 ).toBeUndefined(); 800 await expect( 801 panel(page).getByRole('button', { name: 'Send request', exact: true }) 802 ).toBeDisabled(); 803 await noPrivate(page); 804 }); 805 for (const change of ['cancel', 'account'] as const) 806 test(`HCP108 retired peer lookup cannot replace newer ${change} state`, async ({ 807 page 808 }) => { 809 await ready(page); 810 await unlock(page); 811 holdPeerEose = true; 812 await panel(page) 813 .getByRole('button', { name: 'Send request', exact: true }) 814 .click(); 815 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 816 if (change === 'cancel') { 817 await panel(page) 818 .getByRole('button', { name: 'Cancel', exact: true }) 819 .click(); 820 await panel(page) 821 .getByRole('button', { name: 'Keep editing', exact: true }) 822 .click(); 823 } else await page.evaluate(() => window.hcp107Fixture.logout()); 824 holdPeerEose = false; 825 for (const release of waitingEose) release(); 826 await expect 827 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.busy)) 828 .toBe(false); 829 expect( 830 await page.evaluate(() => window.hcp107Fixture.snapshot()?.copy) 831 ).toContain( 832 change === 'cancel' ? 'Sending is paused.' : 'Connection changed.' 833 ); 834 await noPrivate(page); 835 }); 836 for (const change of ['sold', 'withdrawn', 'version'] as const) 837 test(`HCP108 ${change} during peer lookup reports listing review without relabelling a seller inbox failure`, async ({ 838 page 839 }) => { 840 await uncertain(page); 841 await unlock(page); 842 holdPeerEose = true; 843 await panel(page) 844 .getByRole('button', { name: 'Send request', exact: true }) 845 .click(); 846 await expect 847 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) 848 .toBe('checking'); 849 if (change === 'withdrawn') { 850 listingStatus = 'withdrawn'; 851 for (const update of deletionUpdates) update(); 852 } else { 853 listingStatus = change === 'sold' ? 'sold' : 'active'; 854 for (const update of headUpdates) update(); 855 } 856 await expect 857 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.busy)) 858 .toBe(false); 859 expect( 860 await page.evaluate(() => window.hcp107Fixture.snapshot()?.copy) 861 ).toContain('Review the current listing before sending.'); 862 await noPrivate(page); 863 }); 864 async function connect(page: Page) { 865 await panel(page) 866 .getByRole('button', { name: 'Connect extension', exact: true }) 867 .click(); 868 await expect( 869 panel(page).getByRole('button', { 870 name: 'Check messaging support', 871 exact: true 872 }) 873 ).toBeVisible(); 874 await panel(page) 875 .getByRole('button', { name: 'Check messaging support', exact: true }) 876 .click(); 877 await expect(panel(page)).toContainText('Messaging support checked.'); 878 } 879 async function unlock(page: Page) { 880 await connect(page); 881 await panel(page) 882 .getByRole('button', { name: 'Check current preference', exact: true }) 883 .click(); 884 await panel(page) 885 .getByRole('button', { name: 'Unlock inbox', exact: true }) 886 .click(); 887 await expect( 888 panel(page).getByRole('button', { name: 'Send request', exact: true }) 889 ).toBeEnabled(); 890 } 891 async function noPrivate(page: Page, marker?: string) { 892 expect(events.filter((row) => row.event.kind === 1059)).toEqual([]); 893 expect( 894 await page.evaluate(async () => (await window.hcp107Fixture.native()).sends) 895 ).toEqual([]); 896 if (marker) 897 expect( 898 await page.evaluate(() => window.hcp107Fixture.persistentText()) 899 ).not.toContain(marker); 900 } 901 test('guest text is memory only, with no automatic identity or private intent', async ({ 902 page 903 }) => { 904 await ready(page); 905 await editor(page).fill('guest-private-marker'); 906 expect(await page.evaluate(() => window.hcp107Fixture.counts())).toEqual({ 907 keys: 0, 908 encrypts: 0, 909 decrypts: 0, 910 signs: 0 911 }); 912 await noPrivate(page, 'guest-private-marker'); 913 }); 914 test('same-page Connect preserves edited text and never sends', async ({ 915 page 916 }) => { 917 await ready(page); 918 await editor(page).fill('connect-private-marker'); 919 await panel(page) 920 .getByRole('button', { name: 'Connect extension', exact: true }) 921 .click(); 922 await expect(editor(page)).toHaveValue('connect-private-marker'); 923 await noPrivate(page, 'connect-private-marker'); 924 }); 925 test('explicit support probe preserves text and creates no private send', async ({ 926 page 927 }) => { 928 await ready(page); 929 await editor(page).fill('probe-private-marker'); 930 await connect(page); 931 await expect(editor(page)).toHaveValue('probe-private-marker'); 932 await noPrivate(page, 'probe-private-marker'); 933 }); 934 test('existing preference and unlock are separate from final Send', async ({ 935 page 936 }) => { 937 await ready(page); 938 await unlock(page); 939 expect(events).toEqual([]); 940 await noPrivate(page); 941 }); 942 test('public preference enablement is explicit and never autosends the request', async ({ 943 page 944 }) => { 945 missingOwn = true; 946 await ready(page); 947 await editor(page).fill('setup-private-marker'); 948 await connect(page); 949 await panel(page) 950 .getByRole('button', { name: 'Check current preference', exact: true }) 951 .click(); 952 await panel(page) 953 .getByRole('checkbox', { name: 'wss://archive.example.org', exact: true }) 954 .check(); 955 await panel(page) 956 .getByRole('button', { name: 'Review inbox change', exact: true }) 957 .click(); 958 expect(events).toEqual([]); 959 await panel(page) 960 .getByRole('button', { name: 'Enable inbox', exact: true }) 961 .click(); 962 await expect 963 .poll(() => events.filter((row) => row.event.kind === 10050).length) 964 .toBeGreaterThan(0); 965 await expect(editor(page)).toHaveValue('setup-private-marker'); 966 await noPrivate(page, 'setup-private-marker'); 967 }); 968 test('unqualified access cannot enable final Send', async ({ page }) => { 969 await ready(page, false); 970 await connect(page); 971 await panel(page) 972 .getByRole('button', { name: 'Check current preference', exact: true }) 973 .click(); 974 await panel(page) 975 .getByRole('button', { name: 'Unlock inbox', exact: true }) 976 .click(); 977 await expect(panel(page)).toContainText( 978 'Inbox access has not been qualified' 979 ); 980 await expect( 981 panel(page).getByRole('button', { name: 'Send request', exact: true }) 982 ).toBeDisabled(); 983 await noPrivate(page); 984 }); 985 test('only the current task has one enabled primary action', async ({ 986 page 987 }) => { 988 await ready(page); 989 await expect( 990 panel(page).locator('button.button--primary:enabled') 991 ).toHaveCount(1); 992 await connect(page); 993 await expect( 994 panel(page).locator('button.button--primary:enabled') 995 ).toHaveCount(1); 996 await panel(page) 997 .getByRole('button', { name: 'Check current preference', exact: true }) 998 .click(); 999 await expect( 1000 panel(page).locator('button.button--primary:enabled') 1001 ).toHaveCount(1); 1002 }); 1003 test('refused Connect keeps unsaved text and performs no send', async ({ 1004 page 1005 }) => { 1006 await ready(page); 1007 await editor(page).fill('refused-private-marker'); 1008 await page.evaluate(() => window.hcp107Fixture.mode('refused_key')); 1009 await panel(page) 1010 .getByRole('button', { name: 'Connect extension', exact: true }) 1011 .click(); 1012 await expect(panel(page)).toContainText('Connection was not approved'); 1013 await expect(editor(page)).toHaveValue('refused-private-marker'); 1014 await noPrivate(page); 1015 }); 1016 test('held Connect can be cancelled without losing text or autosending later', async ({ 1017 page 1018 }) => { 1019 await ready(page); 1020 await editor(page).fill('held-connect-marker'); 1021 await page.evaluate(() => window.hcp107Fixture.mode('hold_key')); 1022 await panel(page) 1023 .getByRole('button', { name: 'Connect extension', exact: true }) 1024 .click(); 1025 await expect 1026 .poll(() => page.evaluate(() => window.hcp107Fixture.pending())) 1027 .toBe(true); 1028 await panel(page) 1029 .getByRole('button', { name: 'Cancel', exact: true }) 1030 .click(); 1031 await panel(page) 1032 .getByRole('button', { name: 'Keep editing', exact: true }) 1033 .click(); 1034 await page.evaluate(() => window.hcp107Fixture.settle()); 1035 await expect(editor(page)).toHaveValue('held-connect-marker'); 1036 await noPrivate(page); 1037 }); 1038 test('copied owners and unreviewed Send are rejected', async ({ page }) => { 1039 await ready(page); 1040 expect(await page.evaluate(() => window.hcp107Fixture.copied())).toEqual({ 1041 create: false, 1042 snapshot: undefined, 1043 configure: false, 1044 send: { status: 'invalid' } 1045 }); 1046 expect(await page.evaluate(() => window.hcp107Fixture.unreviewed())).toEqual({ 1047 status: 'invalid' 1048 }); 1049 await noPrivate(page); 1050 }); 1051 test('final explicit Send publishes only ciphertext to the intended named destinations', async ({ 1052 page 1053 }) => { 1054 await ready(page); 1055 await unlock(page); 1056 const expected = await page.evaluate(() => window.hcp107Fixture.message()); 1057 expect(expected).toBeDefined(); 1058 await panel(page) 1059 .getByRole('button', { name: 'Send request', exact: true }) 1060 .click(); 1061 await expect 1062 .poll(() => events.filter((row) => row.event.kind === 1059).length) 1063 .toBeGreaterThanOrEqual(2); 1064 expect(events.every((row) => row.event.kind === 1059)).toBe(true); 1065 expect(new Set(events.map((row) => row.origin))).toEqual( 1066 new Set(['wss://archive.example.org', 'wss://peer.example.org']) 1067 ); 1068 expect( 1069 events.every((row) => !row.event.content.includes('Verified carrots')) 1070 ).toBe(true); 1071 await expect(panel(page)).not.toContainText('Delivered'); 1072 await expect 1073 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) 1074 .toBe('completed'); 1075 await expect(panel(page)).not.toContainText('No message has been sent.'); 1076 expect(events).toHaveLength(2); 1077 const { nip44 } = await import('applesauce-core/helpers/encryption'); 1078 const { getEventHash } = await import('applesauce-core/helpers'); 1079 const rumors = events.map(({ event: outer }) => { 1080 const recipient = outer.tags.find((tag) => tag[0] === 'p')?.[1]; 1081 expect([owner, peer]).toContain(recipient); 1082 const key = new Uint8Array(32).fill(recipient === owner ? 83 : 84); 1083 try { 1084 const seal = JSON.parse( 1085 nip44.v2.decrypt( 1086 outer.content, 1087 nip44.v2.utils.getConversationKey(key, outer.pubkey) 1088 ) 1089 ) as { pubkey: string; content: string; kind: number; tags: string[][] }; 1090 expect(seal.kind).toBe(13); 1091 expect(seal.pubkey).toBe(owner); 1092 expect(seal.tags).toEqual([]); 1093 const rumor = JSON.parse( 1094 nip44.v2.decrypt( 1095 seal.content, 1096 nip44.v2.utils.getConversationKey(key, seal.pubkey) 1097 ) 1098 ) as { 1099 id: string; 1100 kind: number; 1101 pubkey: string; 1102 content: string; 1103 tags: string[][]; 1104 created_at: number; 1105 }; 1106 expect(rumor.kind).toBe(14); 1107 expect(rumor.pubkey).toBe(owner); 1108 expect(rumor.tags).toEqual([['p', peer]]); 1109 expect(rumor.content).toBe(expected?.content); 1110 expect(rumor.content).toContain('Viewed listing: nostr:nevent1'); 1111 expect(rumor.content).toContain('Product: nostr:naddr1'); 1112 expect(getEventHash(rumor)).toBe(rumor.id); 1113 return rumor; 1114 } finally { 1115 key.fill(0); 1116 } 1117 }); 1118 expect(rumors[0]).toEqual(rumors[1]); 1119 }); 1120 test('held self seal reports multiple approvals and does not publish ahead of persistence', async ({ 1121 page 1122 }) => { 1123 await ready(page); 1124 await unlock(page); 1125 await page.evaluate(() => window.hcp107Fixture.mode('hold_seal')); 1126 await panel(page) 1127 .getByRole('button', { name: 'Send request', exact: true }) 1128 .click(); 1129 await expect 1130 .poll(() => page.evaluate(() => window.hcp107Fixture.pending())) 1131 .toBe(true); 1132 await expect(panel(page)).toContainText('approval'); 1133 expect(events).toEqual([]); 1134 await page.evaluate(() => window.hcp107Fixture.settle()); 1135 }); 1136 test('Cancel retires a held private Send while Keep preserves unsaved text', async ({ 1137 page 1138 }) => { 1139 await ready(page); 1140 await unlock(page); 1141 await editor(page).fill('cancel-held-seal-marker'); 1142 await page.evaluate(() => window.hcp107Fixture.mode('hold_seal')); 1143 await panel(page) 1144 .getByRole('button', { name: 'Send request', exact: true }) 1145 .click(); 1146 await expect 1147 .poll(() => page.evaluate(() => window.hcp107Fixture.pending())) 1148 .toBe(true); 1149 const before = await page.evaluate(() => window.hcp107Fixture.native()); 1150 const calls = await page.evaluate(() => window.hcp107Fixture.counts()); 1151 await panel(page) 1152 .getByRole('button', { name: 'Cancel', exact: true }) 1153 .click(); 1154 await panel(page) 1155 .getByRole('button', { name: 'Keep editing', exact: true }) 1156 .click(); 1157 await expect(editor(page)).toHaveValue('cancel-held-seal-marker'); 1158 expect(await page.evaluate(() => window.hcp107Fixture.pending())).toBe(true); 1159 await page.evaluate(() => window.hcp107Fixture.settle()); 1160 await expect 1161 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.busy)) 1162 .toBe(false); 1163 expect(await page.evaluate(() => window.hcp107Fixture.native())).toEqual( 1164 before 1165 ); 1166 expect(await page.evaluate(() => window.hcp107Fixture.counts())).toEqual( 1167 calls 1168 ); 1169 expect(events).toEqual([]); 1170 }); 1171 test('declined encryption retains unsaved text without publication', async ({ 1172 page 1173 }) => { 1174 await ready(page); 1175 await unlock(page); 1176 await editor(page).fill('declined-encryption-marker'); 1177 await page.evaluate(() => window.hcp107Fixture.mode('declined_encrypt')); 1178 await panel(page) 1179 .getByRole('button', { name: 'Send request', exact: true }) 1180 .click(); 1181 await expect(editor(page)).toHaveValue('declined-encryption-marker'); 1182 expect(events).toEqual([]); 1183 }); 1184 test('disconnect during held crypto prevents late publication', async ({ 1185 page 1186 }) => { 1187 await ready(page); 1188 await unlock(page); 1189 await page.evaluate(() => window.hcp107Fixture.mode('hold_encrypt')); 1190 const before = await page.evaluate(async () => ({ 1191 native: await window.hcp107Fixture.native(), 1192 counts: window.hcp107Fixture.counts() 1193 })); 1194 await page.evaluate(() => { 1195 const original = Date.now; 1196 const fixed = original(); 1197 const samples: { 1198 milliseconds: number; 1199 actualMilliseconds: number; 1200 stack?: string; 1201 }[] = []; 1202 Date.now = () => { 1203 const milliseconds = fixed; 1204 if (samples.length < 128) 1205 samples.push({ 1206 milliseconds, 1207 actualMilliseconds: original(), 1208 stack: new Error().stack?.split('\n').slice(0, 5).join('\n') 1209 }); 1210 return milliseconds; 1211 }; 1212 window.hcp126HeldClock = { 1213 samples, 1214 restore: () => { 1215 Date.now = original; 1216 } 1217 }; 1218 }); 1219 try { 1220 await panel(page) 1221 .getByRole('button', { name: 'Send request', exact: true }) 1222 .click(); 1223 await expect 1224 .poll(() => 1225 page.evaluate(() => { 1226 const snapshot = window.hcp107Fixture.snapshot(); 1227 return ( 1228 window.hcp107Fixture.pending() || 1229 (snapshot?.state === 'needs_action' && !snapshot.busy) 1230 ); 1231 }) 1232 ) 1233 .toBe(true); 1234 expect(await page.evaluate(() => window.hcp107Fixture.pending())).toBe( 1235 true 1236 ); 1237 await page.evaluate(() => { 1238 window.hcp126HeldClock.restore(); 1239 window.hcp107Fixture.logout(); 1240 window.hcp107Fixture.settle(); 1241 }); 1242 await expect 1243 .poll(() => page.evaluate(() => window.hcp107Fixture.pending())) 1244 .toBe(false); 1245 expect(events).toEqual([]); 1246 } finally { 1247 const terminal = await page.evaluate(async () => { 1248 window.hcp126HeldClock.restore(); 1249 return { 1250 snapshot: window.hcp107Fixture.snapshot(), 1251 pending: window.hcp107Fixture.pending(), 1252 native: await window.hcp107Fixture.native(), 1253 counts: window.hcp107Fixture.counts(), 1254 text: window.hcp107Fixture.text(), 1255 samples: window.hcp126HeldClock.samples 1256 }; 1257 }); 1258 console.log( 1259 JSON.stringify({ 1260 fixture: 'HCP126_ORIGINAL_HELD_SEND_DIAGNOSTIC', 1261 before, 1262 terminal, 1263 events 1264 }) 1265 ); 1266 } 1267 }); 1268 test('dirty Cancel defaults to Keep editing with focus restored', async ({ 1269 page 1270 }) => { 1271 await ready(page); 1272 await editor(page).fill('dirty-cancel-marker'); 1273 await panel(page) 1274 .getByRole('button', { name: 'Cancel', exact: true }) 1275 .click(); 1276 await expect( 1277 panel(page).getByRole('button', { name: 'Keep editing', exact: true }) 1278 ).toBeFocused(); 1279 await panel(page) 1280 .getByRole('button', { name: 'Keep editing', exact: true }) 1281 .click(); 1282 await expect(editor(page)).toHaveValue('dirty-cancel-marker'); 1283 await expect(editor(page)).toBeFocused(); 1284 await noPrivate(page); 1285 }); 1286 test('dirty navigation is cancelled and Keep leaves the URL unchanged', async ({ 1287 page 1288 }) => { 1289 await ready(page); 1290 await editor(page).fill('navigation-private-marker'); 1291 const url = page.url(); 1292 expect( 1293 (await page.evaluate(() => window.hcp107Fixture.navigate())).cancelled 1294 ).toBe(true); 1295 await panel(page) 1296 .getByRole('button', { name: 'Keep editing', exact: true }) 1297 .click(); 1298 expect(page.url()).toBe(url); 1299 await expect(editor(page)).toHaveValue('navigation-private-marker'); 1300 await noPrivate(page, 'navigation-private-marker'); 1301 }); 1302 test('editing after confirmation invalidates stale discard permission', async ({ 1303 page 1304 }) => { 1305 await ready(page); 1306 await editor(page).fill('revision-one'); 1307 await page.evaluate(() => window.hcp107Fixture.request()); 1308 await page.evaluate(() => window.hcp107Fixture.update('revision-two')); 1309 expect(await page.evaluate(() => window.hcp107Fixture.discard())).not.toBe( 1310 'allowed' 1311 ); 1312 await expect(editor(page)).toHaveValue('revision-two'); 1313 await noPrivate(page); 1314 }); 1315 test('explicit discard clears unsaved text without saving or sending it', async ({ 1316 page 1317 }) => { 1318 await ready(page); 1319 await editor(page).fill('discard-private-marker'); 1320 await panel(page) 1321 .getByRole('button', { name: 'Cancel', exact: true }) 1322 .click(); 1323 await panel(page) 1324 .getByRole('button', { name: 'Discard draft', exact: true }) 1325 .click(); 1326 await expect(editor(page)).toHaveCount(0); 1327 await noPrivate(page, 'discard-private-marker'); 1328 }); 1329 test('a genuine second draft writer invalidates stale discard permission', async ({ 1330 page 1331 }) => { 1332 await ready(page); 1333 await editor(page).fill('original-writer-one'); 1334 await page.evaluate(() => window.hcp107Fixture.request()); 1335 expect( 1336 await page.evaluate(() => 1337 window.hcp107Fixture.directUpdate('original-writer-two') 1338 ) 1339 ).toBe(true); 1340 expect(await page.evaluate(() => window.hcp107Fixture.discard())).not.toBe( 1341 'allowed' 1342 ); 1343 await expect(editor(page)).toHaveValue('original-writer-two'); 1344 await noPrivate(page); 1345 }); 1346 for (const revoke of ['close', 'expiry'] as const) { 1347 test( 1348 'headless original ' + 1349 revoke + 1350 ' prevents later internal crypto and native self commit', 1351 async ({ page }) => { 1352 await ready(page); 1353 await unlock(page); 1354 await page.evaluate(() => window.hcp107Fixture.mode('hold_seal')); 1355 await page.evaluate(() => { 1356 void window.hcp107Fixture.beginHeadless(); 1357 }); 1358 await expect 1359 .poll(() => page.evaluate(() => window.hcp107Fixture.pending())) 1360 .toBe(true); 1361 const before = await page.evaluate(() => window.hcp107Fixture.native()); 1362 const calls = await page.evaluate(() => window.hcp107Fixture.counts()); 1363 await page.evaluate((revoke) => { 1364 if (revoke === 'close') window.hcp107Fixture.revokeView(); 1365 else window.hcp107Fixture.advance(); 1366 window.hcp107Fixture.settle(); 1367 }, revoke); 1368 await expect 1369 .poll(() => 1370 page.evaluate( 1371 () => window.hcp107Fixture.headlessSnapshot()?.busy ?? false 1372 ) 1373 ) 1374 .toBe(false); 1375 expect(await page.evaluate(() => window.hcp107Fixture.native())).toEqual( 1376 before 1377 ); 1378 expect(await page.evaluate(() => window.hcp107Fixture.counts())).toEqual( 1379 calls 1380 ); 1381 expect(events).toEqual([]); 1382 if (revoke === 'expiry') 1383 expect( 1384 await page.evaluate(() => window.hcp107Fixture.headlessText()) 1385 ).toContain('Verified carrots'); 1386 } 1387 ); 1388 } 1389 test('original view closure revokes the mounted draft and later Send', async ({ 1390 page 1391 }) => { 1392 await ready(page); 1393 await editor(page).fill('close-private-marker'); 1394 await page.evaluate(() => window.hcp107Fixture.closeView()); 1395 await expect(editor(page)).toHaveCount(0); 1396 await noPrivate(page, 'close-private-marker'); 1397 }); 1398 test('protocol freshness expiry preserves text but blocks final Send', async ({ 1399 page 1400 }) => { 1401 await ready(page); 1402 await unlock(page); 1403 await editor(page).fill('stale-private-marker'); 1404 await page.evaluate(() => window.hcp107Fixture.advance()); 1405 await expect(editor(page)).toHaveValue('stale-private-marker'); 1406 await expect( 1407 panel(page).getByRole('button', { name: 'Send request', exact: true }) 1408 ).toBeDisabled(); 1409 await noPrivate(page); 1410 }); 1411 test('inbox Check waits for actual bounded EOSE without sending', async ({ 1412 page 1413 }) => { 1414 await ready(page); 1415 await connect(page); 1416 holdOwnEose = true; 1417 await panel(page) 1418 .getByRole('button', { name: 'Check current preference', exact: true }) 1419 .click(); 1420 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 1421 expect(await page.evaluate(() => window.hcp107Fixture.setup().status)).toBe( 1422 'checking' 1423 ); 1424 await noPrivate(page); 1425 holdOwnEose = false; 1426 for (const release of waitingEose) release(); 1427 waitingEose = []; 1428 await expect( 1429 panel(page).getByRole('button', { name: 'Unlock inbox', exact: true }) 1430 ).toBeVisible(); 1431 await noPrivate(page); 1432 }); 1433 test('Cancel during actual inbox lookup preserves text and rejects late EOSE', async ({ 1434 page 1435 }) => { 1436 await ready(page); 1437 await editor(page).fill('cancel-inbox-lookup-marker'); 1438 await connect(page); 1439 holdOwnEose = true; 1440 const calls = await page.evaluate(() => window.hcp107Fixture.counts()); 1441 await panel(page) 1442 .getByRole('button', { name: 'Check current preference', exact: true }) 1443 .click(); 1444 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 1445 await panel(page) 1446 .getByRole('button', { name: 'Cancel', exact: true }) 1447 .click(); 1448 await panel(page) 1449 .getByRole('button', { name: 'Keep editing', exact: true }) 1450 .click(); 1451 holdOwnEose = false; 1452 for (const release of waitingEose) release(); 1453 waitingEose = []; 1454 await expect(editor(page)).toHaveValue('cancel-inbox-lookup-marker'); 1455 await expect 1456 .poll(() => page.evaluate(() => window.hcp107Fixture.setup().busy)) 1457 .toBe(false); 1458 expect(await page.evaluate(() => window.hcp107Fixture.counts())).toEqual( 1459 calls 1460 ); 1461 await noPrivate(page, 'cancel-inbox-lookup-marker'); 1462 }); 1463 test('original deadline ends a held incomplete inbox lookup without inventing readiness', async ({ 1464 page 1465 }) => { 1466 await ready(page); 1467 await editor(page).fill('expired-inbox-lookup-marker'); 1468 await connect(page); 1469 holdOwnEose = true; 1470 await panel(page) 1471 .getByRole('button', { name: 'Check current preference', exact: true }) 1472 .click(); 1473 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 1474 await page.evaluate(() => window.hcp107Fixture.advance()); 1475 await expect 1476 .poll(() => page.evaluate(() => window.hcp107Fixture.setup().busy)) 1477 .toBe(false); 1478 await expect(panel(page)).toContainText('lookup is incomplete'); 1479 await expect(editor(page)).toHaveValue('expired-inbox-lookup-marker'); 1480 await expect( 1481 panel(page).getByRole('button', { name: 'Send request', exact: true }) 1482 ).toBeDisabled(); 1483 await noPrivate(page); 1484 }); 1485 test('new genuine text during held peer lookup stops the original frozen Send', async ({ 1486 page 1487 }) => { 1488 await ready(page); 1489 await unlock(page); 1490 await editor(page).fill('peer-lookup-original'); 1491 holdPeerEose = true; 1492 const calls = await page.evaluate(() => window.hcp107Fixture.counts()); 1493 await panel(page) 1494 .getByRole('button', { name: 'Send request', exact: true }) 1495 .click(); 1496 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 1497 expect( 1498 await page.evaluate(() => 1499 window.hcp107Fixture.directUpdate('peer-lookup-newer') 1500 ) 1501 ).toBe(true); 1502 holdPeerEose = false; 1503 for (const release of waitingEose) release(); 1504 waitingEose = []; 1505 await expect 1506 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.busy)) 1507 .toBe(false); 1508 await expect(editor(page)).toHaveValue('peer-lookup-newer'); 1509 expect(await page.evaluate(() => window.hcp107Fixture.counts())).toEqual( 1510 calls 1511 ); 1512 await noPrivate(page); 1513 }); 1514 test('closing the original view during held peer lookup refuses late Send', async ({ 1515 page 1516 }) => { 1517 await ready(page); 1518 await unlock(page); 1519 holdPeerEose = true; 1520 await panel(page) 1521 .getByRole('button', { name: 'Send request', exact: true }) 1522 .click(); 1523 await expect.poll(() => waitingEose.length).toBeGreaterThan(0); 1524 await page.evaluate(() => window.hcp107Fixture.closeView()); 1525 holdPeerEose = false; 1526 for (const release of waitingEose) release(); 1527 waitingEose = []; 1528 await expect(editor(page)).toHaveCount(0); 1529 await noPrivate(page); 1530 }); 1531 test('native unload warns for unsaved private text without saving', async ({ 1532 page 1533 }) => { 1534 await ready(page); 1535 await editor(page).fill('unload-private-marker'); 1536 expect( 1537 await page.evaluate(() => { 1538 const event = new Event('beforeunload', { cancelable: true }); 1539 window.dispatchEvent(event); 1540 return event.defaultPrevented; 1541 }) 1542 ).toBe(true); 1543 await noPrivate(page, 'unload-private-marker'); 1544 }); 1545 1546 for (const outcome of [ 1547 'storage_denied', 1548 'busy', 1549 'confirmed_abort', 1550 'unknown_after_commit' 1551 ] as const) 1552 test(`CR003 actual ${outcome} keeps draft and permits only truthful explicit retry`, async ({ 1553 page 1554 }) => { 1555 await ready(page); 1556 await unlock(page); 1557 await editor(page).fill('CR003_TEST_ONLY_original_unsent_question'); 1558 const before = await page.evaluate(async () => ({ 1559 counts: window.hcp107Fixture.counts(), 1560 native: await window.hcp107Fixture.native() 1561 })); 1562 await page.evaluate(async (outcome) => { 1563 if (outcome === 'storage_denied') { 1564 const descriptor = Object.getOwnPropertyDescriptor(indexedDB, 'open'); 1565 indexedDB.open = () => { 1566 throw new DOMException('Controlled denied storage', 'SecurityError'); 1567 }; 1568 Reflect.set(window, 'cr003RestorePut', () => { 1569 if (descriptor) Object.defineProperty(indexedDB, 'open', descriptor); 1570 else Reflect.deleteProperty(indexedDB, 'open'); 1571 }); 1572 return; 1573 } 1574 if (outcome === 'busy') { 1575 let entered = () => {}, 1576 release = () => {}; 1577 const ready = new Promise<void>((resolve) => { 1578 entered = resolve; 1579 }); 1580 const held = navigator.locks.request( 1581 'harvestcircle:owner:' + window.hcp107Fixture.owner, 1582 () => 1583 new Promise<void>((resolve) => { 1584 release = resolve; 1585 entered(); 1586 }) 1587 ); 1588 await ready; 1589 Reflect.set(window, 'cr003RestorePut', async () => { 1590 release(); 1591 await held; 1592 }); 1593 return; 1594 } 1595 const originalPut = Reflect.get<IDBObjectStore, 'put'>( 1596 IDBObjectStore.prototype, 1597 'put' 1598 ); 1599 const originalAbort = Reflect.get<IDBTransaction, 'abort'>( 1600 IDBTransaction.prototype, 1601 'abort' 1602 ); 1603 let intercepted = false; 1604 IDBObjectStore.prototype.put = function (...args) { 1605 if (this.name !== 'private_sends' || intercepted) 1606 return Reflect.apply(originalPut, this, args); 1607 intercepted = true; 1608 const request = Reflect.apply(originalPut, this, args); 1609 if (outcome === 'confirmed_abort') 1610 request.addEventListener( 1611 'success', 1612 () => Reflect.apply(originalAbort, this.transaction, []), 1613 { once: true } 1614 ); 1615 else { 1616 this.transaction.abort = () => { 1617 throw Error('controlled lost abort capability'); 1618 }; 1619 throw Error('controlled lost put result after actual queued write'); 1620 } 1621 return request; 1622 }; 1623 // Only the actual trusted prototype's put is intercepted for one command. 1624 Reflect.set(window, 'cr003RestorePut', () => { 1625 IDBObjectStore.prototype.put = originalPut; 1626 }); 1627 }, outcome); 1628 try { 1629 await panel(page) 1630 .getByRole('button', { name: 'Send request', exact: true }) 1631 .click(); 1632 await expect 1633 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.busy)) 1634 .toBe(false); 1635 } finally { 1636 await page.evaluate(async () => { 1637 const restore = Reflect.get( 1638 window, 1639 'cr003RestorePut' 1640 ) as () => void | Promise<void>; 1641 await restore(); 1642 Reflect.deleteProperty(window, 'cr003RestorePut'); 1643 }); 1644 } 1645 const terminal = await page.evaluate(async () => ({ 1646 snapshot: window.hcp107Fixture.snapshot(), 1647 text: window.hcp107Fixture.text(), 1648 counts: window.hcp107Fixture.counts(), 1649 native: await window.hcp107Fixture.native() 1650 })); 1651 expect(terminal.text).toBe('CR003_TEST_ONLY_original_unsent_question'); 1652 expect(terminal.counts).toEqual(before.counts); 1653 expect(events.filter((row) => row.event.kind === 1059)).toEqual([]); 1654 if (outcome !== 'unknown_after_commit') { 1655 expect(terminal.snapshot).toMatchObject({ 1656 state: 'idle', 1657 readyToSend: true 1658 }); 1659 expect(terminal.native).toEqual(before.native); 1660 expect( 1661 await page.evaluate(() => 1662 window.hcp107Fixture.update('CR003_TEST_ONLY_edited_after_abort') 1663 ) 1664 ).toBe(true); 1665 await panel(page) 1666 .getByRole('button', { name: 'Send request', exact: true }) 1667 .click(); 1668 await expect 1669 .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) 1670 .toBe('completed'); 1671 expect(events.filter((row) => row.event.kind === 1059)).toHaveLength(2); 1672 } else { 1673 expect(terminal.snapshot).toMatchObject({ 1674 state: 'needs_action', 1675 readyToSend: false 1676 }); 1677 expect(terminal.native.sends).toHaveLength( 1678 before.native.sends.length + 1 1679 ); 1680 expect( 1681 await page.evaluate(() => 1682 window.hcp107Fixture.update('attempted different body') 1683 ) 1684 ).toBe(false); 1685 expect(await page.evaluate(() => window.hcp107Fixture.send())).toEqual({ 1686 status: 'needs_action' 1687 }); 1688 expect(await page.evaluate(() => window.hcp107Fixture.native())).toEqual( 1689 terminal.native 1690 ); 1691 expect(events.filter((row) => row.event.kind === 1059)).toEqual([]); 1692 } 1693 }); 1694 1695 test('CR007 pending actual product request EVENT plus route close settles stopped and preserves cleanup', async ({ 1696 page 1697 }) => { 1698 await ready(page); 1699 await unlock(page); 1700 holdPrivateAck = true; 1701 await page.evaluate(() => { 1702 window.cr007DelayPrivateClose = true; 1703 window.cr007PendingSend = window.hcp107Fixture.beginHeadless(); 1704 }); 1705 await expect 1706 .poll(() => events.filter(({ event }) => event.kind === 1059).length) 1707 .toBe(1); 1708 await page.evaluate(() => window.hcp107Fixture.closeView()); 1709 expect(await page.evaluate(() => window.cr007PendingSend)).toEqual({ 1710 status: 'stopped' 1711 }); 1712 expect( 1713 await page.evaluate(() => window.hcp107Fixture.headlessSnapshot()) 1714 ).toBeUndefined(); 1715 expect(events.filter(({ event }) => event.kind === 1059)).toHaveLength(1); 1716 expect( 1717 await page.evaluate(() => window.cr007DelayedCloses?.length ?? 0) 1718 ).toBeGreaterThan(0); 1719 await page.evaluate(() => { 1720 window.cr007DelayPrivateClose = false; 1721 for (const release of window.cr007DelayedCloses ?? []) release(); 1722 }); 1723 });