commit 045ac2d10bf7b56786751412ca467a31eb8c4428
parent 8d86e7f7c9696c88aeb98549cd92ce28e9818ff7
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 07:10:32 +0000
publishing: present public operation facts and local readback (HCP-114)
Diffstat:
8 files changed, 1485 insertions(+), 16 deletions(-)
diff --git a/web/src/lib/components/OperationStatus.svelte b/web/src/lib/components/OperationStatus.svelte
@@ -1,28 +1,100 @@
<script lang="ts">
import Notice from './Notice.svelte';
import {
+ listingOperationSnapshot,
+ subscribeListingOperationView,
+ type ListingOperationView
+ } from '../publishing/listing-operation-view.ts';
+ import {
statusCopy,
receiptCopy,
type OperationFact,
type TargetReceipt
} from '../presentation/status-copy';
let {
- fact,
- receipts = []
- }: { fact: OperationFact; receipts?: readonly TargetReceipt[] } = $props();
- const summary = $derived(statusCopy(fact));
+ fact = 'unknown',
+ receipts = [],
+ publicOperation
+ }: {
+ fact?: OperationFact;
+ receipts?: readonly TargetReceipt[];
+ publicOperation?: ListingOperationView;
+ } = $props();
+ let retired = $state(false);
+ const publicSnapshot = $derived(
+ publicOperation && !retired
+ ? listingOperationSnapshot(publicOperation)
+ : undefined
+ );
+ const summary = $derived(
+ publicOperation
+ ? (publicSnapshot?.summary ?? statusCopy('unknown'))
+ : statusCopy(fact)
+ );
+ $effect(() => {
+ retired = false;
+ if (!publicOperation) return;
+ return subscribeListingOperationView(publicOperation, () => {
+ retired = true;
+ });
+ });
</script>
<div class="stack stack--tight">
<Notice tone={summary.tone} text={summary.text} />
- {#each receipts as receipt, index (index)}
- {@const copy = receiptCopy(receipt)}
- <div class="stack stack--tight">
- <p class="key">
- Event: {receipt.eventId} · Target: {receipt.destination}
- </p>
- <Notice tone={copy.tone} text={copy.text} />
- <p>{copy.readback}</p>
- </div>
- {/each}
+ {#if publicSnapshot}
+ <p>
+ Relay acceptance recorded for {publicSnapshot.acceptanceCount} of {publicSnapshot
+ .targets.length} targets.
+ </p>
+ <p>
+ Exact read-back recorded for {publicSnapshot.readbackCount} of {publicSnapshot
+ .targets.length} targets.
+ </p>
+ <p>
+ {publicSnapshot.localSource === 'retained-prototype'
+ ? 'Retained prototype source is available in this browser. Editing requires a separate current-head check.'
+ : 'No supported retained prototype source is available for editing. Keep this listing read-only.'}
+ </p>
+ {#if publicSnapshot.needsAction}
+ <Notice
+ tone="warning"
+ text="Needs action. Earlier acceptance and exact read-back facts are preserved."
+ />
+ {/if}
+ {#each publicSnapshot.targets as target (target.origin)}
+ <div class="stack stack--tight">
+ <p class="key">Event: {target.eventId} · Target: {target.origin}</p>
+ <p>
+ {target.accepted
+ ? 'Acceptance recorded for this event and target.'
+ : 'No acceptance recorded for this event and target.'}
+ </p>
+ <p>
+ {target.readback === 'confirmed'
+ ? 'Exact read-back is confirmed for this event and target.'
+ : 'Exact read-back was not observed for this event and target.'}
+ </p>
+ {#each target.receipts as receipt, index (index)}
+ <p>
+ Attempt {receipt.attempt} · Recorded outcome: {receipt.status ===
+ 'timed_out'
+ ? 'timed out'
+ : receipt.status}.
+ </p>
+ {/each}
+ </div>
+ {/each}
+ {:else if !publicOperation}
+ {#each receipts as receipt, index (index)}
+ {@const copy = receiptCopy(receipt)}
+ <div class="stack stack--tight">
+ <p class="key">
+ Event: {receipt.eventId} · Target: {receipt.destination}
+ </p>
+ <Notice tone={copy.tone} text={copy.text} />
+ <p>{copy.readback}</p>
+ </div>
+ {/each}
+ {/if}
</div>
diff --git a/web/src/lib/publishing/listing-operation-view.ts b/web/src/lib/publishing/listing-operation-view.ts
@@ -0,0 +1,294 @@
+import { canonicalLocalId } from '../private-handles.ts';
+import {
+ publicPublicationOwner,
+ readPublicListingIntent,
+ type PublicPublicationRepository
+} from '../persistence/public-publications.ts';
+import { publicRecordSnapshot } from '../persistence/records.ts';
+import {
+ identitySessionSnapshot,
+ subscribeIdentityInvalidation,
+ type IdentitySession
+} from '../runtime/identity-session.ts';
+import {
+ listingSigningSnapshot,
+ subscribeListingSigning,
+ type ListingSigning
+} from './sign-listing.ts';
+import { inspectLocalTemplate } from '../nostr/local-template.ts';
+import { projectFoodParts } from '../contracts/food-availability-v1/read.ts';
+import type { PublicTargetReceipt } from '../contracts/local-records.ts';
+import type { StatusCopy } from '../presentation/status-copy.ts';
+
+declare const viewBrand: unique symbol;
+export type ListingOperationView = Readonly<{ [viewBrand]: true }>;
+export type ListingOperationSnapshot = Readonly<{
+ owner: string;
+ command: string;
+ revision: number;
+ eventId: string;
+ artifact: 'unsigned' | 'signed';
+ state:
+ | 'prepared'
+ | 'signing'
+ | 'partial'
+ | 'accepted'
+ | 'readback'
+ | 'unknown'
+ | 'needs-action';
+ acceptanceCount: number;
+ readbackCount: number;
+ needsAction: boolean;
+ localSource: 'retained-prototype' | 'read-only';
+ summary: StatusCopy;
+ targets: readonly Readonly<{
+ origin: string;
+ eventId: string;
+ accepted: boolean;
+ readback: 'confirmed' | 'not-observed';
+ latestOutcome: PublicTargetReceipt['status'] | 'unattempted';
+ receipts: readonly PublicTargetReceipt[];
+ }>[];
+}>;
+type View = Readonly<{
+ wire: string;
+ current(): boolean;
+ retire(): void;
+ subscribe(listener: () => void): () => void;
+}>;
+const views = new WeakMap<ListingOperationView, View>();
+const active = new WeakMap<
+ PublicPublicationRepository,
+ Map<string, Readonly<{ stamp: symbol; retire(): void }>>
+>();
+
+// This is account-local presentation only. Reading a retained operation grants
+// no sign, send, edit, current-head or relay qualification capability.
+export async function readListingOperationView(
+ repository: PublicPublicationRepository,
+ identity: IdentitySession,
+ command: unknown,
+ signing?: ListingSigning
+): Promise<
+ | Readonly<{ status: 'found'; view: ListingOperationView }>
+ | Readonly<{ status: 'unavailable' }>
+> {
+ const owner = publicPublicationOwner(repository),
+ id = canonicalLocalId(command);
+ const identityOwner = () => {
+ const snapshot = identitySessionSnapshot(identity);
+ return 'publicKey' in snapshot ? snapshot.publicKey : undefined;
+ };
+ if (!owner || !id || identityOwner() !== owner)
+ return { status: 'unavailable' };
+ const cache =
+ active.get(repository) ??
+ new Map<string, Readonly<{ stamp: symbol; retire(): void }>>();
+ active.set(repository, cache);
+ cache.get(id)?.retire();
+ const stamp = Symbol(),
+ listeners = new Map<symbol, () => void>();
+ let alive = true,
+ unsubscribe = () => {},
+ unsubscribeSigning = () => {},
+ observesSigning = false;
+ function retire() {
+ if (!alive) return;
+ alive = false;
+ unsubscribe();
+ unsubscribeSigning();
+ if (cache.get(id!)?.stamp === stamp) cache.delete(id!);
+ for (const listener of listeners.values()) {
+ try {
+ listener();
+ } catch {
+ /* Presentation callbacks cannot retain original custody. */
+ }
+ }
+ listeners.clear();
+ }
+ function current() {
+ const live =
+ observesSigning && signing ? listingSigningSnapshot(signing) : undefined;
+ const originalSigningCurrent =
+ !observesSigning ||
+ !!(
+ live &&
+ live.signing &&
+ !live.stopped &&
+ live.owner === owner &&
+ live.command === id
+ );
+ return (
+ originalSigningCurrent &&
+ alive &&
+ cache.get(id!)?.stamp === stamp &&
+ publicPublicationOwner(repository) === owner &&
+ identityOwner() === owner
+ );
+ }
+ cache.set(id, { stamp, retire });
+ unsubscribe = subscribeIdentityInvalidation(identity, retire);
+ try {
+ const read = await readPublicListingIntent(repository, id);
+ const row =
+ read.status === 'found' && publicRecordSnapshot(read.record, owner, id);
+ if (
+ !current() ||
+ !row ||
+ row.family !== 'public_operation' ||
+ row.capture.kind !== 30402 ||
+ row.capture.targets.length === 0 ||
+ (!row.artifact && (row.revision > 1 || row.receipts.length !== 0)) ||
+ (row.artifact && row.revision < 2)
+ ) {
+ retire();
+ return { status: 'unavailable' };
+ }
+ const template = inspectLocalTemplate(row.capture.wire, owner, 30402);
+ if (!template || projectFoodParts(template).outcome !== 'focused') {
+ retire();
+ return { status: 'unavailable' };
+ }
+ const targets = row.capture.targets.map((origin) => {
+ const receipts = row.receipts.filter(
+ (receipt) =>
+ receipt.origin === origin && receipt.eventId === row.capture.hash
+ );
+ return {
+ origin,
+ eventId: row.capture.hash,
+ accepted: receipts.some((receipt) => receipt.status === 'accepted'),
+ readback: receipts.some((receipt) => receipt.readbackWire !== null)
+ ? ('confirmed' as const)
+ : ('not-observed' as const),
+ latestOutcome: receipts.at(-1)?.status ?? ('unattempted' as const),
+ receipts
+ };
+ });
+ const acceptanceCount = targets.filter((target) => target.accepted).length,
+ readbackCount = targets.filter(
+ (target) => target.readback === 'confirmed'
+ ).length;
+ const needsAction = targets.some((target) =>
+ ['refused', 'timed_out', 'unknown', 'stopped'].includes(
+ target.latestOutcome
+ )
+ );
+ const live = signing && listingSigningSnapshot(signing);
+ const genuinelySigning =
+ live &&
+ live.owner === owner &&
+ live.command === id &&
+ live.hash === row.capture.hash &&
+ live.signing &&
+ !live.stopped;
+ const state: ListingOperationSnapshot['state'] = !row.artifact
+ ? row.revision === 0
+ ? 'prepared'
+ : genuinelySigning
+ ? 'signing'
+ : 'unknown'
+ : readbackCount === targets.length
+ ? 'readback'
+ : acceptanceCount === targets.length
+ ? 'accepted'
+ : acceptanceCount > 0 || readbackCount > 0
+ ? 'partial'
+ : targets.some(
+ (target) =>
+ target.latestOutcome === 'refused' ||
+ target.latestOutcome === 'stopped'
+ )
+ ? 'needs-action'
+ : row.receipts.length > 0
+ ? 'unknown'
+ : 'prepared';
+ observesSigning = state === 'signing';
+ if (observesSigning && signing)
+ unsubscribeSigning = subscribeListingSigning(signing, retire);
+ const text =
+ state === 'signing'
+ ? 'Waiting for your extension to sign the retained listing.'
+ : state === 'unknown'
+ ? 'The outcome is unknown. Keep the original listing operation for reconciliation.'
+ : state === 'needs-action'
+ ? 'Needs action. Keep the original listing operation and its recorded target outcomes.'
+ : state === 'partial'
+ ? 'Publication evidence is partial. Check the individual target outcomes.'
+ : state === 'readback'
+ ? 'Exact listing read-back is recorded for each frozen target.'
+ : state === 'accepted'
+ ? 'Each frozen target accepted this listing event. Exact read-back is recorded separately.'
+ : row.artifact
+ ? 'Signed listing saved in this browser. No relay acceptance is recorded.'
+ : 'Saved in this browser. The retained listing has not been signed.';
+ const snapshot: ListingOperationSnapshot = {
+ owner,
+ command: id,
+ revision: row.revision,
+ eventId: row.capture.hash,
+ artifact: row.artifact ? 'signed' : 'unsigned',
+ state,
+ acceptanceCount,
+ readbackCount,
+ needsAction,
+ localSource:
+ row.artifact && row.source.type === 'draft'
+ ? 'retained-prototype'
+ : 'read-only',
+ summary: {
+ tone:
+ needsAction || state === 'unknown' || state === 'partial'
+ ? 'warning'
+ : 'info',
+ text
+ },
+ targets
+ };
+ if (!current()) {
+ retire();
+ return { status: 'unavailable' };
+ }
+ const view = Object.freeze({}) as ListingOperationView;
+ views.set(view, {
+ wire: JSON.stringify(snapshot),
+ current,
+ retire,
+ subscribe(listener) {
+ if (!current()) return () => {};
+ const key = Symbol();
+ listeners.set(key, listener);
+ return () => {
+ listeners.delete(key);
+ };
+ }
+ });
+ return { status: 'found', view };
+ } catch {
+ retire();
+ return { status: 'unavailable' };
+ }
+}
+export function listingOperationSnapshot(
+ token: ListingOperationView
+): ListingOperationSnapshot | undefined {
+ const value = views.get(token);
+ if (!value) return;
+ if (!value.current()) {
+ value.retire();
+ return;
+ }
+ return JSON.parse(value.wire) as ListingOperationSnapshot;
+}
+export function closeListingOperationView(token: ListingOperationView): void {
+ views.get(token)?.retire();
+}
+export function subscribeListingOperationView(
+ token: ListingOperationView,
+ listener: () => void
+): () => void {
+ const value = views.get(token);
+ if (!value?.current()) return () => {};
+ return value.subscribe(listener);
+}
diff --git a/web/src/lib/publishing/sign-listing.ts b/web/src/lib/publishing/sign-listing.ts
@@ -49,6 +49,7 @@ type Model = Readonly<{
getSigning(): boolean;
startSigning(): void;
finishSigning(): void;
+ subscribe(listener: () => void): () => void;
getMarked(): PublicRecordHandle | undefined;
setMarked(value: PublicRecordHandle): void;
getArtifact(): CapturedArtifact | undefined;
@@ -64,8 +65,34 @@ function createModel(original: Ownership): Model {
let marked: PublicRecordHandle | undefined;
let artifact: CapturedArtifact | undefined;
let publication: ListingPublication | undefined;
+ const listeners = new Map<symbol, () => void>();
+ let notifying = false;
+ function notify() {
+ if (notifying) return;
+ notifying = true;
+ try {
+ const callbacks = Array.from(listeners.entries());
+ for (const [key, listener] of callbacks) {
+ if (listeners.get(key) !== listener) continue;
+ try {
+ listener();
+ } catch {
+ /* Disclosure observers never control signing. */
+ }
+ }
+ } finally {
+ notifying = false;
+ }
+ }
return {
original,
+ subscribe(listener) {
+ const key = Symbol();
+ listeners.set(key, listener);
+ return () => {
+ listeners.delete(key);
+ };
+ },
getOperation: () => operation,
setOperation: (value) => {
operation = value;
@@ -76,14 +103,20 @@ function createModel(original: Ownership): Model {
},
getStopped: () => stopped,
stop: () => {
+ if (stopped) return;
stopped = true;
+ notify();
},
getSigning: () => signing,
startSigning: () => {
+ if (signing) return;
signing = true;
+ notify();
},
finishSigning: () => {
+ if (!signing) return;
signing = false;
+ notify();
},
getMarked: () => marked,
setMarked: (value) => {
@@ -170,9 +203,17 @@ export function listingSigningSnapshot(token: ListingSigning) {
hash: row.capture.hash,
stopped: model.getStopped(),
attempted: model.getAttempted(),
+ signing: model.getSigning() && current(model),
lateAvailable: operation?.lateAvailable ?? false
};
}
+// Original-token lifecycle observation only; no sign, retry or send authority.
+export function subscribeListingSigning(
+ token: ListingSigning,
+ listener: () => void
+): () => void {
+ return signings.get(token)?.subscribe(listener) ?? (() => {});
+}
// Detached disclosure is never a send capability. HCP112 must independently
// admit the original plan, reread storage and obtain final network ownership.
export function listingPublicationSnapshot(token: ListingPublication) {
diff --git a/web/tests/e2e/harness/listing-operation-view.ts b/web/tests/e2e/harness/listing-operation-view.ts
@@ -0,0 +1,563 @@
+import { subscribeListingSigning } from '../../../src/lib/publishing/sign-listing.ts';
+import { mount, unmount, type ComponentProps } from 'svelte';
+import OperationStatus from '../../../src/lib/components/OperationStatus.svelte';
+import {
+ getPublicPool,
+ closePublicPool,
+ type PublicPool
+} from '../../../src/lib/nostr/public-pool.ts';
+import { deliverListing } from '../../../src/lib/publishing/deliver-listing.ts';
+import { makeFixture } from './approved-signing.ts';
+import { fixturePolicy, discovery, inbox } from './inbox-setup.ts';
+import {
+ readRelayPolicy,
+ publicRelayTargets,
+ validateRelayPolicy
+} from '../../../src/lib/config/relays.ts';
+import {
+ readListingOperationView,
+ listingOperationSnapshot,
+ closeListingOperationView,
+ type ListingOperationView
+} from '../../../src/lib/publishing/listing-operation-view.ts';
+import {
+ createIdentitySession,
+ connectIdentity,
+ probeIdentityMessaging,
+ disconnectIdentity
+} from '../../../src/lib/runtime/identity-session.ts';
+import {
+ createPublicScheduler,
+ createPublicRun,
+ openInboxRequest,
+ closePublicScheduler
+} from '../../../src/lib/nostr/request-scope.ts';
+import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts';
+import {
+ createInboxSetupView,
+ checkInboxSetupView,
+ unlockInboxSetupView,
+ closeInboxSetupView
+} from '../../../src/lib/messaging/inbox-setup-view.ts';
+import { captureNewListingReadiness } from '../../../src/lib/publishing/new-listing-readiness.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import {
+ createPublicPublicationRepository,
+ publicPublicationDraftRepository,
+ readPublicListingIntent
+} from '../../../src/lib/persistence/public-publications.ts';
+import {
+ createPublicDraftController,
+ closePublicDraftController
+} from '../../../src/lib/publishing/draft-controller.ts';
+import {
+ reviewNewListing,
+ reserveNewListing,
+ listingReviewSnapshot
+} from '../../../src/lib/publishing/prepare-listing.ts';
+import { publicRecordSnapshot } from '../../../src/lib/persistence/records.ts';
+import type { PublicOperationRecord } from '../../../src/lib/contracts/local-records.ts';
+import {
+ beginListingSigning,
+ runListingSigning,
+ stopListingSigning
+} from '../../../src/lib/publishing/sign-listing.ts';
+
+export async function createFixture() {
+ const signer = makeFixture(10050),
+ identity = createIdentitySession(),
+ policy = validateRelayPolicy(
+ JSON.stringify({
+ ...readRelayPolicy(fixturePolicy()),
+ public: [
+ ...readRelayPolicy(fixturePolicy()).public,
+ {
+ origin: 'wss://second.example.org',
+ read: true,
+ write: true,
+ nip50: false
+ }
+ ]
+ })
+ );
+ if (!policy) throw Error('controlled policy unavailable');
+ const preference = signer.sign({
+ ...signer.template,
+ kind: 10050,
+ created_at: 100,
+ tags: [['relay', inbox]],
+ content: ''
+ });
+ const prior = Object.getOwnPropertyDescriptor(window, 'nostr');
+ let signs = 0,
+ keys = 0;
+ const mode = 'exact' as const,
+ observedOwner = signer.owner;
+ let beforeSign: (() => Promise<void>) | undefined;
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () => {
+ keys++;
+ return Promise.resolve(observedOwner);
+ },
+ signEvent: async (input: Parameters<typeof signer.sign>[0]) => {
+ signs++;
+ await beforeSign?.();
+ return signer.sign(input, mode);
+ },
+ nip44: {
+ encrypt: (_peer: string, text: string) =>
+ Promise.resolve('fixture:' + text),
+ decrypt: (_peer: string, text: string) => Promise.resolve(text.slice(8))
+ }
+ }
+ });
+ await connectIdentity(identity);
+ await probeIdentityMessaging(identity, 'reviewed_self_copy');
+ const scheduler = createPublicScheduler({
+ now: () => 0,
+ schedule: () => () => {}
+ });
+ const run = createPublicRun(scheduler, policy);
+ const resolver = createInboxResolver(
+ run,
+ signer.owner,
+ (next) =>
+ openInboxRequest(
+ run,
+ signer.owner,
+ (sink) => {
+ sink({
+ type: 'EVENT',
+ from: discovery,
+ id: 'fixture',
+ event: preference
+ });
+ for (const origin of publicRelayTargets(policy, 'read'))
+ sink({ type: 'EOSE', from: origin, id: 'fixture' });
+ return () => {};
+ },
+ next
+ ),
+ () => true
+ );
+ // HC_TEST_ONLY_QUALIFICATION_PORT: original SDK owners, controlled exercised
+ // access observation; no real extension/operator/relay qualification.
+ const setup = createInboxSetupView({
+ identity,
+ policy,
+ lookup: () => Promise.resolve(resolver),
+ observeAccess: (context) => ({
+ ...context,
+ readTargets: context.readTargets.slice(),
+ archiveTargets: context.archiveTargets.slice(),
+ receive: 'qualified_exercised',
+ archive: 'qualified_exercised',
+ current: () => true
+ })
+ });
+ if (!setup) throw Error('original setup missing');
+ await checkInboxSetupView(setup);
+ await unlockInboxSetupView(setup);
+ const ready = captureNewListingReadiness(
+ identity,
+ setup,
+ 'reviewed_new_listing_inbox'
+ );
+ if (!ready) throw Error('original readiness missing');
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner,
+ repository = createPublicPublicationRepository(database, signer.owner);
+ const drafts = repository && publicPublicationDraftRepository(repository);
+ if (!repository || !drafts) throw Error('original repository missing');
+ const originalRepository = repository;
+ const controller = await createPublicDraftController(drafts, {
+ title: 'Carrots',
+ description: 'Exact signed description',
+ location: 'Local farm',
+ amount: '2',
+ currency: 'USD',
+ unit: 'kg',
+ quantity: '',
+ contactType: '',
+ contactValue: ''
+ });
+ if (!controller) throw Error('original controller missing');
+ const command = crypto.randomUUID();
+ const reviewed = await reviewNewListing(
+ repository,
+ controller,
+ ready,
+ command,
+ 'reviewed_new_listing'
+ );
+ if (reviewed.status !== 'review') throw Error(reviewed.reason);
+ const original = reviewed.review,
+ preview = listingReviewSnapshot(original);
+ if (!preview) throw Error('original preview missing');
+ const reserved = await reserveNewListing(
+ original,
+ 'publish_reviewed_listing'
+ );
+ if (reserved.status !== 'saved') throw Error(reserved.status);
+ const signing = beginListingSigning(original, 'sign_reviewed_listing');
+ if (!signing) throw Error('original signing missing');
+ const originalSigning = signing;
+ async function stored() {
+ const read = await readPublicListingIntent(originalRepository, command);
+ const row =
+ read.status === 'found' &&
+ publicRecordSnapshot(read.record, signer.owner, command);
+ if (!row || row.family !== 'public_operation')
+ throw Error('original stored command missing');
+ return row;
+ }
+ function invoke() {
+ return runListingSigning(originalSigning, 'sign_reviewed_listing');
+ }
+ let mounted: ReturnType<typeof mount> | undefined;
+ let target: HTMLElement | undefined;
+ let view: ListingOperationView | undefined, pool: PublicPool | undefined;
+ let pendingSigning: ReturnType<typeof invoke> | undefined;
+ let release = () => {};
+ async function show(original = true) {
+ const next = await readListingOperationView(
+ originalRepository,
+ identity,
+ command,
+ original ? originalSigning : undefined
+ );
+ if (next.status !== 'found') return next;
+ view = next.view;
+ return listingOperationSnapshot(view);
+ }
+ function nativeWrite(
+ store: 'public_operations' | 'public_drafts',
+ action: (value: IDBObjectStore) => void
+ ) {
+ const transaction = browserDatabaseTransaction(
+ database,
+ [store],
+ 'readwrite'
+ );
+ return new Promise<void>((resolve, reject) => {
+ transaction.addEventListener('complete', () => resolve());
+ transaction.addEventListener('abort', () =>
+ reject(Error('controlled transaction abort'))
+ );
+ action(transaction.objectStore(store));
+ });
+ }
+ return {
+ owner: signer.owner,
+ command,
+ show,
+ async renderView(copied = false) {
+ if (mounted) await unmount(mounted);
+ target?.remove();
+ target = document.createElement('div');
+ target.id = 'hcp114-operation';
+ document.body.append(target);
+ const value = await show();
+ if (!view) throw Error('original view missing');
+ mounted = mount(OperationStatus, {
+ target,
+ props: {
+ publicOperation: copied ? { ...view } : view
+ } as ComponentProps<typeof OperationStatus>
+ });
+ return value;
+ },
+ snapshot() {
+ return view && listingOperationSnapshot(view);
+ },
+ copiedSnapshot() {
+ return view && listingOperationSnapshot({ ...view });
+ },
+ async row() {
+ return await stored();
+ },
+ async signed() {
+ return (await invoke()).status;
+ },
+ async deliver() {
+ const signed = await invoke();
+ if (signed.status !== 'prepared') return signed.status;
+ pool = getPublicPool(policy);
+ if (!pool) throw Error('original pool unavailable');
+ return (
+ await deliverListing(
+ signed.publication,
+ pool,
+ policy,
+ 'publish_stored_listing'
+ )
+ ).status;
+ },
+ async holdSigning() {
+ let entered = () => {};
+ const enteredPromise = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ beforeSign = () => {
+ entered();
+ return held;
+ };
+ pendingSigning = invoke();
+ await enteredPromise;
+ },
+ async observerAddition() {
+ let first = 0,
+ added = 0,
+ offAdded = () => {};
+ const off = subscribeListingSigning(originalSigning, () => {
+ first++;
+ offAdded = subscribeListingSigning(originalSigning, () => {
+ added++;
+ });
+ });
+ stopListingSigning(originalSigning);
+ off();
+ offAdded();
+ release();
+ await pendingSigning;
+ return { first, added };
+ },
+ async observerStop() {
+ let first = 0;
+ const off = subscribeListingSigning(originalSigning, () => {
+ first++;
+ if (first === 1) stopListingSigning(originalSigning);
+ });
+ stopListingSigning(originalSigning);
+ off();
+ release();
+ await pendingSigning;
+ return { first };
+ },
+ async releaseSigning() {
+ release();
+ const result = await pendingSigning;
+ return result?.status;
+ },
+ async stopSigning() {
+ stopListingSigning(originalSigning);
+ release();
+ const result = await pendingSigning;
+ return result?.status;
+ },
+ async replace(row: PublicOperationRecord) {
+ await nativeWrite('public_operations', (store) => {
+ store.put({
+ owner: signer.owner,
+ id: command,
+ wire: JSON.stringify(row)
+ });
+ });
+ },
+ async externalSource() {
+ const row = await stored();
+ if (!row.artifact) throw Error('signed original missing');
+ const original = JSON.parse(row.capture.wire) as Parameters<
+ typeof signer.sign
+ >[0];
+ const template = { ...original, created_at: original.created_at + 1 };
+ const artifact = signer.sign(template);
+ await nativeWrite('public_operations', (store) => {
+ store.put({
+ owner: signer.owner,
+ id: command,
+ wire: JSON.stringify({
+ ...row,
+ revision: 2,
+ source: { type: 'public_head', wire: row.artifact!.wire },
+ capture: {
+ ...row.capture,
+ wire: JSON.stringify(template),
+ hash: artifact.id
+ },
+ artifact: { eventId: artifact.id, wire: JSON.stringify(artifact) },
+ receipts: []
+ })
+ });
+ });
+ },
+ async removeDraft() {
+ await nativeWrite('public_drafts', (store) => {
+ store.delete([signer.owner, preview.draftId]);
+ });
+ },
+ async evidence(
+ status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped',
+ target: number,
+ readback: boolean
+ ) {
+ const row = await stored();
+ if (!row.artifact) throw Error('original artifact missing');
+ const receipt = {
+ actionId: crypto.randomUUID(),
+ origin: row.capture.targets[target],
+ role: 'publication' as const,
+ attempt: 1,
+ eventId: row.artifact.eventId,
+ status,
+ observedAtMilliseconds: Date.now(),
+ readbackWire: readback ? row.artifact.wire : null
+ };
+ // HC_TEST_ONLY stored observation metadata, never an actual relay qualification claim.
+ await nativeWrite('public_operations', (store) => {
+ store.put({
+ owner: signer.owner,
+ id: command,
+ wire: JSON.stringify({
+ ...row,
+ revision: row.revision + 1,
+ receipts: [...row.receipts, receipt]
+ })
+ });
+ });
+ },
+ async supersede() {
+ const old = view;
+ await show();
+ return old && listingOperationSnapshot(old);
+ },
+ async readWhileLogout() {
+ const prototype = IDBTransaction.prototype,
+ descriptor = Object.getOwnPropertyDescriptor(
+ prototype,
+ 'addEventListener'
+ );
+ const inherited =
+ descriptor ??
+ Object.getOwnPropertyDescriptor(
+ EventTarget.prototype,
+ 'addEventListener'
+ );
+ if (!inherited) throw Error('native registration missing');
+ const native = inherited.value as IDBTransaction['addEventListener'];
+ let entered = () => {},
+ releaseRead = () => {},
+ completed = 0;
+ const enteredPromise = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const restore = () => {
+ if (descriptor)
+ Object.defineProperty(prototype, 'addEventListener', descriptor);
+ else Reflect.deleteProperty(prototype, 'addEventListener');
+ };
+ prototype.addEventListener = function (
+ type: string,
+ listener: EventListenerOrEventListenerObject,
+ options?: boolean | AddEventListenerOptions
+ ) {
+ if (
+ type !== 'complete' ||
+ !listener ||
+ this.mode !== 'readonly' ||
+ !this.objectStoreNames.contains('public_operations')
+ )
+ return native.call(this, type, listener, options);
+ restore();
+ return native.call(
+ this,
+ type,
+ function (event: Event) {
+ const transaction = event.currentTarget;
+ if (!(transaction instanceof IDBTransaction))
+ throw Error('native complete missing');
+ completed++;
+ releaseRead = () => {
+ if (typeof listener === 'function')
+ listener.call(transaction, event);
+ else listener.handleEvent(event);
+ };
+ entered();
+ },
+ options
+ );
+ };
+ try {
+ const pending = show();
+ await enteredPromise;
+ disconnectIdentity(identity);
+ releaseRead();
+ return { result: await pending, nativeCompletions: completed };
+ } finally {
+ releaseRead();
+ restore();
+ }
+ },
+ logout() {
+ disconnectIdentity(identity);
+ },
+ closeView() {
+ if (view) closeListingOperationView(view);
+ },
+ counts() {
+ return { signs, keys };
+ },
+ close() {
+ release();
+ if (mounted) void unmount(mounted);
+ target?.remove();
+ if (pool) closePublicPool(pool);
+ if (view) closeListingOperationView(view);
+ closePublicDraftController(controller);
+ closeBrowserDatabase(database);
+ closeInboxSetupView(setup);
+ disconnectIdentity(identity);
+ closePublicScheduler(scheduler);
+ signer.close();
+ if (prior) Object.defineProperty(window, 'nostr', prior);
+ else Reflect.deleteProperty(window, 'nostr');
+ }
+ };
+}
+
+export async function reopen(owner: string, command: string) {
+ const prior = Object.getOwnPropertyDescriptor(window, 'nostr');
+ let signs = 0;
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () => Promise.resolve(owner),
+ signEvent: () => {
+ signs++;
+ return Promise.reject(Error('read-only reopen never signs'));
+ }
+ }
+ });
+ const identity = createIdentitySession();
+ await connectIdentity(identity);
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner,
+ repository = createPublicPublicationRepository(database, owner);
+ if (!repository) throw Error('reopened repository missing');
+ const result = await readListingOperationView(repository, identity, command);
+ return {
+ result:
+ result.status === 'found'
+ ? listingOperationSnapshot(result.view)
+ : result,
+ counts: () => ({ signs }),
+ close() {
+ if (result.status === 'found') closeListingOperationView(result.view);
+ closeBrowserDatabase(database);
+ disconnectIdentity(identity);
+ if (prior) Object.defineProperty(window, 'nostr', prior);
+ else Reflect.deleteProperty(window, 'nostr');
+ }
+ };
+}
diff --git a/web/tests/e2e/listing-operation-view.spec.ts b/web/tests/e2e/listing-operation-view.spec.ts
@@ -0,0 +1,435 @@
+import { expect, test } from '@playwright/test';
+import { build } from 'vite';
+import { svelte } from '@sveltejs/vite-plugin-svelte';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/listing-operation-view.ts';
+declare global {
+ interface Window {
+ hcp114: typeof Fixture;
+ hcp114Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ hcp114Reopened: Awaited<ReturnType<typeof Fixture.reopen>>;
+ }
+}
+const first = 'wss://discovery.example.org',
+ second = 'wss://second.example.org';
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ bundle: string,
+ endpoint: string;
+let frames: { origin: string; message: unknown[] }[] = [];
+let stored: Record<string, unknown> | undefined;
+let responses = new Map<
+ string,
+ 'accepted' | 'refused' | 'literal-timeout' | 'silent' | 'held'
+>();
+let holdReadback = false,
+ observeExact = true;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 262144
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string')
+ throw Error('loopback unavailable');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket, request) => {
+ const origin = request.url === '/b' ? second : first;
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes.toString()
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes).toString()
+ : Buffer.from(bytes).toString();
+ const message = JSON.parse(raw) as unknown[];
+ frames.push({ origin, message });
+ if (message[0] === 'EVENT') {
+ stored = message[1] as Record<string, unknown>;
+ const response = responses.get(origin) ?? 'accepted';
+ if (response === 'held' || response === 'silent') return;
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ stored.id,
+ response === 'accepted',
+ response === 'accepted'
+ ? ''
+ : response === 'literal-timeout'
+ ? 'Timeout'
+ : 'blocked: controlled refusal'
+ ])
+ );
+ } else if (message[0] === 'REQ' && !holdReadback) {
+ if (stored && observeExact)
+ socket.send(JSON.stringify(['EVENT', message[1], stored]));
+ socket.send(JSON.stringify(['EOSE', message[1]]));
+ }
+ });
+ });
+ const built = await build({
+ configFile: false,
+ plugins: [svelte({ configFile: false })],
+ resolve: { conditions: ['browser'] },
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/listing-operation-view.ts', import.meta.url)
+ ),
+ name: 'hcp114',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(built) ? built[0] : built;
+ if (!('output' in output)) throw Error('bundle unavailable');
+ const chunks = output.output.filter((row) => row.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets.clients) socket.terminate();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+test.beforeEach(async ({ page }) => {
+ frames = [];
+ stored = undefined;
+ responses = new Map();
+ holdReadback = false;
+ observeExact = true;
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ class LoopbackSocket extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ const role =
+ String(url) === 'wss://discovery.example.org/'
+ ? '/a'
+ : String(url) === 'wss://second.example.org/'
+ ? '/b'
+ : undefined;
+ if (!role) throw Error('unfrozen controlled target');
+ super(endpoint + role, protocols);
+ }
+ }
+ window.WebSocket = LoopbackSocket;
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ window.hcp114Fixture = await window.hcp114.createFixture();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => {
+ window.hcp114Reopened?.close();
+ window.hcp114Fixture?.close();
+ });
+});
+
+test('HCP114 unsigned prepared source is local and renders no acceptance or edit permission', async ({
+ page
+}) => {
+ const v = await page.evaluate(() => window.hcp114Fixture.renderView());
+ expect(v).toMatchObject({
+ state: 'prepared',
+ artifact: 'unsigned',
+ acceptanceCount: 0,
+ readbackCount: 0,
+ localSource: 'read-only'
+ });
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.counts())
+ ).toMatchObject({ signs: 0 });
+ expect(frames).toEqual([]);
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'Saved in this browser'
+ );
+ await expect(page.locator('#hcp114-operation')).not.toContainText(
+ 'globally published'
+ );
+});
+test('HCP114 genuine live signing differs from unsigned uncertainty and actual restart never resets it fresh', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.holdSigning());
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ state: 'signing',
+ artifact: 'unsigned'
+ });
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.show(false))
+ ).toMatchObject({ state: 'unknown' });
+ await page.evaluate(() => window.hcp114Fixture.stopSigning());
+ const row = await page.evaluate(() => window.hcp114Fixture.row());
+ expect(row.revision).toBe(1);
+ expect(row.artifact).toBeNull();
+ await page.evaluate(() => window.hcp114Fixture.close());
+ await page.reload();
+ await page.addScriptTag({ content: bundle });
+ const result = await page.evaluate(
+ async ({ owner, command }) => {
+ window.hcp114Reopened = await window.hcp114.reopen(owner, command);
+ return window.hcp114Reopened.result;
+ },
+ { owner: row.owner, command: row.id }
+ );
+ expect(result).toMatchObject({
+ state: 'unknown',
+ artifact: 'unsigned',
+ revision: 1
+ });
+ expect(await page.evaluate(() => window.hcp114Reopened.counts())).toEqual({
+ signs: 0
+ });
+ expect(frames).toEqual([]);
+});
+test('HCP114 copied disclosure cannot present original local evidence', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ await page.evaluate(() => window.hcp114Fixture.renderView(true));
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.copiedSnapshot())
+ ).toBeUndefined();
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'outcome is unknown'
+ );
+ await expect(page.locator('#hcp114-operation')).not.toContainText(
+ 'Relay acceptance recorded'
+ );
+ expect(frames).toEqual([]);
+});
+test('HCP114 actual SDK acceptance by one of two targets is partial and does not invent readback', async ({
+ page
+}) => {
+ observeExact = false;
+ responses.set(second, 'refused');
+ expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
+ 'needs_action'
+ );
+ const v = await page.evaluate(() => window.hcp114Fixture.renderView());
+ expect(v).toMatchObject({
+ state: 'partial',
+ acceptanceCount: 1,
+ readbackCount: 0,
+ needsAction: true
+ });
+ expect(frames.filter((x) => x.message[0] === 'EVENT')).toHaveLength(2);
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'Relay acceptance recorded for 1 of 2 targets.'
+ );
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'Exact read-back recorded for 0 of 2 targets.'
+ );
+});
+test('HCP114 actual SDK exact readback without an ACK stays separate from acceptance', async ({
+ page
+}) => {
+ responses.set(first, 'silent');
+ responses.set(second, 'refused');
+ expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
+ 'needs_action'
+ );
+ const v = await page.evaluate(() => window.hcp114Fixture.show());
+ expect(v).toMatchObject({
+ state: 'partial',
+ acceptanceCount: 0,
+ readbackCount: 1
+ });
+ expect(v && 'targets' in v && v.targets[0]).toMatchObject({
+ accepted: false,
+ readback: 'confirmed',
+ latestOutcome: 'timed_out'
+ });
+});
+test('HCP114 actual all-target ACKs alone are accepted with exact readback still unobserved', async ({
+ page
+}) => {
+ observeExact = false;
+ expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
+ 'completed'
+ );
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ state: 'accepted',
+ acceptanceCount: 2,
+ readbackCount: 0
+ });
+});
+test('HCP114 actual all-target readback is distinct from a browser-only signed artifact', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ state: 'prepared',
+ artifact: 'signed',
+ acceptanceCount: 0,
+ readbackCount: 0
+ });
+ expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
+ 'completed'
+ );
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ state: 'readback',
+ acceptanceCount: 2,
+ readbackCount: 2
+ });
+});
+test('HCP114 controlled later Stop and refusal retain earlier named acceptance and readback facts', async ({
+ page
+}) => {
+ expect(await page.evaluate(() => window.hcp114Fixture.deliver())).toBe(
+ 'completed'
+ );
+ await page.evaluate(async () => {
+ await window.hcp114Fixture.evidence('stopped', 0, false);
+ await window.hcp114Fixture.evidence('refused', 1, false);
+ });
+ const v = await page.evaluate(() => window.hcp114Fixture.show());
+ expect(v).toMatchObject({
+ acceptanceCount: 2,
+ readbackCount: 2,
+ needsAction: true
+ });
+ expect(v && 'targets' in v && v.targets.map((t) => t.latestOutcome)).toEqual([
+ 'stopped',
+ 'refused'
+ ]);
+});
+test('HCP114 contradictory native record fields fail closed rather than becoming prepared', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ await page.evaluate(() =>
+ window.hcp114Fixture.evidence('accepted', 0, false)
+ );
+ await page.evaluate(async () => {
+ const row = await window.hcp114Fixture.row();
+ await window.hcp114Fixture.replace({ ...row, artifact: null });
+ });
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toEqual({
+ status: 'unavailable'
+ });
+ expect(frames).toEqual([]);
+});
+test('HCP114 retained prototype capture remains available after draft cleanup but external-head records stay read-only', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ await page.evaluate(() => window.hcp114Fixture.removeDraft());
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ localSource: 'retained-prototype'
+ });
+ await page.evaluate(() => window.hcp114Fixture.externalSource());
+ expect(await page.evaluate(() => window.hcp114Fixture.show())).toMatchObject({
+ localSource: 'read-only'
+ });
+ expect(frames).toEqual([]);
+});
+test('HCP114 Close and identity invalidation retire original presentation handles', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ await page.evaluate(() => window.hcp114Fixture.renderView());
+ await page.evaluate(() => window.hcp114Fixture.logout());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.snapshot())
+ ).toBeUndefined();
+ await expect(page.locator('#hcp114-operation')).not.toContainText(
+ 'Relay acceptance recorded'
+ );
+ await page.evaluate(() => window.hcp114Fixture.closeView());
+ expect(frames).toEqual([]);
+});
+
+test('HCP114 an explicit fresh native read supersedes the earlier presentation snapshot', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ await page.evaluate(() => window.hcp114Fixture.show());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.supersede())
+ ).toBeUndefined();
+ expect(frames).toEqual([]);
+});
+test('HCP114 logout after actual native transaction completion fences a held application acknowledgement', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.signed());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.readWhileLogout())
+ ).toEqual({ result: { status: 'unavailable' }, nativeCompletions: 1 });
+ expect(frames).toEqual([]);
+});
+
+test('HCP114 retained mounted signing view retires on original Stop without another native read', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.holdSigning());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.renderView())
+ ).toMatchObject({ state: 'signing' });
+ await page.evaluate(() => window.hcp114Fixture.stopSigning());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.snapshot())
+ ).toBeUndefined();
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'The outcome is unknown'
+ );
+ await expect(page.locator('#hcp114-operation')).not.toContainText(
+ 'Waiting for your extension'
+ );
+ expect(frames).toEqual([]);
+});
+test('HCP114 retained mounted signing view retires on signer settlement without another native read', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.holdSigning());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.renderView())
+ ).toMatchObject({ state: 'signing' });
+ expect(await page.evaluate(() => window.hcp114Fixture.releaseSigning())).toBe(
+ 'prepared'
+ );
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.snapshot())
+ ).toBeUndefined();
+ await expect(page.locator('#hcp114-operation')).toContainText(
+ 'The outcome is unknown'
+ );
+ await expect(page.locator('#hcp114-operation')).not.toContainText(
+ 'Waiting for your extension'
+ );
+ expect(frames).toEqual([]);
+});
+
+test('HCP114 notification excludes original-token listeners subscribed during notification', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.holdSigning());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.observerAddition())
+ ).toEqual({ first: 1, added: 0 });
+ expect(frames).toEqual([]);
+});
+test('HCP114 notification makes original-token reentrant Stop idempotent', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp114Fixture.holdSigning());
+ expect(
+ await page.evaluate(() => window.hcp114Fixture.observerStop())
+ ).toEqual({ first: 1 });
+ expect(frames).toEqual([]);
+});
diff --git a/web/tests/e2e/notices.spec.ts b/web/tests/e2e/notices.spec.ts
@@ -37,6 +37,8 @@ test.beforeAll(async () => {
'web/src/lib/components/OperationStatus.svelte',
'web/src/lib/components/ErrorSummary.svelte',
'web/src/lib/presentation/status-copy.ts',
+ 'web/src/lib/publishing/listing-operation-view.ts',
+ 'web/src/lib/publishing/sign-listing.ts',
'web/tests/unit/status-copy.test.ts',
'web/tests/unit/components/notices.test.ts',
'web/tests/unit/components/NoticeHarness.svelte',
@@ -87,6 +89,8 @@ test.beforeAll(async () => {
'web/src/lib/components/OperationStatus.svelte',
'web/src/lib/components/ErrorSummary.svelte',
'web/src/lib/presentation/status-copy.ts',
+ 'web/src/lib/publishing/listing-operation-view.ts',
+ 'web/src/lib/publishing/sign-listing.ts',
'web/src/lib/components/primitives/FormField.svelte',
'web/src/lib/components/primitives/Button.svelte',
'web/src/app.css',
diff --git a/web/tests/unit/listing-operation-view.test.ts b/web/tests/unit/listing-operation-view.test.ts
@@ -0,0 +1,56 @@
+import {
+ subscribeListingSigning,
+ type ListingSigning
+} from '../../src/lib/publishing/sign-listing.ts';
+import { expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import OperationStatus from '../../src/lib/components/OperationStatus.svelte';
+import {
+ readListingOperationView,
+ listingOperationSnapshot,
+ closeListingOperationView,
+ subscribeListingOperationView,
+ type ListingOperationView
+} from '../../src/lib/publishing/listing-operation-view.ts';
+import type { PublicPublicationRepository } from '../../src/lib/persistence/public-publications.ts';
+import type { IdentitySession } from '../../src/lib/runtime/identity-session.ts';
+
+it('HCP114 copied repository and identity cannot disclose a stored operation during SSR', async () => {
+ expect(
+ await readListingOperationView(
+ {} as PublicPublicationRepository,
+ {} as IdentitySession,
+ '00000000-0000-4000-8000-000000000001'
+ )
+ ).toEqual({ status: 'unavailable' });
+});
+it('HCP114 detached state combinations cannot replace an original presentation handle', () => {
+ expect(
+ listingOperationSnapshot({
+ state: 'accepted',
+ acceptanceCount: 2,
+ artifact: 'unsigned'
+ } as unknown as ListingOperationView)
+ ).toBeUndefined();
+});
+it('HCP114 copied Close and subscription cannot borrow another view lifecycle', () => {
+ const copied = {} as ListingOperationView;
+ let calls = 0;
+ const release = subscribeListingOperationView(copied, () => {
+ calls++;
+ });
+ closeListingOperationView(copied);
+ release();
+ subscribeListingSigning({} as ListingSigning, () => {
+ calls++;
+ })();
+ expect(calls).toBe(0);
+});
+it('HCP114 SSR rejects copied public evidence and retains calm unknown copy', () => {
+ const html = render(OperationStatus, {
+ props: { publicOperation: {} as ListingOperationView }
+ }).body;
+ expect(html).toContain('The outcome is unknown');
+ expect(html).not.toContain('Relay acceptance recorded');
+ expect(html).not.toMatch(/globally published|editable|<button/);
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -560,13 +560,17 @@ async function listingPublicationAdmission(web) {
'src/lib/nostr/listing-publisher.ts':
'1c8c3445513329d57fcddc75da63991f0c1c27c28caf87db381d32bba739c872',
'src/lib/publishing/sign-listing.ts':
- 'c33e1399c19e1134a8a9f511800056c65c9f48155358c903dfed7c2c10c32486',
+ '5051a2e0eb3353b9f099cb92dcbd3162003a9a32cebac6035b979ae3a9400bfe',
'src/lib/publishing/retry-listing.ts':
'67b6a110bb116ff2b0791833cc0df02889b206839baf04467e44fa5f2c1ec459',
'src/lib/publishing/resume-listing.ts':
'42cd0404f1e543e03350e6c8c92fce5a1c4f8eb02f9540831fc6c7cf84bba9a9',
'src/lib/publishing/deliver-listing.ts':
- 'a47d3ae5b4bc1d3cd85ff7385851953fbf21bd22e265e875e7710b192830d409'
+ 'a47d3ae5b4bc1d3cd85ff7385851953fbf21bd22e265e875e7710b192830d409',
+ 'src/lib/publishing/listing-operation-view.ts':
+ '5f48bfb7056b56bd29357e605e20ef1375c559973fcc31f38d564a3b9eb07094',
+ 'src/lib/components/OperationStatus.svelte':
+ 'c6a1d741d16b577783e80b8f447cb959d5bf8b2d711cd5abcdc396be430a7472'
};
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);