commit 0d8e6df503f96547fc137f52698c2f5aee06a811
parent 5b8e6b49a4a2d4e26ec587c707008684251cbd83
Author: triesap <tyson@radroots.org>
Date: Fri, 9 Oct 2026 04:03:52 +0000
messages: preserve uncertainty through stop and session loss (HCP-089)
- Bind actual SDK attempt results to original owner and ciphertext scope
- Reconcile stopped and accepted facts through canonical CAS and readback
- Fence new effects on Stop or logout and require explicit Resume
- Verify real browser uncertainty and receipt failure boundaries
Diffstat:
9 files changed, 1057 insertions(+), 5 deletions(-)
diff --git a/web/src/lib/messaging/retry-send.ts b/web/src/lib/messaging/retry-send.ts
@@ -28,6 +28,7 @@ import {
} from '../nostr/private-pool.ts';
import { PRIVATE_PUBLICATION_BUDGETS } from '../config/budgets.ts';
import type { PairedDeliveryContext } from './prepare-send.ts';
+import { reconcilePrivateSendAttempt } from '../persistence/private-send-settlements.ts';
// Codec readback metadata alone is not a qualified authenticated remote query.
// Only named acceptance suppresses retry here; separate readback remains visible.
export function privateRetryTargets(
@@ -195,8 +196,11 @@ export function capturePrivateRetry(
permission,
abort.signal
);
- if (abort.signal.aborted || !ownership.current())
+ if (abort.signal.aborted || !ownership.current()) {
+ if (result.actionId) attempts++;
+ await reconcilePrivateSendAttempt(result);
return finish('stopped');
+ }
if (
!result.actionId &&
pairedDeliveryTargetAccepted(
@@ -241,8 +245,10 @@ export function capturePrivateRetry(
readbackWire: null
})
);
- if (abort.signal.aborted || !ownership.current())
+ if (abort.signal.aborted || !ownership.current()) {
+ await reconcilePrivateSendAttempt(result);
return finish('stopped');
+ }
if (!('record' in saved)) return finish('needs_action');
if (result.status === 'accepted') {
accepted = true;
diff --git a/web/src/lib/messaging/send-status.ts b/web/src/lib/messaging/send-status.ts
@@ -31,7 +31,16 @@ export function privateSendStatus(
refusedTargets: origins('refused'),
timeoutTargets: origins('timed_out'),
unknownTargets: origins('unknown'),
- stoppedTargets: origins('stopped')
+ stoppedTargets: origins('stopped'),
+ uncertainTargets: targets.filter(
+ (origin) =>
+ !acceptedTargets.includes(origin) &&
+ matching.some(
+ (f) =>
+ f.origin === origin &&
+ ['unknown', 'timed_out', 'stopped'].includes(f.status)
+ )
+ )
};
}
const recipientFacts = role(
diff --git a/web/src/lib/messaging/stop-send.ts b/web/src/lib/messaging/stop-send.ts
@@ -0,0 +1,26 @@
+import {
+ stopPrivateRetry,
+ privateRetrySnapshot,
+ type PrivateRetry
+} from './retry-send.ts';
+// Stop prevents future scheduling. It does not retract a relay attempt or
+// acknowledge recipient delivery. Original attempt facts reconcile separately.
+export function stopPrivateSend(operation: PrivateRetry): void {
+ stopPrivateRetry(operation);
+}
+export function privateStopSendSnapshot(operation: PrivateRetry) {
+ const view = privateRetrySnapshot(operation);
+ return (
+ view && {
+ ...view,
+ labels:
+ view.state === 'stopped'
+ ? [
+ 'Stopped',
+ 'Already attempted delivery may remain uncertain',
+ 'Resume requires an explicit matching-account action'
+ ]
+ : []
+ }
+ );
+}
diff --git a/web/src/lib/nostr/private-pool.ts b/web/src/lib/nostr/private-pool.ts
@@ -32,6 +32,7 @@ import {
type PrivateSession
} from '../runtime/private-session.ts';
import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import type { PrivateStorageRepository } from '../persistence/private-storage.ts';
declare const poolBrand: unique symbol;
export type PrivatePool = Readonly<{ [poolBrand]: true }>;
export type PrivateGiftWrapAttemptResult = Readonly<{
@@ -42,6 +43,25 @@ export type PrivateGiftWrapAttemptResult = Readonly<{
actionId?: string;
attempt?: number;
}>;
+type AttemptEvidence = Readonly<{
+ repository: PrivateStorageRepository;
+ owner: string;
+ command: string;
+ pairWire: string;
+ receiptWire: string;
+}>;
+const attemptEvidence = new WeakMap<
+ PrivateGiftWrapAttemptResult,
+ AttemptEvidence
+>();
+// Only this module's actual admitted SDK EVENT port mints these observations.
+// Detached/cloned status objects cannot impersonate an attempted operation.
+export function privateGiftWrapAttemptEvidence(
+ result: PrivateGiftWrapAttemptResult
+) {
+ const evidence = attemptEvidence.get(result);
+ return evidence && { ...evidence };
+}
export type PrivatePageMessage =
| Readonly<{ type: 'candidate'; from: string; wire: string }>
| Readonly<{
@@ -223,6 +243,7 @@ export function getPrivatePool(
return await new Promise<PrivateGiftWrapAttemptResult>(
(resolve) => {
let ended = false,
+ attempted = false,
release = () => {},
fenceTimer: ReturnType<typeof setTimeout> | undefined;
function finish(
@@ -241,7 +262,7 @@ export function getPrivatePool(
publicationCleanupRequired = true;
status = 'unknown';
}
- resolve({
+ const result: PrivateGiftWrapAttemptResult = {
status,
role: admitted!.role,
origin: admitted!.origin,
@@ -249,7 +270,26 @@ export function getPrivatePool(
...(network
? { actionId: network.actionId, attempt: network.attempt }
: {})
- });
+ };
+ if (attempted && network) {
+ attemptEvidence.set(result, {
+ repository: admitted!.repository,
+ owner: admitted!.owner,
+ command: admitted!.command,
+ pairWire: admitted!.pairWire,
+ receiptWire: JSON.stringify({
+ actionId: network.actionId,
+ role: admitted!.role,
+ origin: admitted!.origin,
+ eventId: admitted!.eventId,
+ attempt: network.attempt,
+ status,
+ observedAtMilliseconds: Date.now(),
+ readbackWire: null
+ })
+ });
+ }
+ resolve(result);
}
function stop() {
if (ended) {
@@ -299,6 +339,7 @@ export function getPrivatePool(
}
// The only private EVENT port accepts the freshly read-back1059;
// no caller event, key, relay template or SDK option crosses it.
+ attempted = true;
const subscription = relay
.event(admitted.event, 'EVENT')
.subscribe({
diff --git a/web/src/lib/nostr/private-publisher.ts b/web/src/lib/nostr/private-publisher.ts
@@ -377,6 +377,21 @@ export async function takePrivatePublication(
return undefined;
return {
event,
+ repository: saved.repository,
+ // Frozen original operation/artifact scope for metadata-only settlement.
+ // It survives session loss without becoming new effect permission.
+ pairWire: (() => {
+ const row = pairedDeliveryAcknowledgementSnapshot(saved.receipt)!;
+ return JSON.stringify({
+ owner: row.owner,
+ id: row.id,
+ peer: row.peer,
+ rumorHash: row.rumorHash,
+ createdAt: row.createdAt,
+ self: row.self,
+ peerArtifact: row.peerArtifact
+ });
+ })(),
current: () => saved.current(),
owner: saved.owner,
command: saved.command,
diff --git a/web/src/lib/persistence/private-send-settlements.ts b/web/src/lib/persistence/private-send-settlements.ts
@@ -0,0 +1,69 @@
+import {
+ privateGiftWrapAttemptEvidence,
+ type PrivateGiftWrapAttemptResult
+} from '../nostr/private-pool.ts';
+import { privateRecordSnapshot } from './private-records.ts';
+import { loadPrivateRecord } from './private-storage.ts';
+import {
+ preparePrivateReceiptTransition,
+ commitPrivateReceiptTransition,
+ type PrivateReceiptCommitResult
+} from './private-receipts.ts';
+// Late bookkeeping is bound to the original actual EVENT, owner and immutable
+// ciphertexts. It performs no SDK work, resumes nothing and renews no ACK.
+export async function reconcilePrivateSendAttempt(
+ result: PrivateGiftWrapAttemptResult
+): Promise<PrivateReceiptCommitResult> {
+ const original = privateGiftWrapAttemptEvidence(result);
+ if (!original || typeof window === 'undefined' || !navigator.locks?.request)
+ return { status: 'invalid' };
+ try {
+ return await navigator.locks.request(
+ 'harvestcircle:owner:' + original.owner,
+ { mode: 'exclusive' },
+ async () => {
+ const loaded = await loadPrivateRecord(
+ original.repository,
+ 'private_sends',
+ original.command
+ );
+ if (!loaded.ok) return { status: loaded.reason };
+ const row = privateRecordSnapshot(
+ loaded.value,
+ original.owner,
+ original.command
+ );
+ if (
+ !row ||
+ row.family !== 'private_send_operation' ||
+ JSON.stringify({
+ owner: row.owner,
+ id: row.id,
+ peer: row.peer,
+ rumorHash: row.rumorHash,
+ createdAt: row.createdAt,
+ self: row.self,
+ peerArtifact: row.peerArtifact
+ }) !== original.pairWire
+ )
+ return { status: 'conflict' };
+ const transition = preparePrivateReceiptTransition(
+ loaded.value,
+ original.owner,
+ original.command,
+ original.receiptWire
+ );
+ if (!transition.ok)
+ return {
+ status: transition.reason === 'conflict' ? 'conflict' : 'invalid'
+ };
+ return commitPrivateReceiptTransition(
+ original.repository,
+ transition.value
+ );
+ }
+ );
+ } catch {
+ return { status: 'unknown_completion' };
+ }
+}
diff --git a/web/tests/e2e/harness/stop-send.ts b/web/tests/e2e/harness/stop-send.ts
@@ -0,0 +1,346 @@
+import {
+ stopPrivateSend,
+ privateStopSendSnapshot
+} from '../../../src/lib/messaging/stop-send.ts';
+import { privateSendStatus } from '../../../src/lib/messaging/send-status.ts';
+import { reconcilePrivateSendAttempt } from '../../../src/lib/persistence/private-send-settlements.ts';
+import {
+ capturePrivatePublication,
+ capturePrivatePublicationAction
+} from '../../../src/lib/nostr/private-publisher.ts';
+import {
+ publishPrivateGiftWrapAttempt,
+ type PrivateGiftWrapAttemptResult
+} from '../../../src/lib/nostr/private-pool.ts';
+import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts';
+import {
+ validateRelayPolicy,
+ readRelayPolicy
+} from '../../../src/lib/config/relays.ts';
+import { createInboxRoutePlan } from '../../../src/lib/messaging/inbox-routing.ts';
+import {
+ createPrivateSession,
+ closePrivateSession
+} from '../../../src/lib/runtime/private-session.ts';
+import {
+ getPrivatePool,
+ closePrivatePool
+} from '../../../src/lib/nostr/private-pool.ts';
+import {
+ resumeEncryptedPreparation,
+ qualifyRecoveredPrivatePair,
+ resumePreparationSnapshot,
+ resumeRecoveredRumor,
+ stopResumePreparation
+} from '../../../src/lib/messaging/resume-preparation.ts';
+import { rumorPlanSnapshot } from '../../../src/lib/messaging/rumor-plan.ts';
+import { decodePrivateRecord } from '../../../src/lib/persistence/private-records.ts';
+import {
+ capturePrivateRetry,
+ runPrivateRetry,
+ type PrivateRetry
+} from '../../../src/lib/messaging/retry-send.ts';
+import {
+ pairedDeliveryAcknowledgementSnapshot,
+ commitPairedDeliveryReceipt,
+ type PairedDeliveryAcknowledgement
+} from '../../../src/lib/persistence/private-sends.ts';
+export async function makeFixture(initialise = true) {
+ const f = await makeRecoveryFixture(initialise);
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ ...readRelayPolicy(f.context.policy),
+ messagingEnabled: true
+ })
+ );
+ if (!policy) throw Error('invalid private fixture policy');
+ const plan = createInboxRoutePlan(
+ policy,
+ f.owner,
+ f.peer,
+ f.context.own,
+ f.context.other
+ );
+ if (!plan) throw Error('missing private route plan');
+ const context = { ...f.context, policy, plan };
+ const session = await createPrivateSession(
+ f.identity,
+ 'reviewed_private_session'
+ );
+ if (!session) throw Error('missing genuine private session');
+ const pool = getPrivatePool(session, policy, [
+ 'wss://peer.example.org',
+ 'wss://archive.example.org'
+ ]);
+ if (!pool) throw Error('missing private pool');
+ const resume = f.capture();
+ let receipt: PairedDeliveryAcknowledgement | undefined,
+ retry: PrivateRetry | undefined;
+ let observed: PrivateGiftWrapAttemptResult | undefined;
+ let restoreFault = () => {},
+ injected = 0;
+ async function prepare() {
+ const recovered = await resumeEncryptedPreparation(
+ resume,
+ context,
+ 'reviewed_private_resume'
+ );
+ if (!['prepared', 'already_prepared'].includes(recovered.status))
+ return recovered;
+ const qualified = await qualifyRecoveredPrivatePair(
+ resume,
+ context,
+ 'reviewed_stored_private_retry'
+ );
+ if ('receipt' in qualified) receipt = qualified.receipt;
+ return { status: qualified.status };
+ }
+ function capture(review: unknown = 'reviewed_private_retry') {
+ retry = receipt
+ ? capturePrivateRetry(
+ f.repository,
+ session!,
+ receipt,
+ context,
+ pool!,
+ review
+ )
+ : undefined;
+ return !!retry;
+ }
+ return {
+ ...f,
+ async row() {
+ const value = await f.row();
+ if (!value) throw Error('missing actual paired row');
+ return value;
+ },
+ async sendStatus() {
+ const row = await f.row();
+ const decoded = row && decodePrivateRecord(row.wire, f.owner, f.command);
+ return decoded?.ok
+ ? privateSendStatus(decoded.value, f.owner, f.command)
+ : undefined;
+ },
+ async publishObserved() {
+ if (!receipt) throw Error('missing genuine pair');
+ const action = capturePrivatePublicationAction(
+ f.repository,
+ session,
+ receipt,
+ context,
+ 'reviewed_private_retry'
+ );
+ const permission =
+ action &&
+ capturePrivatePublication(
+ f.repository,
+ session,
+ receipt,
+ context,
+ 'peer',
+ 'wss://peer.example.org',
+ 'reviewed_private_delivery',
+ action
+ );
+ if (!permission) throw Error('missing genuine permission');
+ observed = await publishPrivateGiftWrapAttempt(
+ pool,
+ permission,
+ new AbortController().signal
+ );
+ return observed;
+ },
+ settleObserved(clone = false) {
+ if (!observed) throw Error('missing actual SDK result');
+ return reconcilePrivateSendAttempt(clone ? { ...observed } : observed);
+ },
+ async replaceImmutableScope() {
+ let db: IDBDatabase | undefined;
+ const native = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ if (this.objectStore.name === 'private_sends')
+ db = this.objectStore.transaction.db;
+ return native.apply(this, args);
+ };
+ let row;
+ try {
+ row = await f.row();
+ } finally {
+ IDBIndex.prototype.openCursor = native;
+ }
+ if (!db || !row) throw Error('missing native row');
+ const wire = JSON.stringify({
+ ...row.record,
+ revision: row.record.revision + 1,
+ rumorHash: 'b'.repeat(64)
+ });
+ if (!decodePrivateRecord(wire, f.owner, f.command).ok)
+ throw Error('invalid controlled successor');
+ const tx = db.transaction(['private_sends'], 'readwrite');
+ tx.objectStore('private_sends').put({
+ owner: f.owner,
+ id: f.command,
+ wire
+ });
+ await new Promise<void>((resolve, reject) => {
+ tx.addEventListener('complete', () => resolve());
+ tx.addEventListener('abort', () => reject(Error('fixture abort')));
+ });
+ return wire;
+ },
+ faultSettlement(kind: 'abort' | 'readback') {
+ const put = Reflect.get<IDBObjectStore, 'put'>(
+ IDBObjectStore.prototype,
+ 'put'
+ );
+ const cursor = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ let written = false;
+ IDBObjectStore.prototype.put = function (
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const request = put.apply(this, args);
+ if (this.name === 'private_sends') {
+ written = true;
+ if (kind === 'abort') this.transaction.abort();
+ }
+ return request;
+ };
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ if (
+ kind === 'readback' &&
+ written &&
+ this.objectStore.name === 'private_sends' &&
+ this.objectStore.transaction.mode === 'readonly'
+ )
+ throw Error('actual post-put readback failure');
+ return cursor.apply(this, args);
+ };
+ restoreFault = () => {
+ IDBObjectStore.prototype.put = put;
+ IDBIndex.prototype.openCursor = cursor;
+ };
+ },
+ prepare,
+ capture,
+ run: (review: unknown = 'reviewed_private_retry') =>
+ retry
+ ? runPrivateRetry(retry, review)
+ : Promise.resolve({ status: 'invalid' as const }),
+ snapshot: () => retry && privateStopSendSnapshot(retry),
+ proof: () => receipt && pairedDeliveryAcknowledgementSnapshot(receipt),
+ recovered: () => ({
+ snapshot: resumePreparationSnapshot(resume),
+ rumor: !!rumorPlanSnapshot(resumeRecoveredRumor(resume)!)
+ }),
+ stop: () => {
+ if (retry) stopPrivateSend(retry);
+ },
+ clearRecovery: () => stopResumePreparation(resume),
+ countsValue: () => f.counts(),
+ async controlledArchiveSuccessor() {
+ if (!receipt) throw Error('missing genuine custody');
+ const row = (await f.row())?.record;
+ if (!row) throw Error('missing actual ciphertext');
+ // Controlled metadata race, not a claim of an additional relay ACK.
+ return commitPairedDeliveryReceipt(
+ f.repository,
+ receipt,
+ JSON.stringify({
+ actionId: '12345678-1234-4234-8234-123456789abe',
+ role: 'self_archive',
+ origin: 'wss://archive.example.org',
+ attempt: 1,
+ eventId: row.self.eventId,
+ status: 'accepted',
+ observedAtMilliseconds: 100,
+ readbackWire: null
+ })
+ );
+ },
+ async injectUnacknowledgedSuccessBetweenReads() {
+ const stored = await f.row();
+ if (!stored?.record.peerArtifact || !stored.record.deliveryPlan)
+ throw Error('missing real paired record');
+ const row = stored.record;
+ const facts = [
+ row.deliveryPlan!.routes.peer,
+ row.deliveryPlan!.routes.archive
+ ].flatMap((route) =>
+ route.targets.map((origin) => ({
+ actionId: '12345678-1234-4234-8234-123456789abf',
+ role: route.role,
+ origin,
+ attempt: 1,
+ eventId:
+ route.role === 'peer'
+ ? row.peerArtifact!.eventId
+ : row.self.eventId,
+ status: 'accepted',
+ observedAtMilliseconds: 100,
+ readbackWire: null
+ }))
+ );
+ const wire = JSON.stringify({
+ ...row,
+ revision: row.revision + 1,
+ receipts: [...(row.receipts ?? []), ...facts]
+ });
+ if (!decodePrivateRecord(wire, f.owner, f.command).ok)
+ throw Error('invalid controlled race row');
+ const native = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ const request = native.apply(this, args);
+ if (this.objectStore.name === 'private_sends' && injected === 0) {
+ injected++;
+ // Queue real RW behind first genuine verification and ahead of the
+ // next load. No opaque acknowledgement is renewed by this mutation.
+ const transaction = this.objectStore.transaction.db.transaction(
+ ['private_sends'],
+ 'readwrite'
+ );
+ transaction
+ .objectStore('private_sends')
+ .put({ owner: f.owner, id: f.command, wire });
+ }
+ return request;
+ };
+ restoreFault = () => {
+ IDBIndex.prototype.openCursor = native;
+ };
+ return {
+ originalWire: stored.wire,
+ changedWire: wire,
+ revision: row.revision
+ };
+ },
+ injected: () => injected,
+ clearFault() {
+ restoreFault();
+ restoreFault = () => {};
+ },
+ close() {
+ restoreFault();
+ if (retry) stopPrivateSend(retry);
+ stopResumePreparation(resume);
+ closePrivatePool(pool);
+ closePrivateSession(session);
+ f.close();
+ }
+ };
+}
diff --git a/web/tests/e2e/stop-send.spec.ts b/web/tests/e2e/stop-send.spec.ts
@@ -0,0 +1,514 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+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/stop-send.ts';
+declare global {
+ interface Window {
+ hcp089: typeof Fixture;
+ hcp089Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>;
+ hcp089Pending: ReturnType<
+ Awaited<ReturnType<typeof Fixture.makeFixture>>['run']
+ >;
+ hcp089Advance: () => void;
+ hcp089Release: () => void;
+ hcp089Waiting: boolean;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let events: { origin: string; wire: string }[] = [],
+ response: 'accepted' | 'refused' | 'unknown' | 'silent' = 'accepted';
+let archiveResponse: 'accepted' | 'refused' | 'unknown' | 'silent' | undefined;
+let pendingAcks: { socket: import('ws').WebSocket; id: string }[] = [];
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 65536
+ });
+ 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) =>
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes),
+ frame = JSON.parse(raw.toString()) as unknown[];
+ if (frame[0] !== 'EVENT') return;
+ const event = frame[1] as { id: string };
+ pendingAcks.push({ socket, id: event.id });
+ events.push({
+ origin: new URL(request.url!, 'http://localhost').searchParams.get(
+ 'origin'
+ )!,
+ wire: JSON.stringify(event)
+ });
+ const outcome =
+ events.at(-1)!.origin === 'wss://archive.example.org'
+ ? (archiveResponse ?? response)
+ : response;
+ if (outcome !== 'silent')
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ event.id,
+ outcome === 'accepted',
+ outcome === 'unknown'
+ ? 'Timeout'
+ : outcome === 'refused'
+ ? 'auth-required: fixture refusal'
+ : ''
+ ])
+ );
+ })
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/stop-send.ts', import.meta.url)
+ ),
+ name: 'hcp089',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw Error('bundle unavailable');
+ const chunks = output.output.filter((x) => x.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();
+});
+async function load(page: import('@playwright/test').Page, initialise = true) {
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async (initialise) => {
+ window.hcp089Fixture = await window.hcp089.makeFixture(initialise);
+ }, initialise);
+}
+test.beforeEach(async ({ page }) => {
+ events = [];
+ response = 'accepted';
+ archiveResponse = undefined;
+ pendingAcks = [];
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ const origin = new URL(String(url)).origin;
+ if (
+ !['wss://peer.example.org', 'wss://archive.example.org'].includes(
+ origin
+ )
+ )
+ throw Error('unapproved destination');
+ super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await load(page);
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => window.hcp089Fixture?.close());
+});
+test('Stop after an actual silent EVENT preserves original uncertain target receipt', async ({
+ page
+}) => {
+ response = 'silent';
+ const before = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ const before = await f.row();
+ window.hcp089Pending = f.run();
+ return before;
+ });
+ await expect.poll(() => events.length).toBe(1);
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.stop();
+ return {
+ result: await window.hcp089Pending,
+ row: await f.row(),
+ snapshot: f.snapshot()
+ };
+ });
+ expect(r.result.status).toBe('stopped');
+ expect(events).toHaveLength(1);
+ expect(r.row.record.self).toEqual(before.record.self);
+ expect(r.row.record.peerArtifact).toEqual(before.record.peerArtifact);
+ expect(r.row.record.receipts).toHaveLength(1);
+ expect(r.row.record.receipts![0]).toMatchObject({
+ role: 'peer',
+ origin: 'wss://peer.example.org',
+ eventId: before.record.peerArtifact!.eventId,
+ status: 'stopped',
+ attempt: 1
+ });
+});
+test('disconnect during actual publish retains original-owner uncertainty without archive or auto resume', async ({
+ page
+}) => {
+ response = 'silent';
+ const before = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ const before = await f.row();
+ window.hcp089Pending = f.run();
+ return before;
+ });
+ await expect.poll(() => events.length).toBe(1);
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.disconnect();
+ const result = await window.hcp089Pending;
+ return {
+ result,
+ row: await f.row(),
+ recapture: f.capture(),
+ rerun: await f.run()
+ };
+ });
+ expect(r.result.status).toBe('stopped');
+ expect(r.recapture).toBe(false);
+ expect(r.rerun.status).toBe('invalid');
+ expect(events).toHaveLength(1);
+ expect(r.row.record.owner).toBe(before.record.owner);
+ expect(r.row.record.self).toEqual(before.record.self);
+ expect(r.row.record.peerArtifact).toEqual(before.record.peerArtifact);
+ expect(r.row.record.receipts).toHaveLength(1);
+ expect(r.row.record.receipts![0].status).toBe('stopped');
+});
+test('Stop before execution preserves exact bytes with no attempted fact or EVENT', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ const before = await f.row();
+ f.stop();
+ return { before, after: await f.row(), result: await f.run() };
+ });
+ expect(r.result.status).toBe('stopped');
+ expect(r.after.wire).toBe(r.before.wire);
+ expect(events).toEqual([]);
+});
+test('late ACK after Stop cannot erase uncertainty or publish sender archive', async ({
+ page
+}) => {
+ response = 'silent';
+ await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ window.hcp089Pending = f.run();
+ });
+ await expect.poll(() => events.length).toBe(1);
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.stop();
+ await window.hcp089Pending;
+ return f.row();
+ });
+ for (const ack of pendingAcks)
+ if (ack.socket.readyState === 1)
+ ack.socket.send(JSON.stringify(['OK', ack.id, true, '']));
+ const after = await page.evaluate(() => window.hcp089Fixture.row());
+ expect(r.record.receipts).toHaveLength(1);
+ expect(r.record.receipts![0].status).toBe('stopped');
+ expect(after.wire).toBe(r.wire);
+ expect(events).toHaveLength(1);
+});
+test('real accepted SDK result crossing Stop and logout during receipt read preserves acceptance', async ({
+ page
+}) => {
+ await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ let acknowledged = false,
+ stopped = false;
+ // Observe the actual SDK socket's OK before the receipt read. The native
+ // transport still receives and verifies the same frame through Applesauce.
+ const cursor = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ super(url, protocols);
+ this.addEventListener('message', (event) => {
+ const frame = JSON.parse(String(event.data)) as unknown[];
+ if (frame[0] === 'OK' && frame[2] === true) acknowledged = true;
+ });
+ }
+ };
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ if (
+ acknowledged &&
+ !stopped &&
+ this.objectStore.name === 'private_sends'
+ ) {
+ stopped = true;
+ f.stop();
+ f.disconnect();
+ }
+ return cursor.apply(this, args);
+ };
+ try {
+ window.hcp089Pending = f.run();
+ await window.hcp089Pending;
+ } finally {
+ IDBIndex.prototype.openCursor = cursor;
+ window.WebSocket = Native;
+ }
+ window.hcp089Waiting = stopped;
+ });
+ const r = await page.evaluate(async () => ({
+ stopped: window.hcp089Waiting,
+ result: await window.hcp089Pending,
+ row: await window.hcp089Fixture.row(),
+ status: await window.hcp089Fixture.sendStatus()
+ }));
+ expect(r.stopped).toBe(true);
+ expect(r.result.status).toBe('stopped');
+ expect(events).toHaveLength(1);
+ expect(r.row.record.receipts).toHaveLength(1);
+ expect(r.row.record.receipts![0].status).toBe('accepted');
+ expect(r.status!.recipient.acceptedTargets).toEqual([
+ 'wss://peer.example.org'
+ ]);
+ expect(r.status!.archive.state).toBe('pending');
+});
+test('actual original-owner settlement survives logout, is idempotent and rejects a cloned result', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ const before = await f.row();
+ const result = await f.publishObserved();
+ f.disconnect();
+ const counts = f.countsValue();
+ const clone = await f.settleObserved(true),
+ first = await f.settleObserved(),
+ after = await f.row(),
+ again = await f.settleObserved(),
+ final = await f.row();
+ return {
+ result,
+ before,
+ clone,
+ first: first.status,
+ again: again.status,
+ after,
+ final,
+ counts,
+ countsAfter: f.countsValue()
+ };
+ });
+ expect(r.result.status).toBe('accepted');
+ expect(r.clone.status).toBe('invalid');
+ expect(r.first).toBe('saved');
+ expect(r.again).toBe('existing');
+ expect(r.after.wire).toBe(r.final.wire);
+ expect(r.after.record.receipts).toHaveLength(1);
+ expect(r.after.record.owner).toBe(r.before.record.owner);
+ expect(r.after.record.self).toEqual(r.before.record.self);
+ expect(r.after.record.peerArtifact).toEqual(r.before.record.peerArtifact);
+ expect(r.countsAfter).toEqual(r.counts);
+ expect(events).toHaveLength(1);
+});
+test('late actual result cannot attach to a different immutable operation scope', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ await f.publishObserved();
+ const wire = await f.replaceImmutableScope();
+ return { wire, result: await f.settleObserved(), after: await f.row() };
+ });
+ expect(r.result.status).toBe('conflict');
+ expect(r.after.wire).toBe(r.wire);
+ expect(r.after.record.receipts).toBeUndefined();
+ expect(events).toHaveLength(1);
+});
+test('real settlement IDB abort is not durable success and explicit metadata retry preserves the original result', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ await f.publishObserved();
+ const before = await f.row();
+ f.disconnect();
+ f.faultSettlement('abort');
+ const failed = await f.settleObserved();
+ f.clearFault();
+ const after = await f.row();
+ const retried = await f.settleObserved();
+ return {
+ before,
+ after,
+ failed,
+ retried: retried.status,
+ row: await f.row()
+ };
+ });
+ expect(r.failed.status).toBe('aborted');
+ expect(r.after.wire).toBe(r.before.wire);
+ expect(r.retried).toBe('saved');
+ expect(r.row.record.receipts).toHaveLength(1);
+ expect(events).toHaveLength(1);
+});
+test('real post-put settlement readback failure remains unknown despite committed bytes', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ await f.publishObserved();
+ f.disconnect();
+ f.faultSettlement('readback');
+ const failed = await f.settleObserved();
+ f.clearFault();
+ const retried = await f.settleObserved();
+ return { failed, retried: retried.status, row: await f.row() };
+ });
+ expect(r.failed.status).toBe('unknown_completion');
+ expect(r.retried).toBe('existing');
+ expect(r.row.record.receipts).toHaveLength(1);
+ expect(events).toHaveLength(1);
+});
+test('stopped projection retains uncertain target and honest recipient/archive language', async ({
+ page
+}) => {
+ response = 'silent';
+ await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ window.hcp089Pending = f.run();
+ });
+ await expect.poll(() => events.length).toBe(1);
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.stop();
+ await window.hcp089Pending;
+ return { snapshot: f.snapshot(), status: await f.sendStatus() };
+ });
+ expect(r.snapshot!.labels).toContain('Stopped');
+ expect(r.status!.recipient.uncertainTargets).toEqual([
+ 'wss://peer.example.org'
+ ]);
+ expect(r.status!.labels).toContain('Recipient delivery unknown');
+ expect(r.status!.labels).toContain('Sender archive pending');
+ expect([...r.snapshot!.labels, ...r.status!.labels].join(' ')).not.toMatch(
+ /Order accepted|Seen|Read|Delivered to person|permanent retention|guaranteed notification/
+ );
+});
+test('reload remembers ciphertext but only explicit matching-owner Resume publishes original artifacts', async ({
+ page
+}) => {
+ response = 'silent';
+ const before = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ const row = await f.row();
+ window.hcp089Pending = f.run();
+ return row;
+ });
+ await expect.poll(() => events.length).toBe(1);
+ const stopped = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.stop();
+ await window.hcp089Pending;
+ return f.row();
+ });
+ await page.reload();
+ await load(page, false);
+ expect(events).toHaveLength(1);
+ const captured = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ const prepared = await f.prepare();
+ return { prepared, captured: f.capture(), row: await f.row() };
+ });
+ expect(captured.prepared.status).toBe('existing');
+ expect(captured.captured).toBe(true);
+ expect(events).toHaveLength(1);
+ expect(captured.row.wire).toBe(stopped.wire);
+ response = 'accepted';
+ const resumed = await page.evaluate(async () => ({
+ result: await window.hcp089Fixture.run(),
+ row: await window.hcp089Fixture.row()
+ }));
+ expect(resumed.result.status).toBe('completed');
+ expect(events).toHaveLength(3);
+ expect(events.slice(1).map((e) => e.wire)).toEqual([
+ before.record.peerArtifact!.wire,
+ before.record.self.wire
+ ]);
+ expect(resumed.row.record.receipts).toHaveLength(3);
+ expect(resumed.row.record.receipts![0]).toEqual(stopped.record.receipts![0]);
+});
+test('Stop in sender archive preserves actual prior recipient acceptance and partial archive uncertainty', async ({
+ page
+}) => {
+ archiveResponse = 'silent';
+ await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ await f.prepare();
+ f.capture();
+ window.hcp089Pending = f.run();
+ });
+ await expect.poll(() => events.length).toBe(2);
+ const r = await page.evaluate(async () => {
+ const f = window.hcp089Fixture;
+ f.stop();
+ const result = await window.hcp089Pending;
+ return { result, row: await f.row(), status: await f.sendStatus() };
+ });
+ expect(r.result.status).toBe('stopped');
+ expect(events).toHaveLength(2);
+ expect(r.row.record.receipts!.map((f) => [f.role, f.status])).toEqual([
+ ['peer', 'accepted'],
+ ['self_archive', 'stopped']
+ ]);
+ expect(r.status!.recipient.state).toBe('accepted_by_inbox_relay');
+ expect(r.status!.archive.state).toBe('pending');
+ expect(r.status!.partial).toBe(true);
+ expect(r.status!.labels).toContain('Accepted by recipient inbox relay');
+ expect(r.status!.labels).toContain('Partial delivery');
+ expect(r.status!.labels).toContain('Sender archive pending');
+});
diff --git a/web/tests/unit/stop-send.test.ts b/web/tests/unit/stop-send.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect } from 'vitest';
+import { reconcilePrivateSendAttempt } from '../../src/lib/persistence/private-send-settlements.ts';
+import {
+ stopPrivateSend,
+ privateStopSendSnapshot
+} from '../../src/lib/messaging/stop-send.ts';
+import type { PrivateRetry } from '../../src/lib/messaging/retry-send.ts';
+describe('original-operation stopped send provenance', () => {
+ it('structural accepted result cannot mint any original-owner receipt', async () => {
+ expect(
+ await reconcilePrivateSendAttempt({
+ status: 'accepted',
+ role: 'peer',
+ origin: 'wss://peer.example.org',
+ eventId: 'a'.repeat(64),
+ actionId: '12345678-1234-4234-8234-123456789abc',
+ attempt: 1
+ })
+ ).toEqual({ status: 'invalid' });
+ });
+ it('forged retry has no stopped send projection or effect', () => {
+ const retry = {} as PrivateRetry;
+ stopPrivateSend(retry);
+ expect(privateStopSendSnapshot(retry)).toBeUndefined();
+ });
+});