app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

reply-composer.spec.ts (34066B)


      1 import { test, expect } 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, type WebSocket } from 'ws';
      7 import { createStaticHarness } from '../integration/harness/static.ts';
      8 import type * as Fixture from './harness/reply-composer.ts';
      9 import { finalizeEvent } from 'applesauce-core/helpers';
     10 declare global {
     11   interface Window {
     12     cr007PendingSend?: Promise<unknown>;
     13     cr007DelayPrivateClose?: boolean;
     14     cr007DelayedCloses?: (() => void)[];
     15     hcp104: typeof Fixture;
     16     hcp104Fixture: Awaited<ReturnType<typeof Fixture.renderReplyFixture>>;
     17     hcp104Pending?: Promise<unknown>;
     18   }
     19 }
     20 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     21   sockets: WebSocketServer,
     22   endpoint: string,
     23   bundle: string;
     24 let events: unknown[][] = [],
     25   requests: unknown[][] = [];
     26 let servePeerPreference = false;
     27 let holdPeerEose = false;
     28 let holdPrivateAck = false;
     29 let heldPeerRequest:
     30   | {
     31       socket: WebSocket;
     32       id: string;
     33       filter: unknown;
     34       eventSent: boolean;
     35       eoseSent: boolean;
     36       closed: boolean;
     37       closedBeforeEose: boolean;
     38       disconnectedBeforeCompletion: boolean;
     39     }
     40   | undefined;
     41 const peerPreference = finalizeEvent(
     42   {
     43     kind: 10050,
     44     created_at: 100,
     45     tags: [['relay', 'wss://peer.example.org']],
     46     content: ''
     47   },
     48   new Uint8Array(32).fill(84)
     49 );
     50 test.beforeAll(async () => {
     51   server = await createStaticHarness();
     52   sockets = new WebSocketServer({
     53     host: '127.0.0.1',
     54     port: 0,
     55     maxPayload: 65536
     56   });
     57   await once(sockets, 'listening');
     58   const address = sockets.address();
     59   if (!address || typeof address === 'string') throw Error('no loopback');
     60   endpoint = 'ws://127.0.0.1:' + address.port;
     61   sockets.on('connection', (socket) => {
     62     socket.on('close', () => {
     63       if (heldPeerRequest?.socket === socket && !heldPeerRequest.closed)
     64         heldPeerRequest.disconnectedBeforeCompletion = true;
     65     });
     66     socket.on('message', (bytes) => {
     67       const raw = Buffer.isBuffer(bytes)
     68           ? bytes
     69           : Array.isArray(bytes)
     70             ? Buffer.concat(bytes)
     71             : Buffer.from(bytes),
     72         frame = JSON.parse(raw.toString()) as unknown[];
     73       if (
     74         frame[0] === 'CLOSE' &&
     75         heldPeerRequest?.socket === socket &&
     76         heldPeerRequest.id === frame[1]
     77       ) {
     78         if (heldPeerRequest.eoseSent) heldPeerRequest.closed = true;
     79         else heldPeerRequest.closedBeforeEose = true;
     80       }
     81       if (frame[0] === 'EVENT') {
     82         events.push(frame);
     83         const event = frame[1] as { id: string };
     84         if (!holdPrivateAck)
     85           socket.send(JSON.stringify(['OK', event.id, true, '']));
     86       }
     87       if (frame[0] === 'REQ') {
     88         requests.push(frame);
     89         const filter = frame[2] as { kinds?: number[]; authors?: string[] };
     90         if (
     91           servePeerPreference &&
     92           filter.kinds?.includes(10050) &&
     93           filter.authors?.includes(peerPreference.pubkey)
     94         ) {
     95           if (holdPeerEose) {
     96             if (heldPeerRequest) throw Error('duplicate held peer request');
     97             heldPeerRequest = {
     98               socket,
     99               id: String(frame[1]),
    100               filter: frame[2],
    101               eventSent: true,
    102               eoseSent: false,
    103               closed: false,
    104               closedBeforeEose: false,
    105               disconnectedBeforeCompletion: false
    106             };
    107           }
    108           socket.send(JSON.stringify(['EVENT', frame[1], peerPreference]));
    109           if (holdPeerEose) return;
    110         }
    111         socket.send(JSON.stringify(['EOSE', frame[1]]));
    112       }
    113     });
    114   });
    115   const result = await build({
    116     configFile: false,
    117     logLevel: 'silent',
    118     plugins: [svelte({ configFile: false })],
    119     resolve: {
    120       conditions: ['browser'],
    121       alias: {
    122         '$app/navigation': fileURLToPath(
    123           new URL('./harness/reply-composer.ts', import.meta.url)
    124         )
    125       }
    126     },
    127     build: {
    128       write: false,
    129       minify: false,
    130       lib: {
    131         entry: fileURLToPath(
    132           new URL('./harness/reply-composer.ts', import.meta.url)
    133         ),
    134         name: 'hcp104',
    135         formats: ['iife']
    136       }
    137     }
    138   });
    139   const output = Array.isArray(result) ? result[0] : result;
    140   if (!('output' in output)) throw Error('no bundle');
    141   const chunks = output.output.filter((row) => row.type === 'chunk');
    142   expect(chunks).toHaveLength(1);
    143   bundle = chunks[0].code;
    144 });
    145 test.afterAll(async () => {
    146   for (const socket of sockets.clients) socket.terminate();
    147   await new Promise<void>((resolve) => sockets.close(() => resolve()));
    148   await server.close();
    149 });
    150 async function load(page: import('@playwright/test').Page) {
    151   await page.addInitScript(
    152     ({ endpoint }) => {
    153       const Native = window.WebSocket;
    154       window.WebSocket = class extends Native {
    155         constructor(url: string | URL, protocols?: string | string[]) {
    156           if (
    157             ![
    158               'wss://peer.example.org',
    159               'wss://archive.example.org',
    160               'wss://discovery.example.org'
    161             ].includes(new URL(String(url)).origin)
    162           )
    163             throw Error('unapproved destination');
    164           super(endpoint, protocols);
    165           this.cr007Private =
    166             new URL(String(url)).origin !== 'wss://discovery.example.org';
    167         }
    168         readonly cr007Private: boolean;
    169         override close(code?: number, reason?: string) {
    170           if (this.cr007Private && window.cr007DelayPrivateClose)
    171             (window.cr007DelayedCloses ??= []).push(() =>
    172               super.close(code, reason)
    173             );
    174           else super.close(code, reason);
    175         }
    176       };
    177     },
    178     { endpoint }
    179   );
    180   await page.goto(server.url + '/search');
    181   await page.addScriptTag({ content: bundle });
    182 }
    183 test.beforeEach(async ({ page }) => {
    184   events = [];
    185   requests = [];
    186   servePeerPreference = false;
    187   holdPeerEose = false;
    188   holdPrivateAck = false;
    189   heldPeerRequest = undefined;
    190   await load(page);
    191 });
    192 test.afterEach(async ({ page }) => {
    193   if (!page.isClosed())
    194     await page.evaluate(async () => {
    195       window.hcp104Fixture?.settle();
    196       await window.hcp104Pending;
    197       window.cr007DelayPrivateClose = false;
    198       for (const release of window.cr007DelayedCloses ?? []) release();
    199       await window.hcp104Fixture?.close();
    200     });
    201 });
    202 async function ready(
    203   page: import('@playwright/test').Page,
    204   qualified = true,
    205   production = false
    206 ) {
    207   await page.evaluate(
    208     async ({ qualified, production }) => {
    209       window.hcp104Fixture = await window.hcp104.renderReplyFixture(
    210         qualified,
    211         production
    212       );
    213     },
    214     { qualified, production }
    215   );
    216   await expect(
    217     page.locator('[data-reply-fixture]').getByLabel('Reply', { exact: true })
    218   ).toBeVisible();
    219   await expect
    220     .poll(() =>
    221       page.evaluate(async () => {
    222         const native = await window.hcp104Fixture.native();
    223         return native.received.every((row) => {
    224           const record = JSON.parse((row as { wire: string }).wire) as {
    225             read: unknown;
    226           };
    227           return record.read !== null;
    228         });
    229       })
    230     )
    231     .toBe(true);
    232 }
    233 const composer = (page: import('@playwright/test').Page) =>
    234   page.locator('[data-reply-fixture]');
    235 const sentinel = 'HCP104_UNSENT_MEMORY_ONLY & <private>\nThursday pickup?';
    236 
    237 for (const crossSecond of [false, true]) {
    238   test(
    239     crossSecond
    240       ? 'CR003 production reply reserves across a real owner second boundary'
    241       : 'production explicit Send renews an expired peer lookup without losing the draft or automatically sending',
    242     async ({ page }) => {
    243       await ready(page, true, true);
    244       await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    245       const before = await page.evaluate(async () => ({
    246         native: await window.hcp104Fixture.native(),
    247         delta: window.hcp104Fixture.delta()
    248       }));
    249       expect(requests).toEqual([]);
    250       expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    251         status: 'needs_action'
    252       });
    253       await expect.poll(() => requests.length).toBe(1);
    254       expect(requests[0][2]).toMatchObject({
    255         kinds: [10050],
    256         authors: [peerPreference.pubkey],
    257         limit: 200
    258       });
    259       // An active missing-peer run is reused. Neither its EOSE nor another Send
    260       // silently resets the bounded lookup or invents private readiness.
    261       expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    262         status: 'needs_action'
    263       });
    264       expect(requests).toHaveLength(1);
    265       expect(events).toEqual([]);
    266       await page.evaluate(async () => {
    267         window.hcp104Fixture.advance();
    268         await window.hcp104Fixture.refreshSetup();
    269       });
    270       expect(requests).toHaveLength(1);
    271       expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
    272         sentinel
    273       );
    274       expect(
    275         await page.evaluate(async () => ({
    276           native: await window.hcp104Fixture.native(),
    277           delta: window.hcp104Fixture.delta()
    278         }))
    279       ).toEqual(before);
    280       servePeerPreference = true;
    281       holdPeerEose = true;
    282       expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    283         status: 'needs_action'
    284       });
    285       // The unchanged producer never issues this second original runtime query.
    286       await expect.poll(() => requests.length).toBe(2);
    287       expect(requests[1][2]).toEqual(requests[0][2]);
    288       expect(events).toEqual([]);
    289       expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
    290         sentinel
    291       );
    292       expect(heldPeerRequest?.id).toBe(requests[1][1]);
    293       expect(heldPeerRequest?.filter).toEqual(requests[1][2]);
    294       expect(heldPeerRequest).toMatchObject({
    295         eventSent: true,
    296         eoseSent: false,
    297         closed: false,
    298         closedBeforeEose: false,
    299         disconnectedBeforeCompletion: false
    300       });
    301       expect(
    302         await page.evaluate(() => window.hcp104Fixture.snapshot()?.state)
    303       ).toBe('needs_action');
    304       expect(
    305         await page.evaluate(async () => ({
    306           native: await window.hcp104Fixture.native(),
    307           delta: window.hcp104Fixture.delta()
    308         }))
    309       ).toEqual(before);
    310       // Server REQ arrival is not consumer readiness. With the original run's
    311       // virtual clock held, this exact subscription can finish only after its
    312       // actual signed EVENT and released EOSE are consumed and cleaned up.
    313       const originalPeerRequest = heldPeerRequest;
    314       if (!originalPeerRequest) throw Error('missing original peer request');
    315       originalPeerRequest.eoseSent = true;
    316       originalPeerRequest.socket.send(
    317         JSON.stringify(['EOSE', originalPeerRequest.id])
    318       );
    319       await expect.poll(() => originalPeerRequest.closed).toBe(true);
    320       expect(originalPeerRequest.closedBeforeEose).toBe(false);
    321       expect(originalPeerRequest.disconnectedBeforeCompletion).toBe(false);
    322       expect(requests).toHaveLength(2);
    323       expect(events).toEqual([]);
    324       await page.evaluate(
    325         (crossSecond) => window.hcp104Fixture.configureSendClock(crossSecond),
    326         crossSecond
    327       );
    328       await page.evaluate(() => window.hcp104Fixture.resetDiagnostics());
    329       const beforeSend = await page.evaluate(() =>
    330         window.hcp104Fixture.diagnostic()
    331       );
    332       await composer(page)
    333         .getByRole('button', { name: 'Send reply', exact: true })
    334         .click();
    335       // Observe actual completion before inspecting the owned operation.
    336       // Observe completion of the attempt before asserting its complete outcome.
    337       await expect
    338         .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.busy))
    339         .toBe(false);
    340       await page.evaluate(() => window.hcp104Fixture.restoreSendClock());
    341       const terminal = await page.evaluate(async () => ({
    342         snapshot: window.hcp104Fixture.snapshot(),
    343         diagnostic: await window.hcp104Fixture.diagnostic(),
    344         native: await window.hcp104Fixture.native(),
    345         delta: window.hcp104Fixture.delta()
    346       }));
    347       if (crossSecond) {
    348         const samples = terminal.diagnostic.clockSamples;
    349         expect(Math.floor(samples[1].value / 1000)).toBeGreaterThan(
    350           Math.floor(samples[0].value / 1000)
    351         );
    352         expect(terminal.diagnostic.nativeTransactions.length).toBeGreaterThan(
    353           0
    354         );
    355         expect(
    356           terminal.diagnostic.nativeTransactions.every(
    357             (row) => row.outcome === 'complete'
    358           )
    359         ).toBe(true);
    360       }
    361       expect(
    362         terminal,
    363         JSON.stringify({ beforeSend, terminal, published: events.length })
    364       ).toMatchObject({
    365         snapshot: { state: 'completed', busy: false }
    366       });
    367       expect(requests).toHaveLength(2);
    368       expect(events).toHaveLength(2);
    369       expect(
    370         await page.evaluate(() => window.hcp104Fixture.delta())
    371       ).toMatchObject({
    372         encrypts: before.delta.encrypts + 2,
    373         signs: before.delta.signs + 2
    374       });
    375     }
    376   );
    377 }
    378 
    379 test('typing is memory only with no autosave SDK discovery publication or order transition', async ({
    380   page
    381 }) => {
    382   const messages: string[] = [];
    383   page.on('console', (message) => messages.push(message.text()));
    384   page.on('pageerror', (error) => messages.push(error.message));
    385   await ready(page);
    386   const before = await page.evaluate(async () => ({
    387     native: await window.hcp104Fixture.native(),
    388     delta: window.hcp104Fixture.delta()
    389   }));
    390   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    391   await expect(composer(page)).toContainText('unsaved memory');
    392   await expect(composer(page)).toContainText('does not accept an order');
    393   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
    394   expect(await page.evaluate(() => window.hcp104Fixture.lookups())).toBe(0);
    395   expect(
    396     await page.evaluate(async () => ({
    397       native: await window.hcp104Fixture.native(),
    398       delta: window.hcp104Fixture.delta()
    399     }))
    400   ).toEqual(before);
    401   expect(events).toEqual([]);
    402   expect(requests).toEqual([]);
    403   expect(
    404     await composer(page)
    405       .getByRole('button', { name: /Accept order/i })
    406       .count()
    407   ).toBe(0);
    408   expect(
    409     await page.evaluate(
    410       (text) =>
    411         JSON.stringify({
    412           local: { ...localStorage },
    413           session: { ...sessionStorage }
    414         }).includes(text),
    415       sentinel
    416     )
    417   ).toBe(false);
    418   // This controlled composer is mounted on Search, not a private route.
    419   // Real private title/noindex qualification is in privacy-output.spec.ts.
    420   expect(await page.locator('head').textContent()).not.toContain(sentinel);
    421   expect(page.url()).not.toContain(encodeURIComponent(sentinel));
    422   expect(messages.join('\n')).not.toContain(sentinel);
    423   await expect(composer(page).getByText(/unsaved memory/)).toBeVisible();
    424   await expect(
    425     composer(page).getByText('It does not accept an order.', { exact: false })
    426   ).toBeVisible();
    427 });
    428 
    429 test('explicit Send creates an actual self-first paired reply with the authenticated peer and direct inner parent', async ({
    430   page
    431 }) => {
    432   await ready(page);
    433   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    434   // This controlled-provider source case exercises successful paired delivery.
    435   // The production scenarios above also use an advancing actual wall clock.
    436   await page.evaluate(() => window.hcp104Fixture.configureSendClock(false));
    437   const before = await page.evaluate(() => window.hcp104Fixture.delta());
    438   await composer(page)
    439     .getByRole('button', { name: 'Send reply', exact: true })
    440     .click();
    441   await expect
    442     .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.busy))
    443     .toBe(false);
    444   const terminal = await page.evaluate(async () => ({
    445     snapshot: window.hcp104Fixture.snapshot(),
    446     diagnostic: await window.hcp104Fixture.diagnostic()
    447   }));
    448   expect(terminal, JSON.stringify(terminal)).toMatchObject({
    449     snapshot: { state: 'completed', busy: false }
    450   });
    451   expect(events).toHaveLength(2);
    452   expect(
    453     events.every((frame) => (frame[1] as { kind: number }).kind === 1059)
    454   ).toBe(true);
    455   expect(await page.evaluate(() => window.hcp104Fixture.delta())).toMatchObject(
    456     { encrypts: before.encrypts + 2, signs: before.signs + 2 }
    457   );
    458   await expect(composer(page)).toContainText('Saved encrypted in this browser');
    459   await expect(composer(page)).toContainText(
    460     'Accepted by recipient inbox relay'
    461   );
    462   expect(
    463     await page.evaluate(() => window.hcp104Fixture.list().requests)
    464   ).toEqual([]);
    465   expect(
    466     await page.evaluate(() =>
    467       window.hcp104Fixture.list().conversations.map((row) => row.peer)
    468     )
    469   ).toEqual([await page.evaluate(() => window.hcp104Fixture.peer)]);
    470   const { nip44 } = await import('applesauce-core/helpers/encryption');
    471   const { getEventHash } = await import('applesauce-core/helpers');
    472   const owner = await page.evaluate(() => window.hcp104Fixture.owner),
    473     peer = await page.evaluate(() => window.hcp104Fixture.peer),
    474     parent = await page.evaluate(() => window.hcp104Fixture.parent);
    475   const rumors = events.map((frame) => {
    476     const outer = frame[1] as {
    477       pubkey: string;
    478       content: string;
    479       tags: string[][];
    480     };
    481     const key = new Uint8Array(32).fill(outer.tags[0][1] === owner ? 83 : 84);
    482     const seal = JSON.parse(
    483       nip44.v2.decrypt(
    484         outer.content,
    485         nip44.v2.utils.getConversationKey(key, outer.pubkey)
    486       )
    487     ) as { pubkey: string; content: string; kind: number; tags: string[][] };
    488     expect(seal.kind).toBe(13);
    489     expect(seal.tags).toEqual([]);
    490     expect(seal.pubkey).toBe(owner);
    491     const rumor = JSON.parse(
    492       nip44.v2.decrypt(
    493         seal.content,
    494         nip44.v2.utils.getConversationKey(key, seal.pubkey)
    495       )
    496     ) as {
    497       id: string;
    498       kind: number;
    499       pubkey: string;
    500       tags: string[][];
    501       content: string;
    502       created_at: number;
    503     };
    504     expect(rumor.kind).toBe(14);
    505     expect(rumor.pubkey).toBe(owner);
    506     expect(rumor.content).toBe(sentinel);
    507     expect(rumor.tags).toEqual([
    508       ['p', peer],
    509       ['e', parent]
    510     ]);
    511     expect(getEventHash(rumor)).toBe(rumor.id);
    512     key.fill(0);
    513     return rumor;
    514   });
    515   expect(rumors[0]).toEqual(rumors[1]);
    516   expect(requests).toEqual([]);
    517 });
    518 
    519 for (const outcome of [
    520   'busy',
    521   'confirmed_abort',
    522   'unknown_after_commit'
    523 ] as const)
    524   test(`CR003 actual reply ${outcome} retains draft with the correct retry disposition`, async ({
    525     page
    526   }) => {
    527     await ready(page);
    528     await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    529     const before = await page.evaluate(async () => ({
    530       native: await window.hcp104Fixture.native(),
    531       delta: window.hcp104Fixture.delta()
    532     }));
    533     await page.evaluate(async (outcome) => {
    534       let restore = () => {};
    535       if (outcome === 'busy') {
    536         let entered = () => {},
    537           release = () => {};
    538         const ready = new Promise<void>((resolve) => {
    539           entered = resolve;
    540         });
    541         const held = navigator.locks.request(
    542           'harvestcircle:owner:' + window.hcp104Fixture.owner,
    543           () =>
    544             new Promise<void>((resolve) => {
    545               release = resolve;
    546               entered();
    547             })
    548         );
    549         await ready;
    550         Reflect.set(window, 'cr003ReplyRelease', async () => {
    551           release();
    552           await held;
    553         });
    554       } else {
    555         const originalPut = Reflect.get<IDBObjectStore, 'put'>(
    556             IDBObjectStore.prototype,
    557             'put'
    558           ),
    559           originalAbort = Reflect.get<IDBTransaction, 'abort'>(
    560             IDBTransaction.prototype,
    561             'abort'
    562           );
    563         let intercepted = false;
    564         IDBObjectStore.prototype.put = function (...args) {
    565           if (this.name !== 'private_sends' || intercepted)
    566             return Reflect.apply(originalPut, this, args);
    567           intercepted = true;
    568           const request = Reflect.apply(originalPut, this, args);
    569           if (outcome === 'confirmed_abort')
    570             request.addEventListener(
    571               'success',
    572               () => Reflect.apply(originalAbort, this.transaction, []),
    573               { once: true }
    574             );
    575           else {
    576             this.transaction.abort = () => {
    577               throw Error('controlled lost abort capability');
    578             };
    579             throw Error('controlled lost result after actual queued write');
    580           }
    581           return request;
    582         };
    583         restore = () => {
    584           IDBObjectStore.prototype.put = originalPut;
    585         };
    586       }
    587       Reflect.set(window, 'cr003ReplyRestore', restore);
    588     }, outcome);
    589     try {
    590       await composer(page)
    591         .getByRole('button', { name: 'Send reply', exact: true })
    592         .click();
    593       await expect
    594         .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.busy))
    595         .toBe(false);
    596     } finally {
    597       await page.evaluate(async () => {
    598         (Reflect.get(window, 'cr003ReplyRestore') as () => void)();
    599         const release = Reflect.get(window, 'cr003ReplyRelease') as
    600           (() => Promise<void>) | undefined;
    601         await release?.();
    602         Reflect.deleteProperty(window, 'cr003ReplyRestore');
    603         Reflect.deleteProperty(window, 'cr003ReplyRelease');
    604       });
    605     }
    606     const terminal = await page.evaluate(async () => ({
    607       snapshot: window.hcp104Fixture.snapshot(),
    608       text: window.hcp104Fixture.text(),
    609       native: await window.hcp104Fixture.native(),
    610       delta: window.hcp104Fixture.delta()
    611     }));
    612     expect(terminal.text).toBe(sentinel);
    613     expect(terminal.delta).toEqual(before.delta);
    614     expect(events).toEqual([]);
    615     if (outcome === 'unknown_after_commit') {
    616       expect(terminal.snapshot).toMatchObject({
    617         state: 'needs_action',
    618         readyToSend: false
    619       });
    620       expect(terminal.native.sends).toHaveLength(
    621         before.native.sends.length + 1
    622       );
    623       expect(
    624         await page.evaluate(() =>
    625           window.hcp104Fixture.update('different attempted body')
    626         )
    627       ).toBe(false);
    628       expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    629         status: 'needs_action'
    630       });
    631       expect(await page.evaluate(() => window.hcp104Fixture.native())).toEqual(
    632         terminal.native
    633       );
    634     } else {
    635       expect(terminal.snapshot).toMatchObject({
    636         state: 'idle',
    637         readyToSend: true
    638       });
    639       expect(terminal.native).toEqual(before.native);
    640       expect(
    641         await page.evaluate(() =>
    642           window.hcp104Fixture.update('CR003_TEST_ONLY_edited_reply')
    643         )
    644       ).toBe(true);
    645       await composer(page)
    646         .getByRole('button', { name: 'Send reply', exact: true })
    647         .click();
    648       await expect
    649         .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.state))
    650         .toBe('completed');
    651       expect(events).toHaveLength(2);
    652     }
    653   });
    654 
    655 test('cancelled same-page setup retains the exact draft and clearing the gate never auto-sends', async ({
    656   page
    657 }) => {
    658   await ready(page);
    659   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    660   const before = await page.evaluate(async () => ({
    661     native: await window.hcp104Fixture.native(),
    662     delta: window.hcp104Fixture.delta()
    663   }));
    664   await page.evaluate(() => window.hcp104Fixture.gate(true));
    665   expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    666     status: 'needs_action'
    667   });
    668   await expect(composer(page).getByLabel('Reply', { exact: true })).toHaveValue(
    669     sentinel
    670   );
    671   await page.evaluate(() => window.hcp104Fixture.gate(false));
    672   expect(
    673     await page.evaluate(async () => ({
    674       native: await window.hcp104Fixture.native(),
    675       delta: window.hcp104Fixture.delta()
    676     }))
    677   ).toEqual(before);
    678   expect(events).toEqual([]);
    679   expect(requests).toEqual([]);
    680 });
    681 
    682 test('unexercised original inbox access leaves the memory draft honest and cannot send', async ({
    683   page
    684 }) => {
    685   await ready(page, false);
    686   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    687   const before = await page.evaluate(async () => ({
    688     native: await window.hcp104Fixture.native(),
    689     delta: window.hcp104Fixture.delta()
    690   }));
    691   expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
    692     status: 'needs_action'
    693   });
    694   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
    695   expect(
    696     await page.evaluate(async () => ({
    697       native: await window.hcp104Fixture.native(),
    698       delta: window.hcp104Fixture.delta()
    699     }))
    700   ).toEqual(before);
    701   expect(events).toEqual([]);
    702 });
    703 
    704 test('unreviewed Send and oversized edits retain the previous memory revision without effects', async ({
    705   page
    706 }) => {
    707   await ready(page);
    708   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    709   expect(
    710     await page.evaluate(() => window.hcp104Fixture.update('x'.repeat(4097)))
    711   ).toBe(false);
    712   expect(
    713     await page.evaluate(() => window.hcp104Fixture.send('unreviewed'))
    714   ).toEqual({ status: 'invalid' });
    715   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
    716   expect(await page.evaluate(() => window.hcp104Fixture.lookups())).toBe(0);
    717   expect(events).toEqual([]);
    718 });
    719 
    720 test('dirty route navigation defaults to Keep editing and preserves the draft and focus', async ({
    721   page
    722 }) => {
    723   await ready(page);
    724   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    725   expect(await page.evaluate(() => window.hcp104Fixture.navigate())).toBe(true);
    726   await expect(
    727     composer(page).getByRole('button', { name: 'Keep editing', exact: true })
    728   ).toBeFocused();
    729   await composer(page)
    730     .getByRole('button', { name: 'Keep editing', exact: true })
    731     .click();
    732   await expect(composer(page).getByLabel('Reply', { exact: true })).toHaveValue(
    733     sentinel
    734   );
    735   await expect(
    736     composer(page).getByLabel('Reply', { exact: true })
    737   ).toBeFocused();
    738   expect(
    739     await page.evaluate(() => window.hcp104Fixture.destinations())
    740   ).toEqual([]);
    741   expect(events).toEqual([]);
    742 });
    743 
    744 test('reviewed navigation discard clears only the same draft and returns to the safe inbox', async ({
    745   page
    746 }) => {
    747   await ready(page);
    748   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    749   const before = await page.evaluate(() => window.hcp104Fixture.native());
    750   expect(await page.evaluate(() => window.hcp104Fixture.navigate())).toBe(true);
    751   await composer(page)
    752     .getByRole('button', { name: 'Discard draft', exact: true })
    753     .click();
    754   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe('');
    755   expect(
    756     await page.evaluate(() => window.hcp104Fixture.destinations())
    757   ).toEqual(['/messages']);
    758   expect(await page.evaluate(() => window.hcp104Fixture.native())).toEqual(
    759     before
    760   );
    761   expect(events).toEqual([]);
    762 });
    763 
    764 test('actual native unload event warns for unsaved text without attempting a save', async ({
    765   page
    766 }) => {
    767   await ready(page);
    768   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    769   const before = await page.evaluate(() => window.hcp104Fixture.delta());
    770   expect(
    771     await page.evaluate(() => {
    772       const event = new Event('beforeunload', { cancelable: true });
    773       return window.dispatchEvent(event);
    774     })
    775   ).toBe(false);
    776   expect(await page.evaluate(() => window.hcp104Fixture.delta())).toEqual(
    777     before
    778   );
    779   expect(events).toEqual([]);
    780 });
    781 
    782 test('unmount during the actual held seal signature retires continuations and never auto-publishes a late result', async ({
    783   page
    784 }) => {
    785   await ready(page);
    786   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    787   await page.evaluate(() => {
    788     window.hcp104Fixture.holdSigner();
    789     window.hcp104Pending = window.hcp104Fixture.send();
    790   });
    791   await expect
    792     .poll(() => page.evaluate(() => window.hcp104Fixture.pending()))
    793     .toBe(true);
    794   await expect(composer(page)).toContainText('Preparing');
    795   expect(events).toEqual([]);
    796   await page.evaluate(() => window.hcp104Fixture.closeComposer());
    797   await page.evaluate(async () => {
    798     window.hcp104Fixture.settle();
    799     await window.hcp104Pending;
    800   });
    801   expect(
    802     await page.evaluate(() => window.hcp104Fixture.text())
    803   ).toBeUndefined();
    804   expect(events).toEqual([]);
    805   expect(requests).toEqual([]);
    806   expect(await page.evaluate(() => window.hcp104Fixture.delta())).toMatchObject(
    807     { encrypts: 1, signs: 1 }
    808   );
    809 });
    810 
    811 test('logout during actual held signer work hides the draft and refuses late peer crypto or publication', async ({
    812   page
    813 }) => {
    814   await ready(page);
    815   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    816   await page.evaluate(() => {
    817     window.hcp104Fixture.holdSigner();
    818     window.hcp104Pending = window.hcp104Fixture.send();
    819   });
    820   await expect
    821     .poll(() => page.evaluate(() => window.hcp104Fixture.pending()))
    822     .toBe(true);
    823   await page.evaluate(() => window.hcp104Fixture.logout());
    824   await page.evaluate(async () => {
    825     window.hcp104Fixture.settle();
    826     await window.hcp104Pending;
    827   });
    828   expect(
    829     await page.evaluate(() => window.hcp104Fixture.text())
    830   ).toBeUndefined();
    831   expect(events).toEqual([]);
    832   await expect(composer(page).getByLabel('Reply', { exact: true })).toHaveCount(
    833     0
    834   );
    835   expect(await page.locator('body').textContent()).not.toContain(sentinel);
    836   expect(await page.locator('head').textContent()).not.toContain(sentinel);
    837 });
    838 
    839 test('copied controllers and arbitrary private or product hashes cannot borrow reply custody', async ({
    840   page
    841 }) => {
    842   await ready(page);
    843   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    844   expect(await page.evaluate(() => window.hcp104Fixture.copied())).toEqual({
    845     update: false,
    846     send: { status: 'invalid' },
    847     navigation: 'invalid',
    848     keep: false,
    849     discard: 'invalid'
    850   });
    851   expect(
    852     await page.evaluate(() => window.hcp104Fixture.selectParent('f'.repeat(64)))
    853   ).toBe(false);
    854   expect(
    855     await page.evaluate(() =>
    856       window.hcp104Fixture.selectParent('nostr:naddr1invalid')
    857     )
    858   ).toBe(false);
    859   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
    860   expect(events).toEqual([]);
    861   expect(requests).toEqual([]);
    862 });
    863 
    864 test('explicitly leaving and reloading loses the unsaved memory draft while ciphertext remains intact', async ({
    865   page
    866 }) => {
    867   await ready(page);
    868   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    869   const before = await page.evaluate(() => window.hcp104Fixture.native());
    870   await page.evaluate(() => window.hcp104Fixture.close());
    871   await page.reload();
    872   expect(
    873     await page.evaluate(() =>
    874       document.body.textContent?.includes('HCP104_UNSENT_MEMORY_ONLY')
    875     )
    876   ).toBe(false);
    877   expect(
    878     await page.evaluate(
    879       (rows) => JSON.stringify(rows).includes('HCP104_UNSENT_MEMORY_ONLY'),
    880       before
    881     )
    882   ).toBe(false);
    883   expect(events).toEqual([]);
    884   expect(requests).toEqual([]);
    885 });
    886 
    887 test('later actual admitted Room replies reject every copied custody token and a genuine different same-owner identity generation', async ({
    888   page
    889 }) => {
    890   await ready(page);
    891   const before = await page.evaluate(() => window.hcp104Fixture.native());
    892   const admission = await page.evaluate(() => window.hcp104Fixture.admission());
    893   expect(admission.copied).toEqual([false, false, false, false]);
    894   expect(admission.foreign).toBe(false);
    895   const rumor = JSON.parse(admission.wire!) as {
    896     pubkey: string;
    897     tags: string[][];
    898     content: string;
    899     kind: number;
    900   };
    901   expect(rumor.pubkey).toBe(
    902     await page.evaluate(() => window.hcp104Fixture.owner)
    903   );
    904   expect(rumor.tags).toEqual([
    905     ['p', await page.evaluate(() => window.hcp104Fixture.peer)],
    906     ['e', await page.evaluate(() => window.hcp104Fixture.parent)]
    907   ]);
    908   expect(rumor.kind).toBe(14);
    909   expect(rumor.content).toBe('Local admission fixture only');
    910   expect(await page.evaluate(() => window.hcp104Fixture.native())).toEqual(
    911     before
    912   );
    913   expect(events).toEqual([]);
    914   expect(requests).toEqual([]);
    915 });
    916 
    917 test('later edit after opening dirty warning invalidates the reviewed discard revision without erasing the new draft or navigating', async ({
    918   page
    919 }) => {
    920   await ready(page);
    921   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    922   expect(await page.evaluate(() => window.hcp104Fixture.navigate())).toBe(true);
    923   await composer(page)
    924     .getByLabel('Reply', { exact: true })
    925     .fill(sentinel + '\nKeep this newer text');
    926   await composer(page)
    927     .getByRole('button', { name: 'Discard draft', exact: true })
    928     .click();
    929   expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
    930     sentinel + '\nKeep this newer text'
    931   );
    932   expect(
    933     await page.evaluate(() => window.hcp104Fixture.destinations())
    934   ).toEqual([]);
    935   expect(events).toEqual([]);
    936   expect(requests).toEqual([]);
    937 });
    938 
    939 test('CR007 pending actual reply EVENT plus route close settles stopped and preserves physical cleanup', async ({
    940   page
    941 }) => {
    942   await ready(page);
    943   await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
    944   holdPrivateAck = true;
    945   await page.evaluate(() => {
    946     window.cr007DelayPrivateClose = true;
    947     window.cr007PendingSend = window.hcp104Fixture.send();
    948   });
    949   await expect.poll(() => events.length).toBe(1);
    950   await page.evaluate(() => window.hcp104Fixture.closeComposer());
    951   expect(await page.evaluate(() => window.cr007PendingSend)).toEqual({
    952     status: 'stopped'
    953   });
    954   expect(
    955     await page.evaluate(() => window.hcp104Fixture.snapshot())
    956   ).toBeUndefined();
    957   expect(
    958     await page.evaluate(() => window.hcp104Fixture.text())
    959   ).toBeUndefined();
    960   expect(events).toHaveLength(1);
    961   expect(
    962     await page.evaluate(() => window.cr007DelayedCloses?.length ?? 0)
    963   ).toBeGreaterThan(0);
    964   await page.evaluate(() => {
    965     window.cr007DelayPrivateClose = false;
    966     for (const release of window.cr007DelayedCloses ?? []) release();
    967   });
    968 });