app

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

listing-operation-view.spec.ts (14844B)


      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 { WebSocketServer } from 'ws';
      7 import { createStaticHarness } from '../integration/harness/static.ts';
      8 import type * as Fixture from './harness/listing-operation-view.ts';
      9 declare global {
     10   interface Window {
     11     hcp114: typeof Fixture;
     12     hcp114Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     13     hcp114Reopened: Awaited<ReturnType<typeof Fixture.reopen>>;
     14   }
     15 }
     16 const first = 'wss://discovery.example.org',
     17   second = 'wss://second.example.org';
     18 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     19   sockets: WebSocketServer,
     20   bundle: string,
     21   endpoint: string;
     22 let frames: { origin: string; message: unknown[] }[] = [];
     23 let stored: Record<string, unknown> | undefined;
     24 let responses = new Map<
     25   string,
     26   'accepted' | 'refused' | 'literal-timeout' | 'silent' | 'held'
     27 >();
     28 let holdReadback = false,
     29   observeExact = true;
     30 test.beforeAll(async () => {
     31   server = await createStaticHarness();
     32   sockets = new WebSocketServer({
     33     host: '127.0.0.1',
     34     port: 0,
     35     maxPayload: 262144
     36   });
     37   await once(sockets, 'listening');
     38   const address = sockets.address();
     39   if (!address || typeof address === 'string')
     40     throw Error('loopback unavailable');
     41   endpoint = 'ws://127.0.0.1:' + address.port;
     42   sockets.on('connection', (socket, request) => {
     43     const origin = request.url === '/b' ? second : first;
     44     socket.on('message', (bytes) => {
     45       const raw = Buffer.isBuffer(bytes)
     46         ? bytes.toString()
     47         : Array.isArray(bytes)
     48           ? Buffer.concat(bytes).toString()
     49           : Buffer.from(bytes).toString();
     50       const message = JSON.parse(raw) as unknown[];
     51       frames.push({ origin, message });
     52       if (message[0] === 'EVENT') {
     53         stored = message[1] as Record<string, unknown>;
     54         const response = responses.get(origin) ?? 'accepted';
     55         if (response === 'held' || response === 'silent') return;
     56         socket.send(
     57           JSON.stringify([
     58             'OK',
     59             stored.id,
     60             response === 'accepted',
     61             response === 'accepted'
     62               ? ''
     63               : response === 'literal-timeout'
     64                 ? 'Timeout'
     65                 : 'blocked: controlled refusal'
     66           ])
     67         );
     68       } else if (message[0] === 'REQ' && !holdReadback) {
     69         if (stored && observeExact)
     70           socket.send(JSON.stringify(['EVENT', message[1], stored]));
     71         socket.send(JSON.stringify(['EOSE', message[1]]));
     72       }
     73     });
     74   });
     75   const built = await build({
     76     configFile: false,
     77     plugins: [svelte({ configFile: false })],
     78     resolve: { conditions: ['browser'] },
     79     logLevel: 'silent',
     80     build: {
     81       write: false,
     82       minify: false,
     83       lib: {
     84         entry: fileURLToPath(
     85           new URL('./harness/listing-operation-view.ts', import.meta.url)
     86         ),
     87         name: 'hcp114',
     88         formats: ['iife']
     89       }
     90     }
     91   });
     92   const output = Array.isArray(built) ? built[0] : built;
     93   if (!('output' in output)) throw Error('bundle unavailable');
     94   const chunks = output.output.filter((row) => row.type === 'chunk');
     95   expect(chunks).toHaveLength(1);
     96   bundle = chunks[0].code;
     97 });
     98 test.afterAll(async () => {
     99   for (const socket of sockets.clients) socket.terminate();
    100   await new Promise<void>((resolve) => sockets.close(() => resolve()));
    101   await server.close();
    102 });
    103 test.beforeEach(async ({ page }) => {
    104   frames = [];
    105   stored = undefined;
    106   responses = new Map();
    107   holdReadback = false;
    108   observeExact = true;
    109   await page.addInitScript(
    110     ({ endpoint }) => {
    111       const Native = window.WebSocket;
    112       class LoopbackSocket extends Native {
    113         constructor(url: string | URL, protocols?: string | string[]) {
    114           const role =
    115             String(url) === 'wss://discovery.example.org/'
    116               ? '/a'
    117               : String(url) === 'wss://second.example.org/'
    118                 ? '/b'
    119                 : undefined;
    120           if (!role) throw Error('unfrozen controlled target');
    121           super(endpoint + role, protocols);
    122         }
    123       }
    124       window.WebSocket = LoopbackSocket;
    125     },
    126     { endpoint }
    127   );
    128   await page.goto(server.url + '/search');
    129   await page.addScriptTag({ content: bundle });
    130   await page.evaluate(async () => {
    131     window.hcp114Fixture = await window.hcp114.createFixture();
    132   });
    133 });
    134 test.afterEach(async ({ page }) => {
    135   if (!page.isClosed())
    136     await page.evaluate(() => {
    137       window.hcp114Reopened?.close();
    138       window.hcp114Fixture?.close();
    139     });
    140 });
    141 
    142 test('HCP114 unsigned prepared source is local and renders no acceptance or edit permission', async ({
    143   page
    144 }) => {
    145   const v = await page.evaluate(() => window.hcp114Fixture.renderView());
    146   expect(v).toMatchObject({
    147     state: 'prepared',
    148     artifact: 'unsigned',
    149     acceptanceCount: 0,
    150     readbackCount: 0,
    151     localSource: 'read-only'
    152   });
    153   expect(
    154     await page.evaluate(() => window.hcp114Fixture.counts())
    155   ).toMatchObject({ signs: 0 });
    156   expect(frames).toEqual([]);
    157   await expect(page.locator('#hcp114-operation')).toContainText(
    158     'Saved in this browser'
    159   );
    160   await expect(page.locator('#hcp114-operation')).not.toContainText(
    161     'globally published'
    162   );
    163 });
    164 test('HCP114 genuine live signing differs from unsigned uncertainty and actual restart never resets it fresh', async ({
    165   page
    166 }) => {
    167   await page.evaluate(() => window.hcp114Fixture.holdSigning());
    168   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    169     state: 'signing',
    170     artifact: 'unsigned'
    171   });
    172   expect(
    173     await page.evaluate(() => window.hcp114Fixture.show(false))
    174   ).toMatchObject({ state: 'unknown' });
    175   await page.evaluate(() => window.hcp114Fixture.stopSigning());
    176   const row = await page.evaluate(() => window.hcp114Fixture.row());
    177   expect(row.revision).toBe(1);
    178   expect(row.artifact).toBeNull();
    179   await page.evaluate(() => window.hcp114Fixture.close());
    180   await page.reload();
    181   await page.addScriptTag({ content: bundle });
    182   const result = await page.evaluate(
    183     async ({ owner, command }) => {
    184       window.hcp114Reopened = await window.hcp114.reopen(owner, command);
    185       return window.hcp114Reopened.result;
    186     },
    187     { owner: row.owner, command: row.id }
    188   );
    189   expect(result).toMatchObject({
    190     state: 'unknown',
    191     artifact: 'unsigned',
    192     revision: 1
    193   });
    194   expect(await page.evaluate(() => window.hcp114Reopened.counts())).toEqual({
    195     signs: 0
    196   });
    197   expect(frames).toEqual([]);
    198 });
    199 test('HCP114 copied disclosure cannot present original local evidence', async ({
    200   page
    201 }) => {
    202   await page.evaluate(() => window.hcp114Fixture.signed());
    203   await page.evaluate(() => window.hcp114Fixture.renderView(true));
    204   expect(
    205     await page.evaluate(() => window.hcp114Fixture.copiedSnapshot())
    206   ).toBeUndefined();
    207   await expect(page.locator('#hcp114-operation')).toContainText(
    208     'outcome is unknown'
    209   );
    210   await expect(page.locator('#hcp114-operation')).not.toContainText(
    211     'Relay acceptance recorded'
    212   );
    213   expect(frames).toEqual([]);
    214 });
    215 test('HCP114 actual SDK acceptance by one of two targets is partial and does not invent readback', async ({
    216   page
    217 }) => {
    218   observeExact = false;
    219   responses.set(second, 'refused');
    220   expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
    221     'needs_action'
    222   );
    223   const v = await page.evaluate(() => window.hcp114Fixture.renderView());
    224   expect(v).toMatchObject({
    225     state: 'partial',
    226     acceptanceCount: 1,
    227     readbackCount: 0,
    228     needsAction: true
    229   });
    230   expect(frames.filter((x) => x.message[0] === 'EVENT')).toHaveLength(2);
    231   await expect(page.locator('#hcp114-operation')).toContainText(
    232     'Relay acceptance recorded for 1 of 2 targets.'
    233   );
    234   await expect(page.locator('#hcp114-operation')).toContainText(
    235     'Exact read-back recorded for 0 of 2 targets.'
    236   );
    237 });
    238 test('HCP114 actual SDK exact readback without an ACK stays separate from acceptance', async ({
    239   page
    240 }) => {
    241   responses.set(first, 'silent');
    242   responses.set(second, 'refused');
    243   expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
    244     'needs_action'
    245   );
    246   const v = await page.evaluate(() => window.hcp114Fixture.show());
    247   expect(v).toMatchObject({
    248     state: 'partial',
    249     acceptanceCount: 0,
    250     readbackCount: 1
    251   });
    252   expect(v && 'targets' in v && v.targets[0]).toMatchObject({
    253     accepted: false,
    254     readback: 'confirmed',
    255     latestOutcome: 'timed_out'
    256   });
    257 });
    258 test('HCP114 actual all-target ACKs alone are accepted with exact readback still unobserved', async ({
    259   page
    260 }) => {
    261   observeExact = false;
    262   expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
    263     'completed'
    264   );
    265   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    266     state: 'accepted',
    267     acceptanceCount: 2,
    268     readbackCount: 0
    269   });
    270 });
    271 test('HCP114 actual all-target readback is distinct from a browser-only signed artifact', async ({
    272   page
    273 }) => {
    274   await page.evaluate(() => window.hcp114Fixture.signed());
    275   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    276     state: 'prepared',
    277     artifact: 'signed',
    278     acceptanceCount: 0,
    279     readbackCount: 0
    280   });
    281   expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
    282     'completed'
    283   );
    284   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    285     state: 'readback',
    286     acceptanceCount: 2,
    287     readbackCount: 2
    288   });
    289 });
    290 test('HCP114 controlled later Stop and refusal retain earlier named acceptance and readback facts', async ({
    291   page
    292 }) => {
    293   expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
    294     'completed'
    295   );
    296   await page.evaluate(async () => {
    297     await window.hcp114Fixture.evidence('stopped', 0, false);
    298     await window.hcp114Fixture.evidence('refused', 1, false);
    299   });
    300   const v = await page.evaluate(() => window.hcp114Fixture.show());
    301   expect(v).toMatchObject({
    302     acceptanceCount: 2,
    303     readbackCount: 2,
    304     needsAction: true
    305   });
    306   expect(v && 'targets' in v && v.targets.map((t) => t.latestOutcome)).toEqual([
    307     'stopped',
    308     'refused'
    309   ]);
    310 });
    311 test('HCP114 contradictory native record fields fail closed rather than becoming prepared', async ({
    312   page
    313 }) => {
    314   await page.evaluate(() => window.hcp114Fixture.signed());
    315   await page.evaluate(() =>
    316     window.hcp114Fixture.evidence('accepted', 0, false)
    317   );
    318   await page.evaluate(async () => {
    319     const row = await window.hcp114Fixture.row();
    320     await window.hcp114Fixture.replace({ ...row, artifact: null });
    321   });
    322   expect(await page.evaluate(() => window.hcp114Fixture.show())).toEqual({
    323     status: 'unavailable'
    324   });
    325   expect(frames).toEqual([]);
    326 });
    327 test('HCP114 retained prototype capture remains available after draft cleanup but external-head records stay read-only', async ({
    328   page
    329 }) => {
    330   await page.evaluate(() => window.hcp114Fixture.signed());
    331   await page.evaluate(() => window.hcp114Fixture.removeDraft());
    332   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    333     localSource: 'retained-prototype'
    334   });
    335   await page.evaluate(() => window.hcp114Fixture.externalSource());
    336   expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
    337     localSource: 'read-only'
    338   });
    339   expect(frames).toEqual([]);
    340 });
    341 test('HCP114 Close and identity invalidation retire original presentation handles', async ({
    342   page
    343 }) => {
    344   await page.evaluate(() => window.hcp114Fixture.signed());
    345   await page.evaluate(() => window.hcp114Fixture.renderView());
    346   await page.evaluate(() => window.hcp114Fixture.logout());
    347   expect(
    348     await page.evaluate(() => window.hcp114Fixture.snapshot())
    349   ).toBeUndefined();
    350   await expect(page.locator('#hcp114-operation')).not.toContainText(
    351     'Relay acceptance recorded'
    352   );
    353   await page.evaluate(() => window.hcp114Fixture.closeView());
    354   expect(frames).toEqual([]);
    355 });
    356 
    357 test('HCP114 an explicit fresh native read supersedes the earlier presentation snapshot', async ({
    358   page
    359 }) => {
    360   await page.evaluate(() => window.hcp114Fixture.signed());
    361   await page.evaluate(() => window.hcp114Fixture.show());
    362   expect(
    363     await page.evaluate(() => window.hcp114Fixture.supersede())
    364   ).toBeUndefined();
    365   expect(frames).toEqual([]);
    366 });
    367 test('HCP114 logout after actual native transaction completion fences a held application acknowledgement', async ({
    368   page
    369 }) => {
    370   await page.evaluate(() => window.hcp114Fixture.signed());
    371   expect(
    372     await page.evaluate(() => window.hcp114Fixture.readWhileLogout())
    373   ).toEqual({ result: { status: 'unavailable' }, nativeCompletions: 1 });
    374   expect(frames).toEqual([]);
    375 });
    376 
    377 test('HCP114 retained mounted signing view retires on original Stop without another native read', async ({
    378   page
    379 }) => {
    380   await page.evaluate(() => window.hcp114Fixture.holdSigning());
    381   expect(
    382     await page.evaluate(() => window.hcp114Fixture.renderView())
    383   ).toMatchObject({ state: 'signing' });
    384   await page.evaluate(() => window.hcp114Fixture.stopSigning());
    385   expect(
    386     await page.evaluate(() => window.hcp114Fixture.snapshot())
    387   ).toBeUndefined();
    388   await expect(page.locator('#hcp114-operation')).toContainText(
    389     'The outcome is unknown'
    390   );
    391   await expect(page.locator('#hcp114-operation')).not.toContainText(
    392     'Waiting for your extension'
    393   );
    394   expect(frames).toEqual([]);
    395 });
    396 test('HCP114 retained mounted signing view retires on signer settlement without another native read', async ({
    397   page
    398 }) => {
    399   await page.evaluate(() => window.hcp114Fixture.holdSigning());
    400   expect(
    401     await page.evaluate(() => window.hcp114Fixture.renderView())
    402   ).toMatchObject({ state: 'signing' });
    403   expect(await page.evaluate(() => window.hcp114Fixture.releaseSigning())).toBe(
    404     'prepared'
    405   );
    406   expect(
    407     await page.evaluate(() => window.hcp114Fixture.snapshot())
    408   ).toBeUndefined();
    409   await expect(page.locator('#hcp114-operation')).toContainText(
    410     'The outcome is unknown'
    411   );
    412   await expect(page.locator('#hcp114-operation')).not.toContainText(
    413     'Waiting for your extension'
    414   );
    415   expect(frames).toEqual([]);
    416 });
    417 
    418 test('HCP114 notification excludes original-token listeners subscribed during notification', async ({
    419   page
    420 }) => {
    421   await page.evaluate(() => window.hcp114Fixture.holdSigning());
    422   expect(
    423     await page.evaluate(() => window.hcp114Fixture.observerAddition())
    424   ).toEqual({ first: 1, added: 0 });
    425   expect(frames).toEqual([]);
    426 });
    427 test('HCP114 notification makes original-token reentrant Stop idempotent', async ({
    428   page
    429 }) => {
    430   await page.evaluate(() => window.hcp114Fixture.holdSigning());
    431   expect(
    432     await page.evaluate(() => window.hcp114Fixture.observerStop())
    433   ).toEqual({ first: 1 });
    434   expect(frames).toEqual([]);
    435 });