app

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

revise-listing.spec.ts (19740B)


      1 import { expect, test } 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 { writeFile } from 'node:fs/promises';
      7 import { WebSocketServer } from 'ws';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/revise-listing.ts';
     10 import type { NostrEvent } from 'applesauce-core/helpers';
     11 declare global {
     12   interface Window {
     13     hcp119: typeof Fixture;
     14     hcp119Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     15     hcp119Second: Awaited<ReturnType<typeof Fixture.openSecondEditor>>;
     16     hcp119OriginalSign(input: Fixture.ControlledSignInput): Promise<NostrEvent>;
     17   }
     18 }
     19 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     20   sockets: WebSocketServer,
     21   endpoint: string,
     22   bundle: string;
     23 let event: NostrEvent | undefined,
     24   partial = false,
     25   effects: NostrEvent[] = [];
     26 let tabs: import('@playwright/test').Page[] = [];
     27 test.beforeAll(async () => {
     28   server = await createStaticHarness();
     29   sockets = new WebSocketServer({
     30     host: '127.0.0.1',
     31     port: 0,
     32     maxPayload: 262144
     33   });
     34   await once(sockets, 'listening');
     35   const address = sockets.address();
     36   if (!address || typeof address === 'string') throw Error('loopback missing');
     37   endpoint = 'ws://127.0.0.1:' + address.port;
     38   sockets.on('connection', (socket) =>
     39     socket.on('message', (bytes) => {
     40       const raw = Buffer.isBuffer(bytes)
     41         ? bytes
     42         : Array.isArray(bytes)
     43           ? Buffer.concat(bytes)
     44           : Buffer.from(bytes);
     45       const frame = JSON.parse(raw.toString()) as unknown[];
     46       if (frame[0] === 'EVENT') {
     47         event = frame[1] as NostrEvent;
     48         effects.push(event);
     49         socket.send(JSON.stringify(['OK', event.id, true, '']));
     50         return;
     51       }
     52       if (frame[0] !== 'REQ') return;
     53       const filters = frame.slice(2) as {
     54         kinds?: number[];
     55         ids?: string[];
     56         authors?: string[];
     57         '#d'?: string[];
     58       }[];
     59       if (
     60         event &&
     61         filters.some(
     62           (filter) =>
     63             (!filter.kinds || filter.kinds.includes(event!.kind)) &&
     64             (!filter.ids || filter.ids.includes(event!.id)) &&
     65             (!filter.authors || filter.authors.includes(event!.pubkey)) &&
     66             (!filter['#d'] ||
     67               filter['#d'].includes(
     68                 event!.tags.find((tag) => tag[0] === 'd')?.[1] ?? ''
     69               ))
     70         )
     71       )
     72         socket.send(JSON.stringify(['EVENT', frame[1], event]));
     73       if (!(partial && filters.some((filter) => filter.kinds?.includes(5))))
     74         socket.send(JSON.stringify(['EOSE', frame[1]]));
     75     })
     76   );
     77   const built = await build({
     78     configFile: false,
     79     plugins: [svelte({ configFile: false })],
     80     resolve: { conditions: ['browser'] },
     81     logLevel: 'silent',
     82     build: {
     83       write: false,
     84       minify: false,
     85       lib: {
     86         entry: fileURLToPath(
     87           new URL('./harness/revise-listing.ts', import.meta.url)
     88         ),
     89         name: 'hcp119',
     90         formats: ['iife']
     91       }
     92     }
     93   });
     94   const result = Array.isArray(built) ? built[0] : built;
     95   if (!('output' in result)) throw Error('actual fixture bundle missing');
     96   const chunks = result.output.filter((row) => row.type === 'chunk');
     97   expect(chunks).toHaveLength(1);
     98   bundle = chunks[0].code;
     99 });
    100 test.afterAll(async () => {
    101   for (const socket of sockets?.clients ?? []) socket.terminate();
    102   if (sockets)
    103     await new Promise<void>((resolve, reject) =>
    104       sockets.close((error) => (error ? reject(error) : resolve()))
    105     );
    106   await server?.close();
    107 });
    108 test.beforeEach(async ({ page }) => {
    109   tabs = [];
    110   event = undefined;
    111   partial = false;
    112   effects = [];
    113   await page.addInitScript((endpoint) => {
    114     const Native = window.WebSocket;
    115     window.WebSocket = class extends Native {
    116       constructor(url: string | URL, protocols?: string | string[]) {
    117         if (
    118           ![
    119             'wss://discovery.example.org',
    120             'wss://inbox.example.org',
    121             'wss://second.example.org'
    122           ].includes(new URL(url.toString()).origin)
    123         )
    124           throw Error('no live relay permission');
    125         super(endpoint, protocols);
    126       }
    127     };
    128   }, endpoint);
    129   await page.goto(server.url + '/search');
    130   await page.addScriptTag({ content: bundle });
    131   event = await page.evaluate(async () => {
    132     window.hcp119Fixture = await window.hcp119.createFixture();
    133     return window.hcp119Fixture.event;
    134   });
    135 });
    136 test.afterEach(async ({ page }) => {
    137   for (const tab of tabs) {
    138     if (!tab.isClosed()) {
    139       await tab.evaluate(async () => {
    140         await window.hcp119Second?.close();
    141       });
    142       await tab.close();
    143     }
    144   }
    145   await page.evaluate(async () => {
    146     await window.hcp119Fixture?.close();
    147   });
    148 });
    149 async function editor(page: import('@playwright/test').Page) {
    150   await page.evaluate(() => window.hcp119Fixture.renderEditor());
    151   await expect(page.locator('#listing-title')).not.toHaveAttribute(
    152     'readonly',
    153     ''
    154   );
    155 }
    156 async function review(page: import('@playwright/test').Page) {
    157   await editor(page);
    158   await page.locator('#listing-title').fill('Actual revised carrots');
    159   await page
    160     .locator('#listing-description')
    161     .fill('Complete exact revised public description.');
    162   await page
    163     .getByRole('button', { name: 'Review changes', exact: true })
    164     .click();
    165   await expect(
    166     page.getByRole('region', { name: 'Public listing review' })
    167   ).toBeVisible();
    168 }
    169 test('HCP119 exact review retains coordinate/published_at and performs no reservation sign or send', async ({
    170   page
    171 }) => {
    172   const before = await page.evaluate(() => window.hcp119Fixture.counts());
    173   await review(page);
    174   const region = page.getByRole('region', { name: 'Public listing review' });
    175   await expect(region).toContainText(
    176     'Complete exact revised public description.'
    177   );
    178   await expect(region).toContainText(
    179     await page.evaluate(() => window.hcp119Fixture.naddr)
    180   );
    181   expect(await page.evaluate(() => window.hcp119Fixture.counts())).toEqual(
    182     before
    183   );
    184   expect(
    185     await page.evaluate(() => window.hcp119Fixture.operations())
    186   ).toHaveLength(1);
    187   expect(effects).toHaveLength(0);
    188   await page.getByRole('button', { name: 'Edit details', exact: true }).click();
    189   await expect(page.locator('#listing-title')).toHaveValue(
    190     'Actual revised carrots'
    191   );
    192   await expect(page.locator('#listing-title')).toBeFocused();
    193 });
    194 test('HCP119 explicit Publish changes persists one genuine signed update with original coordinate and durable target facts', async ({
    195   page
    196 }) => {
    197   const base = await page.evaluate(() => window.hcp119Fixture.event);
    198   const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
    199   await review(page);
    200   await page
    201     .getByRole('button', { name: 'Publish changes', exact: true })
    202     .click();
    203   await expect.poll(() => effects.length).toBeGreaterThan(0);
    204   await expect
    205     .poll(() =>
    206       page.evaluate(
    207         async () =>
    208           (await window.hcp119Fixture.operations())
    209             .find(
    210               (row) => row.artifact?.eventId !== window.hcp119Fixture.event.id
    211             )
    212             ?.receipts.filter((fact) => fact.readbackWire !== null).length ?? 0
    213       )
    214     )
    215     .toBe(1);
    216   const rows = await page.evaluate(() => window.hcp119Fixture.operations());
    217   expect(rows).toHaveLength(2);
    218   const revised = rows.find((row) => row.artifact?.eventId !== base.id);
    219   expect(revised?.capture.targets).toEqual(['wss://discovery.example.org']);
    220   expect(revised?.artifact).toBeTruthy();
    221   const wire = JSON.parse(revised!.artifact!.wire) as NostrEvent;
    222   expect(wire.kind).toBe(30402);
    223   expect(wire.pubkey).toBe(base.pubkey);
    224   expect(wire.tags.find((tag) => tag[0] === 'd')).toEqual(
    225     base.tags.find((tag) => tag[0] === 'd')
    226   );
    227   expect(wire.tags.find((tag) => tag[0] === 'published_at')).toEqual(
    228     base.tags.find((tag) => tag[0] === 'published_at')
    229   );
    230   expect(wire.created_at).toBeGreaterThan(base.created_at);
    231   expect(wire.created_at - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(
    232     300
    233   );
    234   expect(
    235     effects.every((effect) => effect.id === wire.id && effect.kind === 30402)
    236   ).toBe(true);
    237   expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
    238     before + 1
    239   );
    240   expect(
    241     rows.find((row) => row.artifact?.eventId === base.id)?.artifact?.wire
    242   ).toBe(JSON.stringify(base));
    243   await page.evaluate(() => window.hcp119Fixture.open());
    244   await expect
    245     .poll(() => page.evaluate(() => window.hcp119Fixture.snapshot()?.status))
    246     .toBe('ready');
    247   const reopened = await page.evaluate(() => window.hcp119Fixture.snapshot());
    248   expect(reopened?.sourceEventId).toBe(wire.id);
    249   expect(reopened?.form.title).toBe('Actual revised carrots');
    250   expect(reopened?.publishedAtSeconds).toBe(
    251     Number(base.tags.find((tag) => tag[0] === 'published_at')![1])
    252   );
    253 });
    254 test('HCP119 separate sold consequence review is not payment or stock reservation and emits only reviewed kind30402', async ({
    255   page
    256 }) => {
    257   await editor(page);
    258   const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
    259   await page.getByText('Other listing actions', { exact: true }).click();
    260   await page.getByRole('button', { name: 'Mark as sold', exact: true }).click();
    261   await expect(
    262     page.getByRole('region', { name: 'Confirm sold update' })
    263   ).toContainText('not a payment or stock reservation receipt');
    264   expect(effects).toHaveLength(0);
    265   await page
    266     .getByRole('button', { name: 'Review sold update', exact: true })
    267     .click();
    268   await expect(
    269     page.getByRole('region', { name: 'Public listing review' })
    270   ).toContainText('Sold');
    271   expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
    272     before
    273   );
    274   await page
    275     .getByRole('button', { name: 'Publish sold update', exact: true })
    276     .click();
    277   await expect.poll(() => effects.length).toBeGreaterThan(0);
    278   expect(
    279     effects.every(
    280       (effect) =>
    281         effect.kind === 30402 &&
    282         effect.tags.some((tag) => tag[0] === 'status' && tag[1] === 'sold')
    283     )
    284   ).toBe(true);
    285   expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
    286     before + 1
    287   );
    288 });
    289 test('HCP119 cancel sold confirmation preserves proposal and performs no effect', async ({
    290   page
    291 }) => {
    292   await editor(page);
    293   await page.locator('#listing-title').fill('Keep my exact proposal');
    294   const before = await page.evaluate(() => window.hcp119Fixture.counts());
    295   await page.getByText('Other listing actions', { exact: true }).click();
    296   await page.getByRole('button', { name: 'Mark as sold', exact: true }).click();
    297   await page.getByRole('button', { name: 'Keep editing', exact: true }).click();
    298   await expect(page.locator('#listing-title')).toHaveValue(
    299     'Keep my exact proposal'
    300   );
    301   expect(await page.evaluate(() => window.hcp119Fixture.counts())).toEqual(
    302     before
    303   );
    304   expect(effects).toHaveLength(0);
    305 });
    306 test('HCP119 independently changed head fences an already reviewed proposal before publication', async ({
    307   page
    308 }) => {
    309   await review(page);
    310   event = await page.evaluate(() => window.hcp119Fixture.competing());
    311   const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
    312   await page.evaluate(() => window.hcp119Fixture.lookupAgain());
    313   await expect(
    314     page.getByRole('button', { name: 'Publish changes', exact: true })
    315   ).toHaveCount(0);
    316   await expect(page.locator('#listing-title')).toHaveValue(
    317     'Actual revised carrots'
    318   );
    319   await expect(page.locator('#listing-title')).toHaveAttribute('readonly', '');
    320   expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
    321     before
    322   );
    323   expect(effects).toHaveLength(0);
    324 });
    325 test('HCP119 incomplete critical deletion coverage cannot expose revision or sold actions', async ({
    326   page
    327 }) => {
    328   partial = true;
    329   await page.evaluate(() => window.hcp119Fixture.renderEditor());
    330   await expect(page.locator('#listing-title')).toHaveAttribute('readonly', '');
    331   await expect(
    332     page.getByRole('button', { name: /Review changes|Mark as sold/ })
    333   ).toHaveCount(0);
    334   expect(effects).toHaveLength(0);
    335 });
    336 test('HCP119 actual backward wall-clock change fences the captured review without inventing a later timestamp', async ({
    337   page
    338 }) => {
    339   await review(page);
    340   const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
    341   await page.evaluate(() => {
    342     const actualNow = Date.now;
    343     Date.now = () => actualNow() - 301000;
    344   });
    345   await expect(
    346     page.getByRole('button', { name: 'Publish changes', exact: true })
    347   ).toHaveCount(0);
    348   await expect(page.locator('#listing-title')).toHaveValue(
    349     'Actual revised carrots'
    350   );
    351   expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
    352     before
    353   );
    354   expect(
    355     await page.evaluate(() => window.hcp119Fixture.operations())
    356   ).toHaveLength(1);
    357   expect(effects).toHaveLength(0);
    358 });
    359 for (const width of [320, 1024])
    360   test(`HCP119 ${width}px exact revision review and sold confirmation remain readable`, async ({
    361     page
    362   }) => {
    363     await page.setViewportSize({ width, height: 900 });
    364     await review(page);
    365     await expect(
    366       page.getByRole('region', { name: 'Public listing review' })
    367     ).toContainText('Actual revised carrots');
    368     expect(
    369       await page.evaluate(
    370         () => document.documentElement.scrollWidth <= window.innerWidth
    371       )
    372     ).toBe(true);
    373     await page
    374       .getByRole('button', { name: 'Edit details', exact: true })
    375       .click();
    376     await page.getByText('Other listing actions', { exact: true }).click();
    377     await page
    378       .getByRole('button', { name: 'Mark as sold', exact: true })
    379       .click();
    380     await expect(
    381       page.getByRole('region', { name: 'Confirm sold update' })
    382     ).toBeVisible();
    383     expect(
    384       await page.evaluate(
    385         () => document.documentElement.scrollWidth <= window.innerWidth
    386       )
    387     ).toBe(true);
    388     expect(effects).toHaveLength(0);
    389   });
    390 
    391 test('HCP119 two original editors cannot reserve against an unresolved retained coordinate capture', async ({
    392   page
    393 }) => {
    394   await review(page);
    395   const first = page.locator('#hcp118-conflict');
    396   const tab = await page.context().newPage();
    397   tabs.push(tab);
    398   const errors: string[] = [];
    399   tab.on('pageerror', (error) => errors.push(error.message));
    400   const source = await page.evaluate(() => ({
    401     owner: window.hcp119Fixture.owner,
    402     naddr: window.hcp119Fixture.naddr
    403   }));
    404   await tab.exposeFunction(
    405     'hcp119OriginalSign',
    406     async (input: Fixture.ControlledSignInput) =>
    407       await page.evaluate(
    408         (input) => window.hcp119Fixture.signOriginal(input),
    409         input
    410       )
    411   );
    412   await tab.addInitScript(
    413     ({ endpoint, owner }) => {
    414       const Native = window.WebSocket;
    415       window.WebSocket = class extends Native {
    416         constructor(url: string | URL, protocols?: string | string[]) {
    417           if (
    418             ![
    419               'wss://discovery.example.org',
    420               'wss://inbox.example.org',
    421               'wss://second.example.org'
    422             ].includes(new URL(url.toString()).origin)
    423           )
    424             throw Error('no live relay permission');
    425           super(endpoint, protocols);
    426         }
    427       };
    428       Object.defineProperty(window, 'nostr', {
    429         configurable: true,
    430         value: {
    431           getPublicKey: () => Promise.resolve(owner),
    432           signEvent: (input: Fixture.ControlledSignInput) =>
    433             window.hcp119OriginalSign(input)
    434         }
    435       });
    436     },
    437     { endpoint, owner: source.owner }
    438   );
    439   await tab.goto(server.url + '/search');
    440   await tab.addScriptTag({ content: bundle });
    441   await tab.evaluate(async ({ owner, naddr }) => {
    442     window.hcp119Second = await window.hcp119.openSecondEditor(owner, naddr);
    443   }, source);
    444   const second = tab.locator('#hcp119-second');
    445   await expect(second.locator('#listing-title')).not.toHaveAttribute(
    446     'readonly',
    447     ''
    448   );
    449   await second.locator('#listing-title').fill('Second tab proposed carrots');
    450   await second
    451     .getByRole('button', { name: 'Review changes', exact: true })
    452     .click();
    453   await expect(
    454     second.getByRole('region', { name: 'Public listing review' })
    455   ).toBeVisible();
    456   await page.evaluate(() => window.hcp119Fixture.refuseNextSignature());
    457   await first
    458     .getByRole('button', { name: 'Publish changes', exact: true })
    459     .click();
    460   await expect(
    461     first.getByText(
    462       'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.',
    463       { exact: true }
    464     )
    465   ).toBeVisible();
    466   expect(await page.evaluate(() => window.hcp119Fixture.signRequests())).toBe(
    467     1
    468   );
    469   expect(
    470     await page.evaluate(() => window.hcp119Fixture.operations())
    471   ).toHaveLength(2);
    472   expect(effects).toHaveLength(0);
    473   await second
    474     .getByRole('button', { name: 'Publish changes', exact: true })
    475     .click();
    476   // Wait for either genuine settled outcome, then assert the exact native rows.
    477   // The assertion never equates a still-pending request with successful fencing.
    478   await writeFile(
    479     test.info().outputPath('actual-second-tab-early-public-state.json'),
    480     JSON.stringify({
    481       phase: 'EARLY_AFTER_ACTION_NO_SETTLED_OR_ASSERTION_CREDIT',
    482       errors,
    483       secondText: await second.innerText(),
    484       operations: await page.evaluate(() => window.hcp119Fixture.operations()),
    485       signRequests: await page.evaluate(() =>
    486         window.hcp119Fixture.signRequests()
    487       ),
    488       effects
    489     })
    490   );
    491   try {
    492     await expect
    493       .poll(
    494         async () =>
    495           errors.length +
    496           (await second
    497             .getByText(
    498               /Relay acceptance recorded for|The update did not complete\.|Supported local listing values are not available for editing/
    499             )
    500             .count())
    501       )
    502       .toBeGreaterThan(0);
    503   } finally {
    504     const actualState = JSON.stringify({
    505       errors,
    506       secondText: await second.innerText(),
    507       publishingButtons: await second
    508         .getByRole('button', { name: 'Publishing update', exact: true })
    509         .count(),
    510       operations: await page.evaluate(() => window.hcp119Fixture.operations()),
    511       signRequests: await page.evaluate(() =>
    512         window.hcp119Fixture.signRequests()
    513       ),
    514       effects
    515     });
    516     await writeFile(
    517       test.info().outputPath('actual-second-tab-public-state.json'),
    518       actualState
    519     );
    520     await test.info().attach('actual-second-tab-public-state', {
    521       path: test.info().outputPath('actual-second-tab-public-state.json'),
    522       contentType: 'application/json'
    523     });
    524   }
    525   expect(errors).toEqual([]);
    526   expect(
    527     await page.evaluate(() => window.hcp119Fixture.operations())
    528   ).toHaveLength(2);
    529   expect(await page.evaluate(() => window.hcp119Fixture.signRequests())).toBe(
    530     1
    531   );
    532   expect(effects).toHaveLength(0);
    533   await expect(
    534     second.getByRole('region', { name: 'Public listing review' })
    535   ).toContainText('Second tab proposed carrots');
    536 });
    537 
    538 test('HCP119 a retained pending signature fences a fresh editor without adopting another local capture', async ({
    539   page
    540 }) => {
    541   await review(page);
    542   await page.evaluate(() => window.hcp119Fixture.holdNextSignature());
    543   await page
    544     .getByRole('button', { name: 'Publish changes', exact: true })
    545     .click();
    546   await expect
    547     .poll(() => page.evaluate(() => window.hcp119Fixture.signRequests()))
    548     .toBe(1);
    549   expect(
    550     await page.evaluate(() => window.hcp119Fixture.open())
    551   ).toBeUndefined();
    552   expect(effects).toHaveLength(0);
    553   await page.evaluate(() => window.hcp119Fixture.releaseSignature());
    554   await expect.poll(() => effects.length).toBeGreaterThan(0);
    555 });