commit e150d061ae96fd78cfaa119929d3b6ce444c689a
parent f5799cc957d3b205696b1c4c2de01419e18103ed
Author: triesap <tyson@radroots.org>
Date: Fri, 9 Oct 2026 16:39:32 +0000
web: render the plain chronological conversation (HCP-103)
Diffstat:
14 files changed, 1942 insertions(+), 112 deletions(-)
diff --git a/web/src/lib/components/ConversationThread.svelte b/web/src/lib/components/ConversationThread.svelte
@@ -0,0 +1,191 @@
+<script lang="ts">
+ import { getContext, onMount, tick } from 'svelte';
+ import InboxStatus from './InboxStatus.svelte';
+ import Button from './primitives/Button.svelte';
+ import MessageItem from './MessageItem.svelte';
+ import {
+ IDENTITY_VIEW_CONTEXT,
+ identityViewSession,
+ subscribeIdentityView,
+ type IdentityViewContext
+ } from '../runtime/view-context.ts';
+ import {
+ PUBLIC_RUNTIME_CONTEXT,
+ publicRuntimeReady,
+ type PublicRuntimeContext,
+ type PublicRuntime
+ } from '../runtime/public-runtime.ts';
+ import {
+ createRuntimeInboxSetupView,
+ closeInboxSetupView
+ } from '../messaging/inbox-setup-view.ts';
+ import {
+ createInboxView,
+ inboxViewSnapshot,
+ inboxViewSetup,
+ subscribeInboxView,
+ closeInboxView,
+ inboxThreadSnapshot,
+ inboxThreadRevision,
+ markInboxConversationDisplayed,
+ type InboxView
+ } from '../messaging/inbox-view.ts';
+ let {
+ controller,
+ conversationId
+ }: { controller?: InboxView; conversationId: string } = $props();
+ const identity = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT),
+ publicContext = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);
+ let owned = $state.raw<InboxView | undefined>(),
+ model = $state(inboxThreadSnapshot(undefined, '')),
+ announcement = $state(''),
+ readProblem = $state(false),
+ retryRevision = $state(0),
+ displayedPending = $state(false);
+ let runtime: PublicRuntime | undefined,
+ off = () => {},
+ initialized = false,
+ previous = Array.from<string>([]),
+ attempted = Array.from<string>([]),
+ disposed = false;
+ onMount(() => {
+ let observedRevision = -2,
+ observedMode = '';
+ function acquire() {
+ if (disposed) return;
+ if (owned && inboxViewSnapshot(owned).owner) return;
+ off();
+ if (owned && !controller) closeInboxView(owned);
+ owned = controller;
+ if (!owned && runtime) {
+ const session = identityViewSession(identity),
+ setup = createRuntimeInboxSetupView(identity, runtime);
+ if (session && setup) {
+ owned = createInboxView({ identity: session, setup, conversationId });
+ if (!owned) closeInboxSetupView(setup);
+ }
+ }
+ observedRevision = -2;
+ off = subscribeInboxView(owned, (panel) => {
+ const revision = inboxThreadRevision(owned),
+ mode = panel.state + ':' + panel.count + ':' + (panel.reason ?? '');
+ if (revision === observedRevision && mode === observedMode) return;
+ observedRevision = revision;
+ observedMode = mode;
+ const next = inboxThreadSnapshot(owned, conversationId);
+ if (next.status !== 'ready') {
+ model = next;
+ announcement = '';
+ readProblem = false;
+ initialized = false;
+ previous = [];
+ attempted = [];
+ return;
+ }
+ const ids = next.messages.map((row) => row.data.rumorId),
+ added = ids.filter((id) => !previous.includes(id)).length;
+ if (ids.length > 0 && initialized && added)
+ announcement =
+ added + (added === 1 ? ' message added.' : ' messages added.');
+ if (ids.length > 0) initialized = true;
+ previous = ids;
+ model = next;
+ });
+ }
+ const identityOff = identity
+ ? subscribeIdentityView(identity, acquire)
+ : () => {};
+ acquire();
+ if (!controller && publicContext)
+ void publicRuntimeReady(publicContext)
+ .then((value) => {
+ if (!disposed) {
+ runtime = value;
+ acquire();
+ }
+ })
+ .catch(() => {});
+ return () => {
+ disposed = true;
+ identityOff();
+ off();
+ if (owned && !controller) {
+ const setup = inboxViewSetup(owned);
+ closeInboxView(owned);
+ if (setup) closeInboxSetupView(setup);
+ }
+ };
+ });
+ $effect(() => {
+ const original = owned,
+ selected = conversationId,
+ rows = model.messages;
+ void retryRevision;
+ if (!original || model.status !== 'ready' || displayedPending) return;
+ const ids = rows
+ .map((row) => row.data.rumorId)
+ .filter((id) => !attempted.includes(id));
+ if (!ids.length) return;
+ attempted = attempted.concat(ids);
+ displayedPending = true;
+ void tick()
+ .then(async () => {
+ if (disposed || owned !== original || conversationId !== selected)
+ return;
+ const actual = inboxThreadSnapshot(original, selected);
+ if (
+ actual.status !== 'ready' ||
+ ids.some(
+ (id) => !actual.messages.some((row) => row.data.rumorId === id)
+ )
+ )
+ return;
+ const result = await markInboxConversationDisplayed(
+ original,
+ selected,
+ ids,
+ 'reviewed_displayed_conversation'
+ );
+ if (!disposed && owned === original && conversationId === selected)
+ readProblem = !result;
+ })
+ .finally(() => {
+ displayedPending = false;
+ });
+ });
+</script>
+
+{#if owned}<InboxStatus
+ controller={owned}
+ showLists={false}
+ manageController={false}
+ />{:else}<InboxStatus showLists={false} manageController={false} />{/if}
+<div class="page page--reading stack">
+ <h2>Conversation</h2>
+ {#if owned && model.status === 'ready'}
+ {#each model.messages as message (message.data.rumorId)}<MessageItem
+ controller={owned}
+ {conversationId}
+ {message}
+ />{/each}
+ {:else}<p>
+ This conversation is unavailable until it is unlocked in the matching
+ browser and account.
+ </p>{/if}
+ {#if readProblem}<p class="notice">
+ Local read status could not be confirmed. Encrypted copies are preserved.
+ </p>
+ <Button
+ label="Retry local read status"
+ disabled={displayedPending}
+ onclick={() => {
+ attempted = [];
+ readProblem = false;
+ retryRevision++;
+ }}
+ />{/if}
+ <p role="status" aria-live="polite" data-thread-announcement>
+ {announcement}
+ </p>
+ <a href="/messages">Back to messages</a>
+</div>
diff --git a/web/src/lib/components/InboxStatus.svelte b/web/src/lib/components/InboxStatus.svelte
@@ -43,7 +43,15 @@
closeInboxView,
type InboxView
} from '../messaging/inbox-view.ts';
- let { controller }: { controller?: InboxView } = $props();
+ let {
+ controller,
+ showLists = true,
+ manageController = true
+ }: {
+ controller?: InboxView;
+ showLists?: boolean;
+ manageController?: boolean;
+ } = $props();
const identityContext = getContext<IdentityViewContext>(
IDENTITY_VIEW_CONTEXT
),
@@ -106,7 +114,7 @@
? subscribeIdentityView(identityContext, acquire)
: () => {};
acquire();
- if (!controller && publicContext)
+ if (manageController && !controller && publicContext)
void publicRuntimeReady(publicContext)
.then((value) => {
if (disposed) return;
@@ -252,7 +260,7 @@
}}
/>
{/if}
- {#if owned && list.status === 'ready'}
+ {#if showLists && owned && list.status === 'ready'}
{#if list.requests.length > 0}<section
class="stack"
aria-label="Message requests"
diff --git a/web/src/lib/components/MessageItem.svelte b/web/src/lib/components/MessageItem.svelte
@@ -0,0 +1,57 @@
+<script lang="ts">
+ import {
+ inboxMessageSnapshot,
+ type InboxView
+ } from '../messaging/inbox-view.ts';
+ import type { ThreadMessage } from '../messaging/conversation-thread.ts';
+ import { internalHref } from '../navigation-url.ts';
+ let {
+ controller,
+ conversationId,
+ message
+ }: { controller: InboxView; conversationId: string; message: ThreadMessage } =
+ $props();
+ // Copied rows select only a hash. Render fresh current original room bytes.
+ const current = $derived(
+ inboxMessageSnapshot(controller, conversationId, message.data.rumorId)
+ );
+ const time = $derived(
+ current ? new Date(current.data.createdAt * 1000) : undefined
+ );
+</script>
+
+{#if current}
+ <article class="stack" data-message-id={current.data.rumorId}>
+ <div class="cluster">
+ <span
+ >{current.data.role === 'self_archive'
+ ? 'You'
+ : 'Peer ' + current.data.peer.slice(0, 8) + '…'}</span
+ >
+ {#if time && !Number.isNaN(time.getTime())}<time
+ datetime={time.toISOString()}>{time.toLocaleString()}</time
+ >{/if}
+ </div>
+ {#each current.data.content.split('\n') as line, index (index)}<p>
+ {line}
+ </p>{/each}
+ {#if current.parent === 'missing'}<p class="text-small">
+ Earlier message unavailable in this browser.
+ </p>{/if}
+ {#each current.citations as citation (citation.naddr)}
+ <p>
+ <a href={internalHref('/products/' + citation.naddr)}
+ >Product citation: {citation.identifier || 'listing'} (unverified)</a
+ >
+ </p>
+ {/each}
+ {#if current.citations.length || /quoted price/i.test(current.data.content)}<p
+ class="text-small"
+ >
+ A quoted price is not a current or locked quote.
+ </p>{/if}
+ {#each current.delivery ?? [] as label (label)}<p class="text-small">
+ {label}
+ </p>{/each}
+ </article>
+{/if}
diff --git a/web/src/lib/messaging/conversation-thread.ts b/web/src/lib/messaging/conversation-thread.ts
@@ -0,0 +1,84 @@
+import { groupInboxMessages } from './inbox-list.ts';
+import type { ConversationData } from './admit-conversation.ts';
+import { canonicalPublicKey } from '../contracts/public-key.ts';
+import {
+ decodeProductReference,
+ type ProductReference
+} from '../nostr/references.ts';
+import {
+ privateRecordIdentity,
+ privateRecordSnapshot,
+ type PrivateRecordHandle
+} from '../persistence/private-records.ts';
+import { privateSendStatus } from './send-status.ts';
+export type ThreadMessage = Readonly<{
+ data: ConversationData;
+ citations: readonly ProductReference[];
+ parent: 'present' | 'missing' | null;
+ delivery: readonly string[] | null;
+}>;
+export type ThreadSnapshot = Readonly<{
+ status: 'ready' | 'unavailable';
+ messages: readonly ThreadMessage[];
+}>;
+export function unavailableThread(): ThreadSnapshot {
+ return { status: 'unavailable', messages: [] };
+}
+// Detached presentation only; authentication and display custody stay with the
+// current original InboxView room proofs, never these copied data or receipts.
+export function projectConversationThread(
+ owner: unknown,
+ peer: unknown,
+ messages: readonly ConversationData[],
+ records: readonly PrivateRecordHandle[]
+): ThreadSnapshot {
+ if (
+ !canonicalPublicKey(peer) ||
+ peer === owner ||
+ groupInboxMessages(owner, messages, []).status !== 'ready' ||
+ messages.some((row) => row.peer !== peer)
+ )
+ return unavailableThread();
+ const rows = new Map<string, ConversationData>();
+ for (const row of messages) rows.set(row.rumorId, { ...row });
+ const receipts = new Map<string, readonly string[]>();
+ for (const token of records) {
+ const identity = privateRecordIdentity(token),
+ record = identity && privateRecordSnapshot(token, owner, identity.id);
+ if (record?.family !== 'private_send_operation' || record.peer !== peer)
+ continue;
+ const status = privateSendStatus(token, owner, record.id);
+ if (status) receipts.set(record.rumorHash, status.labels.slice());
+ }
+ return {
+ status: 'ready',
+ messages: Array.from(rows.values())
+ .sort(
+ (a, b) =>
+ a.createdAt - b.createdAt || a.rumorId.localeCompare(b.rumorId)
+ )
+ .map((data) => {
+ const citations = new Map<string, ProductReference>();
+ for (const match of data.content.matchAll(
+ /\bnostr:(naddr[0-9a-zA-Z]+)/g
+ )) {
+ const reference = decodeProductReference(match[1]);
+ if (reference) citations.set(reference.naddr, reference);
+ }
+ return {
+ data,
+ citations: Array.from(citations.values()),
+ parent:
+ data.replyTo === null
+ ? null
+ : rows.has(data.replyTo)
+ ? 'present'
+ : 'missing',
+ delivery:
+ data.role === 'inbound'
+ ? null
+ : (receipts.get(data.rumorId) ?? ['Recipient delivery unknown'])
+ };
+ })
+ };
+}
diff --git a/web/src/lib/messaging/inbox-view.ts b/web/src/lib/messaging/inbox-view.ts
@@ -1,3 +1,10 @@
+import {
+ projectConversationThread,
+ unavailableThread,
+ type ThreadSnapshot,
+ type ThreadMessage
+} from './conversation-thread.ts';
+import type { PrivateRecordHandle } from '../persistence/private-records.ts';
import { canonicalPublicKey } from '../contracts/public-key.ts';
import {
groupInboxMessages,
@@ -7,12 +14,14 @@ import {
import {
captureMessageMetadata,
messageMetadataSnapshot,
+ markDisplayedMessage,
type MessageMetadata
} from '../persistence/message-metadata.ts';
import {
captureConversationDirectory,
rememberAdmittedConversation,
closeConversationDirectory,
+ resolveLocalConversation,
type ConversationDirectory
} from './conversation-directory.ts';
import {
@@ -56,6 +65,7 @@ import {
} from '../persistence/database.ts';
import {
createPrivateStorageRepository,
+ listPrivateSendRecords,
type PrivateStorageRepository
} from '../persistence/private-storage.ts';
import {
@@ -97,9 +107,22 @@ export type InboxViewSnapshot = Readonly<{
historyComplete: false;
cleanupRequired: boolean;
}>;
-type Inputs = Readonly<{ identity: IdentitySession; setup: InboxSetupView }>;
+type Inputs = Readonly<{
+ identity: IdentitySession;
+ setup: InboxSetupView;
+ conversationId?: string;
+}>;
type Controller = {
snapshot(): InboxViewSnapshot;
+ thread(id: unknown): ThreadSnapshot;
+ threadRevision(): number;
+ message(id: unknown, rumor: unknown): ThreadMessage | undefined;
+ resolve(id: unknown, review: unknown): Promise<boolean>;
+ displayed(
+ id: unknown,
+ rumors: readonly string[],
+ review: unknown
+ ): Promise<boolean>;
setup(): InboxSetupView | undefined;
list(): InboxListSnapshot;
row(peer: unknown): InboxListRow | undefined;
@@ -158,6 +181,16 @@ export function createInboxView(input: Inputs): InboxView | undefined {
directory: ConversationDirectory | undefined,
older: OlderInbox | undefined;
let list: InboxListSnapshot = groupInboxMessages('', [], []);
+ let threadId: string | undefined,
+ threadPeer: string | undefined,
+ threadEpoch = 0;
+ let threadModel: ThreadSnapshot = unavailableThread();
+ const threadProofs = new Map<
+ string,
+ Readonly<{ room: AdmittedConversation; message: ThreadMessage }>
+ >();
+ let sendRecords: readonly PrivateRecordHandle[] =
+ Array.from<PrivateRecordHandle>([]);
let listReason: string | null = null;
let listRevision = 0;
const rowProofs = new Map<
@@ -188,6 +221,157 @@ export function createInboxView(input: Inputs): InboxView | undefined {
current()
);
}
+ function threadRooms(id: unknown) {
+ if (
+ id !== threadId ||
+ !threadPeer ||
+ !privateCurrent() ||
+ !unlocked ||
+ !queue
+ )
+ return;
+ const rooms = decryptionQueueConversations(queue).filter((room) => {
+ const data = conversationSnapshot(room);
+ return (
+ data?.owner === capture.owner &&
+ data.peer === threadPeer &&
+ unlockedConversationCurrent(unlocked!, room)
+ );
+ });
+ return rooms;
+ }
+ function refreshThread() {
+ threadProofs.clear();
+ threadModel = unavailableThread();
+ const rooms = threadRooms(threadId);
+ if (!rooms || !threadPeer) return;
+ const data = rooms.map(conversationSnapshot);
+ if (data.some((row) => !row)) return;
+ threadModel = projectConversationThread(
+ capture.owner,
+ threadPeer,
+ data.filter((row) => row !== undefined),
+ sendRecords
+ );
+ if (threadModel.status !== 'ready') return;
+ const byRumor = new Map<string, AdmittedConversation>();
+ for (const room of rooms) {
+ const row = conversationSnapshot(room);
+ if (row) byRumor.set(row.rumorId, room);
+ }
+ for (const message of threadModel.messages) {
+ const room = byRumor.get(message.data.rumorId);
+ if (room) threadProofs.set(message.data.rumorId, { room, message });
+ }
+ }
+ function messageSnapshot(
+ id: unknown,
+ rumor: unknown
+ ): ThreadMessage | undefined {
+ if (
+ id !== threadId ||
+ typeof rumor !== 'string' ||
+ !privateCurrent() ||
+ !unlocked ||
+ threadModel.status !== 'ready'
+ )
+ return;
+ const proof = threadProofs.get(rumor);
+ if (!proof || !unlockedConversationCurrent(unlocked, proof.room)) return;
+ const actual = conversationSnapshot(proof.room);
+ if (
+ !actual ||
+ actual.owner !== capture.owner ||
+ actual.peer !== threadPeer ||
+ actual.rumorId !== rumor
+ )
+ return;
+ return {
+ data: { ...actual },
+ citations: proof.message.citations.map((row) => ({ ...row })),
+ parent: proof.message.parent,
+ delivery: proof.message.delivery?.slice() ?? null
+ };
+ }
+ function threadSnapshot(id: unknown): ThreadSnapshot {
+ if (id !== threadId || !privateCurrent() || threadModel.status !== 'ready')
+ return unavailableThread();
+ const messages = threadModel.messages.map((row) =>
+ messageSnapshot(id, row.data.rumorId)
+ );
+ return messages.some((row) => !row)
+ ? unavailableThread()
+ : {
+ status: 'ready',
+ messages: messages.filter((row) => row !== undefined)
+ };
+ }
+ async function resolve(id: unknown, review: unknown) {
+ if (review !== 'reviewed_conversation_navigation') return false;
+ const selection = ++threadEpoch,
+ generation = epoch;
+ threadId = undefined;
+ threadPeer = undefined;
+ threadProofs.clear();
+ threadModel = unavailableThread();
+ notify();
+ if (!directory || !privateCurrent()) return false;
+ const result = await resolveLocalConversation(directory, id);
+ if (
+ selection !== threadEpoch ||
+ !current(generation) ||
+ !privateCurrent() ||
+ result.status !== 'resolved' ||
+ result.owner !== capture.owner
+ )
+ return false;
+ threadId = result.conversationId;
+ threadPeer = result.peer;
+ refreshThread();
+ notify();
+ return true;
+ }
+ async function displayed(
+ id: unknown,
+ rumors: readonly string[],
+ review: unknown
+ ) {
+ if (
+ review !== 'reviewed_displayed_conversation' ||
+ !Array.isArray(rumors) ||
+ !metadata
+ )
+ return false;
+ const rooms = threadRooms(id),
+ selection = threadEpoch,
+ generation = epoch,
+ originalMetadata = metadata;
+ if (!rooms || rumors.length > 2000) return false;
+ for (const rumor of rumors) {
+ const room = rooms.find(
+ (value) => conversationSnapshot(value)?.rumorId === rumor
+ );
+ if (
+ !room ||
+ selection !== threadEpoch ||
+ !current(generation) ||
+ !privateCurrent() ||
+ id !== threadId
+ )
+ return false;
+ const result = await markDisplayedMessage(
+ originalMetadata,
+ room,
+ 'displayed_message'
+ );
+ if (result.status !== 'saved' && result.status !== 'existing')
+ return false;
+ }
+ if (selection !== threadEpoch || !current(generation) || !privateCurrent())
+ return false;
+ await refreshList(generation);
+ return selection === threadEpoch && current(generation) && privateCurrent();
+ }
function rowSnapshot(peer: unknown): InboxListRow | undefined {
if (
typeof peer !== 'string' ||
@@ -228,7 +412,9 @@ export function createInboxView(input: Inputs): InboxView | undefined {
if (!privateCurrent() || !unlocked || !metadata) return false;
try {
const local = await messageMetadataSnapshot(metadata);
+ const sends = repository && (await listPrivateSendRecords(repository));
if (!current(generation) || !privateCurrent() || !unlocked) return false;
+ sendRecords = sends?.ok ? sends.value : [];
const cached = readUnlockedMessages(unlocked);
if (
local.status !== 'ready' ||
@@ -257,6 +443,7 @@ export function createInboxView(input: Inputs): InboxView | undefined {
const room = byRumor.get(row.latest.rumorId);
if (room) rowProofs.set(row.peer, { data: row, room });
}
+ refreshThread();
listRevision++;
listReason = list.status === 'ready' ? null : 'unavailable';
return list.status === 'ready';
@@ -494,6 +681,12 @@ export function createInboxView(input: Inputs): InboxView | undefined {
pendingCleanup = pendingCleanup.concat(cleanup);
}
if (pendingCleanup.length > 0) reason = 'cleanup_required';
+ threadEpoch++;
+ threadProofs.clear();
+ threadModel = unavailableThread();
+ threadId = undefined;
+ threadPeer = undefined;
+ sendRecords = [];
metadata = undefined;
directory = undefined;
older = undefined;
@@ -580,6 +773,8 @@ export function createInboxView(input: Inputs): InboxView | undefined {
async function read(reviewed: unknown) {
if (
reviewed !== 'reviewed_decrypt_batch' ||
+ (input.conversationId !== undefined &&
+ (threadId !== input.conversationId || !threadPeer)) ||
busy ||
!queue ||
!privateCurrent()
@@ -690,6 +885,16 @@ export function createInboxView(input: Inputs): InboxView | undefined {
});
});
if (!privateCurrent()) return false;
+ if (
+ input.conversationId !== undefined &&
+ !(await resolve(
+ input.conversationId,
+ 'reviewed_conversation_navigation'
+ ))
+ ) {
+ reason = 'unavailable';
+ return false;
+ }
const result = await runDecryptionBatch(queue, 'reviewed_decrypt_batch');
if (!current(generation) || !privateCurrent()) return false;
await refreshList(generation);
@@ -758,6 +963,11 @@ export function createInboxView(input: Inputs): InboxView | undefined {
}
views.set(token, {
snapshot,
+ thread: threadSnapshot,
+ threadRevision: () => (privateCurrent() ? listRevision + threadEpoch : -1),
+ message: messageSnapshot,
+ resolve,
+ displayed,
list: listSnapshot,
row: rowSnapshot,
revision: () => (privateCurrent() ? listRevision : -1),
@@ -898,3 +1108,38 @@ export function inboxConversationRow(
export function inboxListRevision(token: InboxView | undefined): number {
return token ? (views.get(token)?.revision() ?? -1) : -1;
}
+
+export function inboxThreadSnapshot(
+ token: InboxView | undefined,
+ id: unknown
+): ThreadSnapshot {
+ return (token && views.get(token)?.thread(id)) || unavailableThread();
+}
+export function inboxMessageSnapshot(
+ token: InboxView,
+ id: unknown,
+ rumor: unknown
+): ThreadMessage | undefined {
+ return views.get(token)?.message(id, rumor);
+}
+export function resolveInboxConversation(
+ token: InboxView,
+ id: unknown,
+ review: unknown
+): Promise<boolean> {
+ return views.get(token)?.resolve(id, review) ?? Promise.resolve(false);
+}
+export function markInboxConversationDisplayed(
+ token: InboxView,
+ id: unknown,
+ rumors: readonly string[],
+ review: unknown
+): Promise<boolean> {
+ return (
+ views.get(token)?.displayed(id, rumors, review) ?? Promise.resolve(false)
+ );
+}
+
+export function inboxThreadRevision(token: InboxView | undefined): number {
+ return token ? (views.get(token)?.threadRevision() ?? -1) : -1;
+}
diff --git a/web/src/lib/persistence/private-storage.ts b/web/src/lib/persistence/private-storage.ts
@@ -393,6 +393,32 @@ export function listPrivateReceivedRecords(
);
}
+// Strict bounded readonly outbox observations; no publication authority.
+export function listPrivateSendRecords(
+ repository: PrivateStorageRepository
+): Promise<PrivateStorageResult<readonly PrivateRecordHandle[]>> {
+ const scope = scopeOf(repository);
+ if (!scope) return Promise.resolve(failed('invalid_scope'));
+ return transaction<readonly PrivateRecordHandle[]>(
+ scope,
+ 'private_sends',
+ 'readonly',
+ (rows) => {
+ let handles = Array.from<PrivateRecordHandle>([]);
+ for (const row of rows) {
+ const decoded = decodePrivateRecord(
+ row.wire,
+ scope.owner,
+ row.record.id
+ );
+ if (!decoded.ok) return failed('corrupt_record');
+ handles = handles.concat(decoded.value);
+ }
+ return { ok: true, value: handles };
+ }
+ );
+}
+
// Explicit original-owner local received-copy loss only. Immutable selected
// whole wires CAS before any delete; independent outbox is never opened.
// Actual close aborts an admitted transaction where still possible. Native
diff --git a/web/src/routes/messages/[conversationId=local_id]/+page.svelte b/web/src/routes/messages/[conversationId=local_id]/+page.svelte
@@ -1,77 +1,8 @@
<script lang="ts">
- import { getContext, onMount } from 'svelte';
import { page } from '$app/state';
- import AccountGate from '../../../lib/components/AccountGate.svelte';
- import {
- CONVERSATION_DIRECTORY_CONTEXT,
- resolveLocalConversation,
- subscribeConversationDirectory,
- type ConversationDirectory
- } from '../../../lib/messaging/conversation-directory.ts';
- import {
- IDENTITY_VIEW_CONTEXT,
- identityViewMatchesOwner,
- subscribeIdentityView,
- type IdentityViewContext
- } from '../../../lib/runtime/view-context.ts';
- const directory = getContext<ConversationDirectory | undefined>(
- CONVERSATION_DIRECTORY_CONTEXT
- );
- const identity = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);
- let resolved = $state(false),
- mounted = $state(false);
- let generation = 0;
- async function refresh(conversationId = page.params.conversationId) {
- const original = ++generation;
- resolved = false;
- if (!directory || !mounted) return;
- const result = await resolveLocalConversation(directory, conversationId);
- if (original !== generation || !mounted) return;
- resolved =
- result.status === 'resolved' &&
- identityViewMatchesOwner(identity, result.owner);
- }
- onMount(() => {
- mounted = true;
- const offIdentity = subscribeIdentityView(identity, () => {
- void refresh();
- });
- const offDirectory = directory
- ? subscribeConversationDirectory(directory, () => {
- void refresh();
- })
- : () => {};
- void refresh();
- return () => {
- mounted = false;
- generation++;
- offIdentity();
- offDirectory();
- };
- });
- $effect(() => {
- const conversationId = page.params.conversationId;
- if (mounted) void refresh(conversationId);
- });
+ import ConversationThread from '../../../lib/components/ConversationThread.svelte';
</script>
-<svelte:head>
- {#if resolved}
- <title>HarvestCircle</title><meta name="robots" content="noindex" />
- {/if}
-</svelte:head>
-{#if resolved}
- <div class="page page--reading stack">
- <h1>Conversation</h1>
- <p>Unlock message contents to read this conversation.</p>
- </div>
-{:else}
- <AccountGate />
- <div class="page page--reading stack">
- <p>
- This conversation is unavailable until it is unlocked in the matching
- browser and account.
- </p>
- </div>
-{/if}
-<div class="page page--reading"><a href="/messages">Back to messages</a></div>
+{#key page.params.conversationId}<ConversationThread
+ conversationId={page.params.conversationId ?? ''}
+ />{/key}
diff --git a/web/tests/e2e/conversation-thread.spec.ts b/web/tests/e2e/conversation-thread.spec.ts
@@ -0,0 +1,537 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+import { svelte } from '@sveltejs/vite-plugin-svelte';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/conversation-thread.ts';
+declare global {
+ interface Window {
+ hcp103: typeof Fixture;
+ hcp103Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>;
+ hcp103Pending?: Promise<boolean>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let events: unknown[][] = [],
+ requests: unknown[][] = [];
+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('no loopback');
+ 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),
+ frame = JSON.parse(raw.toString()) as unknown[];
+ if (frame[0] === 'EVENT') {
+ events.push(frame);
+ const event = frame[1] as { id: string };
+ socket.send(JSON.stringify(['OK', event.id, true, '']));
+ }
+ if (frame[0] === 'REQ') {
+ requests.push(frame);
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ }
+ })
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [svelte({ configFile: false })],
+ resolve: {
+ conditions: ['browser'],
+ alias: {
+ '$app/navigation': fileURLToPath(
+ new URL('./harness/conversation-thread.ts', import.meta.url)
+ )
+ }
+ },
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/conversation-thread.ts', import.meta.url)
+ ),
+ name: 'hcp103',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw Error('no bundle');
+ const chunks = output.output.filter((row) => row.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets.clients) socket.terminate();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+async function load(page: import('@playwright/test').Page) {
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://peer.example.org',
+ 'wss://archive.example.org',
+ 'wss://discovery.example.org'
+ ].includes(new URL(String(url)).origin)
+ )
+ throw Error('unapproved destination');
+ super(endpoint, protocols);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+}
+test.beforeEach(async ({ page }) => {
+ events = [];
+ requests = [];
+ await load(page);
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(async () => {
+ window.hcp103Fixture?.settle();
+ await window.hcp103Pending;
+ await window.hcp103Fixture?.close();
+ });
+});
+async function ready(
+ page: import('@playwright/test').Page,
+ kind: Fixture.Scenario = 'inbound',
+ selectedId?: string
+) {
+ await page.evaluate(
+ async ({ kind, selectedId }) => {
+ window.hcp103Fixture = await window.hcp103.renderFixture(
+ kind,
+ selectedId
+ );
+ },
+ { kind, selectedId }
+ );
+ await page.getByRole('button', { name: 'Check current preference' }).click();
+}
+async function unlock(page: import('@playwright/test').Page) {
+ await page
+ .getByRole('button', { name: 'Unlock messages', exact: true })
+ .click();
+ await expect
+ .poll(() => page.evaluate(() => window.hcp103Fixture.thread().status))
+ .toBe('ready');
+ await expect(page.locator('[data-message-id]')).not.toHaveCount(0);
+}
+const missing = '12345678-1234-4234-8234-123456789abd';
+function records(rows: unknown[]) {
+ return rows.map(
+ (row) =>
+ JSON.parse((row as { wire: string }).wire) as {
+ outer: string;
+ read: { rumorHash: string } | null;
+ }
+ );
+}
+test('production private guest load keeps generic title noindex safe inbox link and no private effects', async ({
+ page
+}) => {
+ await page.goto(server.url + '/messages/' + missing);
+ await expect(
+ page.getByRole('heading', { name: 'Connect or unlock' })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('link', { name: 'Back to messages' })
+ ).toHaveAttribute('href', '/messages');
+ await expect(page).toHaveTitle('HarvestCircle');
+ await expect(page.locator('meta[name="robots"]')).toHaveAttribute(
+ 'content',
+ 'noindex'
+ );
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('actual owner UUID and ciphertext stay unpreviewed and unread before explicit unlock', async ({
+ page
+}) => {
+ await ready(page);
+ const native = await page.evaluate(() => window.hcp103Fixture.native());
+ expect(native.pairs).toHaveLength(1);
+ expect(records(native.received).every((row) => row.read === null)).toBe(true);
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ await expect(
+ page.getByText('Actual encrypted thread fixture', { exact: true })
+ ).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp103Fixture.delta())).toEqual({
+ decrypts: 0,
+ signs: 0,
+ encrypts: 0
+ });
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('original explicit decrypt renders authenticated sender inner time and plain body in one chronological column', async ({
+ page
+}) => {
+ await ready(page);
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toHaveCount(1);
+ await expect(
+ page.getByText('Actual encrypted thread fixture', { exact: true })
+ ).toBeVisible();
+ await expect(page.locator('[data-message-id]')).toContainText('Peer');
+ await expect(page.locator('[data-message-id] time')).toHaveAttribute(
+ 'datetime',
+ '2023-11-14T22:13:20.000Z'
+ );
+ expect(await page.evaluate(() => window.hcp103Fixture.delta())).toEqual({
+ decrypts: 2,
+ signs: 0,
+ encrypts: 0
+ });
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('two actual encrypted product contexts sort per message with their own citation and no current price claim', async ({
+ page
+}) => {
+ await ready(page, 'contexts');
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toHaveCount(3);
+ const texts = await page.locator('[data-message-id]').allTextContents();
+ expect(texts[0]).toContain('Actual encrypted thread fixture');
+ expect(texts[1]).toContain('About apples');
+ expect(texts[2]).toContain('About carrots');
+ const refs = await page.evaluate(() => ({
+ apples: window.hcp103Fixture.apples,
+ carrots: window.hcp103Fixture.carrots
+ }));
+ await expect(
+ page.locator('[data-message-id]').nth(1).getByRole('link')
+ ).toHaveAttribute('href', '/products/' + refs.apples);
+ await expect(
+ page.locator('[data-message-id]').nth(2).getByRole('link')
+ ).toHaveAttribute('href', '/products/' + refs.carrots);
+ await expect(page.locator('[data-message-id]').nth(1)).toContainText(
+ 'unverified'
+ );
+ await expect(page.locator('[data-message-id]').nth(2)).toContainText(
+ 'not a current'
+ );
+ expect(requests).toEqual([]);
+ expect(events).toEqual([]);
+});
+test('original self archive labels You without inventing a recipient ACK or remote read', async ({
+ page
+}) => {
+ await ready(page, 'self_archive');
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toContainText('You');
+ await expect(page.locator('[data-message-id]')).toContainText(
+ 'Recipient delivery unknown'
+ );
+ await expect(page.locator('[data-message-id]')).not.toContainText(
+ 'Accepted by recipient inbox relay'
+ );
+ await expect(page.locator('[data-message-id]')).not.toContainText('Seen');
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('actual original loopback SDK ACK and native receipt supply relay acceptance without thread publication', async ({
+ page
+}) => {
+ await ready(page, 'receipt');
+ expect(events).toHaveLength(2);
+ const native = await page.evaluate(() => window.hcp103Fixture.native());
+ expect(
+ (
+ JSON.parse((native.sends[0] as { wire: string }).wire) as {
+ receipts: { role: string; status: string }[];
+ }
+ ).receipts.some(
+ (row: { role: string; status: string }) =>
+ row.role === 'peer' && row.status === 'accepted'
+ )
+ ).toBe(true);
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toContainText(
+ 'Accepted by recipient inbox relay'
+ );
+ await expect(page.locator('[data-message-id]')).not.toContainText('Seen');
+ expect(events).toHaveLength(2);
+ expect(requests).toEqual([]);
+});
+test('different genuine outer wraps of the same rumor render once and retain both ciphertext copies', async ({
+ page
+}) => {
+ await ready(page, 'duplicate');
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toHaveCount(1);
+ expect(
+ (await page.evaluate(() => window.hcp103Fixture.native())).received
+ ).toHaveLength(2);
+ expect(await page.evaluate(() => window.hcp103Fixture.delta())).toEqual({
+ decrypts: 4,
+ signs: 0,
+ encrypts: 0
+ });
+});
+test('only actual displayed original room records local read without changing ciphertext or notifying peer', async ({
+ page
+}) => {
+ await ready(page);
+ const before = await page.evaluate(() => window.hcp103Fixture.native());
+ await unlock(page);
+ await expect
+ .poll(
+ async () =>
+ records(
+ (await page.evaluate(() => window.hcp103Fixture.native())).received
+ ).filter((row) => row.read !== null).length
+ )
+ .toBe(1);
+ const after = await page.evaluate(() => window.hcp103Fixture.native());
+ expect(records(after.received).map((row) => row.outer)).toEqual(
+ records(before.received).map((row) => row.outer)
+ );
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('copied original controller cannot import bodies navigation or native display effects', async ({
+ page
+}) => {
+ await ready(page);
+ await unlock(page);
+ const result = await page.evaluate(async () => {
+ const f = window.hcp103Fixture,
+ before = await f.native();
+ return {
+ copied: await f.copied(),
+ before,
+ after: await f.native(),
+ delta: f.delta()
+ };
+ });
+ expect(result.copied.snapshot).toMatchObject({
+ status: 'unavailable',
+ messages: []
+ });
+ expect(result.copied.message).toBeUndefined();
+ expect(result.copied.resolve).toBe(false);
+ expect(result.copied.read).toBe(false);
+ expect(result.after).toEqual(result.before);
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
+test('unknown original UUID refuses before SDK decrypt and never substitutes an existing pair', async ({
+ page
+}) => {
+ await ready(page, 'inbound', missing);
+ const before = await page.evaluate(() => window.hcp103Fixture.native());
+ expect(await page.evaluate(() => window.hcp103Fixture.unlock())).toBe(false);
+ expect(await page.evaluate(() => window.hcp103Fixture.next())).toBe(false);
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp103Fixture.native())).toEqual(
+ before
+ );
+ expect(await page.evaluate(() => window.hcp103Fixture.delta())).toEqual({
+ decrypts: 0,
+ signs: 0,
+ encrypts: 0
+ });
+});
+test('same-owner UUID in a separate real storage profile is unavailable without peer inference', async ({
+ page,
+ browser
+}) => {
+ await ready(page);
+ const id = await page.evaluate(() => window.hcp103Fixture.conversationId),
+ context = await browser.newContext();
+ try {
+ const other = await context.newPage();
+ await load(other);
+ await ready(other, 'inbound', id);
+ const before = await other.evaluate(() => window.hcp103Fixture.native());
+ expect(await other.evaluate(() => window.hcp103Fixture.unlock())).toBe(
+ false
+ );
+ await expect(other.locator('[data-message-id]')).toHaveCount(0);
+ expect(await other.evaluate(() => window.hcp103Fixture.native())).toEqual(
+ before
+ );
+ expect(await other.evaluate(() => window.hcp103Fixture.delta())).toEqual({
+ decrypts: 0,
+ signs: 0,
+ encrypts: 0
+ });
+ await other.evaluate(() => window.hcp103Fixture.close());
+ } finally {
+ await context.close();
+ }
+});
+test('Stop and owner logout clear original thread bodies and deny stale display effects', async ({
+ page
+}) => {
+ await ready(page);
+ await unlock(page);
+ await page.evaluate(() => window.hcp103Fixture.stop());
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ const result = await page.evaluate(async () => {
+ const f = window.hcp103Fixture,
+ before = await f.native();
+ f.logout();
+ return {
+ resolved: await f.resolve(f.conversationId),
+ before,
+ after: await f.native()
+ };
+ });
+ expect(result.resolved).toBe(false);
+ expect(result.after).toEqual(result.before);
+});
+test('logout during held actual extension decrypt prevents late thread disclosure or native read', async ({
+ page
+}) => {
+ await ready(page);
+ await page.evaluate(() => {
+ const f = window.hcp103Fixture;
+ f.mode('hold_decrypt');
+ window.hcp103Pending = f.unlock();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp103Fixture.pending()))
+ .toBe(true);
+ const before = await page.evaluate(() => window.hcp103Fixture.native());
+ await page.evaluate(() => {
+ window.hcp103Fixture.logout();
+ window.hcp103Fixture.settle();
+ });
+ expect(await page.evaluate(() => window.hcp103Pending)).toBe(false);
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp103Fixture.native())).toEqual(
+ before
+ );
+});
+test('initial backfill is not replayed through a live log and later explicit batch preserves focus and reading position', async ({
+ page
+}) => {
+ await ready(page, 'backfill');
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toHaveCount(20);
+ await expect(page.locator('[data-thread-announcement]')).toHaveText('');
+ await expect(
+ page.locator('[data-message-id] [aria-live="polite"]')
+ ).toHaveCount(0);
+ await page.getByRole('button', { name: 'Reading position marker' }).focus();
+ await page.evaluate(() => window.scrollTo(0, 320));
+ await expect
+ .poll(() => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(0);
+ const before = await page.evaluate(() => ({
+ active: document.activeElement?.id,
+ scroll: window.scrollY
+ }));
+ expect(await page.evaluate(() => window.hcp103Fixture.next())).toBe(true);
+ await expect(page.locator('[data-message-id]')).toHaveCount(21);
+ await expect(page.locator('[data-thread-announcement]')).toHaveAttribute(
+ 'aria-live',
+ 'polite'
+ );
+ await expect(page.locator('[data-thread-announcement]')).toHaveText(
+ '1 message added.'
+ );
+ expect(
+ await page.evaluate(() => ({
+ active: document.activeElement?.id,
+ scroll: window.scrollY
+ }))
+ ).toEqual(before);
+});
+test('hostile plaintext and missing parent stay inert without HTML external links or private-ID searches', async ({
+ page
+}) => {
+ await ready(page, 'hostile');
+ await unlock(page);
+ await expect(page.locator('[data-message-id]')).toContainText('<img src=x>');
+ await expect(page.locator('[data-message-id]')).toContainText(
+ 'Earlier message unavailable'
+ );
+ await expect(page.locator('[data-message-id] img')).toHaveCount(0);
+ await expect(page.locator('[data-message-id] a')).toHaveCount(0);
+ expect(requests).toEqual([]);
+ expect(events).toEqual([]);
+ expect(page.url()).not.toContain('f'.repeat(64));
+});
+test('changing to an unknown route selection revokes stale original row lookup without writes or replacement', async ({
+ page
+}) => {
+ await ready(page);
+ await unlock(page);
+ const result = await page.evaluate(async (missing) => {
+ const f = window.hcp103Fixture,
+ before = await f.native(),
+ result = await f.resolve(missing);
+ return { result, old: f.thread(), before, after: await f.native() };
+ }, missing);
+ expect(result.result).toBe(false);
+ expect(result.old).toMatchObject({ status: 'unavailable', messages: [] });
+ await expect(page.locator('[data-message-id]')).toHaveCount(0);
+ expect(result.after).toEqual(result.before);
+});
+
+test('actual native owner lock contention leaves local read unclaimed and explicit retry confirms it after display', async ({
+ page
+}) => {
+ await ready(page);
+ await page.evaluate(() => window.hcp103Fixture.holdReadLock());
+ await unlock(page);
+ await expect(
+ page.getByText(
+ 'Local read status could not be confirmed. Encrypted copies are preserved.',
+ { exact: true }
+ )
+ ).toBeVisible();
+ expect(
+ records(
+ (await page.evaluate(() => window.hcp103Fixture.native())).received
+ ).every((row) => row.read === null)
+ ).toBe(true);
+ await page.evaluate(() => window.hcp103Fixture.releaseRead());
+ await page.getByRole('button', { name: 'Retry local read status' }).click();
+ await expect
+ .poll(
+ async () =>
+ records(
+ (await page.evaluate(() => window.hcp103Fixture.native())).received
+ ).filter((row) => row.read !== null).length
+ )
+ .toBe(1);
+ await expect(
+ page.getByRole('button', { name: 'Retry local read status' })
+ ).toHaveCount(0);
+ expect(events).toEqual([]);
+ expect(requests).toEqual([]);
+});
diff --git a/web/tests/e2e/harness/conversation-thread-panel.svelte b/web/tests/e2e/harness/conversation-thread-panel.svelte
@@ -0,0 +1,11 @@
+<script lang="ts">
+ import ConversationThread from '../../../src/lib/components/ConversationThread.svelte';
+ import type { InboxView } from '../../../src/lib/messaging/inbox-view.ts';
+ let {
+ controller,
+ conversationId
+ }: { controller: InboxView; conversationId: string } = $props();
+</script>
+
+<button id="reading-marker" type="button">Reading position marker</button>
+<ConversationThread {controller} {conversationId} />
diff --git a/web/tests/e2e/harness/conversation-thread.ts b/web/tests/e2e/harness/conversation-thread.ts
@@ -0,0 +1,406 @@
+import { mount, unmount } from 'svelte';
+import Panel from './conversation-thread-panel.svelte';
+import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts';
+import { makeFixture as makeRetryFixture } from './retry-send.ts';
+import {
+ getPublicKey,
+ getEventHash,
+ finalizeEvent,
+ type UnsignedEvent
+} from 'applesauce-core/helpers';
+import { nip44 } from 'applesauce-core/helpers/encryption';
+import { encodeProductReference } from '../../../src/lib/nostr/references.ts';
+import { createPrivateSession } from '../../../src/lib/runtime/private-session.ts';
+import {
+ admitInboxEnvelope,
+ retainInboxEnvelope
+} from '../../../src/lib/persistence/inbox-envelope-repository.ts';
+import {
+ captureReceivedUnwrap,
+ unwrapReceivedEnvelope,
+ stopReceivedUnwrap
+} from '../../../src/lib/nostr/unwrap-admission.ts';
+import { admitReceivedConversation } from '../../../src/lib/messaging/admit-conversation.ts';
+import {
+ captureUnlockedSession,
+ acceptUnlockedConversation,
+ closeUnlockedSession
+} from '../../../src/lib/messaging/unlocked-session.ts';
+import { captureMessageMetadata } from '../../../src/lib/persistence/message-metadata.ts';
+import {
+ captureConversationDirectory,
+ rememberAdmittedConversation,
+ closeConversationDirectory
+} from '../../../src/lib/messaging/conversation-directory.ts';
+import {
+ createInboxSetupView,
+ checkInboxSetupView,
+ closeInboxSetupView
+} from '../../../src/lib/messaging/inbox-setup-view.ts';
+import {
+ readRelayPolicy,
+ validateRelayPolicy
+} from '../../../src/lib/config/relays.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import {
+ createInboxView,
+ inboxViewSnapshot,
+ unlockInboxView,
+ readNewInboxView,
+ inboxThreadSnapshot,
+ inboxMessageSnapshot,
+ resolveInboxConversation,
+ markInboxConversationDisplayed,
+ stopInboxView,
+ closeInboxView
+} from '../../../src/lib/messaging/inbox-view.ts';
+
+export function goto(): never {
+ throw Error('Thread fixture must not navigate');
+}
+export type Scenario =
+ | 'inbound'
+ | 'self_archive'
+ | 'contexts'
+ | 'duplicate'
+ | 'receipt'
+ | 'backfill'
+ | 'hostile';
+export async function renderFixture(
+ kind: Scenario = 'inbound',
+ selectedId?: string
+) {
+ // Receipt scenario performs actual original SDK retry and receives loopback
+ // OKs before mounting the readonly thread. The UI itself never publishes.
+ const delivery = kind === 'receipt' ? await makeRetryFixture() : undefined,
+ f = delivery ?? (await makeRecoveryFixture()),
+ session = await createPrivateSession(
+ f.identity,
+ 'reviewed_private_session'
+ );
+ if (!session) throw Error('no genuine current private session');
+ let actualDelivery: unknown;
+ if (delivery) {
+ const prepared = await delivery.prepare();
+ if (prepared.status !== 'existing' || !delivery.capture())
+ throw Error('no actual stored pair retry');
+ actualDelivery = await delivery.run();
+ }
+ const ownerSecret = new Uint8Array(32).fill(83),
+ peerSecret = new Uint8Array(32).fill(84);
+ function cipher(
+ content: string,
+ createdAt: number,
+ index: number,
+ parent?: string
+ ) {
+ const sender = getPublicKey(peerSecret),
+ tags = [['p', f.owner]];
+ if (parent) tags.push(['e', parent]);
+ const template: UnsignedEvent = {
+ pubkey: sender,
+ kind: 14,
+ created_at: createdAt,
+ tags,
+ content
+ },
+ rumor = { id: getEventHash(template), ...template };
+ function encrypt(key: Uint8Array, plain: string) {
+ const conversation = nip44.v2.utils.getConversationKey(key, f.owner);
+ try {
+ return nip44.v2.encrypt(plain, conversation);
+ } finally {
+ conversation.fill(0);
+ }
+ }
+ const seal = finalizeEvent(
+ {
+ kind: 13,
+ created_at: 1699999900,
+ tags: [],
+ content: encrypt(peerSecret, JSON.stringify(rumor))
+ },
+ peerSecret
+ ),
+ outerSecret = new Uint8Array(32).fill(85 + index);
+ try {
+ const outer = finalizeEvent(
+ {
+ kind: 1059,
+ created_at: 1699999800 + index,
+ tags: [['p', f.owner]],
+ content: encrypt(outerSecret, JSON.stringify(seal))
+ },
+ outerSecret
+ );
+ return {
+ wire: JSON.stringify(outer),
+ rumorId: rumor.id,
+ body: content,
+ outerId: outer.id
+ };
+ } finally {
+ outerSecret.fill(0);
+ }
+ }
+ const carrots = encodeProductReference({
+ kind: 30402,
+ pubkey: f.peer,
+ identifier: 'carrots'
+ })!,
+ apples = encodeProductReference({
+ kind: 30402,
+ pubkey: f.peer,
+ identifier: 'apples'
+ })!;
+ let first: ReturnType<typeof cipher>,
+ wires = Array.from<ReturnType<typeof cipher>>([]);
+ try {
+ if (kind === 'self_archive' || kind === 'receipt') {
+ const row = (await f.row())!.record,
+ outer = JSON.parse(row.self.wire) as { id: string };
+ first = {
+ wire: row.self.wire,
+ outerId: outer.id,
+ rumorId: row.rumorHash,
+ body: 'Original encrypted self archive'
+ };
+ } else
+ first = cipher(
+ kind === 'hostile'
+ ? '<img src=x> Quoted price 4 GBP https://untrusted.example.org nostr:naddr1invalid'
+ : 'Actual encrypted thread fixture',
+ 1700000000,
+ 0,
+ kind === 'hostile' ? 'f'.repeat(64) : undefined
+ );
+ wires = wires.concat(first);
+ if (kind === 'contexts')
+ wires = wires.concat(
+ cipher(
+ 'About carrots\nProduct: nostr:' + carrots + '\nQuoted price: 4 GBP',
+ 1700000020,
+ 1
+ ),
+ cipher(
+ 'About apples\nProduct: nostr:' + apples + '\nQuoted price: 8 GBP',
+ 1700000010,
+ 2,
+ first.rumorId
+ )
+ );
+ if (kind === 'duplicate')
+ wires = wires.concat(cipher(first.body, 1700000000, 1));
+ if (kind === 'backfill')
+ for (let i = 1; i <= 20; i++)
+ wires = wires.concat(
+ cipher('Actual later message ' + i, 1700000000 + i, i)
+ );
+ for (const wire of wires) {
+ const admitted = admitInboxEnvelope(
+ wire.wire,
+ f.owner,
+ 'wss://archive.example.org',
+ 100
+ );
+ if (
+ !admitted ||
+ (await retainInboxEnvelope(f.repository, session, admitted)).status !==
+ 'retained'
+ )
+ throw Error('actual ciphertext not retained');
+ }
+ } finally {
+ ownerSecret.fill(0);
+ peerSecret.fill(0);
+ }
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error('no actual native database');
+ const database = opened.owner;
+ // Establish only a genuine original-room owner UUID through the existing
+ // non-read native workflow, then discard the warmup plaintext cache. These
+ // preparation SDK calls are distinct from the later explicit UI count.
+ const reader = captureReceivedUnwrap(
+ f.repository,
+ f.identity,
+ first.outerId,
+ 'reviewed_inbox_unlock'
+ );
+ if (!reader) throw Error('no original nested reader');
+ const result = await unwrapReceivedEnvelope(reader);
+ if (result.status !== 'authenticated')
+ throw Error('no actual authenticated fixture');
+ const room = admitReceivedConversation(
+ result.envelope,
+ kind === 'self_archive' || kind === 'receipt' ? 'self_archive' : 'inbound'
+ ),
+ cache = captureUnlockedSession(session, 'reviewed_messages_unlock');
+ if (!room || !cache || acceptUnlockedConversation(cache, room) !== 'added')
+ throw Error('no original cached room');
+ const metadata = captureMessageMetadata(
+ database,
+ session,
+ cache,
+ 'reviewed_local_message_metadata'
+ ),
+ directory =
+ metadata &&
+ captureConversationDirectory(
+ session,
+ metadata,
+ 'reviewed_conversation_directory'
+ );
+ if (!directory) throw Error('no genuine directory');
+ const remembered = await rememberAdmittedConversation(
+ directory,
+ room,
+ 'reviewed_admitted_conversation_navigation'
+ );
+ if (remembered.status !== 'saved' && remembered.status !== 'existing')
+ throw Error('no actual local UUID');
+ const conversationId = selectedId ?? remembered.conversationId;
+ closeConversationDirectory(directory);
+ closeUnlockedSession(cache);
+ stopReceivedUnwrap(reader);
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ ...readRelayPolicy(f.context.policy),
+ messagingEnabled: true
+ })
+ );
+ if (!policy) throw Error('no original policy');
+ const setup = createInboxSetupView({
+ identity: f.identity,
+ policy,
+ lookup: () => Promise.resolve(f.context.own)
+ });
+ if (!setup) throw Error('no original setup');
+ const controller = createInboxView({
+ identity: f.identity,
+ setup,
+ conversationId
+ });
+ if (!controller) throw Error('no genuine thread owner');
+ const target = document.createElement('div');
+ document.body.append(target);
+ const mounted = mount(Panel, {
+ target,
+ props: { controller, conversationId }
+ }),
+ baseline = f.counts();
+ async function native() {
+ const tx = browserDatabaseTransaction(
+ database,
+ ['received_envelopes', 'conversations', 'private_sends'],
+ 'readonly'
+ ),
+ received = tx.objectStore('received_envelopes').getAll(),
+ pairs = tx.objectStore('conversations').getAll(),
+ sends = tx.objectStore('private_sends').getAll();
+ return await new Promise<{
+ received: unknown[];
+ pairs: unknown[];
+ sends: unknown[];
+ }>((resolve, reject) => {
+ tx.addEventListener('complete', () =>
+ resolve({
+ received: received.result,
+ pairs: pairs.result,
+ sends: sends.result
+ })
+ );
+ tx.addEventListener('abort', () => reject(Error('native scan aborted')));
+ });
+ }
+ let releaseReadLock: (() => void) | undefined,
+ readLockPending: Promise<unknown> | undefined;
+ async function holdReadLock() {
+ if (readLockPending) throw Error('already held');
+ await new Promise<void>((resolve) => {
+ readLockPending = navigator.locks.request(
+ 'harvestcircle:owner:' + f.owner,
+ async () => {
+ await new Promise<void>((release) => {
+ releaseReadLock = release;
+ resolve();
+ });
+ }
+ );
+ });
+ }
+ async function releaseRead() {
+ releaseReadLock?.();
+ await readLockPending;
+ releaseReadLock = undefined;
+ readLockPending = undefined;
+ }
+ return {
+ holdReadLock,
+ releaseRead,
+ controller,
+ owner: f.owner,
+ peer: f.peer,
+ conversationId,
+ knownId: remembered.conversationId,
+ firstRumor: first.rumorId,
+ carrots,
+ apples,
+ actualDelivery,
+ preparationCounts: baseline,
+ native,
+ snapshot: () => inboxViewSnapshot(controller),
+ thread: () => inboxThreadSnapshot(controller, conversationId),
+ checkSetup: () => checkInboxSetupView(setup),
+ unlock: () => unlockInboxView(controller, 'reviewed_messages_unlock'),
+ next: () => readNewInboxView(controller, 'reviewed_decrypt_batch'),
+ delta: () => ({
+ decrypts: f.counts().decrypts - baseline.decrypts,
+ signs: f.counts().signs - baseline.signs,
+ encrypts: f.counts().encrypts - baseline.encrypts
+ }),
+ copied: async () => ({
+ snapshot: inboxThreadSnapshot({ ...controller }, conversationId),
+ message: inboxMessageSnapshot(
+ { ...controller },
+ conversationId,
+ first.rumorId
+ ),
+ resolve: await resolveInboxConversation(
+ { ...controller },
+ conversationId,
+ 'reviewed_conversation_navigation'
+ ),
+ read: await markInboxConversationDisplayed(
+ { ...controller },
+ conversationId,
+ [first.rumorId],
+ 'reviewed_displayed_conversation'
+ )
+ }),
+ resolve: (id: string) =>
+ resolveInboxConversation(
+ controller,
+ id,
+ 'reviewed_conversation_navigation'
+ ),
+ stop: () => stopInboxView(controller),
+ logout: () => f.disconnect(),
+ mode: f.mode,
+ settle: () => f.settle(),
+ pending: () => f.pending(),
+ async close() {
+ await releaseRead();
+ f.settle();
+ closeInboxView(controller);
+ closeInboxSetupView(setup);
+ await unmount(mounted);
+ closeBrowserDatabase(database);
+ f.close();
+ target.remove();
+ }
+ };
+}
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -305,7 +305,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
const f = await fixture(t);
const files = await f.audit();
// Exact eleven-route module/page/static admission; CSS stays once-imported.
- assert.equal(files.length, 50);
+ assert.equal(files.length, 51);
// The actual SDK payload crosses the reader scratch boundary; a reused
// scratch buffer must still preserve every compiler/static byte exactly.
const sizes = await Promise.all(
@@ -347,7 +347,12 @@ import { auditOutput } from '../../tools/check-output.mjs';
'src/lib/messaging/inbox-sync.ts',
'src/lib/messaging/decryption-queue.ts',
'src/lib/components/ConversationRow.svelte',
- 'src/lib/messaging/inbox-list.ts'
+ 'src/lib/messaging/inbox-list.ts',
+ 'src/lib/components/ConversationThread.svelte',
+ 'src/lib/components/MessageItem.svelte',
+ 'src/lib/messaging/conversation-thread.ts',
+ 'src/lib/persistence/private-storage.ts',
+ 'src/routes/messages/[conversationId=local_id]/+page.svelte'
])
await check(
'linked inbox presentation requires exact owned source ' +
@@ -389,7 +394,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
assert.ok(row);
return row;
};
- const [key, row] = find('conversation-directory');
+ const [key, row] = find('InboxStatus');
if (mutation === 'missing-private-cache-directory')
delete manifest[key];
if (mutation === 'extra-private-edge')
@@ -410,7 +415,10 @@ import { auditOutput } from '../../tools/check-output.mjs';
for (const mutation of [
'directory-missing-context',
'directory-entry-role',
- 'directory-duplicate-role'
+ 'directory-duplicate-role',
+ 'thread-missing-edge',
+ 'thread-dynamic',
+ 'thread-entry-role'
])
await check(
'actual inbox list compiler rejects ' + mutation,
@@ -422,18 +430,29 @@ import { auditOutput } from '../../tools/check-output.mjs';
),
manifest = JSON.parse(await readFile(file, 'utf8'));
const entry = Object.entries(manifest).find(
- ([, row]) => row.name === 'conversation-directory'
+ ([, row]) =>
+ row.name ===
+ (mutation.startsWith('thread-') ? 'nodes/5' : 'InboxStatus')
);
assert.ok(entry);
const [, row] = entry;
if (mutation === 'directory-missing-context')
row.imports = row.imports.filter(
(/** @type {string} */ value) =>
- manifest[value].name !== 'AccountGate'
+ manifest[value].name !== 'InboxSetup'
);
if (mutation === 'directory-entry-role') row.isEntry = true;
if (mutation === 'directory-duplicate-role')
manifest['_forged_directory.js'] = { ...row };
+ if (mutation === 'thread-missing-edge')
+ row.imports = row.imports.slice(1);
+ if (mutation === 'thread-dynamic')
+ row.dynamicImports = [
+ Object.keys(manifest).find(
+ (key) => manifest[key].name === 'read'
+ )
+ ];
+ if (mutation === 'thread-entry-role') row.isEntry = false;
await writeFile(file, JSON.stringify(manifest));
await assert.rejects(f.audit, /compiler|duplicate|inventory/);
}
@@ -496,7 +515,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
assert.ok(Buffer.byteLength(expanded) > 64 * 1024);
await writeFile(file, expanded);
await refresh(f);
- assert.equal((await f.audit()).length, 50);
+ assert.equal((await f.audit()).length, 51);
}
);
@@ -1047,7 +1066,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
}
await writeFile(file, JSON.stringify(manifest));
if (mutation === 'permuted-edges')
- assert.equal((await f.audit()).length, 50);
+ assert.equal((await f.audit()).length, 51);
else await assert.rejects(f.audit, /compiler|references/);
}
);
diff --git a/web/tests/unit/conversation-thread.test.ts b/web/tests/unit/conversation-thread.test.ts
@@ -0,0 +1,279 @@
+import { describe, expect, it } from 'vitest';
+import { getPublicKey, finalizeEvent } from 'applesauce-core/helpers';
+import { nip44 } from 'applesauce-core/helpers/encryption';
+import { projectConversationThread } from '../../src/lib/messaging/conversation-thread.ts';
+import type { ConversationData } from '../../src/lib/messaging/admit-conversation.ts';
+import { encodeProductReference } from '../../src/lib/nostr/references.ts';
+import { decodePrivateRecord } from '../../src/lib/persistence/private-records.ts';
+import {
+ resolveInboxConversation,
+ inboxThreadSnapshot,
+ inboxMessageSnapshot,
+ markInboxConversationDisplayed,
+ type InboxView
+} from '../../src/lib/messaging/inbox-view.ts';
+
+const owner = getPublicKey(new Uint8Array(32).fill(83)),
+ peer = getPublicKey(new Uint8Array(32).fill(84)),
+ other = getPublicKey(new Uint8Array(32).fill(85)),
+ command = '12345678-1234-4234-8234-123456789abc';
+function message(overrides: Partial<ConversationData> = {}): ConversationData {
+ return {
+ owner,
+ peer,
+ sender: peer,
+ recipient: owner,
+ role: 'inbound',
+ rumorId: 'a'.repeat(64),
+ createdAt: 1700000000,
+ content: 'Actual message text',
+ subject: null,
+ replyTo: null,
+ ...overrides
+ };
+}
+function archive(overrides: Partial<ConversationData> = {}): ConversationData {
+ return message({
+ role: 'self_archive',
+ sender: owner,
+ recipient: peer,
+ ...overrides
+ });
+}
+// Structural local receipt projection fixture; no factory, native commit or
+// real target delivery authority is claimed by this pure unit fixture.
+function receipt(role: 'peer' | 'self_archive', rumorHash = 'a'.repeat(64)) {
+ const key = new Uint8Array(32).fill(83);
+ try {
+ function artifact(destination: string) {
+ const conversation = nip44.v2.utils.getConversationKey(key, destination);
+ try {
+ const event = finalizeEvent(
+ {
+ kind: 1059,
+ created_at: 1700000000,
+ tags: [['p', destination]],
+ content: nip44.v2.encrypt(
+ 'Structural codec fixture only',
+ conversation
+ )
+ },
+ key
+ );
+ return { eventId: event.id, wire: JSON.stringify(event) };
+ } finally {
+ conversation.fill(0);
+ }
+ }
+ function route(
+ author: string,
+ kind: 'peer' | 'self_archive',
+ origin: string
+ ) {
+ return {
+ author,
+ role: kind,
+ targets: [origin],
+ knownBase: { author, id: 'b'.repeat(64), createdAt: 1 },
+ sources: [{ source: 'wss://discovery.example.org', state: 'eose' }]
+ };
+ }
+ const self = artifact(owner),
+ peerArtifact = artifact(peer),
+ row = {
+ schema: 1,
+ family: 'private_send_operation',
+ owner,
+ id: command,
+ revision: 3,
+ peer,
+ rumorHash,
+ createdAt: 1700000000,
+ self,
+ peerArtifact,
+ deliveryPlan: {
+ state: 'prepared',
+ routes: {
+ peer: route(peer, 'peer', 'wss://peer.example.org'),
+ archive: route(owner, 'self_archive', 'wss://archive.example.org')
+ }
+ },
+ receipts: [
+ {
+ actionId: '12345678-1234-4234-8234-123456789abd',
+ role,
+ origin:
+ role === 'peer'
+ ? 'wss://peer.example.org'
+ : 'wss://archive.example.org',
+ attempt: 1,
+ eventId: role === 'peer' ? peerArtifact.eventId : self.eventId,
+ status: 'accepted',
+ observedAtMilliseconds: 100,
+ readbackWire: null
+ }
+ ]
+ },
+ decoded = decodePrivateRecord(JSON.stringify(row), owner, command);
+ if (!decoded.ok) throw Error('invalid structural codec fixture');
+ return decoded.value;
+ } finally {
+ key.fill(0);
+ }
+}
+describe('detached plain chronological pair presentation grants no custody', () => {
+ it('orders by actual inner time then stable rumor identity without room-level product state', () => {
+ const first = message({
+ rumorId: 'b'.repeat(64),
+ createdAt: 2,
+ content: 'About apples'
+ }),
+ second = archive({ createdAt: 1, content: 'About carrots' }),
+ view = projectConversationThread(owner, peer, [first, second], []);
+ expect(view.status).toBe('ready');
+ expect(view.messages.map((row) => row.data.content)).toEqual([
+ 'About carrots',
+ 'About apples'
+ ]);
+ expect(view.messages.map((row) => row.data.role)).toEqual([
+ 'self_archive',
+ 'inbound'
+ ]);
+ });
+ it('deduplicates the same verified rumor and returns detached independent rows', () => {
+ const original = message(),
+ view = projectConversationThread(
+ owner,
+ peer,
+ [original, { ...original }],
+ []
+ );
+ expect(view.messages).toHaveLength(1);
+ expect(view.messages[0].data).not.toBe(original);
+ expect(original.content).toBe('Actual message text');
+ });
+ it('rejects conflicting same-rumor data instead of substituting later bytes', () => {
+ expect(
+ projectConversationThread(
+ owner,
+ peer,
+ [message(), message({ content: 'Changed' })],
+ []
+ ).status
+ ).toBe('unavailable');
+ });
+ it('rejects foreign owner, different pair and false sender roles', () => {
+ for (const row of [
+ message({ owner: other }),
+ message({ peer: other }),
+ message({ sender: owner })
+ ])
+ expect(projectConversationThread(owner, peer, [row], []).status).toBe(
+ 'unavailable'
+ );
+ });
+ it('keeps canonical public citations on their own message without promoting a listing claim', () => {
+ const carrots = encodeProductReference({
+ kind: 30402,
+ pubkey: peer,
+ identifier: 'carrots'
+ })!,
+ apples = encodeProductReference({
+ kind: 30402,
+ pubkey: peer,
+ identifier: 'apples'
+ })!,
+ view = projectConversationThread(
+ owner,
+ peer,
+ [
+ message({ content: 'Product: nostr:' + carrots }),
+ message({
+ rumorId: 'b'.repeat(64),
+ content: 'Product: nostr:' + apples
+ })
+ ],
+ []
+ );
+ expect(view.messages[0].citations.map((row) => row.naddr)).toEqual([
+ carrots
+ ]);
+ expect(view.messages[1].citations.map((row) => row.naddr)).toEqual([
+ apples
+ ]);
+ });
+ it('preserves quoted price and hostile text as text without HTML or external URL projection', () => {
+ const content =
+ '<img src=x> Quoted price 4 GBP https://untrusted.example.org nostr:naddr1invalid',
+ view = projectConversationThread(owner, peer, [message({ content })], []);
+ expect(view.messages[0].data.content).toBe(content);
+ expect(view.messages[0].citations).toEqual([]);
+ });
+ it('recognizes only a present parent in the same admitted pair without an external private-ID lookup', () => {
+ const parent = message(),
+ reply = archive({ rumorId: 'b'.repeat(64), replyTo: parent.rumorId }),
+ missing = message({ rumorId: 'c'.repeat(64), replyTo: 'd'.repeat(64) }),
+ view = projectConversationThread(
+ owner,
+ peer,
+ [parent, reply, missing],
+ []
+ );
+ expect(
+ view.messages.find((row) => row.data.rumorId === reply.rumorId)?.parent
+ ).toBe('present');
+ expect(
+ view.messages.find((row) => row.data.rumorId === missing.rumorId)?.parent
+ ).toBe('missing');
+ });
+ it('never upgrades sender archive acceptance to recipient acceptance or reports incoming remote reads', () => {
+ const view = projectConversationThread(
+ owner,
+ peer,
+ [archive()],
+ [receipt('self_archive')]
+ );
+ expect(view.messages[0].delivery).toContain('Recipient delivery unknown');
+ expect(view.messages[0].delivery).not.toContain(
+ 'Accepted by recipient inbox relay'
+ );
+ expect(
+ projectConversationThread(owner, peer, [message()], [receipt('peer')])
+ .messages[0].delivery
+ ).toBeNull();
+ });
+ it('uses only an exact local owner peer rumor receipt projection, never a different message fact', () => {
+ expect(
+ projectConversationThread(owner, peer, [archive()], [receipt('peer')])
+ .messages[0].delivery
+ ).toContain('Accepted by recipient inbox relay');
+ expect(
+ projectConversationThread(
+ owner,
+ peer,
+ [archive()],
+ [receipt('peer', 'b'.repeat(64))]
+ ).messages[0].delivery
+ ).toContain('Recipient delivery unknown');
+ });
+ it('unavailable copied and SSR controllers cannot import thread bodies or native display custody', async () => {
+ const fake = {} as InboxView;
+ expect(inboxThreadSnapshot(fake, command).status).toBe('unavailable');
+ expect(inboxMessageSnapshot(fake, command, 'a'.repeat(64))).toBeUndefined();
+ expect(
+ await resolveInboxConversation(
+ fake,
+ command,
+ 'reviewed_conversation_navigation'
+ )
+ ).toBe(false);
+ expect(
+ await markInboxConversationDisplayed(
+ fake,
+ command,
+ ['a'.repeat(64)],
+ 'reviewed_displayed_conversation'
+ )
+ ).toBe(false);
+ });
+});
diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts
@@ -74,9 +74,16 @@ describe('thin protected route SSR', () => {
expect(output.head).toContain('<title>HarvestCircle</title>');
expect(output.head).toMatch(/name="robots" content="noindex"/);
expect(output.body).toContain('Connect or unlock');
- expect(output.body).toContain(
- 'Private views and editing are unavailable during development.'
- );
+ if (name === 'Conversation') {
+ expect(output.body).toMatch(
+ /This conversation is unavailable until it is unlocked in the matching\s+browser and account\./
+ );
+ expect(output.body).toContain('href="/messages"');
+ expect(output.body).not.toContain('data-message-id');
+ } else
+ expect(output.body).toContain(
+ 'Private views and editing are unavailable during development.'
+ );
expect(output.body).toMatch(
/<button[^>]*disabled[^>]*>Connect extension/
);
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -509,9 +509,9 @@ async function inboxPresentationAdmission(web) {
'src/routes/messages/+page.svelte':
'8279a92770f38858e197e790839bc98b4d7889214ebecdf47e542d632afbc84f',
'src/lib/components/InboxStatus.svelte':
- '519d13dad65d3d57db57329ee693cd6a2ea3e14bb1b51f334d8d58c3b677bf92',
+ '29f17df1ccece671ea2ba57578dc028fa541ce924e1cdc4b3e7753da500da53f',
'src/lib/messaging/inbox-view.ts':
- '9fb55cd5a227d4a23f56a5ff6d30902cdf7c8bfb16cb313e36f55d78cce9a7ec',
+ '7a66afb2a1dad62f6c8c8a4753f8129d4a1fcd2b00116edbab6ac422f489d83f',
'src/lib/messaging/inbox-sync.ts':
'84f9b3bb165a81878bb281c51d245aff7eb06a0fa55b857a49b13d0cb1cff8ae',
'src/lib/messaging/inbox-setup-view.ts':
@@ -521,7 +521,17 @@ async function inboxPresentationAdmission(web) {
'src/lib/components/ConversationRow.svelte':
'c5d0926ac9cdda18a6befe365227dfe62405f71598f59964ff36af9a0e85d743',
'src/lib/messaging/inbox-list.ts':
- '9cc82877bfa8dbb2a7fa41bceb842793349416271f19569f49fdd5cfc1de07e5'
+ '9cc82877bfa8dbb2a7fa41bceb842793349416271f19569f49fdd5cfc1de07e5',
+ 'src/lib/components/ConversationThread.svelte':
+ 'accd91eb5b5ada0f07158dbe7ddfccdd3af65f92536427d0a717a7c18aad7aca',
+ 'src/lib/components/MessageItem.svelte':
+ '7a33a603f806686c29f5b9faec2758f8b78339593d7a7aefa1a3ec1c7ce6f01e',
+ 'src/lib/messaging/conversation-thread.ts':
+ '7367f0e6d96a9f249514f66c2459274e856eb83462523e37264d4cd97d2e36d1',
+ 'src/lib/persistence/private-storage.ts':
+ 'e45a95c9b12e8534a6ab0a4ec8ee1c86e730bba2f252dc1947954439720f2bfc',
+ 'src/routes/messages/[conversationId=local_id]/+page.svelte':
+ 'b06c6189adee80b68bc6657fa0e8504551fe9a8b1655a6d81807ebee9930a5e7'
};
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
@@ -689,7 +699,7 @@ export async function auditOutput(webDirectory) {
if (hasProductPresentation) names.add('publishers');
if (hasInboxSetup) names.add('private-handles');
if (hasInboxPresentation)
- for (const name of ['conversation-directory', 'read']) names.add(name);
+ for (const name of ['InboxStatus', 'InboxSetup', 'read']) names.add(name);
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -960,14 +970,17 @@ export async function auditOutput(webDirectory) {
const [, gate] = requiredRecord('AccountGate');
equal(
gate.imports,
- [
- 'public-key',
- 'private-handles',
- 'public-runtime',
- 'client',
- 'Button',
- 'view-context'
- ].map((name) => requiredRecord(name)[0]),
+ (hasInboxPresentation
+ ? ['client', 'view-context', 'InboxSetup']
+ : [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'view-context'
+ ]
+ ).map((name) => requiredRecord(name)[0]),
'Invalid owned inbox compiler dependencies'
);
if (gate.dynamicImports !== undefined)
@@ -1004,41 +1017,46 @@ export async function auditOutput(webDirectory) {
/** @type {[string,string[]][]} */
const dependencies = [
[
- 'conversation-directory',
+ 'InboxStatus',
[
'public-key',
'private-handles',
'public-runtime',
+ 'references',
+ 'client',
'Button',
- 'AccountGate'
+ 'navigation',
+ 'view-context',
+ 'InboxSetup',
+ 'read'
]
],
- ['read', ['public-runtime']],
[
- 'nodes/4',
+ 'InboxSetup',
[
'public-key',
+ 'private-handles',
'public-runtime',
- 'references',
'client',
'Button',
- 'navigation',
- 'view-context',
- 'AccountGate',
- 'conversation-directory',
- 'read'
+ 'view-context'
]
],
+ ['read', ['public-runtime']],
+ ['nodes/4', ['client', 'AccountGate', 'InboxStatus']],
[
'nodes/5',
[
'public-key',
+ 'public-runtime',
'client',
+ 'Button',
'client.svelte',
'state',
'view-context',
- 'AccountGate',
- 'conversation-directory'
+ 'legacy',
+ 'InboxSetup',
+ 'InboxStatus'
]
]
];
@@ -1053,6 +1071,17 @@ export async function auditOutput(webDirectory) {
throw new Error(
'Invalid owned inbox presentation compiler dynamic imports'
);
+ if (name.startsWith('nodes/')) {
+ if (
+ row.src !== key ||
+ row.isEntry !== true ||
+ row.isDynamicEntry !== undefined ||
+ row.css !== undefined
+ )
+ throw new Error(
+ 'Invalid owned inbox presentation compiler entry role'
+ );
+ }
if (!name.startsWith('nodes/')) {
if (
!/^_[A-Za-z0-9_-]+\.js$/.test(key) ||