commit f410e0bebdca9506740708e4bf21823eaf0d6412
parent 966fa040937e8c209ee0e5e9b9a7c8c567736515
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 23:48:22 +0000
web: complete the seller workspace index (HCP-121)
- Group seller attention, drafts and listings by original ownership.
- Preserve publication receipts and source-aware continuation links.
- Retire account-bound rows across explicit identity transitions.
- Verify browser behavior against the accepted Rust 1.99 basis.
Diffstat:
11 files changed, 1663 insertions(+), 20 deletions(-)
diff --git a/web/src/lib/components/SellingRow.svelte b/web/src/lib/components/SellingRow.svelte
@@ -0,0 +1,29 @@
+<script lang="ts">
+ import type { SellingRow } from '../publishing/selling-view.ts';
+ import { internalHref } from '../navigation-url.ts';
+ import Disclosure from './primitives/Disclosure.svelte';
+ import OperationStatus from './OperationStatus.svelte';
+ let { row }: { row: SellingRow } = $props();
+</script>
+
+<article class="stack">
+ <h3>{row.title}</h3>
+ <p>{row.status}</p>
+ <p>
+ {row.provenance}{#if !row.editHref && !row.draftHref}
+ · Read-only{/if}
+ </p>
+ <div class="cluster">
+ {#if row.draftHref}<a href={internalHref(row.draftHref)}>Continue editing</a
+ >{/if}
+ {#if row.href}<a href={internalHref(row.href)}>View listing</a>{/if}
+ {#if row.editHref}<a href={internalHref(row.editHref)}>Edit</a>{/if}
+ </div>
+ {#if row.operations.length}
+ <Disclosure summary="Delivery details">
+ {#each row.operations as operation (operation)}
+ <OperationStatus publicOperation={operation} />
+ {/each}
+ </Disclosure>
+ {/if}
+</article>
diff --git a/web/src/lib/publishing/selling-view.ts b/web/src/lib/publishing/selling-view.ts
@@ -0,0 +1,577 @@
+import {
+ identityViewSession,
+ identityViewMatchesOwner,
+ subscribeIdentityView,
+ type IdentityViewContext
+} from '../runtime/view-context.ts';
+import { identitySessionSnapshot } from '../runtime/identity-session.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ type BrowserDatabase
+} from '../persistence/database.ts';
+import {
+ createPublicPublicationRepository,
+ publicPublicationDraftRepository,
+ publicPublicationQuotaRepository,
+ readPublicListingIntent
+} from '../persistence/public-publications.ts';
+import { listPublicDrafts } from '../persistence/drafts.ts';
+import {
+ inspectPublicStorage,
+ publicInventorySnapshot
+} from '../persistence/quota.ts';
+import { publicRecordSnapshot } from '../persistence/records.ts';
+import { inspectLocalTemplate } from '../nostr/local-template.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../nostr/verified-envelope.ts';
+import { encodeProductReference } from '../nostr/references.ts';
+import { internalHref } from '../navigation-url.ts';
+import {
+ projectFoodParts,
+ type FoodProjection
+} from '../contracts/food-availability-v1/read.ts';
+import {
+ readListingOperationView,
+ listingOperationSnapshot,
+ closeListingOperationView,
+ type ListingOperationView
+} from './listing-operation-view.ts';
+import {
+ openOwnedEditSource,
+ ownedEditSourceSnapshot,
+ closeOwnedEditSource
+} from './edit-source.ts';
+import {
+ createPublicView,
+ beginPublicViewRun,
+ subscribePublicView,
+ disposePublicView,
+ publicViewOwnsRun,
+ publicViewProjectionAvailable,
+ publicViewRunCurrent,
+ type PublicRuntime,
+ type PublicView
+} from '../runtime/public-runtime.ts';
+import {
+ createPublicHeadCandidate,
+ publicHeadKey,
+ publicHeadSnapshot,
+ selectPublicHead,
+ type PublicHead
+} from '../catalog/heads.ts';
+import {
+ createPublicViewHeadResolver,
+ resolveHeads,
+ headResolutionSnapshot,
+ closeHeadResolver,
+ type HeadResolver
+} from '../catalog/resolve-head.ts';
+import {
+ publicRequestScopeSnapshot,
+ publicRunSnapshot,
+ type PublicRequest,
+ type PublicRun
+} from '../nostr/request-scope.ts';
+import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';
+
+declare const viewBrand: unique symbol;
+export type SellingView = Readonly<{ [viewBrand]: true }>;
+export type SellingRow = Readonly<{
+ key: string;
+ title: string;
+ status: string;
+ provenance: string;
+ href?: string;
+ editHref?: string;
+ draftHref?: string;
+ operations: readonly ListingOperationView[];
+}>;
+export type SellingSnapshot = Readonly<{
+ attention: readonly SellingRow[];
+ drafts: readonly SellingRow[];
+ listings: readonly SellingRow[];
+ remote: 'checking' | 'bounded' | 'partial' | 'unavailable';
+ local: 'ready' | 'unavailable';
+}>;
+type Controller = {
+ snapshot(): SellingSnapshot | undefined;
+ subscribe(listener: () => void): () => void;
+ close(): void;
+};
+type Group = {
+ key: string;
+ food: FoodProjection;
+ createdAt: number;
+ eventId: string;
+ removal: boolean;
+ operations: ListingOperationView[];
+ attention: boolean;
+ supportedEventId?: string;
+ draftId?: string;
+};
+const views = new WeakMap<SellingView, Controller>();
+const active = new WeakMap<IdentityViewContext, Controller>();
+
+// Account-local presentation only. Neither a row, link nor operation disclosure
+// grants signing, delivery, adopted-source or current-head permission.
+export async function openSellingView(
+ context: IdentityViewContext,
+ runtime?: PublicRuntime
+): Promise<SellingView | undefined> {
+ const identity = identityViewSession(context);
+ const observed = identity && identitySessionSnapshot(identity);
+ const owner =
+ observed && 'publicKey' in observed ? observed.publicKey : undefined;
+ if (!identity || !owner || !identityViewMatchesOwner(context, owner)) return;
+ active.get(context)?.close();
+ let alive = true,
+ database: BrowserDatabase | undefined;
+ let publicView: PublicView | undefined, run: PublicRun | undefined;
+ let resolver: HeadResolver | undefined, discovery: PublicRequest | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let offIdentity = () => {};
+ let local: SellingSnapshot['local'] = 'unavailable';
+ let remote: SellingSnapshot['remote'] = runtime ? 'checking' : 'unavailable';
+ const listeners = new Map<symbol, () => void>();
+ const groups = new Map<string, Group>();
+ const draftRows = new Map<string, SellingRow>();
+ let operationViews = Array.from<ListingOperationView>([]);
+ const heads = new Map<string, PublicHead>();
+ const linkedDrafts = new Map<string, true>();
+ const current = () =>
+ alive &&
+ active.get(context) === controller &&
+ identityViewSession(context) === identity &&
+ identityViewMatchesOwner(context, owner);
+ function notify() {
+ for (const listener of listeners.values()) {
+ try {
+ listener();
+ } catch {
+ /* Presentation cannot interrupt owned cleanup. */
+ }
+ }
+ }
+ function close() {
+ if (!alive) return;
+ alive = false;
+ offIdentity();
+ if (timer !== undefined) clearTimeout(timer);
+ for (const view of operationViews) closeListingOperationView(view);
+ try {
+ if (resolver) closeHeadResolver(resolver);
+ } finally {
+ try {
+ if (publicView) disposePublicView(publicView);
+ } finally {
+ if (database) closeBrowserDatabase(database);
+ }
+ }
+ if (active.get(context) === controller) active.delete(context);
+ groups.clear();
+ draftRows.clear();
+ heads.clear();
+ notify();
+ listeners.clear();
+ }
+ const hrefFor = (identifier: string) => {
+ const naddr = encodeProductReference({
+ kind: 30402,
+ pubkey: owner,
+ identifier
+ });
+ return naddr ? internalHref(`/products/${naddr}`) : undefined;
+ };
+ function snapshot(): SellingSnapshot | undefined {
+ if (!current()) return;
+ let attention = Array.from<SellingRow>([]),
+ listings = Array.from<SellingRow>([]);
+ const rows =
+ resolver &&
+ publicView &&
+ run &&
+ publicViewOwnsRun(publicView, run) &&
+ publicViewProjectionAvailable(publicView)
+ ? headResolutionSnapshot(resolver)
+ : [];
+ const remoteByIdentifier = new Map(
+ rows.map((row) => [row.state.head.identifier, row])
+ );
+ for (const group of groups.values()) {
+ const known = remoteByIdentifier.get(group.food.identifier);
+ const food = known?.state.food ?? group.food;
+ const suppressed = known?.deletion.outcome === 'suppressed';
+ const href = hrefFor(food.identifier);
+ const canEdit = !!(
+ href &&
+ group.supportedEventId &&
+ !group.removal &&
+ !suppressed &&
+ (!known ||
+ (known.state.head.id === group.supportedEventId &&
+ known.state.display === 'focused_known'))
+ );
+ const row: SellingRow = {
+ key: group.key,
+ title: food.title,
+ status: group.removal
+ ? 'Removal request retained locally'
+ : suppressed
+ ? 'Listing no longer shown; delivery records retained'
+ : known?.state.food
+ ? food.status === 'sold'
+ ? 'Marked sold'
+ : 'Marked available'
+ : 'Saved public operation; current availability unconfirmed',
+ provenance: 'Local publication evidence · Remote discovery is bounded',
+ ...(href ? { href } : {}),
+ ...(canEdit ? { editHref: internalHref(`${href}/edit`) } : {}),
+ ...(group.attention &&
+ group.draftId &&
+ draftRows.get(group.draftId)?.draftHref
+ ? { draftHref: draftRows.get(group.draftId)?.draftHref }
+ : {}),
+ operations: group.operations.slice()
+ };
+ if (group.attention) attention = attention.concat(row);
+ else listings = listings.concat(row);
+ remoteByIdentifier.delete(group.food.identifier);
+ }
+ for (const row of remoteByIdentifier.values()) {
+ if (
+ !row.state.food ||
+ row.state.head.pubkey !== owner ||
+ row.state.display !== 'focused_known' ||
+ row.deletion.outcome === 'suppressed'
+ )
+ continue;
+ const href = hrefFor(row.state.food.identifier);
+ if (!href) continue;
+ listings = listings.concat({
+ key: row.key,
+ title: row.state.food.title,
+ status:
+ row.state.food.status === 'sold' ? 'Marked sold' : 'Marked available',
+ provenance:
+ 'Bounded remote discovery · Read-only; no supported retained prototype source',
+ href,
+ operations: []
+ });
+ }
+ return {
+ attention,
+ drafts: Array.from(draftRows, ([id, row]) =>
+ linkedDrafts.has(id) ? undefined : row
+ ).filter((row): row is SellingRow => !!row),
+ listings,
+ local,
+ remote
+ };
+ }
+ const controller: Controller = {
+ snapshot,
+ subscribe(listener) {
+ const stamp = Symbol();
+ listeners.set(stamp, listener);
+ return () => {
+ listeners.delete(stamp);
+ };
+ },
+ close
+ };
+ active.set(context, controller);
+ offIdentity = subscribeIdentityView(context, () => {
+ if (!current()) close();
+ });
+ try {
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') {
+ close();
+ return;
+ }
+ if (!current()) {
+ closeBrowserDatabase(opened.owner);
+ close();
+ return;
+ }
+ database = opened.owner;
+ const repository = createPublicPublicationRepository(database, owner);
+ const drafts = repository && publicPublicationDraftRepository(repository);
+ const quota = repository && publicPublicationQuotaRepository(repository);
+ if (!repository || !drafts || !quota) {
+ close();
+ return;
+ }
+ const saved = await listPublicDrafts(drafts);
+ if (!current() || !saved.ok) {
+ close();
+ return;
+ }
+ for (const draft of saved.value) {
+ const href = internalHref(`/selling/drafts/${draft.id}`);
+ if (href)
+ draftRows.set(draft.id, {
+ key: `draft:${draft.id}`,
+ title: draft.form.title || 'Untitled draft',
+ status: 'Saved in this browser · Not published',
+ provenance: 'Local draft',
+ draftHref: href,
+ operations: []
+ });
+ }
+ const inspected = await inspectPublicStorage(quota);
+ if (!current() || !inspected.ok) {
+ close();
+ return;
+ }
+ const inventory = publicInventorySnapshot(quota, inspected.value);
+ if (!inventory) {
+ close();
+ return;
+ }
+ for (const item of inventory.rows) {
+ if (item.family !== 'public_operation') continue;
+ const read = await readPublicListingIntent(repository, item.id);
+ if (!current() || read.status !== 'found') {
+ close();
+ return;
+ }
+ const record = publicRecordSnapshot(read.record, owner, item.id);
+ if (!record || record.family !== 'public_operation') {
+ close();
+ return;
+ }
+ if (record.capture.kind !== 30402 && record.capture.kind !== 5) continue;
+ const template = inspectLocalTemplate(
+ record.capture.wire,
+ owner,
+ record.capture.kind
+ );
+ const base =
+ record.capture.kind === 5 && record.source.type === 'public_head'
+ ? verifyEnvelope(record.source.wire)
+ : undefined;
+ const source = base?.ok ? verifiedEnvelopeSnapshot(base.value) : template;
+ const projected = source && projectFoodParts(source);
+ if (!template || !projected || projected.outcome !== 'focused') continue;
+ const key = JSON.stringify([
+ 30402,
+ owner,
+ projected.projection.identifier
+ ]);
+ const presented = await readListingOperationView(
+ repository,
+ identity,
+ item.id
+ );
+ if (!current() || presented.status !== 'found') {
+ if (presented.status === 'found')
+ closeListingOperationView(presented.view);
+ close();
+ return;
+ }
+ operationViews = operationViews.concat(presented.view);
+ const facts = listingOperationSnapshot(presented.view);
+ if (!facts) {
+ close();
+ return;
+ }
+ let group = groups.get(key);
+ if (!group) {
+ group = {
+ key,
+ food: projected.projection,
+ createdAt: template.created_at,
+ eventId: record.capture.hash,
+ removal: template.kind === 5,
+ attention: false,
+ operations: [],
+ ...(record.source.type === 'draft'
+ ? { draftId: record.source.id }
+ : {})
+ };
+ groups.set(key, group);
+ }
+ if (
+ template.created_at > group.createdAt ||
+ (template.created_at === group.createdAt &&
+ record.capture.hash < group.eventId)
+ ) {
+ group = {
+ ...group,
+ food: projected.projection,
+ createdAt: template.created_at,
+ eventId: record.capture.hash,
+ removal: template.kind === 5,
+ ...(record.source.type === 'draft'
+ ? { draftId: record.source.id }
+ : {})
+ };
+ }
+ group = {
+ ...group,
+ operations: group.operations.concat(presented.view),
+ attention:
+ group.attention ||
+ facts.needsAction ||
+ !record.artifact ||
+ facts.targets.some(
+ (target) => !target.accepted || target.readback !== 'confirmed'
+ )
+ };
+ groups.set(key, group);
+ const capturedSource = record.source;
+ if (
+ capturedSource.type === 'draft' &&
+ saved.value.some(
+ (draft) =>
+ draft.id === capturedSource.id &&
+ draft.revision === capturedSource.revision
+ )
+ )
+ linkedDrafts.set(capturedSource.id, true);
+ if (record.artifact && record.capture.kind === 30402) {
+ const proof = verifyEnvelope(record.artifact.wire);
+ const head = proof.ok && createPublicHeadCandidate(proof.value);
+ if (head) {
+ const prior = heads.get(publicHeadKey(head));
+ heads.set(publicHeadKey(head), selectPublicHead(prior, head).head);
+ }
+ }
+ }
+ // Reuse the original retained-source verifier without starting a network
+ // run or adopting a remote source. Edit's route performs its own fresh
+ // independent current-head checks; this metadata grants no effect custody.
+ for (const group of groups.values()) {
+ if (group.attention && group.draftId && draftRows.has(group.draftId))
+ linkedDrafts.set(group.draftId, true);
+ const naddr = encodeProductReference({
+ kind: 30402,
+ pubkey: owner,
+ identifier: group.food.identifier
+ });
+ const source =
+ naddr && (await openOwnedEditSource(repository, context, naddr));
+ if (!current()) {
+ if (source) closeOwnedEditSource(source);
+ close();
+ return;
+ }
+ const supported = source ? ownedEditSourceSnapshot(source) : undefined;
+ if (supported)
+ groups.set(group.key, {
+ ...group,
+ supportedEventId: supported.sourceEventId
+ });
+ if (source) closeOwnedEditSource(source);
+ }
+ local = 'ready';
+ if (runtime) {
+ try {
+ publicView = createPublicView(runtime);
+ run = beginPublicViewRun(publicView);
+ resolver = createPublicViewHeadResolver(publicView, run, {
+ nowSeconds: () => Math.floor(Date.now() / 1000)
+ });
+ discovery = subscribePublicView(
+ publicView,
+ run,
+ 'head',
+ [
+ {
+ kinds: [30402],
+ authors: [owner],
+ limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay
+ }
+ ],
+ (proof) => {
+ if (!current()) return;
+ const head = createPublicHeadCandidate(proof);
+ if (!head || publicHeadSnapshot(head).pubkey !== owner) return;
+ const key = publicHeadKey(head);
+ if (
+ !heads.has(key) &&
+ heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun
+ )
+ return;
+ heads.set(key, selectPublicHead(heads.get(key), head).head);
+ }
+ );
+ function observe() {
+ if (!current()) return;
+ if (
+ !publicView ||
+ !run ||
+ !resolver ||
+ !discovery ||
+ !publicViewOwnsRun(publicView, run) ||
+ !publicViewProjectionAvailable(publicView)
+ ) {
+ remote = 'unavailable';
+ notify();
+ return;
+ }
+ try {
+ if (publicViewRunCurrent(publicView, run))
+ resolveHeads(
+ resolver,
+ Array.from(heads.values()).slice(
+ 0,
+ PUBLIC_QUERY_BUDGETS.coordinatesPerRun
+ )
+ );
+ const rows = headResolutionSnapshot(resolver);
+ const source = publicRequestScopeSnapshot(discovery);
+ remote =
+ source.state === 'eose' &&
+ source.result.coverage === 'bounded-eose' &&
+ rows.every((row) => row.coverage === 'bounded-eose')
+ ? 'bounded'
+ : publicRunSnapshot(run).activeRequests > 0
+ ? 'checking'
+ : 'partial';
+ } catch {
+ remote = 'partial';
+ }
+ notify();
+ if (
+ current() &&
+ publicRunSnapshot(run).active &&
+ publicRunSnapshot(run).activeRequests > 0
+ )
+ timer = setTimeout(observe, 250);
+ }
+ observe();
+ } catch {
+ remote = 'unavailable';
+ }
+ }
+ if (!current()) {
+ close();
+ return;
+ }
+ const token = Object.freeze({}) as SellingView;
+ views.set(token, controller);
+ return token;
+ } catch {
+ close();
+ return;
+ }
+}
+export function sellingViewSnapshot(
+ view: SellingView
+): SellingSnapshot | undefined {
+ return views.get(view)?.snapshot();
+}
+export function subscribeSellingView(
+ view: SellingView,
+ listener: () => void
+): () => void {
+ return views.get(view)?.subscribe(listener) ?? (() => {});
+}
+export function closeSellingView(view: SellingView): void {
+ views.get(view)?.close();
+}
diff --git a/web/src/routes/selling/+page.svelte b/web/src/routes/selling/+page.svelte
@@ -1,5 +1,173 @@
<script lang="ts">
- import AccountGate from '../../lib/components/AccountGate.svelte';
+ import { getContext, onMount } from 'svelte';
+ import CapabilityGate from '../../lib/components/CapabilityGate.svelte';
+ import SellingRow from '../../lib/components/SellingRow.svelte';
+ import InboxSetup from '../../lib/components/InboxSetup.svelte';
+ import Disclosure from '../../lib/components/primitives/Disclosure.svelte';
+ import { internalHref } from '../../lib/navigation-url.ts';
+ import {
+ IDENTITY_VIEW_CONTEXT,
+ identityViewSnapshot,
+ identityViewSession,
+ subscribeIdentityView,
+ connectIdentityView,
+ disconnectIdentityView,
+ type IdentityViewContext
+ } from '../../lib/runtime/view-context.ts';
+ import {
+ PUBLIC_RUNTIME_CONTEXT,
+ publicRuntimeReady,
+ type PublicRuntimeContext,
+ type PublicRuntime
+ } from '../../lib/runtime/public-runtime.ts';
+ import {
+ openSellingView,
+ sellingViewSnapshot,
+ subscribeSellingView,
+ closeSellingView,
+ type SellingView,
+ type SellingSnapshot
+ } from '../../lib/publishing/selling-view.ts';
+ const identityContext = getContext<IdentityViewContext>(
+ IDENTITY_VIEW_CONTEXT
+ );
+ const publicContext = getContext<PublicRuntimeContext>(
+ PUBLIC_RUNTIME_CONTEXT
+ );
+ let identity = $state(identityViewSnapshot(identityContext));
+ let result = $state.raw<SellingSnapshot | undefined>();
+ let unavailable = $state(false);
+ onMount(() => {
+ let disposed = false,
+ runtimeReady = false,
+ runtime: PublicRuntime | undefined;
+ let owner: string | undefined,
+ generation = Symbol();
+ let session: ReturnType<typeof identityViewSession>;
+ let view: SellingView | undefined,
+ off = () => {};
+ function acquire() {
+ const observed = identityViewSnapshot(identityContext);
+ identity = observed;
+ const selected =
+ observed.mounted && 'publicKey' in observed.identity
+ ? observed.identity.publicKey
+ : undefined;
+ const selectedSession = identityViewSession(identityContext);
+ if (!runtimeReady || (selected === owner && selectedSession === session))
+ return;
+ owner = selected;
+ session = selectedSession;
+ generation = Symbol();
+ const original = generation;
+ off();
+ if (view) closeSellingView(view);
+ view = undefined;
+ result = undefined;
+ unavailable = false;
+ if (!selected) return;
+ void openSellingView(identityContext, runtime)
+ .then((next) => {
+ if (disposed || generation !== original) {
+ if (next) closeSellingView(next);
+ return;
+ }
+ if (!next) {
+ unavailable = true;
+ return;
+ }
+ view = next;
+ result = sellingViewSnapshot(next);
+ off = subscribeSellingView(next, () => {
+ result = sellingViewSnapshot(next);
+ unavailable = !result;
+ });
+ })
+ .catch(() => {
+ if (!disposed && generation === original) unavailable = true;
+ });
+ }
+ const identityOff = subscribeIdentityView(identityContext, acquire);
+ void publicRuntimeReady(publicContext)
+ .then((next) => {
+ if (disposed) return;
+ runtime = next;
+ runtimeReady = true;
+ acquire();
+ })
+ .catch(() => {
+ if (!disposed) {
+ runtimeReady = true;
+ acquire();
+ }
+ });
+ return () => {
+ disposed = true;
+ generation = Symbol();
+ identityOff();
+ off();
+ if (view) closeSellingView(view);
+ };
+ });
+ function connect() {
+ return connectIdentityView(identityContext);
+ }
+ function disconnect() {
+ disconnectIdentityView(identityContext);
+ }
+ const empty = $derived(
+ result?.local === 'ready' &&
+ result.remote === 'bounded' &&
+ !result.attention.length &&
+ !result.drafts.length &&
+ !result.listings.length
+ );
</script>
-<AccountGate />
+<svelte:head
+ ><title>HarvestCircle</title><meta
+ name="robots"
+ content="noindex"
+ /></svelte:head
+>
+<div class="page page--reading stack">
+ <div class="cluster">
+ <h1>Selling</h1>
+ <a href={internalHref('/sell')}>List food</a>
+ </div>
+ <CapabilityGate
+ identity={identity.identity}
+ required="connection"
+ focusTarget="protected"
+ onconnect={identity.mounted ? connect : undefined}
+ ondisconnect={disconnect}
+ />
+ {#if unavailable}<p class="notice">
+ Saved seller work is unavailable. Existing records have not been cleared.
+ </p>{/if}
+ {#if empty}<p>
+ No listings yet. Create a listing so people can ask about your food.
+ </p>{/if}
+ {#if result}
+ {#if result.attention.length}<section class="stack">
+ <h2>Needs attention</h2>
+ {#each result.attention as row (row.key)}<SellingRow {row} />{/each}
+ </section>{/if}
+ {#if result.drafts.length}<section class="stack">
+ <h2>Drafts</h2>
+ {#each result.drafts as row (row.key)}<SellingRow {row} />{/each}
+ </section>{/if}
+ {#if result.listings.length}<section class="stack">
+ <h2>Listings</h2>
+ {#each result.listings as row (row.key)}<SellingRow {row} />{/each}
+ </section>{/if}
+ <p>
+ {result.remote === 'checking'
+ ? 'Checking bounded remote listing sources.'
+ : result.remote === 'bounded'
+ ? 'Remote discovery is bounded. Other relay copies may exist.'
+ : 'Remote listing lookup is incomplete. Local records remain separate from remote discovery.'}
+ </p>
+ {/if}
+ <Disclosure summary="Inbox settings"><InboxSetup /></Disclosure>
+</div>
diff --git a/web/tests/e2e/harness/selling-index.ts b/web/tests/e2e/harness/selling-index.ts
@@ -0,0 +1,216 @@
+// HC_TEST_ONLY_RELAY/QUALIFICATION_PORT: original installed provider, native
+// IndexedDB and bounded SDK loopback. Controlled observations are not live Q.
+import { mount, unmount } from 'svelte';
+import Selling from '../../../src/routes/selling/+page.svelte';
+import { createFixture as publicationFixture } from './listing-operation-view.ts';
+import { makeFixture } from './approved-signing.ts';
+import { fixturePolicy } from './inbox-setup.ts';
+import {
+ createIdentityViewContext,
+ mountIdentityView,
+ connectIdentityView,
+ disconnectIdentityView,
+ closeIdentityView,
+ IDENTITY_VIEW_CONTEXT
+} from '../../../src/lib/runtime/view-context.ts';
+import {
+ createPublicRuntimeContext,
+ mountPublicRuntime,
+ closePublicRuntime,
+ PUBLIC_RUNTIME_CONTEXT
+} from '../../../src/lib/runtime/public-runtime.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import {
+ createPublicDraftRepository,
+ createPublicDraft,
+ readPublicDraft,
+ savePublicDraft
+} from '../../../src/lib/persistence/drafts.ts';
+import type { PublicDraftForm } from '../../../src/lib/contracts/local-records.ts';
+import type { NostrEvent } from 'applesauce-core/helpers';
+import { buildFoodTemplate } from '../../../src/lib/contracts/food-availability-v1/write.ts';
+
+export async function createFixture(mode: 'empty' | 'retained' = 'retained') {
+ const original = mode === 'retained' ? await publicationFixture() : undefined;
+ const signer = mode === 'empty' ? makeFixture() : undefined;
+ const prior = Object.getOwnPropertyDescriptor(window, 'nostr');
+ if (signer)
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: { getPublicKey: () => Promise.resolve(signer.owner) }
+ });
+ if (original && (await original.signed()) !== 'prepared')
+ throw Error('original signed source missing');
+ const row = await original?.row();
+ const event = row?.artifact
+ ? (JSON.parse(row.artifact.wire) as NostrEvent)
+ : undefined;
+ const owner = original?.owner ?? signer?.owner;
+ if (!owner) throw Error('controlled owner missing');
+ const context = createIdentityViewContext();
+ mountIdentityView(context);
+ await connectIdentityView(context);
+ const publicContext = createPublicRuntimeContext();
+ mountPublicRuntime(publicContext, fixturePolicy());
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner;
+ let panel: ReturnType<typeof mount> | undefined;
+ let target: HTMLElement | undefined;
+ let switched: ReturnType<typeof makeFixture> | undefined;
+ return {
+ owner,
+ event,
+ command: original?.command,
+ remoteListing() {
+ if (!signer) throw Error('remote-only installed owner missing');
+ const now = Math.floor(Date.now() / 1000);
+ const built = buildFoodTemplate({
+ identifier: 'remote-only-food',
+ title: 'Remote own eggs',
+ description: 'Full external own listing description',
+ location: 'External farm',
+ amount: '6',
+ currency: 'CAD',
+ unit: 'each',
+ created_at: now,
+ published_at: now,
+ status: 'active'
+ });
+ if (!built.ok) throw Error('focused external fixture invalid');
+ return signer.sign({
+ kind: 30402,
+ created_at: now,
+ tags: built.wire_parts.tags.map((tag) => [...tag]),
+ content: built.wire_parts.content
+ });
+ },
+ async switchOwner() {
+ switched = makeFixture();
+ const next = switched.owner;
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: { getPublicKey: () => Promise.resolve(next) }
+ });
+ await connectIdentityView(context);
+ return next;
+ },
+ async render() {
+ if (panel) await unmount(panel);
+ target?.remove();
+ target = document.createElement('div');
+ target.id = 'hcp121-selling';
+ document.body.append(target);
+ panel = mount(Selling, {
+ target,
+ context: new Map<string, unknown>([
+ [IDENTITY_VIEW_CONTEXT, context],
+ [PUBLIC_RUNTIME_CONTEXT, publicContext]
+ ])
+ });
+ },
+ async external() {
+ await original?.externalSource();
+ const next = await original?.row();
+ return next?.artifact
+ ? (JSON.parse(next.artifact.wire) as NostrEvent)
+ : undefined;
+ },
+ async observed(
+ status: 'accepted' | 'refused' | 'timed_out',
+ target: number,
+ readback: boolean
+ ) {
+ await original?.evidence(status, target, readback);
+ },
+ async settled() {
+ if (!original) throw Error('original operation missing');
+ const current = await original.row();
+ for (let i = 0; i < current.capture.targets.length; i++)
+ await original.evidence('accepted', i, true);
+ },
+ async draft(title = 'Unfinished spinach') {
+ const repository = createPublicDraftRepository(database, owner);
+ if (!repository) throw Error('original draft repository missing');
+ const form: PublicDraftForm = {
+ title,
+ description: '',
+ location: '',
+ amount: '',
+ currency: '',
+ unit: '',
+ quantity: '',
+ contactType: '',
+ contactValue: ''
+ };
+ const saved = await createPublicDraft(repository, form);
+ if (!saved.ok) throw Error(saved.reason);
+ return saved.value;
+ },
+ async changeCapturedDraft() {
+ const row = await original?.row();
+ if (!row || row.source.type !== 'draft')
+ throw Error('original draft capture missing');
+ const repository = createPublicDraftRepository(database, owner);
+ if (!repository) throw Error('original draft repository missing');
+ const read = await readPublicDraft(repository, row.source.id);
+ if (!read.ok) throw Error(read.reason);
+ const saved = await savePublicDraft(
+ repository,
+ read.value.id,
+ read.value.revision,
+ {
+ ...read.value.form,
+ title: 'Unfinished proposed carrots',
+ description: ''
+ }
+ );
+ if (!saved.ok) throw Error(saved.reason);
+ return saved.value;
+ },
+ async records() {
+ const transaction = browserDatabaseTransaction(
+ database,
+ ['public_drafts', 'public_operations'],
+ 'readonly'
+ );
+ const drafts = transaction.objectStore('public_drafts').getAll();
+ const operations = transaction.objectStore('public_operations').getAll();
+ return await new Promise<{ drafts: unknown[]; operations: unknown[] }>(
+ (resolve, reject) => {
+ transaction.addEventListener('complete', () =>
+ resolve({ drafts: drafts.result, operations: operations.result })
+ );
+ transaction.addEventListener('abort', () =>
+ reject(Error('native seller read failed'))
+ );
+ }
+ );
+ },
+ counts: () => original?.counts() ?? { signs: 0, keys: 0 },
+ reconnect() {
+ return connectIdentityView(context);
+ },
+ disconnect() {
+ disconnectIdentityView(context);
+ },
+ async close() {
+ if (panel) await unmount(panel);
+ target?.remove();
+ closePublicRuntime(publicContext);
+ closeIdentityView(context);
+ closeBrowserDatabase(database);
+ original?.close();
+ signer?.close();
+ switched?.close();
+ if (signer) {
+ if (prior) Object.defineProperty(window, 'nostr', prior);
+ else Reflect.deleteProperty(window, 'nostr');
+ }
+ }
+ };
+}
diff --git a/web/tests/e2e/route-inventory.spec.ts b/web/tests/e2e/route-inventory.spec.ts
@@ -155,9 +155,10 @@ for (const routeCase of cases) {
if (routeCase.private) {
await expect(
page.getByRole('heading', {
- name: routeCase.editor
- ? 'Connect to continue'
- : 'Connect or unlock',
+ name:
+ routeCase.editor || routeCase.path === '/selling'
+ ? 'Connect to continue'
+ : 'Connect or unlock',
exact: true
})
).toBeVisible();
@@ -177,6 +178,30 @@ for (const routeCase of cases) {
page.getByRole('button', { name: 'Not now', exact: true })
).toHaveCount(0);
} else {
+ if (routeCase.path === '/selling') {
+ await expect(
+ page.locator('main').getByRole('link', {
+ name: 'List food',
+ exact: true
+ })
+ ).toHaveAttribute('href', '/sell');
+ await expect(
+ page.locator('main').getByRole('button')
+ ).toHaveCount(1);
+ await expect(
+ page.getByRole('button', {
+ name: 'Check current preference',
+ exact: true
+ })
+ ).toHaveCount(0);
+ const settings = page.locator('main details');
+ await expect(settings).toHaveCount(1);
+ await expect(settings).not.toHaveAttribute('open', '');
+ await settings
+ .getByText('Inbox settings', { exact: true })
+ .click();
+ await expect(settings).toHaveAttribute('open', '');
+ }
await expect(
page.getByRole('button', {
name: 'Check current preference',
diff --git a/web/tests/e2e/selling-index.spec.ts b/web/tests/e2e/selling-index.spec.ts
@@ -0,0 +1,391 @@
+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 { writeFile } from 'node:fs/promises';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/selling-index.ts';
+import type { NostrEvent } from 'applesauce-core/helpers';
+declare global {
+ interface Window {
+ hcp121: typeof Fixture;
+ hcp121Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let events: NostrEvent[] = [],
+ effects = 0;
+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 missing');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket) =>
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const frame = JSON.parse(raw.toString()) as unknown[];
+ if (frame[0] === 'EVENT') {
+ effects++;
+ return;
+ }
+ if (frame[0] !== 'REQ') return;
+ const filters = frame.slice(2) as {
+ kinds?: number[];
+ authors?: string[];
+ ids?: string[];
+ '#d'?: string[];
+ }[];
+ for (const event of events)
+ if (
+ filters.some(
+ (filter) =>
+ (!filter.kinds || filter.kinds.includes(event.kind)) &&
+ (!filter.authors || filter.authors.includes(event.pubkey)) &&
+ (!filter.ids || filter.ids.includes(event.id)) &&
+ (!filter['#d'] ||
+ event.tags.some(
+ (tag) => tag[0] === 'd' && filter['#d']!.includes(tag[1])
+ ))
+ )
+ )
+ socket.send(JSON.stringify(['EVENT', frame[1], event]));
+ socket.send(JSON.stringify(['EOSE', frame[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/selling-index.ts', import.meta.url)
+ ),
+ name: 'hcp121',
+ formats: ['iife']
+ }
+ }
+ });
+ const result = Array.isArray(built) ? built[0] : built;
+ if (!('output' in result)) throw Error('actual fixture bundle missing');
+ const chunks = result.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();
+ if (sockets)
+ await new Promise<void>((resolve, reject) =>
+ sockets.close((error) => (error ? reject(error) : resolve()))
+ );
+ await server?.close();
+});
+test.beforeEach(async ({ page }) => {
+ events = [];
+ effects = 0;
+ await page.addInitScript((endpoint) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://discovery.example.org',
+ 'wss://inbox.example.org',
+ 'wss://second.example.org'
+ ].includes(new URL(url.toString()).origin)
+ )
+ throw Error('no live relay permission');
+ super(endpoint, protocols);
+ }
+ };
+ }, endpoint);
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+});
+test.afterEach(async ({ page }) => {
+ await page.evaluate(async () => {
+ await window.hcp121Fixture?.close();
+ });
+});
+async function start(
+ page: import('@playwright/test').Page,
+ mode: 'empty' | 'retained' = 'retained'
+) {
+ const event = await page.evaluate(async (mode) => {
+ window.hcp121Fixture = await window.hcp121.createFixture(mode);
+ return window.hcp121Fixture.event;
+ }, mode);
+ if (event) events.push(event);
+}
+async function render(page: import('@playwright/test').Page) {
+ await page.evaluate(() => window.hcp121Fixture.render());
+}
+test('HCP121 genuine empty workspace has a real List food link and omits empty panels', async ({
+ page
+}) => {
+ await start(page, 'empty');
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ // Immediate DOM count supplies meaningful pre-producer RED without waiting
+ // for a future link that the original AccountGate does not render.
+ expect(
+ await section.getByRole('link', { name: 'List food', exact: true }).count()
+ ).toBe(1);
+ await expect(section).toContainText('No listings yet.');
+ for (const name of ['Needs attention', 'Drafts', 'Listings'])
+ await expect(
+ section.getByRole('heading', { name, exact: true })
+ ).toHaveCount(0);
+ await expect(
+ section.getByRole('link', { name: 'List food', exact: true })
+ ).toHaveAttribute('href', '/sell');
+ expect(effects).toBe(0);
+});
+test('HCP121 unresolved original listing is one attention row without duplicate draft/listing and retains exact target detail', async ({
+ page
+}) => {
+ await start(page);
+ const before = await page.evaluate(() => window.hcp121Fixture.records());
+ const counts = await page.evaluate(() => window.hcp121Fixture.counts());
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(
+ section.getByRole('heading', { name: 'Needs attention', exact: true })
+ ).toBeVisible();
+ await expect(section.locator('article')).toHaveCount(1);
+ await expect(
+ section.getByRole('heading', { name: 'Drafts', exact: true })
+ ).toHaveCount(0);
+ await expect(
+ section.getByRole('heading', { name: 'Listings', exact: true })
+ ).toHaveCount(0);
+ await section.getByText('Delivery details', { exact: true }).click();
+ await expect(section).toContainText(
+ 'Relay acceptance recorded for 0 of 2 targets.'
+ );
+ await expect(section).toContainText(
+ 'Exact read-back recorded for 0 of 2 targets.'
+ );
+ expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
+ before
+ );
+ expect((await page.evaluate(() => window.hcp121Fixture.counts())).signs).toBe(
+ counts.signs
+ );
+ expect(effects).toBe(0);
+ await writeFile(
+ test.info().outputPath('hcp121-original-native-records.json'),
+ JSON.stringify(before, null, 2)
+ );
+});
+test('HCP121 explicit same-author reconnect reacquires original seller work without native mutation or publication', async ({
+ page
+}) => {
+ await start(page);
+ const before = await page.evaluate(() => window.hcp121Fixture.records());
+ const counts = await page.evaluate(() => window.hcp121Fixture.counts());
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(section.locator('article')).toHaveCount(1);
+ await page.evaluate(() => window.hcp121Fixture.reconnect());
+ await expect(section.locator('article')).toHaveCount(1);
+ await expect(
+ section.getByRole('heading', { name: 'Needs attention', exact: true })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
+ before
+ );
+ expect((await page.evaluate(() => window.hcp121Fixture.counts())).signs).toBe(
+ counts.signs
+ );
+ expect(effects).toBe(0);
+});
+test('HCP121 changed proposed draft stays on its original attention row with exact saved values', async ({
+ page
+}) => {
+ await start(page);
+ const draft = await page.evaluate(() =>
+ window.hcp121Fixture.changeCapturedDraft()
+ );
+ const before = await page.evaluate(() => window.hcp121Fixture.records());
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(
+ section.getByRole('heading', { name: 'Needs attention', exact: true })
+ ).toBeVisible();
+ await expect(section.locator('article')).toHaveCount(1);
+ await expect(
+ section.getByRole('heading', { name: 'Drafts', exact: true })
+ ).toHaveCount(0);
+ await expect(
+ section.getByRole('link', { name: 'Continue editing', exact: true })
+ ).toHaveAttribute('href', '/selling/drafts/' + draft.id);
+ expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
+ before
+ );
+ expect(draft.form.title).toBe('Unfinished proposed carrots');
+ expect(draft.form.description).toBe('');
+ expect(effects).toBe(0);
+});
+
+test('HCP121 external own source stays visible and read-only with safe source-aware links', async ({
+ page
+}) => {
+ await start(page);
+ const event = await page.evaluate(() => window.hcp121Fixture.external());
+ events = event ? [event] : [];
+ await page.evaluate(() => window.hcp121Fixture.settled());
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(
+ section.getByRole('heading', { name: 'Listings', exact: true })
+ ).toBeVisible();
+ await expect(section).toContainText('Read-only');
+ await expect(
+ section.getByRole('link', { name: 'Edit', exact: true })
+ ).toHaveCount(0);
+ await expect(
+ section.getByRole('link', { name: 'View listing', exact: true })
+ ).toHaveAttribute('href', /^\/products\/naddr1/);
+ expect(effects).toBe(0);
+});
+test('HCP121 actual bounded remote-only own listing never becomes an adopted local source', async ({
+ page
+}) => {
+ await start(page, 'empty');
+ events = [await page.evaluate(() => window.hcp121Fixture.remoteListing())];
+ const before = await page.evaluate(() => window.hcp121Fixture.records());
+ expect(before).toEqual({ drafts: [], operations: [] });
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(
+ section.getByRole('heading', { name: 'Listings', exact: true })
+ ).toBeVisible();
+ await expect(section).toContainText('Remote own eggs');
+ await expect(section).toContainText('Bounded remote discovery');
+ await expect(section).toContainText('Read-only');
+ await expect(
+ section.getByRole('link', { name: 'Edit', exact: true })
+ ).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
+ before
+ );
+ expect(effects).toBe(0);
+});
+
+test('HCP121 actual installed account switch retires original local rows without adopting foreign records', async ({
+ page
+}) => {
+ await start(page);
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(section.locator('article')).toHaveCount(1);
+ const before = await page.evaluate(() => window.hcp121Fixture.records());
+ const next = await page.evaluate(() => window.hcp121Fixture.switchOwner());
+ await expect(section.locator('article')).toHaveCount(0);
+ await expect(section).toContainText(
+ 'The extension identity changed. Connect again to continue.'
+ );
+ await page.evaluate(() => window.hcp121Fixture.reconnect());
+ await expect(section).toContainText('No listings yet.');
+ await expect(section.getByText('Carrots', { exact: true })).toHaveCount(0);
+ expect(next).not.toBe(events[0].pubkey);
+ expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
+ before
+ );
+ expect(effects).toBe(0);
+});
+
+test('HCP121 settled retained listing and unfinished draft preserve ordering values links and minimal controls', async ({
+ page
+}) => {
+ await start(page);
+ await page.evaluate(() => window.hcp121Fixture.settled());
+ const draft = await page.evaluate(() => window.hcp121Fixture.draft());
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(
+ section.getByRole('heading', { name: 'Drafts', exact: true })
+ ).toBeVisible();
+ await expect(
+ section.getByRole('heading', { name: 'Listings', exact: true })
+ ).toBeVisible();
+ await expect(
+ section.getByRole('link', { name: 'Continue editing', exact: true })
+ ).toHaveAttribute('href', '/selling/drafts/' + draft.id);
+ await expect(
+ section.getByRole('link', { name: 'Edit', exact: true })
+ ).toHaveAttribute('href', /^\/products\/naddr1.+\/edit$/);
+ await expect(section).toContainText('Unfinished spinach');
+ await expect(
+ section.getByRole('heading', { name: 'Needs attention', exact: true })
+ ).toHaveCount(0);
+ const headings = await section
+ .locator(':scope > .page > section > h2')
+ .allTextContents();
+ expect(headings).toEqual(['Drafts', 'Listings']);
+ expect(await section.getByRole('checkbox').count()).toBe(0);
+ expect(
+ await section
+ .getByText(/revenue|orders|inventory total|bulk|performance graph/i)
+ .count()
+ ).toBe(0);
+ expect(effects).toBe(0);
+});
+test('HCP121 original partial delivery keeps acceptance distinct from readback and disconnect retires account rows', async ({
+ page
+}) => {
+ await start(page);
+ await page.evaluate(() =>
+ window.hcp121Fixture.observed('accepted', 0, false)
+ );
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await section.getByText('Delivery details', { exact: true }).click();
+ await expect(section).toContainText(
+ 'Relay acceptance recorded for 1 of 2 targets.'
+ );
+ await expect(section).toContainText(
+ 'Exact read-back recorded for 0 of 2 targets.'
+ );
+ await page.evaluate(() => window.hcp121Fixture.disconnect());
+ await expect(section.locator('article')).toHaveCount(0);
+ await expect(
+ section.getByRole('link', { name: 'Edit', exact: true })
+ ).toHaveCount(0);
+ expect(effects).toBe(0);
+});
+for (const width of [320, 1024])
+ test(`HCP121 ${width}px index has readable rows and separately operable visible links`, async ({
+ page
+ }) => {
+ await page.setViewportSize({ width, height: 800 });
+ await start(page);
+ await render(page);
+ const section = page.locator('#hcp121-selling');
+ await expect(section.locator('article')).toHaveCount(1);
+ await section.getByText('Delivery details', { exact: true }).click();
+ const overflow = await page.evaluate(
+ () => document.documentElement.scrollWidth > window.innerWidth
+ );
+ expect(overflow).toBe(false);
+ expect(effects).toBe(0);
+ });
diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts
@@ -74,6 +74,17 @@ await test('navigation fallback serves actual separate output and preserves miss
assert.match(html, /Connect to continue/);
assert.match(html, /<button[^>]*disabled[^>]*>Connect extension/);
assert.doesNotMatch(html, /Inbox setup|Check current preference/);
+ } else if (pathname === '/selling') {
+ assert.match(html, /Connect to continue/);
+ assert.match(html, /<button[^>]*disabled[^>]*>Connect extension/);
+ assert.match(html, /href="\/sell"/);
+ assert.match(html, /List food/);
+ assert.match(html, /Inbox settings/);
+ assert.match(html, /Inbox setup is unavailable/);
+ assert.doesNotMatch(
+ html,
+ /No listings yet\.|<h2>Needs attention|<h2>Drafts|<h2>Listings/
+ );
} else {
assert.match(
html,
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -131,7 +131,13 @@ import { auditOutput } from '../../tools/check-output.mjs';
async function restoreHistoricalPublicProducers(web) {
for (const [name, value] of Object.entries({
...historicalPublicProducerClosure,
- ...historicalWithdrawalProducerClosure
+ ...historicalWithdrawalProducerClosure,
+ 'src/routes/selling/+page.svelte': {
+ source:
+ '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n',
+ sha256:
+ '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a'
+ }
})) {
assert.equal(
createHash('sha256').update(value.source).digest('hex'),
@@ -563,6 +569,20 @@ import { auditOutput } from '../../tools/check-output.mjs';
/** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */
const check = (name, run, timeout = 1800000) =>
t.test(name, { timeout }, run);
+ const originalCompilerManifest = JSON.parse(
+ await readFile(
+ path.join(
+ base,
+ 'web/.svelte-kit/output/client/.vite/manifest.json'
+ ),
+ 'utf8'
+ )
+ );
+ const compiledAccountGate = Object.values(
+ originalCompilerManifest
+ ).some((row) => row.name === 'AccountGate');
+ const gateRole = compiledAccountGate ? 'AccountGate' : 'nodes/4';
+ const unrelatedRole = compiledAccountGate ? 'AccountGate' : 'nodes/11';
await check(
'actual compiled payload passes and build dispatch invokes the guard last',
async (t) => {
@@ -817,7 +837,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
for (const name of [
'references',
'public-runtime',
- 'AccountGate',
+ gateRole,
'Disclosure'
])
await check(
@@ -1169,8 +1189,9 @@ import { auditOutput } from '../../tools/check-output.mjs';
mutation === 'missing-gate-edge'
) {
const [, consumer] = find(
- mutation === 'missing-root-edge' ? 'nodes/0' : 'AccountGate'
+ mutation === 'missing-root-edge' ? 'nodes/0' : gateRole
);
+ assert.ok(consumer.imports.includes(identityKey));
consumer.imports = consumer.imports.filter(
/** @param {string} dependency */
(dependency) => dependency !== identityKey
@@ -1385,12 +1406,14 @@ import { auditOutput } from '../../tools/check-output.mjs';
if (mutation === 'missing') delete manifest[key];
if (mutation === 'missing-edge')
row.imports = row.imports.slice(1);
- if (mutation === 'extra-edge')
- row.imports = row.imports.concat(
- Object.keys(manifest).find(
- (key) => manifest[key].name === 'AccountGate'
- )
+ if (mutation === 'extra-edge') {
+ const extra = Object.entries(manifest).find(
+ ([, record]) => record.name === unrelatedRole
);
+ assert.ok(extra, 'Missing actual unrelated compiler role');
+ assert.ok(!row.imports.includes(extra[0]));
+ row.imports = row.imports.concat(extra[0]);
+ }
if (mutation === 'duplicate-edge')
row.imports = row.imports.concat(row.imports[0]);
if (mutation === 'permuted-edges')
@@ -1453,6 +1476,28 @@ import { auditOutput } from '../../tools/check-output.mjs';
}
);
}
+ for (const producer of [
+ 'src/routes/selling/+page.svelte',
+ 'src/lib/components/SellingRow.svelte',
+ 'src/lib/publishing/selling-view.ts'
+ ]) {
+ await check(
+ 'seller workspace rejects changed owned producer ' + producer,
+ async (t) => {
+ const f = await fixture(t);
+ await writeFile(
+ path.join(f.web, producer),
+ (await readFile(path.join(f.web, producer), 'utf8')) +
+ '\n// owned seller source mutation\n'
+ );
+ await refresh(f);
+ await assert.rejects(
+ f.audit,
+ /Invalid owned selling workspace source/
+ );
+ }
+ );
+ }
for (const route of [
'src/routes/sell/+page.svelte',
'src/routes/selling/drafts/[draftId=local_id]/+page.svelte',
@@ -1537,8 +1582,11 @@ import { auditOutput } from '../../tools/check-output.mjs';
for (const name of ['nodes/7', 'nodes/9']) {
const row = find(name)[1];
row.imports = [...row.imports].reverse();
- if (mutation === 'extra-edge')
- row.imports = row.imports.concat(find('AccountGate')[0]);
+ if (mutation === 'extra-edge') {
+ const extra = find(unrelatedRole)[0];
+ assert.ok(!row.imports.includes(extra));
+ row.imports = row.imports.concat(extra);
+ }
if (mutation === 'duplicate-edge')
row.imports = row.imports.concat(row.imports[0]);
}
@@ -1571,12 +1619,14 @@ import { auditOutput } from '../../tools/check-output.mjs';
assert.ok(entry);
const [key, row] = entry;
if (mutation === 'missing') delete manifest[key];
- if (mutation === 'extra-edge')
- row.imports = row.imports.concat(
- Object.keys(manifest).find(
- (name) => manifest[name].name === 'AccountGate'
- )
+ if (mutation === 'extra-edge') {
+ const extra = Object.entries(manifest).find(
+ ([, record]) => record.name === unrelatedRole
);
+ assert.ok(extra, 'Missing actual unrelated compiler role');
+ assert.ok(!row.imports.includes(extra[0]));
+ row.imports = row.imports.concat(extra[0]);
+ }
if (mutation === 'missing-edge')
row.imports = row.imports.slice(1);
if (mutation === 'duplicate-edge')
diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts
@@ -98,6 +98,24 @@ describe('thin protected route SSR', () => {
expect(output.head).toContain('<title>HarvestCircle</title>');
expect(output.head).toMatch(/name="robots" content="noindex"/);
+ if (name === 'Selling') {
+ expect(output.body).toContain('Connect to continue');
+ expect(output.body).toContain('href="/sell"');
+ expect(output.body).toContain('List food');
+ expect(output.body).toContain('Inbox settings');
+ expect(output.body).toContain('Inbox setup is unavailable');
+ expect(output.body).toMatch(
+ /<button[^>]*disabled[^>]*>Connect extension/
+ );
+ expect(output.body).toMatch(
+ /<button[^>]*disabled[^>]*>Check current preference/
+ );
+ expect(output.body).not.toMatch(
+ /<form|<textarea|<input|<select|PRIVATE_TEST_ONLY|naddr1|No listings yet\.|<h2>Needs attention|<h2>Drafts|<h2>Listings/
+ );
+ // Original SSR effect tripwires still reject IDB/extension/socket/fetch.
+ return;
+ }
expect(output.body).toContain('Connect or unlock');
if (name === 'Conversation') {
expect(output.body).toMatch(
diff --git a/web/tests/unit/selling-view.test.ts b/web/tests/unit/selling-view.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'vitest';
+import {
+ openSellingView,
+ sellingViewSnapshot,
+ closeSellingView
+} from '../../src/lib/publishing/selling-view.ts';
+import type { IdentityViewContext } from '../../src/lib/runtime/view-context.ts';
+import type { SellingView } from '../../src/lib/publishing/selling-view.ts';
+
+for (const context of [undefined, null, {}, { owner: 'copied' }])
+ test(`seller index cannot acquire account storage from ${JSON.stringify(context)}`, async () => {
+ const view = await openSellingView(context as IdentityViewContext);
+ expect(view).toBeUndefined();
+ });
+
+test('copied seller presentation token has no original snapshot or retirement authority', () => {
+ const copied = {} as SellingView;
+ expect(sellingViewSnapshot(copied)).toBeUndefined();
+ expect(() => closeSellingView(copied)).not.toThrow();
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -606,6 +606,84 @@ async function listingPublicationAdmission(web) {
}
return true;
}
+/** @param {string} web */
+async function sellingWorkspaceAdmission(web) {
+ const source = await readOwned(web, 'src/routes/selling/+page.svelte');
+ publicText(source);
+ if (
+ createHash('sha256').update(source).digest('hex') ===
+ '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a'
+ )
+ return false;
+ /** @type {Record<string,string>} */
+ const producers = {
+ 'src/routes/sell/+page.svelte':
+ '97f22f9a0309621e9acb5f1b328d3376bc9c5affbe5a7ea1b85ece76097b9c08',
+ 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte':
+ '1df59a753fbef2bc2ebf77890a79cbd3d7a5bb0dcef34c219df1b5e8043cf787',
+ 'src/routes/products/[naddr=naddr]/edit/+page.svelte':
+ '09c3a6bde766045319cd36a00a82ca565f9f3b5cd5322982be9482836f312998',
+ 'src/lib/components/ListingEditor.svelte':
+ '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6',
+ 'src/lib/publishing/listing-editor.ts':
+ 'fe067bc1609f783aeee8ad5a0f3178cff50cae81085377b2bbec7874b5f4349d',
+ 'src/lib/components/ListingReview.svelte':
+ 'deee41ca6c60b346afc7ed5e62e3101ee03b04fdd2a9aa8fa3f3dec585e3863b',
+ 'src/lib/publishing/editor-workflow.ts':
+ 'c87e4f46793fd9beeedb5027cdbb06d533cf7e5df7378c030355c4608738e0f6',
+ 'src/lib/components/ConflictNotice.svelte':
+ 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c',
+ 'src/lib/publishing/edit-source.ts':
+ '1432a8ada3d822cc9f634d40a7847a4d6d02c202ecfe59a9634543d57202f56b',
+ 'src/lib/publishing/prepare-listing.ts':
+ '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9',
+ 'src/lib/publishing/new-listing-readiness.ts':
+ 'ba76be4d7309b1a6beb0c8e0f19b89f2595049e94709486b79eff38953e68893',
+ 'src/lib/runtime/public-runtime.ts':
+ '8d2b840e94448b55642b1481d12785ed76d326735a4461e9795f57a98e8d2530',
+ 'src/lib/persistence/public-publications.ts':
+ 'be99c4114fb32880e0a9b48ab3593645532853fb4166fb506f398416db41a194',
+ 'src/lib/persistence/quota.ts':
+ 'e261a7c9c81d0685021663639b1bb543192e65580edb64fa58ccbb9a4a04cc95',
+ 'src/lib/publishing/revise-listing.ts':
+ '1f03d43f460feb12a02489226131ec2f7b95df5f534fcbb0b49ccc686a1b0c06',
+ 'src/lib/publishing/mark-sold.ts':
+ '80beaf8ad38b396154d5556e50e2cf5cd9f327bcdbc05f0db1ce190bf29f7234',
+ 'src/lib/components/ConfirmPanel.svelte':
+ '9e25745303bdf408a14df5153a28e9579bfa019ab083225acb7d874e93a17d59',
+ 'src/lib/nostr/listing-publisher.ts':
+ '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9',
+ 'src/lib/publishing/withdraw-listing.ts':
+ '168064a7ce271f8342c7b7cbbf996bd96f8968e405eee0bb3e3dba1bdaf346fb',
+ 'src/lib/publishing/sign-listing.ts':
+ 'a1c123c40a190699b57378c5569fcbbfbc5e23ab4d4c0df499ca40ff82fe1a10',
+ 'src/lib/persistence/artifact-records.ts':
+ 'e3b235c5aaf19558b557feb6e17a35b2b1de39c1aa49cb2ef14084d670138d16',
+ 'src/lib/publishing/listing-operation-view.ts':
+ '07f94625c0231a62f25c1db98c9459f8939c32505453633b58d2f72a894858ce',
+ 'src/lib/components/OperationStatus.svelte':
+ 'ca3a007899996f6331fadd2ead4c55dc7116c273626ecd2f36bcd4701065ae5f',
+ 'src/lib/runtime/effect-ownership.ts':
+ 'a181d1fa8b18d45b3e143de19af4dfdaab91779ac44df972d22e7fada645778b',
+ 'src/lib/nostr/public-pool.ts':
+ '220b0b9ca0cea20c1a2e1a08a82fc4b68a1ba4dd6ffff1f45154b54735233806',
+ 'src/lib/persistence/public-receipts.ts':
+ '10743a9d855c4f573eb42ca90a13c550dee9620e4ad3aac322858c696152e564',
+ 'src/routes/selling/+page.svelte':
+ '65d982bdf3f625a38b6c886a31a2a699c92e9231636debc16d501e78d7c8faa0',
+ 'src/lib/components/SellingRow.svelte':
+ 'ce00de1bd033860b9c0a85a49c90c8a4d5b8a8223cfd5c0872572e548e79331d',
+ 'src/lib/publishing/selling-view.ts':
+ 'a9e896db6f0485699c069ee31eb20a6c5476095d0ffef1160aa76cc64a364dc2'
+ };
+ for (const [name, pin] of Object.entries(producers)) {
+ const bytes = await readOwned(web, name);
+ publicText(bytes);
+ if (createHash('sha256').update(bytes).digest('hex') !== pin)
+ throw new Error('Invalid owned selling workspace source');
+ }
+ return true;
+}
// HCP115 one shared editor activates all three routes together. Historical
// AccountGate routes remain labelled compatibility producers only.
/** @param {string} web */
@@ -1059,6 +1137,10 @@ export async function auditOutput(webDirectory) {
const hasListingEditor = hasFullRoutes && (await listingEditorAdmission(web));
if (hasListingEditor && !(hasListingPublication && hasInboxSetup))
throw new Error('Invalid owned listing editor runtime authority');
+ const hasSellingWorkspace =
+ hasFullRoutes && (await sellingWorkspaceAdmission(web));
+ if (hasSellingWorkspace && hasListingEditor !== 'owned-withdrawal')
+ throw new Error('Invalid owned selling workspace activation');
const hasListingRevision =
hasListingEditor === 'owned-revision' ||
hasListingEditor === 'owned-withdrawal';
@@ -1184,6 +1266,10 @@ export async function auditOutput(webDirectory) {
names.delete(name);
names.add('rolldown-runtime');
}
+ if (hasSellingWorkspace) {
+ names.delete('AccountGate');
+ names.add('OperationStatus');
+ }
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -3142,6 +3228,58 @@ export async function auditOutput(webDirectory) {
imports: ['references', 'public-runtime', 'Button']
}
});
+ if (hasSellingWorkspace) {
+ delete expected.AccountGate;
+ Object.assign(expected, {
+ ListingEditor: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'ListingEditor',
+ imports: [
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'CapabilityGate',
+ 'InboxSetup',
+ 'OperationStatus'
+ ]
+ },
+ OperationStatus: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'OperationStatus',
+ imports: ['references', 'public-runtime', 'client']
+ },
+ 'nodes/11': {
+ file: '_app/immutable/nodes/11.HASH.js',
+ name: 'nodes/11',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/11.js',
+ isEntry: true,
+ imports: [
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'CapabilityGate',
+ 'Disclosure',
+ 'InboxSetup',
+ 'OperationStatus'
+ ]
+ },
+ 'nodes/4': {
+ file: '_app/immutable/nodes/4.HASH.js',
+ name: 'nodes/4',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/4.js',
+ isEntry: true,
+ imports: [
+ 'public-runtime',
+ 'client',
+ 'CapabilityGate',
+ 'InboxSetup',
+ 'InboxStatus'
+ ]
+ }
+ });
+ }
for (const record of Object.values(manifest)) {
const actual = { ...record };
actual.file = actual.file.includes('/chunks/')