From 4c79fa07c5f918b1609d777c565a34de10e4dd3c Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:12 +1100 Subject: [PATCH 01/12] fix(relay): show the relay's reason when it refuses workflows or emoji MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the relay refused a workflow save, run or delete, or a custom emoji add or remove, Buzz replaced its reason with fixed copy ("Workflow command rejected; retain the draft…", "Failed to add emoji."). A member who adds a Call Webhook step was never told that the step needs owner or admin, and a timed-out member could not tell when to try again. The relay's text is shown only for a real refusal: a PublishRejected that is not a PublishNotSent. Timeouts, lost receipts, signer mismatches, client-side checks and not-sent errors keep today's copy. - transport: `forbidden:` joins the relay-shaped prefixes. The signed writer's keep-filter dropped a 400 `{error:"forbidden: …"}` body, so the reason arrived as "Relay rejected the message (400)". This also fixes Hide conversation's "forbidden: not a member of this DM". - outbox: onReceipt gains an optional `refusal` argument with the clipped display text. The journaled error is unchanged: relay text can quote event content, so it never reaches the journal. - workflows capability: receipt() keeps the refusal as an in-memory rejected result, so Recent activity shows the relay's words for this session. After a reload the journal's fixed copy is the fallback. - session.ts (FOUNDATION, approved for this one-line change): forward the refusal to workflows.receipt. - emoji directory: a refusal reads "Failed to add emoji. " (or the remove equivalent). Timeouts and failed own-set reads are unchanged. - docs: workflows.md and relay-queries.md describe the new behavior. Built on main @ b62173845. None of the touched lines changed since the design note's 9c941525c, and #2085, #2306 and #2281 have not landed, so nothing needed adapting. Not changed here: - Browser host: the broker answers a socket `forbidden:`/`blocked:`/ `restricted:` refusal with 503 `sent:false`, which the client treats as PublishNotSent, so those keep fixed copy there. `invalid:` refusals arrive as 400 and show their reason. - A stale save's 409 now shows the client's own "conflict: the relay state changed; reload before writing again" instead of the fixed workflow copy. - The 200 `{accepted:false}` path still shows the raw prefixed text. Tests: a `forbidden:` row in transport.test.ts; refusal and not-sent cases in capability.test.ts through the real outbox, with saved() checked for relay text; the refusal forward in outbox-receipts.test.ts; exact emoji add/remove refusal copy and a not-sent case in emoji.test.ts and CustomEmojiSettings.test.tsx; workflows.journey.mjs now expects the fixture's refusal text. Each new or tightened assertion fails without the production change. The journey fails without the session.ts forward. Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../emoji/CustomEmojiSettings.test.tsx | 9 +++-- src/bundled/workflows/workflows.journey.mjs | 6 ++-- src/features/relay/emoji-directory.ts | 8 +++-- src/features/relay/emoji.test.ts | 29 +++++++++++---- src/features/relay/outbox-receipts.test.ts | 18 ++++++++-- src/features/relay/outbox.ts | 16 +++++++-- src/features/relay/session.ts | 3 +- src/features/relay/transport.test.ts | 4 +++ src/features/relay/transport.ts | 2 +- src/features/workflows/capability.test.ts | 35 ++++++++++++++++++- src/features/workflows/capability.ts | 10 ++++-- 11 files changed, 115 insertions(+), 25 deletions(-) diff --git a/src/bundled/emoji/CustomEmojiSettings.test.tsx b/src/bundled/emoji/CustomEmojiSettings.test.tsx index 50cd1a86ed..54390206ed 100644 --- a/src/bundled/emoji/CustomEmojiSettings.test.tsx +++ b/src/bundled/emoji/CustomEmojiSettings.test.tsx @@ -325,11 +325,16 @@ it("shows the failed save, keeps the draft and saves on retry", async () => { store.connect(vi.fn(async (file: File) => uploaded(file))); await user.upload(screen.getByLabelText("Upload image"), png("wave.png")); await screen.findByRole("img", { name: "Selected custom emoji preview" }); - store.rejectNext(new PublishRejected("blocked: no")); + store.rejectNext( + new PublishRejected( + "You are timed out until 12:00", + "restricted: you are timed out until 12:00", + ), + ); const save = screen.getByRole("button", { name: "Save emoji" }); await user.click(save); expect(await screen.findByRole("alert")).toHaveTextContent( - "Failed to add emoji.", + /^Failed to add emoji\. You are timed out until 12:00$/, ); expect(save).toBeEnabled(); expect(screen.getByRole("textbox")).toHaveValue("wave"); diff --git a/src/bundled/workflows/workflows.journey.mjs b/src/bundled/workflows/workflows.journey.mjs index 16b2d4f784..3a5e7a60b3 100644 --- a/src/bundled/workflows/workflows.journey.mjs +++ b/src/bundled/workflows/workflows.journey.mjs @@ -1997,11 +1997,9 @@ test("generic Outbox offers message retry but no workflow replay", async ({ await expect( page.getByText("Failed to trigger workflow", { exact: true }), ).toBeVisible(); + // The relay's refusal text replaces the journal's fixed copy in this session. await expect( - page.getByText( - "Workflow command rejected; retain the draft and refresh the saved configuration.", - { exact: true }, - ), + page.getByText("Fixture non-delivery", { exact: true }), ).toBeVisible(); // The Outbox is page chrome beneath the modal editor. await button("Close editor").click(); diff --git a/src/features/relay/emoji-directory.ts b/src/features/relay/emoji-directory.ts index 08d442420f..a88673bc61 100644 --- a/src/features/relay/emoji-directory.ts +++ b/src/features/relay/emoji-directory.ts @@ -13,6 +13,7 @@ import { type CustomEmoji, } from "./emoji"; import { eventDto, newer, type RelayEvent } from "./events"; +import { PublishNotSent, PublishRejected } from "./outbox"; import type { Priority, RelayReader } from "./reader"; import type { RelayWriter } from "./transport"; @@ -244,13 +245,16 @@ export function createEmojiDirectory( signal.throwIfAborted(); accept([event]); return shortcode; - } catch { + } catch (error) { throw new Error( timeout.aborted ? url === undefined ? "Timed out while removing emoji." : "Timed out while adding emoji." - : failure, + : error instanceof PublishRejected && + !(error instanceof PublishNotSent) + ? `${failure} ${error.message}` + : failure, ); } } diff --git a/src/features/relay/emoji.test.ts b/src/features/relay/emoji.test.ts index a8a105c140..f3458e87e4 100644 --- a/src/features/relay/emoji.test.ts +++ b/src/features/relay/emoji.test.ts @@ -12,7 +12,7 @@ import { } from "./emoji"; import { createRelaySession } from "./session"; import { foldMessages } from "./fold"; -import { PublishRejected } from "./outbox"; +import { PublishNotSent, PublishRejected } from "./outbox"; import { ReadError } from "./errors"; import { completeHeads, @@ -767,17 +767,28 @@ it("rejects invalid names before any read and maps publish failure to reference /Invalid emoji name/, ); expect(h.wire.pending).toHaveLength(0); - h.publish.mockRejectedValueOnce(new PublishRejected("blocked: no")); + // A relay refusal adds the relay's reason to the reference copy. + h.publish.mockRejectedValueOnce( + new PublishRejected("You are banned", "blocked: you are banned"), + ); const adding = h.emoji.add?.("party", url); await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); h.ownRead().respond([]); - await expect(adding).rejects.toThrow("Failed to add emoji."); + await expect(adding).rejects.toThrow( + /^Failed to add emoji\. You are banned$/, + ); expect(h.emoji.snapshot().mine).toEqual([]); + // A write that never reached the relay has no reason to show. + h.publish.mockRejectedValueOnce(new PublishNotSent("Relay unreachable")); + const notSent = h.emoji.add?.("party", url); + await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); + h.ownRead().respond([]); + await expect(notSent).rejects.toThrow(/^Failed to add emoji\.$/); const failedRead = h.emoji.add?.("party", url); await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); h.ownRead().fail(new Error("offline")); - await expect(failedRead).rejects.toThrow("Failed to add emoji."); - expect(h.publish).toHaveBeenCalledTimes(1); + await expect(failedRead).rejects.toThrow(/^Failed to add emoji\.$/); + expect(h.publish).toHaveBeenCalledTimes(2); }); it("removes only from the fresh own set and preserves another member's colliding emoji", async () => { const h = authoring(); @@ -862,12 +873,16 @@ it("serializes additions and removals despite a stale own-set read", async () => }); it("keeps the own set after rejected removal and recovers on retry", async () => { const h = authoring(); - h.publish.mockRejectedValueOnce(new PublishRejected("blocked: no")); + h.publish.mockRejectedValueOnce( + new PublishRejected("You are banned", "blocked: you are banned"), + ); const own = set(viewer); const removing = h.emoji.remove?.("party"); await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); h.ownRead().respond([own]); - await expect(removing).rejects.toThrow("Failed to remove emoji."); + await expect(removing).rejects.toThrow( + /^Failed to remove emoji\. You are banned$/, + ); expect(h.emoji.snapshot().mine).toEqual([{ shortcode: "party", url }]); const retry = h.emoji.remove?.("party"); await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); diff --git a/src/features/relay/outbox-receipts.test.ts b/src/features/relay/outbox-receipts.test.ts index 64ac3c6374..d9060626b3 100644 --- a/src/features/relay/outbox-receipts.test.ts +++ b/src/features/relay/outbox-receipts.test.ts @@ -125,7 +125,11 @@ it("echo plus lost receipt remains seen but settles command result as unavailabl h.reject(new Error("connection lost")); await flush(); expect(h.local.snapshot()[0]?.delivery).toBe("seen"); - expect(h.onReceipt).toHaveBeenCalledExactlyOnceWith(h.published(), undefined); + expect(h.onReceipt).toHaveBeenCalledExactlyOnceWith( + h.published(), + undefined, + undefined, + ); }); it("receipt waits are bounded and late results after disposal never publish", async () => { vi.useFakeTimers(); @@ -135,7 +139,11 @@ it("receipt waits are bounded and late results after disposal never publish", as h.observe([h.published()]); await vi.advanceTimersByTimeAsync(101); expect(h.signal().aborted).toBe(true); - expect(h.onReceipt).toHaveBeenCalledExactlyOnceWith(h.published(), undefined); + expect(h.onReceipt).toHaveBeenCalledExactlyOnceWith( + h.published(), + undefined, + undefined, + ); const late = setup(); late.send(); await vi.advanceTimersByTimeAsync(0); @@ -211,6 +219,12 @@ it.each([30620, 46020, 5])( await flush(); expect(h.outbox.snapshot()[0]?.delivery).toBe("failed"); expect(JSON.stringify(h.saved())).not.toContain("PRIVATE"); + // The refusal text reaches the in-memory result owner only. + expect(h.onReceipt).toHaveBeenCalledWith( + expect.anything(), + undefined, + "PRIVATE", + ); h.outbox.retry(id); await flush(); expect(h.publish).toHaveBeenCalledTimes(1); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index a348733cf8..e2b416d048 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -234,7 +234,13 @@ export function createOutbox( timeoutMs?: number; /** Commands await their receipt even after a verified echo. Never persisted. */ needsReceipt?: (event: EventData) => boolean; - onReceipt?: (event: EventData, message: string | undefined) => void; + /** `refusal` is the relay's display text for a refused command. The journal + * keeps fixed copy, because relay text can quote event content. */ + onReceipt?: ( + event: EventData, + message: string | undefined, + refusal?: string, + ) => void; /** `acknowledged` is false when the publisher was entered but delivery is `unknown`. */ onAccepted?: (event: RelayEvent, acknowledged: boolean) => void; profiling?: RelayProfiler; @@ -787,7 +793,13 @@ export function createOutbox( total(!closed && !latest ? "ok" : "error"); if (closed) return; if (latest && awaitsReceipt(latest.event)) - onReceipt(latest.signed ?? latest.event, undefined); + onReceipt( + latest.signed ?? latest.event, + undefined, + error instanceof PublishRejected && !(error instanceof PublishNotSent) + ? clip(error.message) + : undefined, + ); const delivery: Delivery | undefined = latest && (latest.delivery === "seen" || attempt.previousDelivery === "seen" diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index dad8716a70..174dc9147c 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -401,7 +401,8 @@ export function createRelaySession( } }, needsReceipt: isWorkflowOperation, - onReceipt: (event, message) => workflows.receipt(event, message), + onReceipt: (event, message, refusal) => + workflows.receipt(event, message, refusal), // A chat this device is starting takes its events once the relay // has its create; its local agents hear its owner's messages now. // The start's own create and member adds never wait. diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index bdb4252130..9b65ced433 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -243,6 +243,10 @@ it.each([ ], ["blocked: you are banned", "You are banned"], ["restricted: not a channel member", "Not a channel member"], + [ + "forbidden: workflow is disabled or inactive", + "Workflow is disabled or inactive", + ], ["error: internal failure", "Internal failure"], ["pow: difficulty too low", "Difficulty too low"], ["duplicate: already accepted", "Already accepted"], diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index e4ce8d12c0..38c38af285 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -1752,7 +1752,7 @@ export async function acceptReadStatePublish(response: Response, id: string) { const REFUSAL_STATUSES = [400, 401, 403, 404, 413, 422]; /** NIP-01 machine-readable prefixes: the shape of a relay's own refusal. */ const NIP01_PREFIX = - /^(invalid|blocked|restricted|error|pow|duplicate|rate-limited|conflict|auth-required):\s*/; + /^(invalid|blocked|restricted|forbidden|error|pow|duplicate|rate-limited|conflict|auth-required):\s*/; /** Prefixes writers match on, so the text is shown as sent. */ const KEPT_PREFIXES = new Set(["rate-limited", "conflict", "auth-required"]); /** The relay's own `{error}` text for a refused write. Admission otherwise diff --git a/src/features/workflows/capability.test.ts b/src/features/workflows/capability.test.ts index 62abe668e1..e18eedb651 100644 --- a/src/features/workflows/capability.test.ts +++ b/src/features/workflows/capability.test.ts @@ -2,6 +2,7 @@ import { afterEach, assert, expect, it, vi } from "vitest"; import { createWorkflows } from "./capability"; import { createOutbox, + PublishNotSent, PublishRejected, type OutgoingEvent, } from "../relay/outbox"; @@ -56,7 +57,8 @@ function setup( }, { needsReceipt: (event) => [30620, 46020, 5].includes(event.kind), - onReceipt: (event, message) => workflows.receipt(event, message), + onReceipt: (event, message, refusal) => + workflows.receipt(event, message, refusal), }, ); const read = vi.fn(async () => [] as RelayEvent[]); @@ -389,6 +391,37 @@ it("explicit rejection is rejected, not unknown; revocation fences late receipts expect(h.saved().some((row) => row.event.id === id)).toBe(true); expect(JSON.stringify(h.saved())).not.toContain("PRIVATE"); }); +it.each([ + [ + "the relay's reason for a refusal", + new PublishRejected( + "Workflow is disabled or inactive", + "forbidden: workflow is disabled or inactive", + ), + "Workflow is disabled or inactive", + ], + [ + "fixed copy for a not-sent failure", + new PublishNotSent("Relay unreachable"), + "Workflow command rejected; retain the draft and refresh the saved configuration.", + ], +])( + "a rejected run shows %s; the journal never holds relay text", + async (_, error, shown) => { + const h = setup(); + const operation = h.capability.trigger(h.definition); + await flush(); + h.reject(error); + await flush(); + expect(h.capability.operations.snapshot()[0]).toMatchObject({ + eventId: operation, + outcome: "rejected", + error: shown, + }); + // The journal keeps fixed copy; the relay's text lives in memory only. + expect(JSON.stringify(h.saved())).not.toContain(error.message); + }, +); it("a secret-bearing save receipt succeeds; the secret is taken once and never journaled or surfaced", async () => { const h = setup("https://relay.test"); const operation = h.capability.save({ diff --git a/src/features/workflows/capability.ts b/src/features/workflows/capability.ts index a71c3456d1..bcf79a537f 100644 --- a/src/features/workflows/capability.ts +++ b/src/features/workflows/capability.ts @@ -647,12 +647,16 @@ export function createWorkflows({ "Only the author or their verified agent owner can delete this workflow", ); }, - receipt(event: EventData, message: string | undefined) { + receipt(event: EventData, message: string | undefined, refusal?: string) { if (closed || !receiptInterest.delete(event.id)) return; if (event.kind !== 46020) invalidateDefinitionCache(); if (message === undefined) { - if (results.get(event.id)?.outcome !== "succeeded") - results.delete(event.id); + // The relay's reason lives here for this session; the journal keeps fixed copy. + if (results.get(event.id)?.outcome !== "succeeded") { + if (refusal) + results.set(event.id, { outcome: "rejected", error: refusal }); + else results.delete(event.id); + } rebuild(); return; } From d8fcbd113ce2b2a38e4f3cd9d897e99346715676 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:13 +1100 Subject: [PATCH 02/12] fix(channels): offer Refresh channels on stale lifecycle failures Two channel-lifecycle failure toasts told people to refresh, but offered no control to do it. An unconfirmed archive said "Refresh channels before trying again." (twice, with the readback's own text), and that control lived only inside collapsed Diagnostics. After a demotion, Archive said "Refresh channel permissions.", which no control is called, and Settings kept offering Archive and Delete. Refresh is offered only for stale state: an unconfirmed result or a permission that changed since the action was offered. A refusal, an owner's leave reason or an unavailable check keeps Dismiss only. - channel-lifecycle: new ChannelLifecycleStale, which ChannelLifecycleUnconfirmed now extends. "No longer permitted" throws it with "Refresh channels to see what you can do now." The readback error drops its own "Refresh channels before trying again." so the wrapper says it once. "Archive/Delete check unavailable" now says "Try again." instead of naming "Retry channel permissions". - ChannelLifecycleDialog: failed() gains a `refresh` flag, set for a ChannelLifecycleStale. - ChannelNavigationState: the failure ToastNotice gets a Refresh channels Button. It runs refreshList({ consistency: "strong" }) and dismisses the toast. Same pattern as the mute and activity toasts. - ChannelsPage: the Settings ChannelLifecycleActions key includes viewerRole, so a refreshed (or live) role change re-reads permissions. refreshList re-reads the viewer's 39002 rosters, which carry the role (the relay re-signs them on every membership change); the remounted actions re-read 39001/39002 themselves. - docs/channels.md describes the recovery. Tests: a real-session ChannelsPage test demotes the viewer, archives, refreshes from the toast and sees Archive and Delete give way to Leave. ChannelNavigationState shows Refresh only for stale errors and calls a strong refreshList. ChannelLifecycleMenu checks the flag for stale and refused errors. channel-lifecycle asserts the stale class and both exact messages. Reverting each production piece separately fails at least one of these. ChannelSettingsPanel's fixture text follows the new readback copy. Checked in Chromium (throwaway spec, not committed): the unconfirmed archive toast reads "... Refresh channels before trying again. Relay returned an invalid delivery receipt", once. Light and dark, 1280 and 600 wide, 100% and 200% text all fit. Keyboard order is F6, toast, Dismiss notification, Refresh channels, following the shared ToastCard, and focus returns to the composer after Refresh. At 600 px and 200% text, Refresh sits below the bounded stack's fold until Tab scrolls it into view. Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../channels/ChannelLifecycleDialog.tsx | 12 +- .../channels/ChannelLifecycleMenu.test.tsx | 50 ++++++++- .../channels/ChannelSettingsPanel.test.tsx | 2 +- .../channels/ChannelsPage.tabs.test.tsx | 106 +++++++++++++++++- src/bundled/channels/ChannelsPage.tsx | 3 +- .../ChannelNavigationState.test.tsx | 78 ++++++++++++- .../ChannelNavigationState.tsx | 22 +++- src/features/relay/channel-lifecycle.test.ts | 19 +++- src/features/relay/channel-lifecycle.ts | 18 +-- 9 files changed, 285 insertions(+), 25 deletions(-) diff --git a/src/bundled/channels/ChannelLifecycleDialog.tsx b/src/bundled/channels/ChannelLifecycleDialog.tsx index bf0542cc89..ab35a6dcb7 100644 --- a/src/bundled/channels/ChannelLifecycleDialog.tsx +++ b/src/bundled/channels/ChannelLifecycleDialog.tsx @@ -1,6 +1,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { Button } from "../../shared/design-system/ui/Button"; import { + ChannelLifecycleStale, ChannelLifecycleUnconfirmed, type ChannelLifecycleCapability, } from "../../features/relay/channel-lifecycle"; @@ -100,8 +101,14 @@ export function ChannelLifecycleDialog({ onSubmit?(): void; finalFocus?: DialogProps["finalFocus"]; /** `unconfirmed`: the relay may have applied it anyway - * (`ChannelLifecycleUnconfirmed`). */ - failed?(title: string, message: string, unconfirmed: boolean): void; + * (`ChannelLifecycleUnconfirmed`). `refresh`: refreshing channels is the + * recovery (`ChannelLifecycleStale`, which every unconfirmed failure is). */ + failed?( + title: string, + message: string, + unconfirmed: boolean, + refresh: boolean, + ): void; /** Already chosen without a dialog, as Undo is: run it on mount. */ confirmed?: boolean; /** Offered from an immediate archive's result toast. */ @@ -206,6 +213,7 @@ export function ChannelLifecycleDialog({ `${copy.title} failed`, message, error instanceof ChannelLifecycleUnconfirmed, + error instanceof ChannelLifecycleStale, ); else setError(message); } diff --git a/src/bundled/channels/ChannelLifecycleMenu.test.tsx b/src/bundled/channels/ChannelLifecycleMenu.test.tsx index 3b3043f8a6..8e4adb8317 100644 --- a/src/bundled/channels/ChannelLifecycleMenu.test.tsx +++ b/src/bundled/channels/ChannelLifecycleMenu.test.tsx @@ -14,6 +14,7 @@ import { import userEvent from "@testing-library/user-event"; import { ContextMenuRoot, MenuPopup } from "../../shared/design-system/ui/Menu"; import { + ChannelLifecycleStale, ChannelLifecycleUnconfirmed, type ChannelLifecycleCapability, } from "../../features/relay/channel-lifecycle"; @@ -499,6 +500,48 @@ it("uncertain delivery reports refresh guidance in a toast without offering blin expect(lifecycle.run).toHaveBeenCalledOnce(); }); +it.each([ + [ + "a permission that changed", + new ChannelLifecycleStale( + "This action is no longer permitted. Refresh channels to see what you can do now.", + ), + false, + ], + [ + "an unconfirmed result", + new ChannelLifecycleUnconfirmed("connection lost"), + true, + ], +])("flags %s for a channel refresh", async (_, error, unconfirmed) => { + const lifecycle = capability(); + lifecycle.run.mockRejectedValueOnce(error); + const failed = vi.fn(); + render( + + {}} + completed={() => {}} + failed={failed} + /> + , + ); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "Archive channel" })); + await waitFor(() => + expect(failed).toHaveBeenCalledExactlyOnceWith( + "Archive channel failed", + error.message, + unconfirmed, + true, + ), + ); +}); + it.each( ([{ action: "delete", label: "Delete channel" }] as const).flatMap( ({ action, label }) => @@ -683,8 +726,8 @@ it("chat archive runs without confirmation, then Undo unarchives from its result completed(); setOpen(false); }} - failed={(title, message) => { - failed(title, message); + failed={(title, message, unconfirmed, refresh) => { + failed(title, message, unconfirmed, refresh); setOpen(false); }} undo={() => { @@ -735,6 +778,9 @@ it("chat archive runs without confirmation, then Undo unarchives from its result expect(failed).toHaveBeenCalledExactlyOnceWith( "Unarchive chat failed", "Relay rejected the request.", + false, + // A refusal is not stale state; refreshing channels would not help. + false, ), ); await waitFor(() => diff --git a/src/bundled/channels/ChannelSettingsPanel.test.tsx b/src/bundled/channels/ChannelSettingsPanel.test.tsx index 055ef1acab..4c3fdce427 100644 --- a/src/bundled/channels/ChannelSettingsPanel.test.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.test.tsx @@ -631,7 +631,7 @@ it.each([ // As the lifecycle owner throws it when readback never shows the flag. new ChannelLifecycleUnconfirmed( new Error( - "The relay accepted the request, but the change is not confirmed. Refresh channels before trying again.", + "The relay accepted the request, but the change is not confirmed.", ), ), "Saved, but not confirmed yet. Try again to check.", diff --git a/src/bundled/channels/ChannelsPage.tabs.test.tsx b/src/bundled/channels/ChannelsPage.tabs.test.tsx index 2848328e3d..9e9e88b3af 100644 --- a/src/bundled/channels/ChannelsPage.tabs.test.tsx +++ b/src/bundled/channels/ChannelsPage.tabs.test.tsx @@ -22,6 +22,7 @@ import type { import type { PageNavigation } from "../../features/navigation/service"; import type { OpenTarget } from "../../features/navigation/targets"; import { soloDraftTarget } from "../../features/channel-navigation/routes"; +import { ChannelNavigationProvider } from "../../features/channel-navigation/ChannelNavigationState"; import { createRelaySession, type RelaySession, @@ -536,9 +537,12 @@ function workspace( { membership, lifecycle, + handoff = false, }: { membership?: CommunityMembership; lifecycle?: (event: RelayEvent) => Promise; + /** Mount the shell's channel navigation, which owns lifecycle actions. */ + handoff?: boolean; } = {}, ) { const owner = createRelaySession( @@ -589,8 +593,8 @@ function workspace( const navigator = createNavigationController( createMemoryHistory(), ).navigation; - const page = (navigation?: PageNavigation) => ( - + const page = (navigation?: PageNavigation) => { + const content = ( - - ); + ); + return ( + + {handoff ? ( + + {content} + + ) : ( + content + )} + + ); + }; const { rerender } = render(page()); /** Re-route the mounted page; `undefined` returns to the unrouted workspace. */ const visit = (target?: OpenTarget) => @@ -690,6 +705,89 @@ it("hands the community roster to Channel settings and follows the republished f expect(control.closest("dd")?.querySelector("[role=alert]")).toBeNull(); }); +it("a refreshed roster that demotes the viewer retires Archive and Delete in Channel settings", async () => { + const viewer = keypair(), + authority = keypair(), + other = keypair(); + const id = "11111111-1111-4111-8111-111111111111"; + // Both records carry roles, as the relay re-signs them on a role change. + const roles = (role: "owner" | "member", at: number) => [ + signed(authority, { + kind: 39001, + created_at: at, + content: "", + tags: [ + ["d", id], + ["p", other.pubkey, "owner"], + ...(role === "owner" ? [["p", viewer.pubkey, "owner"]] : []), + ], + }), + signed(authority, { + kind: 39002, + created_at: at, + content: "", + tags: [ + ["d", id], + ["p", other.pubkey, "", "owner"], + ["p", viewer.pubkey, "", role], + ], + }), + ]; + const events = [ + metadata(authority, id, "Alpha", undefined, [["t", "stream"]]), + ...roles("owner", 1_700_000_000), + ]; + const publish = vi.fn(async () => {}); + workspace(events, viewer, authority, { lifecycle: publish, handoff: true }); + await screen.findByRole("textbox", { name: "Message #Alpha" }); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "Channel actions" })); + await user.click( + await screen.findByRole("menuitem", { name: "View channel details" }), + ); + const settings = await screen.findByRole("complementary", { + name: "Channel settings", + }); + await within(settings).findByRole("button", { name: "Delete channel" }); + // Another owner demotes the viewer; this page has not seen it. + events.splice(1, 2, ...roles("member", 1_700_000_100)); + await user.click( + within(settings).getByRole("button", { name: "Archive channel" }), + ); + const confirm = await screen.findByRole("dialog", { + name: "Archive channel: Alpha", + }); + await user.click( + within(confirm).getByRole("button", { name: "Archive channel" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Archive channel failed", + }); + expect(toast).toHaveAccessibleDescription( + "This action is no longer permitted. Refresh channels to see what you can do now.", + ); + fireEvent.click( + within(toast).getByRole("button", { name: "Refresh channels" }), + ); + expect( + screen.queryByRole("dialog", { name: "Archive channel failed" }), + ).toBeNull(); + // The refreshed role remounts the actions; Leave arrives with fresh permissions. + await vi.waitFor(() => + expect( + within(settings).queryByRole("button", { name: "Archive channel" }), + ).toBeNull(), + ); + await within(settings).findByRole("button", { name: "Leave channel" }); + expect( + within(settings).queryByRole("button", { name: "Archive channel" }), + ).toBeNull(); + expect( + within(settings).queryByRole("button", { name: "Delete channel" }), + ).toBeNull(); + expect(publish).not.toHaveBeenCalled(); +}); + it("selects a default channel the relay adds after the page opened", async () => { const events: RelayEvent[] = []; const { owner, viewer, authority } = workspace(events); diff --git a/src/bundled/channels/ChannelsPage.tsx b/src/bundled/channels/ChannelsPage.tsx index 3001ce2029..e0ce5f4a5e 100644 --- a/src/bundled/channels/ChannelsPage.tsx +++ b/src/bundled/channels/ChannelsPage.tsx @@ -2560,7 +2560,8 @@ function ChannelWorkspace({ (!current.readOnly || current.viewerRole === "guest") && current.channelType !== "dm" && ( Promise = async () => {}, ) { let ids = ["existing"]; + // A stable snapshot per roster, as the session's list is. + let listed = { ids, list: { channels: ids.map((id) => ({ id })) } }; + const list = () => { + if (listed.ids !== ids) + listed = { ids, list: { channels: ids.map((id) => ({ id })) } }; + return listed.list; + }; + const refreshList = vi.fn(); const session = () => ({ channels: { - list: () => ({ channels: ids.map((id) => ({ id })) }), + list, subscribeList: () => () => {}, + refreshList, }, sidebarPreferences: { setMute: async () => [] }, channelLifecycle: { run }, @@ -62,6 +74,7 @@ function fixture( } as RelayData; return { relay, + refreshList, roster: (next: string[]) => { ids = next; }, @@ -418,3 +431,66 @@ it("keeps a paused delete's confirmation open in place of the failure toast, the expect(run).toHaveBeenCalledTimes(2); expect(view.result.current.lifecycleDialog).toBeUndefined(); }); + +it("offers Refresh channels when a lifecycle action failed on stale state", async () => { + const stale = new ChannelLifecycleStale( + "This action is no longer permitted. Refresh channels to see what you can do now.", + ); + const h = fixture(async () => { + throw stale; + }); + const view = mount(h.relay, true); + act(() => + view.result.current.openLifecycle( + { id: "channel", name: "Channel" }, + "archive", + ), + ); + fireEvent.click( + await screen.findByRole("button", { name: "Archive channel" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Archive channel failed", + }); + expect(toast).toHaveAccessibleDescription(stale.message); + const refresh = within(toast).getByRole("button", { + name: "Refresh channels", + }); + // The shared card puts its dismiss control first, then the actions. + expect(within(toast).getAllByRole("button")).toEqual([ + within(toast).getByRole("button", { name: "Dismiss notification" }), + refresh, + ]); + fireEvent.click(refresh); + expect(h.refreshList).toHaveBeenCalledExactlyOnceWith({ + consistency: "strong", + }); + await waitFor(() => + expect( + screen.queryByRole("dialog", { name: "Archive channel failed" }), + ).toBeNull(), + ); +}); + +it("keeps other lifecycle failures' toasts to Dismiss", async () => { + const h = fixture(async () => { + throw new Error("Archive check unavailable. Try again."); + }); + const view = mount(h.relay, true); + act(() => + view.result.current.openLifecycle( + { id: "channel", name: "Channel" }, + "archive", + ), + ); + fireEvent.click( + await screen.findByRole("button", { name: "Archive channel" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Archive channel failed", + }); + expect(within(toast).getAllByRole("button")).toEqual([ + within(toast).getByRole("button", { name: "Dismiss notification" }), + ]); + expect(h.refreshList).not.toHaveBeenCalled(); +}); diff --git a/src/features/channel-navigation/ChannelNavigationState.tsx b/src/features/channel-navigation/ChannelNavigationState.tsx index 1408a02d78..da7d9b31a0 100644 --- a/src/features/channel-navigation/ChannelNavigationState.tsx +++ b/src/features/channel-navigation/ChannelNavigationState.tsx @@ -177,6 +177,7 @@ export function ChannelNavigationProvider({ session: RelaySession; title: string; message: string; + refresh: boolean; }>(); const activityThread = useRef(undefined); const activityAgent = useRef(undefined); @@ -476,13 +477,14 @@ export function ChannelNavigationProvider({ )?.depart(departOnSubmit ? "current" : "origin"); endLifecycle(state.lifecycleDialog, true); }} - failed={(title, message, unconfirmed) => { + failed={(title, message, unconfirmed, refresh) => { setFailure({ session: connection.session, title, message: departOnSubmit ? `${state.lifecycleDialog?.channel.name}: ${message}` : message, + refresh, }); endLifecycle(state.lifecycleDialog, unconfirmed); }} @@ -493,7 +495,23 @@ export function ChannelNavigationProvider({ title={failure.title} description={failure.message} onDismiss={() => setFailure(undefined)} - /> + > + {failure.refresh && ( + + )} + )} ); diff --git a/src/features/relay/channel-lifecycle.test.ts b/src/features/relay/channel-lifecycle.test.ts index 575d6b3f36..de7d30e9dc 100644 --- a/src/features/relay/channel-lifecycle.test.ts +++ b/src/features/relay/channel-lifecycle.test.ts @@ -19,6 +19,7 @@ import { finalizeEvent, getPublicKey, type EventTemplate } from "nostr-tools"; import { PublishRejected } from "./outbox"; import { createChannelLifecycle, + ChannelLifecycleStale, ChannelLifecycleUnconfirmed, } from "./channel-lifecycle"; import { @@ -678,8 +679,11 @@ it("rereads authority after signing; a removed admin cannot publish", async () = ]); return finalizeEvent(event, key); }); - await expect(h.owner.capability.run("archive", id)).rejects.toThrow( - "no longer permitted", + const run = h.owner.capability.run("archive", id); + // Stale state the viewer can refresh, and copy naming that control. + await expect(run).rejects.toBeInstanceOf(ChannelLifecycleStale); + await expect(run).rejects.toThrow( + /^This action is no longer permitted\. Refresh channels to see what you can do now\.$/, ); expect(h.publish).not.toHaveBeenCalled(); h.owner.dispose(); @@ -973,9 +977,14 @@ describe("Leave confirmation across access revocation", () => { h.read.mockRejectedValueOnce(cancelled()); }); try { - const rejected = expect( - h.owner.capability.run("leave", id), - ).rejects.toBeInstanceOf(ChannelLifecycleUnconfirmed); + const run = h.owner.capability.run("leave", id); + const rejected = Promise.all([ + expect(run).rejects.toBeInstanceOf(ChannelLifecycleUnconfirmed), + // The wrapper names the recovery once; the readback reason adds none. + expect(run).rejects.toThrow( + /^The request may have taken effect\. Refresh channels before trying again\. The relay accepted the request, but the change is not confirmed\.$/, + ), + ]); // The retired read is reread after a real macrotask the fake clock // does not drive; start the poll budget once that reread is issued. while (h.read.mock.calls.length < 4) diff --git a/src/features/relay/channel-lifecycle.ts b/src/features/relay/channel-lifecycle.ts index d9089ba230..5b2b0cb17d 100644 --- a/src/features/relay/channel-lifecycle.ts +++ b/src/features/relay/channel-lifecycle.ts @@ -22,8 +22,12 @@ import { type ChannelLifecycleSettings, } from "./channel-lifecycle-protocol"; +/** The channel state the action relied on may be out of date; refreshing + * channels is the recovery. */ +export class ChannelLifecycleStale extends Error {} + /** No automatic or same-dialog retry after a request may have reached the relay. */ -export class ChannelLifecycleUnconfirmed extends Error { +export class ChannelLifecycleUnconfirmed extends ChannelLifecycleStale { constructor(reason: unknown) { super( `The request may have taken effect. Refresh channels before trying again. ${reason instanceof Error ? reason.message : String(reason)}`, @@ -503,11 +507,11 @@ export function createChannelLifecycle({ hide: settings.canHide, }[action]; if (!permitted) - throw new Error( - action === "leave" && settings.leaveReason - ? settings.leaveReason - : "This action is no longer permitted. Refresh channel permissions.", - ); + throw action === "leave" && settings.leaveReason + ? new Error(settings.leaveReason) + : new ChannelLifecycleStale( + "This action is no longer permitted. Refresh channels to see what you can do now.", + ); }; if (await authorize()) return; const fresh = lifecycleTemplate(action, id); @@ -602,7 +606,7 @@ export function createChannelLifecycle({ } } throw new Error( - "The relay accepted the request, but the change is not confirmed. Refresh channels before trying again.", + "The relay accepted the request, but the change is not confirmed.", ); }); } catch (error) { From a9191e01f57c15aafeedd30013c7d8903a6c5b75 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:13 +1100 Subject: [PATCH 03/12] fix(relay): show only the relay's own refusal words, never for echoed commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to 6c4db52eb3 (show the relay's reason when it refuses workflows or emoji), addressing its review. - outbox: the refusal is forwarded only when this attempt's delivery is `failed`, the same condition that sets `refused`. A command whose verified echo was already `seen` passed the relay's text before, so receipt() stored `outcome: "rejected"` for an event the relay has. Check saved configuration only resolves `unknown` saves, so it could no longer resolve that save. It now stays `unknown`. - outbox: new `isRelayRefusal`, used by the outbox forward, the emoji directory and the auto-join switch. It holds for a sent PublishRejected whose `reason` is relay-shaped (a NIP-01 prefix) with text after the prefix, and whose `message` is not itself prefixed. Status summaries ("Relay rejected the message (403)"), the 200 `{accepted:false}` path, the client's own 409 conflict text, a plain `PublishRejected("…")` and prefixes kept for writers to match on (`auth-required:`) keep today's fixed copy. `NIP01_PREFIX` moves next to PublishRejected so transport keeps importing from outbox, with no cycle. - ChannelSettingsPanel auto-join: a refusal shows the display text, never the raw `reason`. With `forbidden:` relay-shaped, the raw text would have read "forbidden: …"; it already read "invalid: …". Without a relay reason the switch keeps "Only community owners and admins can change this." - agent-config-artifacts `refusal()`: `forbidden` is a permission refusal. The signed writer now keeps `forbidden:` text, which was classified `unknown` and treated as uncertain. - workflows.journey.mjs: reverted to the fixed-copy assertion. The fixture's `PublishRejected("Fixture non-delivery")` has no relay reason, so it keeps the fixed copy. - docs/workflows.md says which failures keep fixed copy. Corrections to 6c4db52eb3's message: - "The relay's text is shown only for a real refusal: a PublishRejected that is not a PublishNotSent" is narrowed as above, and never for a command whose echo was already seen. - "A stale save's 409 now shows the client's own conflict: …" no longer holds: the 409 has no relay reason, so it keeps the fixed workflow copy. - "The 200 {accepted:false} path still shows the raw prefixed text" holds only for generic Outbox writes. Workflow, emoji and auto-join writes keep their fixed copy on that path. - "workflows.journey.mjs now expects the fixture's refusal text" and "The journey fails without the session.ts forward" no longer hold. The journey checks fixed copy again. A real-session test in src/features/workflows/session.test.ts now covers the forward. Every other PublishRejected.reason consumer was checked (identity-archives, channel-details, channel-lifecycle, administration, native, session): none reads `reason`, so `forbidden:` changes nothing there. Tests: - outbox-receipts: echo plus a `forbidden:` PublishRejected stays seen and forwards no refusal. The journal-secrets row now has a relay reason, so its forward assertion still holds. - capability: a status summary and a reason-less refusal keep the fixed copy; Check saved configuration resolves an echoed save after a relay refusal. - emoji: a status summary and a reason-less refusal keep "Failed to add emoji." - transport: acceptPublish and the native signed writer (connectSignedTransport, `refusalText`) both turn a 400 `{error:"forbidden: …"}` into a PublishRejected whose `reason` is the raw text and that `isRelayRefusal` accepts. A table checks the predicate against real transport output for empty, kept-prefix and unprefixed text. - ChannelSettingsPanel: `invalid:` and `forbidden:` refusals show display text; proxy text and a kept prefix show the default. - agent-config-artifacts: `forbidden:` is `permission`, directly and through acceptPublish. - workflows session: through createRelaySession, a `forbidden:` refusal of a run shows the relay's words on the operation while the journal keeps fixed copy. This replaces the journey's coverage of the session.ts forward. Each new or tightened assertion fails with its production piece reverted on its own: the delivery gate (2 failures), the narrowed predicate (9), the auto-join change (4), the `forbidden` classifier (2), the emoji call site (1), `forbidden` in NIP01_PREFIX (3) and the session.ts forward (1). The journey's fixed-copy assertion fails under the old broad rule and passes now. Checked: tsc --noEmit clean; biome clean on the touched files; vitest for transport, outbox, outbox-receipts, src/features/workflows, emoji, CustomEmojiSettings, ChannelSettingsPanel, agent-config-artifacts, session-permissions and src/bundled/workflows: 35 files, 561 tests passed. workflows.journey.mjs in Chromium: 34 passed. Not changed: the outbox's fixed copy still says "refresh the saved configuration"; the control is named "Check saved configuration". Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../channels/ChannelSettingsPanel.test.tsx | 29 ++++++++++- src/bundled/channels/ChannelSettingsPanel.tsx | 19 ++++--- src/bundled/workflows/workflows.journey.mjs | 6 ++- .../agents/agent-config-artifacts.test.ts | 6 +++ src/features/agents/agent-config-artifacts.ts | 1 + src/features/relay/emoji-directory.ts | 5 +- src/features/relay/emoji.test.ts | 24 ++++++--- src/features/relay/outbox-receipts.test.ts | 22 +++++++- src/features/relay/outbox.ts | 36 ++++++++++--- src/features/relay/transport.test.ts | 42 ++++++++++++++- src/features/relay/transport.ts | 5 +- src/features/workflows/capability.test.ts | 32 ++++++++++-- src/features/workflows/session.test.ts | 52 +++++++++++++++++++ 13 files changed, 240 insertions(+), 39 deletions(-) diff --git a/src/bundled/channels/ChannelSettingsPanel.test.tsx b/src/bundled/channels/ChannelSettingsPanel.test.tsx index 4c3fdce427..713a019b48 100644 --- a/src/bundled/channels/ChannelSettingsPanel.test.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.test.tsx @@ -616,16 +616,41 @@ it("runs the matching command, stays pending until it settles, then follows the }); it.each([ + // As the transport shows a refusal: the relay's words without their prefix. [ "the relay's own reason", - new PublishRejected("rejected", "invalid: actor not authorized"), - "invalid: actor not authorized", + new PublishRejected( + "Actor not authorized", + "invalid: actor not authorized", + ), + "Actor not authorized", + ], + [ + "the relay's forbidden reason", + new PublishRejected( + "Only owners and admins can change auto-join", + "forbidden: only owners and admins can change auto-join", + ), + "Only owners and admins can change auto-join", ], [ "the default reason", new PublishRejected("rejected"), "Only community owners and admins can change this.", ], + [ + "the default reason for text that is not the relay's", + new PublishRejected( + "Relay rejected the message (403)", + "Forbidden by proxy", + ), + "Only community owners and admins can change this.", + ], + [ + "the default reason for a machine prefix", + new PublishRejected("auth-required: sign in", "auth-required: sign in"), + "Only community owners and admins can change this.", + ], [ "a retry for an unconfirmed outcome", // As the lifecycle owner throws it when readback never shows the flag. diff --git a/src/bundled/channels/ChannelSettingsPanel.tsx b/src/bundled/channels/ChannelSettingsPanel.tsx index 5e51311c56..2ecb42f409 100644 --- a/src/bundled/channels/ChannelSettingsPanel.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.tsx @@ -14,7 +14,11 @@ import { ChannelLifecycleUnconfirmed, type ChannelLifecycleCapability, } from "../../features/relay/channel-lifecycle"; -import { PublishNotSent, PublishRejected } from "../../features/relay/outbox"; +import { + isRelayRefusal, + PublishNotSent, + PublishRejected, +} from "../../features/relay/outbox"; import { managesCommunity } from "../../features/communities/roster"; import type { CommunityMembership } from "../moderation/membership"; import type { RelaySession } from "../../features/relay/session"; @@ -350,12 +354,13 @@ function AutoJoinSetting({ : // A rate limit or a write that never left this device, not a refusal. error instanceof PublishNotSent ? "Not sent. Try again." - : error instanceof PublishRejected - ? (error.reason ?? - "Only community owners and admins can change this.") - : error instanceof Error - ? error.message - : String(error), + : isRelayRefusal(error) + ? error.message + : error instanceof PublishRejected + ? "Only community owners and admins can change this." + : error instanceof Error + ? error.message + : String(error), }); } finally { operation.current = undefined; diff --git a/src/bundled/workflows/workflows.journey.mjs b/src/bundled/workflows/workflows.journey.mjs index 3a5e7a60b3..16b2d4f784 100644 --- a/src/bundled/workflows/workflows.journey.mjs +++ b/src/bundled/workflows/workflows.journey.mjs @@ -1997,9 +1997,11 @@ test("generic Outbox offers message retry but no workflow replay", async ({ await expect( page.getByText("Failed to trigger workflow", { exact: true }), ).toBeVisible(); - // The relay's refusal text replaces the journal's fixed copy in this session. await expect( - page.getByText("Fixture non-delivery", { exact: true }), + page.getByText( + "Workflow command rejected; retain the draft and refresh the saved configuration.", + { exact: true }, + ), ).toBeVisible(); // The Outbox is page chrome beneath the modal editor. await button("Close editor").click(); diff --git a/src/features/agents/agent-config-artifacts.test.ts b/src/features/agents/agent-config-artifacts.test.ts index 8a0042c422..3905870b6a 100644 --- a/src/features/agents/agent-config-artifacts.test.ts +++ b/src/features/agents/agent-config-artifacts.test.ts @@ -332,6 +332,9 @@ describe("delivery", () => { expect(refusal("conflict: prev is not current")).toBe("conflict"); expect(refusal("duplicate: already have this event")).toBe("duplicate"); expect(refusal("restricted: not a member")).toBe("permission"); + expect(refusal("forbidden: not a member of this channel")).toBe( + "permission", + ); expect(refusal("restricted: channel is archived")).toBe("archived"); expect(refusal("invalid: event too large")).toBe("too-large"); expect(refusal("invalid: bad envelope")).toBe("invalid"); @@ -369,6 +372,9 @@ describe("delivery", () => { expect( await through(body(403, "blocked: you are banned from this community")), ).toMatchObject({ status: "refused", refusal: "permission" }); + expect( + await through(body(400, "forbidden: not a member of this channel")), + ).toMatchObject({ status: "refused", refusal: "permission" }); expect(await through(body(500, "internal server error"))).toMatchObject({ status: "uncertain", }); diff --git a/src/features/agents/agent-config-artifacts.ts b/src/features/agents/agent-config-artifacts.ts index 62cee5444f..0532941e6e 100644 --- a/src/features/agents/agent-config-artifacts.ts +++ b/src/features/agents/agent-config-artifacts.ts @@ -309,6 +309,7 @@ export function refusal(message: string): Refusal { if (/archived/i.test(message)) return "archived"; if ( prefix === "restricted" || + prefix === "forbidden" || prefix === "auth-required" || prefix === "blocked" ) diff --git a/src/features/relay/emoji-directory.ts b/src/features/relay/emoji-directory.ts index a88673bc61..0809ca0f44 100644 --- a/src/features/relay/emoji-directory.ts +++ b/src/features/relay/emoji-directory.ts @@ -13,7 +13,7 @@ import { type CustomEmoji, } from "./emoji"; import { eventDto, newer, type RelayEvent } from "./events"; -import { PublishNotSent, PublishRejected } from "./outbox"; +import { isRelayRefusal } from "./outbox"; import type { Priority, RelayReader } from "./reader"; import type { RelayWriter } from "./transport"; @@ -251,8 +251,7 @@ export function createEmojiDirectory( ? url === undefined ? "Timed out while removing emoji." : "Timed out while adding emoji." - : error instanceof PublishRejected && - !(error instanceof PublishNotSent) + : isRelayRefusal(error) ? `${failure} ${error.message}` : failure, ); diff --git a/src/features/relay/emoji.test.ts b/src/features/relay/emoji.test.ts index f3458e87e4..d668c6b436 100644 --- a/src/features/relay/emoji.test.ts +++ b/src/features/relay/emoji.test.ts @@ -778,17 +778,27 @@ it("rejects invalid names before any read and maps publish failure to reference /^Failed to add emoji\. You are banned$/, ); expect(h.emoji.snapshot().mine).toEqual([]); - // A write that never reached the relay has no reason to show. - h.publish.mockRejectedValueOnce(new PublishNotSent("Relay unreachable")); - const notSent = h.emoji.add?.("party", url); - await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); - h.ownRead().respond([]); - await expect(notSent).rejects.toThrow(/^Failed to add emoji\.$/); + // A write that never reached the relay, or a refusal without the relay's + // own words, has no reason to show. + for (const error of [ + new PublishNotSent("Relay unreachable"), + new PublishRejected( + "Relay rejected the message (403)", + "Forbidden by proxy", + ), + new PublishRejected("Relay rejected the message"), + ]) { + h.publish.mockRejectedValueOnce(error); + const unexplained = h.emoji.add?.("party", url); + await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); + h.ownRead().respond([]); + await expect(unexplained).rejects.toThrow(/^Failed to add emoji\.$/); + } const failedRead = h.emoji.add?.("party", url); await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); h.ownRead().fail(new Error("offline")); await expect(failedRead).rejects.toThrow(/^Failed to add emoji\.$/); - expect(h.publish).toHaveBeenCalledTimes(2); + expect(h.publish).toHaveBeenCalledTimes(4); }); it("removes only from the fresh own set and preserves another member's colliding emoji", async () => { const h = authoring(); diff --git a/src/features/relay/outbox-receipts.test.ts b/src/features/relay/outbox-receipts.test.ts index d9060626b3..f91bf6d48b 100644 --- a/src/features/relay/outbox-receipts.test.ts +++ b/src/features/relay/outbox-receipts.test.ts @@ -131,6 +131,26 @@ it("echo plus lost receipt remains seen but settles command result as unavailabl undefined, ); }); +it("echo plus a relay refusal remains seen and forwards no refusal", async () => { + const h = setup(); + h.send(); + await flush(); + h.observe([h.published()]); + h.reject( + new PublishRejected( + "Workflow is disabled or inactive", + "forbidden: workflow is disabled or inactive", + ), + ); + await flush(); + // The relay has the event, so its result stays unknown, not refused. + expect(h.local.snapshot()[0]?.delivery).toBe("seen"); + expect(h.onReceipt).toHaveBeenCalledExactlyOnceWith( + h.published(), + undefined, + undefined, + ); +}); it("receipt waits are bounded and late results after disposal never publish", async () => { vi.useFakeTimers(); const h = setup(100); @@ -215,7 +235,7 @@ it.each([30620, 46020, 5])( const h = setup(); const id = h.send(kind); await flush(); - h.reject(new PublishRejected("PRIVATE")); + h.reject(new PublishRejected("PRIVATE", "blocked: PRIVATE")); await flush(); expect(h.outbox.snapshot()[0]?.delivery).toBe("failed"); expect(JSON.stringify(h.saved())).not.toContain("PRIVATE"); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index e2b416d048..c391deaaf7 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -174,6 +174,25 @@ export class PublishRejected extends Error { * device, or the relay asked it to wait. Retrying may succeed. */ export class PublishNotSent extends PublishRejected {} +/** NIP-01 machine-readable prefixes: the shape of a relay's own refusal. */ +export const NIP01_PREFIX = + /^(invalid|blocked|restricted|forbidden|error|pow|duplicate|rate-limited|conflict|auth-required):\s*/; + +/** Whether `message` is the relay's own words for a refusal: the write was + * sent and its `reason` is relay-shaped text. Status summaries, client-side + * rejections and prefixed text kept for writers to match on are not, so + * writers show their fixed copy for those. */ +export function isRelayRefusal(error: unknown): error is PublishRejected { + if (!(error instanceof PublishRejected) || error instanceof PublishNotSent) + return false; + const prefix = NIP01_PREFIX.exec(error.reason ?? ""); + return ( + !!prefix && + !!error.reason?.slice(prefix[0].length).trim() && + !NIP01_PREFIX.test(error.message) + ); +} + export { browserOutboxStorage } from "./outbox-storage"; /** The desktop host's answer to a retry the relay would refuse as too old, * when the event cannot be read back. */ @@ -792,14 +811,6 @@ export function createOutbox( // A verified observation ends the attempt even if its HTTP ACK never arrives. total(!closed && !latest ? "ok" : "error"); if (closed) return; - if (latest && awaitsReceipt(latest.event)) - onReceipt( - latest.signed ?? latest.event, - undefined, - error instanceof PublishRejected && !(error instanceof PublishNotSent) - ? clip(error.message) - : undefined, - ); const delivery: Delivery | undefined = latest && (latest.delivery === "seen" || attempt.previousDelivery === "seen" @@ -809,6 +820,15 @@ export function createOutbox( : publishing && !(error instanceof PublishRejected) ? "unknown" : failedDelivery(attempt)); + // Only a failed attempt was refused; an echoed command stays unknown. + if (latest && awaitsReceipt(latest.event)) + onReceipt( + latest.signed ?? latest.event, + undefined, + delivery === "failed" && isRelayRefusal(error) + ? clip(error.message) + : undefined, + ); const message = error instanceof Error ? error.message : String(error); if (latest && delivery) saveStatus({ diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index 9b65ced433..06c19b844d 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -10,7 +10,7 @@ import { ReadStateTimestampRejected, READ_STATE_TIMESTAMP_REFUSAL, } from "./read-state-host"; -import { PublishNotSent, PublishRejected } from "./outbox"; +import { isRelayRefusal, PublishNotSent, PublishRejected } from "./outbox"; import { hostSigner, keypair, signed } from "./testing"; const key = keypair(); afterEach(() => vi.unstubAllGlobals()); @@ -341,6 +341,46 @@ it("carries the relay's refusal text through both publish transports", async () reason: error, }); }); +it("keeps a forbidden: refusal as relay text through acceptPublish and the signed writer", async () => { + const error = + "forbidden: workflows with call_webhook actions require the owner or admin role"; + const event = signed(key, { kind: 9, content: "hello", tags: [["h", "c"]] }); + const transport = await connectSignedTransport( + hostSigner(key), + "https://relay.test", + "relay", + ); + assert.exists(transport.writer); + vi.stubGlobal("fetch", async () => Response.json({ error }, { status: 400 })); + for (const result of [ + await refusal(400, { error }), + await transport.writer + .publish(event, new AbortController().signal) + .catch((reason: unknown) => reason), + ]) { + expect(result).toBeInstanceOf(PublishRejected); + expect(result).toMatchObject({ + message: + "Workflows with call_webhook actions require the owner or admin role", + reason: error, + }); + expect(isRelayRefusal(result)).toBe(true); + } +}); +it.each([ + ["forbidden: not a member of this DM", true], + // Empty text leaves the status summary. + ["invalid: ", false], + // Text writers match on stays machine text, not display words. + ["auth-required: sign in", false], + // Without a NIP-01 prefix the text is not the relay's. + ["Forbidden by proxy", false], +])( + "counts only the relay's own words as its refusal: %j", + async (error, words) => { + expect(isRelayRefusal(await refusal(403, { error }))).toBe(words); + }, +); it("keeps the conflict refusal and the raw reason for classifying writers", async () => { const conflict = await refusal(409, { error: "invalid: whatever" }); expect(conflict).toHaveProperty( diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 38c38af285..77d4667096 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -74,7 +74,7 @@ import { type LiveSubscription, } from "./live"; import { subscribeBrokerTraffic } from "./broker-live"; -import { PublishNotSent, PublishRejected } from "./outbox"; +import { NIP01_PREFIX, PublishNotSent, PublishRejected } from "./outbox"; import { httpReadError, ReadError } from "./errors"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; import type { EventTemplate, VerifiedEvent } from "nostr-tools"; @@ -1750,9 +1750,6 @@ export async function acceptReadStatePublish(response: Response, id: string) { } const REFUSAL_STATUSES = [400, 401, 403, 404, 413, 422]; -/** NIP-01 machine-readable prefixes: the shape of a relay's own refusal. */ -const NIP01_PREFIX = - /^(invalid|blocked|restricted|forbidden|error|pow|duplicate|rate-limited|conflict|auth-required):\s*/; /** Prefixes writers match on, so the text is shown as sent. */ const KEPT_PREFIXES = new Set(["rate-limited", "conflict", "auth-required"]); /** The relay's own `{error}` text for a refused write. Admission otherwise diff --git a/src/features/workflows/capability.test.ts b/src/features/workflows/capability.test.ts index e18eedb651..38c746734d 100644 --- a/src/features/workflows/capability.test.ts +++ b/src/features/workflows/capability.test.ts @@ -405,6 +405,19 @@ it.each([ new PublishNotSent("Relay unreachable"), "Workflow command rejected; retain the draft and refresh the saved configuration.", ], + [ + "fixed copy for a status summary", + new PublishRejected( + "Relay rejected the message (403)", + "Forbidden by proxy", + ), + "Workflow command rejected; retain the draft and refresh the saved configuration.", + ], + [ + "fixed copy for a refusal without a relay reason", + new PublishRejected("Relay rejected the message"), + "Workflow command rejected; retain the draft and refresh the saved configuration.", + ], ])( "a rejected run shows %s; the journal never holds relay text", async (_, error, shown) => { @@ -827,9 +840,20 @@ it.each(["clear", "interrupt"] as const)( }, ); -it.each([true, false])( - "fresh exact saved configuration resolves a lost save receipt without replay (echo=%s)", - async (echo) => { +it.each([ + [false, new Error("lost receipt")], + [true, new Error("lost receipt")], + // The relay already has an echoed save, so its refusal leaves it unknown. + [ + true, + new PublishRejected( + "Workflow is disabled or inactive", + "forbidden: workflow is disabled or inactive", + ), + ], +])( + "fresh exact saved configuration resolves a lost save receipt without replay (echo=%s, %s)", + async (echo, error) => { const h = setup(); const operation = h.capability.save({ channelId, @@ -840,7 +864,7 @@ it.each([true, false])( const event = h.publish.mock.calls[0]?.[0]; if (!event) throw new Error("missing publication"); if (echo) h.outbox.observe([event]); - h.reject(new Error("lost receipt")); + h.reject(error); await flush(); expect(h.capability.operations.snapshot()[0]?.outcome).toBe("unknown"); h.read.mockResolvedValue([event]); diff --git a/src/features/workflows/session.test.ts b/src/features/workflows/session.test.ts index f3c14a1c49..8a441885cc 100644 --- a/src/features/workflows/session.test.ts +++ b/src/features/workflows/session.test.ts @@ -508,6 +508,58 @@ it("existing backend permits workflow commands without lifecycle metadata while expect(publish).toHaveBeenCalledTimes(1); }); +it("a relay refusal reaches the session's run operation; the journal keeps fixed copy", async () => { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let incoming!: (events: readonly RelayEvent[]) => void; + let saved = ""; + const publish = vi.fn(async () => { + throw new PublishRejected( + "Workflow is disabled or inactive", + "forbidden: workflow is disabled or inactive", + ); + }); + const owner = createRelaySession( + { + ...wire.transport, + writer: { + kinds: [46020], + sign: async (template) => signed(viewer, template), + publish, + }, + workflows: { runs: async () => ({ runs: [], next: null }) }, + subscribe(callbacks) { + incoming = callbacks.receive; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { + outboxStorage: { + load: async () => [], + save: async (rows) => { + saved = JSON.stringify(rows); + }, + }, + }, + ); + owners.push(owner); + incoming([roster(relay, channelId, [viewer.pubkey], 1)]); + const operation = owner.session.workflows.trigger({ + ...reference, + yaml: definition.content, + revision: definition.id, + createdAt: 10, + }); + await vi.waitFor(() => + expect(owner.session.workflows.operations.snapshot()[0]).toMatchObject({ + eventId: operation, + outcome: "rejected", + error: "Workflow is disabled or inactive", + }), + ); + await vi.waitFor(() => expect(saved).toContain("Workflow command rejected")); + expect(saved).not.toContain("disabled or inactive"); +}); + it("session fresh definition read resolves a lost save, while ordinary echo does not", async () => { const wire = scriptedTransport(viewer.pubkey, relay.pubkey); let incoming!: (events: readonly RelayEvent[]) => void; From 940b40b6a128b99534adfbe25465be9f718f48ad Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:13 +1100 Subject: [PATCH 04/12] fix(channels): reread Settings' actions from the writer on Refresh channels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to f5eae9bdab (offer Refresh channels on stale lifecycle failures), addressing its review. That commit keyed Settings' ChannelLifecycleActions on `viewerRole` so a refreshed role would reread permissions. `viewerRole` is only the role hint on the viewer's 39002 `p` tag. Authority comes from 39001 and owner-agent attestation in kind-0 profiles. When those changed and the hint did not, Refresh channels left Archive and Delete offered under a toast that said "Refresh channels to see what you can do now." - ChannelNavigationState: new `lifecycleRefreshes` counter in the session-scoped navigation state, bumped by the failure toast's Refresh channels next to the strong refreshList. Session or scope replacement resets it to 0. - ChannelLifecycleActions: new `refreshes` prop. Each change reruns the permission lookup, clearing the old actions while it loads. Once it is nonzero, lookups pass `{ consistency: "strong" }`. ChannelsPage passes the counter through. The key keeps `viewerRole` and archive state for live roster changes. - channel-lifecycle: `load()` takes optional `{ consistency }`. When it is "strong", the 39000/39001/39002 read and the owner-agent kind-0 profile reads both go to the writer. Default reads are unchanged. - channel-lifecycle: ChannelLifecycleStale sets `name`, matching ChannelLifecycleUnconfirmed. Unconfirmed still overrides it. - docs/channels.md describes the reread and its writer routing. The counter goes in as a prop, not in the key as the review suggested. The strong read has to depend on the counter anyway, so with the counter in the key too, the first refresh's rerun had two causes, and the test still passed with the key part removed. One dependency both reruns the lookup and selects the writer, and the tests pin it. Strong reads stay on for the rest of the session after the first refresh, not only for the lookup that refresh starts. The strong refreshList can change `viewerRole` and remount the actions while the refresh's own lookup is in flight. A one-shot strong flag would let that remount read a replica that predates the change. The cost is one writer-routed lookup per Settings mount after a rare recovery action. Tests: - ChannelsPage.tabs: a real-session test changes only 39001. The 39002 hint stays "owner", so the key never changes. Archive's own check reads the demotion and shows the stale toast. A `replica` fixture option then serves the pre-change 39001 to reads that are not strong. After Refresh channels, Settings shows Leave only, Archive and Delete are gone, and nothing was published. - ChannelLifecycleActions: refreshes 0 → 1 → 2 loads three times: once with default reads, then strong twice. - channel-lifecycle: a strong load sends `consistency: "strong"` on all three channel-state filters and the owner profile read. The stale error's `name` is "ChannelLifecycleStale". - ChannelNavigationState: Refresh channels bumps `lifecycleRefreshes` from 0 to 1. With all four production files reverted to b7c2c26488, the ChannelsPage test fails: Archive stays offered after Refresh. Reverting each piece on its own also fails at least one new assertion: no `refreshes` prop from ChannelsPage (1 failure), no counter bump (2), no strong option from Settings (2), `refreshes` missing from the effect deps (2), load ignoring strong for channel state (2), profile reads not strong (1), no `name` (1). Checked: tsc --noEmit clean. biome check clean on the touched sources and tests. vitest, 10 files, 407 passed: channel-lifecycle 214, ChannelLifecycleMenu 36, ChannelLifecycleActions 22, ChannelNavigationState 11, ChannelSettingsPanel 31, ChannelsPage 10, ChannelsPage.tabs 28, ChannelsPage.solo 50, ChannelsPage.conversion 4, ChannelsPage.icon 1. tests/browser/channel-lifecycle.spec.mjs in Chromium: 10 passed. Not changed: the sidebar and header Channel actions menus still read permissions on each open with default routing. docs/relay-queries.md, which lists strong reads, was left alone because the relay-refusal commits own its recent edits. Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../channels/ChannelsPage.tabs.test.tsx | 18 +++++++++++++++- .../ChannelNavigationState.test.tsx | 3 +++ .../ChannelNavigationState.tsx | 9 ++++++++ src/features/relay/channel-lifecycle.test.ts | 19 +++++++++++++++++ src/features/relay/channel-lifecycle.ts | 21 +++++++++++++++---- 5 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/bundled/channels/ChannelsPage.tabs.test.tsx b/src/bundled/channels/ChannelsPage.tabs.test.tsx index 9e9e88b3af..67b0219c1c 100644 --- a/src/bundled/channels/ChannelsPage.tabs.test.tsx +++ b/src/bundled/channels/ChannelsPage.tabs.test.tsx @@ -538,11 +538,14 @@ function workspace( membership, lifecycle, handoff = false, + replica, }: { membership?: CommunityMembership; lifecycle?: (event: RelayEvent) => Promise; /** Mount the shell's channel navigation, which owns lifecycle actions. */ handoff?: boolean; + /** What reads that are not strong see; `events` is the writer. */ + replica?: RelayEvent[]; } = {}, ) { const owner = createRelaySession( @@ -550,7 +553,20 @@ function workspace( viewer: viewer.pubkey, relayAuthor: authority.pubkey, media: () => undefined, - query: async (filters) => relayQuery(authority, events, filters), + query: async (filters) => + replica + ? [ + ...new Set( + filters.flatMap((filter) => + relayQuery( + authority, + filter.consistency === "strong" ? events : replica, + [filter], + ), + ), + ), + ] + : relayQuery(authority, events, filters), writer: { sign: async (template) => signed(viewer, template), publish: async () => {}, diff --git a/src/features/channel-navigation/ChannelNavigationState.test.tsx b/src/features/channel-navigation/ChannelNavigationState.test.tsx index 99714f8f55..c8fdc86182 100644 --- a/src/features/channel-navigation/ChannelNavigationState.test.tsx +++ b/src/features/channel-navigation/ChannelNavigationState.test.tsx @@ -461,10 +461,13 @@ it("offers Refresh channels when a lifecycle action failed on stale state", asyn within(toast).getByRole("button", { name: "Dismiss notification" }), refresh, ]); + expect(view.result.current.lifecycleRefreshes).toBe(0); fireEvent.click(refresh); expect(h.refreshList).toHaveBeenCalledExactlyOnceWith({ consistency: "strong", }); + // Settings reads its channel actions again on each one. + expect(view.result.current.lifecycleRefreshes).toBe(1); await waitFor(() => expect( screen.queryByRole("dialog", { name: "Archive channel failed" }), diff --git a/src/features/channel-navigation/ChannelNavigationState.tsx b/src/features/channel-navigation/ChannelNavigationState.tsx index da7d9b31a0..e340077f4c 100644 --- a/src/features/channel-navigation/ChannelNavigationState.tsx +++ b/src/features/channel-navigation/ChannelNavigationState.tsx @@ -97,6 +97,10 @@ type State = { * else's doing. Each is kept until the relay answers for its channel (see * `answered`). One that failed before publishing is not recorded. */ ownLosses: readonly OwnLoss[]; + /** Counts Refresh channels chosen from a lifecycle failure. Settings reads + * its channel actions again on each one: 39001 roles and owner-agent + * profiles can change without the roster's role hint. */ + lifecycleRefreshes: number; }; type OwnLoss = Readonly<{ channelId: string; @@ -505,6 +509,10 @@ export function ChannelNavigationProvider({ connection.session.channels.refreshList?.({ consistency: "strong", }); + update((previous) => ({ + ...previous, + lifecycleRefreshes: previous.lifecycleRefreshes + 1, + })); setFailure(undefined); }} > @@ -533,5 +541,6 @@ function restore(session: RelaySession, scope: string): State { lifecycleDialog: undefined, queuedUndos: [], ownLosses: [], + lifecycleRefreshes: 0, }; } diff --git a/src/features/relay/channel-lifecycle.test.ts b/src/features/relay/channel-lifecycle.test.ts index de7d30e9dc..c4ab334f57 100644 --- a/src/features/relay/channel-lifecycle.test.ts +++ b/src/features/relay/channel-lifecycle.test.ts @@ -682,6 +682,7 @@ it("rereads authority after signing; a removed admin cannot publish", async () = const run = h.owner.capability.run("archive", id); // Stale state the viewer can refresh, and copy naming that control. await expect(run).rejects.toBeInstanceOf(ChannelLifecycleStale); + await expect(run).rejects.toMatchObject({ name: "ChannelLifecycleStale" }); await expect(run).rejects.toThrow( /^This action is no longer permitted\. Refresh channels to see what you can do now\.$/, ); @@ -1467,6 +1468,24 @@ describe("channel owner-agent Archive and Delete eligibility", () => { h.owner.dispose(); }, ); + it("a strong load reads channel state and owner profiles from the writer", async () => { + const h = ownedAgent("member"); + h.read.mockClear(); + expect( + await h.owner.capability.load(id, undefined, { consistency: "strong" }), + ).toMatchObject({ canArchive: true, canDelete: true }); + expect(h.read.mock.calls.map(([filters]) => filters)).toEqual([ + [39000, 39001, 39002].map((kind) => ({ + kinds: [kind], + consistency: "strong", + authors: [relayAuthor], + "#d": [id], + limit: 1, + })), + [{ kinds: [0], consistency: "strong", authors: [other], limit: 1 }], + ]); + h.owner.dispose(); + }); it("a member owning an owner-agent can archive and unarchive", async () => { const h = ownedAgent("member"); await h.owner.capability.run("archive", id); diff --git a/src/features/relay/channel-lifecycle.ts b/src/features/relay/channel-lifecycle.ts index 5b2b0cb17d..a61fc1545e 100644 --- a/src/features/relay/channel-lifecycle.ts +++ b/src/features/relay/channel-lifecycle.ts @@ -6,7 +6,7 @@ import { PublishRejected } from "./outbox"; import { isTransientFailure, readErrorKind } from "./errors"; import { retryRead } from "./read-retry"; import { yieldToHost } from "./yield"; -import { hasTag, newer, type RelayEvent } from "./events"; +import { hasTag, newer, type ReadFilter, type RelayEvent } from "./events"; import { openMetadata } from "./discovery"; import { FRESH_FOR } from "./store"; import { @@ -24,7 +24,12 @@ import { /** The channel state the action relied on may be out of date; refreshing * channels is the recovery. */ -export class ChannelLifecycleStale extends Error {} +export class ChannelLifecycleStale extends Error { + constructor(message: string) { + super(message); + this.name = "ChannelLifecycleStale"; + } +} /** No automatic or same-dialog retry after a request may have reached the relay. */ export class ChannelLifecycleUnconfirmed extends ChannelLifecycleStale { @@ -49,6 +54,8 @@ export interface ChannelLifecycleCapability { /** The channel's relay records the caller already read, so its answer and * these rights share one snapshot; omitted, load reads them. */ records?: readonly RelayEvent[], + /** "strong" reads the writer, for a reread after a refresh. */ + options?: Pick, ): Promise; run( action: ChannelLifecycleCommand, @@ -199,9 +206,11 @@ export function createChannelLifecycle({ // the channel's state allows and false skips the optional profile reads. need: OwnedAgentAction | "any" | false = "any", records?: readonly RelayEvent[], + strong = false, ) { assertAccess(id); - const events = records ?? (await read([39000, 39001, 39002], id, signal)); + const events = + records ?? (await read([39000, 39001, 39002], id, signal, false, strong)); assertAccess(id); const settings = lifecycleSettings(events, id, viewer, relayAuthor); const metadata = lifecycleRecord(events, 39000, id, relayAuthor); @@ -242,6 +251,7 @@ export function createChannelLifecycle({ reader.read( batch.map((pubkey) => ({ kinds: [0], + ...(strong ? { consistency: "strong" as const } : {}), authors: [pubkey], limit: 1, })), @@ -418,11 +428,14 @@ export function createChannelLifecycle({ value: string, caller?: AbortSignal, records?: readonly RelayEvent[], + options?: Pick, ) { const id = lifecycleChannelId(value); + const strong = options?.consistency === "strong"; return owned({ id, caller }, (signal) => retryRead( - () => reread(signal, () => load(id, signal, "any", records)), + () => + reread(signal, () => load(id, signal, "any", records, strong)), signal, ), ); From bfad7e9bc48d27ac668c5e728b629aed41e225cf Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:13 +1100 Subject: [PATCH 05/12] fix(relay): decide relay refusals by their reason and bound every display Follow-up to b7c2c26488 (show only the relay's own refusal words), addressing the second-pass review of 86ff1bbbf3. Relay-refusal area only; the lifecycle findings are left for a later change. - outbox: KEPT_PREFIXES moves next to NIP01_PREFIX, and transport imports both. isRelayRefusal rejects a kept prefix by checking the prefix of `reason` against KEPT_PREFIXES. It no longer checks whether `message` is prefixed. That check only worked because transport's refusalMessage returns kept-prefix text unchanged and capitalizes everything else. The only constructor that passes a `reason` is acceptPublish's 4xx branch, so the result is the same for every transport output. - outbox: new relayRefusal(error) returns the relay's words clipped to the outbox's 256-character bound, or undefined. The outbox receipt forward, the emoji directory and the auto-join switch all use it, so the rule and the bound live in one place. The emoji and auto-join toasts showed `message` unclipped before, and readApiFailure lets up to 4 KB of `{error}` text through. - docs/relay-queries.md: the emoji reason is described as native-host behavior. The browser host's broker reports a socket `forbidden:`, `blocked:` or `restricted:` refusal as 503 `sent:false`, so that host shows plain copy for those and appends only `invalid:` reasons. - docs/workflows.md: the same browser-host difference, which covers the Call Webhook owner-or-admin refusal. Both docs record it as an unresolved host difference. browser-host/relay-broker.mjs is unchanged. The fixed workflow copy in the outbox journal ("refresh the saved configuration") is still deliberately deferred. Tests: - outbox: a table checks isRelayRefusal and relayRefusal on built errors. A kept prefix on `reason` with an unprefixed message is not a refusal. A prefixed message with an `invalid:` reason is one. No reason and not-sent are not. - transport: a 1000-character `invalid:` reason through acceptPublish keeps its whole `reason`, and relayRefusal shows 256 characters. - emoji: an over-long `blocked:` refusal reads "Failed to add emoji. " plus the clipped words. - ChannelSettingsPanel: an over-long `invalid:` refusal shows the clipped words. - outbox-receipts: an over-long `forbidden:` refusal forwards the clipped words. Reverting each production piece on its own fails at least one of these: - the old message-shape rule in isRelayRefusal: 2 failures (the kept-prefix and prefixed-message rows) - emoji-directory.ts as at 86ff1bbbf3: 1 - ChannelSettingsPanel.tsx as at 86ff1bbbf3: 1 - relayRefusal without the clip: 4 (transport, outbox-receipts, emoji, ChannelSettingsPanel) - the outbox forward without the helper and unclipped: 1 The outbox-receipts case also passes on 86ff1bbbf3, which already clipped the forward. It guards that call site after the move to the helper. Checked: tsc --noEmit clean. biome check clean on the touched sources and tests. vitest, 12 files, 314 passed: transport 68, outbox 50, outbox-receipts 15, workflows capability 50, workflows session 18, workflows pagination 18, workflows protocol 4, workflows http 2, emoji 27, CustomEmojiSettings 12, ChannelSettingsPanel 32, agent-config-artifacts 18. Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../channels/ChannelSettingsPanel.test.tsx | 8 +++++ src/bundled/channels/ChannelSettingsPanel.tsx | 9 +++-- src/features/relay/emoji-directory.ts | 7 ++-- src/features/relay/emoji.test.ts | 13 ++++++- src/features/relay/outbox-receipts.test.ts | 14 ++++++++ src/features/relay/outbox.test.ts | 34 +++++++++++++++++++ src/features/relay/outbox.ts | 20 ++++++++--- src/features/relay/transport.test.ts | 14 +++++++- src/features/relay/transport.ts | 9 +++-- 9 files changed, 110 insertions(+), 18 deletions(-) diff --git a/src/bundled/channels/ChannelSettingsPanel.test.tsx b/src/bundled/channels/ChannelSettingsPanel.test.tsx index 713a019b48..825a506d24 100644 --- a/src/bundled/channels/ChannelSettingsPanel.test.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.test.tsx @@ -633,6 +633,14 @@ it.each([ ), "Only owners and admins can change auto-join", ], + [ + "a long relay reason, clipped,", + new PublishRejected( + `Actor not authorized ${"x".repeat(1000)}`, + `invalid: actor not authorized ${"x".repeat(1000)}`, + ), + `Actor not authorized ${"x".repeat(1000)}`.slice(0, 256), + ], [ "the default reason", new PublishRejected("rejected"), diff --git a/src/bundled/channels/ChannelSettingsPanel.tsx b/src/bundled/channels/ChannelSettingsPanel.tsx index 2ecb42f409..be7eef3ae9 100644 --- a/src/bundled/channels/ChannelSettingsPanel.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.tsx @@ -15,9 +15,9 @@ import { type ChannelLifecycleCapability, } from "../../features/relay/channel-lifecycle"; import { - isRelayRefusal, PublishNotSent, PublishRejected, + relayRefusal, } from "../../features/relay/outbox"; import { managesCommunity } from "../../features/communities/roster"; import type { CommunityMembership } from "../moderation/membership"; @@ -354,13 +354,12 @@ function AutoJoinSetting({ : // A rate limit or a write that never left this device, not a refusal. error instanceof PublishNotSent ? "Not sent. Try again." - : isRelayRefusal(error) - ? error.message - : error instanceof PublishRejected + : (relayRefusal(error) ?? + (error instanceof PublishRejected ? "Only community owners and admins can change this." : error instanceof Error ? error.message - : String(error), + : String(error))), }); } finally { operation.current = undefined; diff --git a/src/features/relay/emoji-directory.ts b/src/features/relay/emoji-directory.ts index 0809ca0f44..1a40dac561 100644 --- a/src/features/relay/emoji-directory.ts +++ b/src/features/relay/emoji-directory.ts @@ -13,7 +13,7 @@ import { type CustomEmoji, } from "./emoji"; import { eventDto, newer, type RelayEvent } from "./events"; -import { isRelayRefusal } from "./outbox"; +import { relayRefusal } from "./outbox"; import type { Priority, RelayReader } from "./reader"; import type { RelayWriter } from "./transport"; @@ -246,13 +246,14 @@ export function createEmojiDirectory( accept([event]); return shortcode; } catch (error) { + const refusal = relayRefusal(error); throw new Error( timeout.aborted ? url === undefined ? "Timed out while removing emoji." : "Timed out while adding emoji." - : isRelayRefusal(error) - ? `${failure} ${error.message}` + : refusal + ? `${failure} ${refusal}` : failure, ); } diff --git a/src/features/relay/emoji.test.ts b/src/features/relay/emoji.test.ts index d668c6b436..f7eb92e0e3 100644 --- a/src/features/relay/emoji.test.ts +++ b/src/features/relay/emoji.test.ts @@ -778,6 +778,17 @@ it("rejects invalid names before any read and maps publish failure to reference /^Failed to add emoji\. You are banned$/, ); expect(h.emoji.snapshot().mine).toEqual([]); + // A long reason is clipped as the outbox clips it. + const words = `You are banned ${"x".repeat(1000)}`; + h.publish.mockRejectedValueOnce( + new PublishRejected(words, `blocked: ${words}`), + ); + const long = h.emoji.add?.("party", url); + await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); + h.ownRead().respond([]); + await expect(long).rejects.toThrow( + new Error(`Failed to add emoji. ${words.slice(0, 256)}`), + ); // A write that never reached the relay, or a refusal without the relay's // own words, has no reason to show. for (const error of [ @@ -798,7 +809,7 @@ it("rejects invalid names before any read and maps publish failure to reference await vi.waitFor(() => expect(h.wire.pending).toHaveLength(1)); h.ownRead().fail(new Error("offline")); await expect(failedRead).rejects.toThrow(/^Failed to add emoji\.$/); - expect(h.publish).toHaveBeenCalledTimes(4); + expect(h.publish).toHaveBeenCalledTimes(5); }); it("removes only from the fresh own set and preserves another member's colliding emoji", async () => { const h = authoring(); diff --git a/src/features/relay/outbox-receipts.test.ts b/src/features/relay/outbox-receipts.test.ts index f91bf6d48b..9bd4dabf25 100644 --- a/src/features/relay/outbox-receipts.test.ts +++ b/src/features/relay/outbox-receipts.test.ts @@ -252,6 +252,20 @@ it.each([30620, 46020, 5])( }, ); +it("forwards a long relay refusal clipped for display", async () => { + const h = setup(); + h.send(); + await flush(); + const words = `Disabled ${"x".repeat(1000)}`; + h.reject(new PublishRejected(words, `forbidden: ${words}`)); + await flush(); + expect(h.onReceipt).toHaveBeenCalledWith( + expect.anything(), + undefined, + words.slice(0, 256), + ); +}); + it.each([30620, 46020, 5])( "unknown kind %s is inspect-only while dismissal remains available", async (kind) => { diff --git a/src/features/relay/outbox.test.ts b/src/features/relay/outbox.test.ts index 892e770456..bc76e99de9 100644 --- a/src/features/relay/outbox.test.ts +++ b/src/features/relay/outbox.test.ts @@ -5,6 +5,8 @@ import { PublishNotSent, PublishRejected, createOutbox, + isRelayRefusal, + relayRefusal, type OutboxStorage, type OutgoingEvent, } from "./outbox"; @@ -1824,3 +1826,35 @@ it("restores an entry saved before held sends existed and retries it as before", await flush(); expect(h.publications.map(({ event }) => event.id)).toEqual([event.id]); }); + +it.each([ + [ + "the relay's own words", + true, + new PublishRejected("Bad tag", "invalid: bad tag"), + ], + // The reason's prefix decides, whatever the transport made of the message. + [ + "a kept prefix", + false, + new PublishRejected("Sign in", "auth-required: sign in"), + ], + [ + "a prefixed message", + true, + new PublishRejected("invalid: bad tag", "invalid: bad tag"), + ], + [ + "no relay reason", + false, + new PublishRejected("Relay rejected the message (403)"), + ], + [ + "a write that was not sent", + false, + new PublishNotSent("Bad tag", "invalid: bad tag"), + ], +])("%s is a relay refusal: %s", (_, refused, error) => { + expect(isRelayRefusal(error)).toBe(refused); + expect(relayRefusal(error)).toBe(refused ? error.message : undefined); +}); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index c391deaaf7..eabaebd0f8 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -177,6 +177,12 @@ export class PublishNotSent extends PublishRejected {} /** NIP-01 machine-readable prefixes: the shape of a relay's own refusal. */ export const NIP01_PREFIX = /^(invalid|blocked|restricted|forbidden|error|pow|duplicate|rate-limited|conflict|auth-required):\s*/; +/** Prefixes writers match on, so the text is shown as sent. */ +export const KEPT_PREFIXES = new Set([ + "rate-limited", + "conflict", + "auth-required", +]); /** Whether `message` is the relay's own words for a refusal: the write was * sent and its `reason` is relay-shaped text. Status summaries, client-side @@ -188,11 +194,17 @@ export function isRelayRefusal(error: unknown): error is PublishRejected { const prefix = NIP01_PREFIX.exec(error.reason ?? ""); return ( !!prefix && - !!error.reason?.slice(prefix[0].length).trim() && - !NIP01_PREFIX.test(error.message) + !KEPT_PREFIXES.has(prefix[1] ?? "") && + !!error.reason?.slice(prefix[0].length).trim() ); } +/** The relay's refusal words to show, clipped like stored diagnostics, or + * undefined when `error` is not the relay's own refusal. */ +export function relayRefusal(error: unknown): string | undefined { + return isRelayRefusal(error) ? clip(error.message) : undefined; +} + export { browserOutboxStorage } from "./outbox-storage"; /** The desktop host's answer to a retry the relay would refuse as too old, * when the event cannot be read back. */ @@ -825,9 +837,7 @@ export function createOutbox( onReceipt( latest.signed ?? latest.event, undefined, - delivery === "failed" && isRelayRefusal(error) - ? clip(error.message) - : undefined, + delivery === "failed" ? relayRefusal(error) : undefined, ); const message = error instanceof Error ? error.message : String(error); if (latest && delivery) diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index 06c19b844d..231999afa5 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -10,7 +10,12 @@ import { ReadStateTimestampRejected, READ_STATE_TIMESTAMP_REFUSAL, } from "./read-state-host"; -import { isRelayRefusal, PublishNotSent, PublishRejected } from "./outbox"; +import { + isRelayRefusal, + PublishNotSent, + PublishRejected, + relayRefusal, +} from "./outbox"; import { hostSigner, keypair, signed } from "./testing"; const key = keypair(); afterEach(() => vi.unstubAllGlobals()); @@ -381,6 +386,13 @@ it.each([ expect(isRelayRefusal(await refusal(403, { error }))).toBe(words); }, ); +it("keeps a long refusal's whole reason but clips its display words", async () => { + // Admission keeps up to 4 KB of `{error}` text, so the bound is the display's. + const error = `invalid: ${"x".repeat(1000)}`; + const result = await refusal(400, { error }); + expect(result).toMatchObject({ reason: error }); + expect(relayRefusal(result)).toBe(`X${"x".repeat(255)}`); +}); it("keeps the conflict refusal and the raw reason for classifying writers", async () => { const conflict = await refusal(409, { error: "invalid: whatever" }); expect(conflict).toHaveProperty( diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 77d4667096..b05656cf48 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -74,7 +74,12 @@ import { type LiveSubscription, } from "./live"; import { subscribeBrokerTraffic } from "./broker-live"; -import { NIP01_PREFIX, PublishNotSent, PublishRejected } from "./outbox"; +import { + KEPT_PREFIXES, + NIP01_PREFIX, + PublishNotSent, + PublishRejected, +} from "./outbox"; import { httpReadError, ReadError } from "./errors"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; import type { EventTemplate, VerifiedEvent } from "nostr-tools"; @@ -1750,8 +1755,6 @@ export async function acceptReadStatePublish(response: Response, id: string) { } const REFUSAL_STATUSES = [400, 401, 403, 404, 413, 422]; -/** Prefixes writers match on, so the text is shown as sent. */ -const KEPT_PREFIXES = new Set(["rate-limited", "conflict", "auth-required"]); /** The relay's own `{error}` text for a refused write. Admission otherwise * reduces every upstream body to a status summary, so a signed publish asks * it to keep this one, bounded by `readApiFailure`. A gateway or VPN edge From bfe545d2101845cfecb0c6162755d0346731375f Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:13 +1100 Subject: [PATCH 06/12] fix(channels): read lifecycle preflights and Hide recovery from the writer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to 86ff1bbbf3 (reread Settings' actions from the writer on Refresh channels), addressing the lifecycle findings of its second-pass review. The relay-refusal logic is unchanged. - channel-lifecycle: run()'s permission preflight for Archive, Unarchive, Delete, Leave and Hide now calls load() with strong reads, both before signing and before publishing. A "no longer permitted… Refresh channels" verdict came from a replica before, so after a refresh Settings (reading the writer) could offer Archive while the preflight, reading a replica that predated a re-promotion or a new owner-agent attestation, refused it again. The 39000/39001/39002 read and any owner-agent kind-0 reads go to the writer. This matches the member-administration and channel-write preflights in relay-queries.md. It costs two writer-routed loads per action. Join and auto-join checks are not permission preflights and keep ordinary routing. - channel-lifecycle: refreshVisibility() takes optional `{ consistency }`. A strong refresh reads 30622 from the writer. It does not join a replica-backed refresh in flight: it aborts that one and starts its own. An ordinary refresh started meanwhile joins the strong one. Ordinary refreshes are otherwise unchanged. - ChannelNavigationState: the failure toast records the failed action. After a failed Hide, Refresh channels also calls refreshVisibility(undefined, { consistency: "strong" }). An unconfirmed Hide is a ChannelLifecycleStale, so its toast offered Refresh channels, but refreshList does not read DM visibility. The button now checks whether the DM was actually hidden. Hide's copy is unchanged. - docs/relay-queries.md: the Read-your-writes list adds lifecycle permission preflights, the toast's writer-backed discovery pass, Settings' writer-routed lookups after a session's first refresh and the Hide visibility reread. The "stay replica-eligible" sentence now names the Channel actions menus and ordinary DM visibility refreshes. - docs/channels.md: the recovery paragraph describes the writer-read preflight and the Hide visibility reread. Tests: - channel-lifecycle: Archive runs and publishes when the replica predates the grant and the writer has it, for a direct role and for owner-agent evidence. An ordinary load still denies Archive. A strong visibility refresh aborts a replica-backed one in flight, reads 30622 with `consistency: "strong"`, is joined by a later ordinary request, and the replica's late empty answer does not unhide the DM. - ChannelNavigationState: after an unconfirmed Hide, Refresh channels calls the strong refreshList and the strong refreshVisibility. The archive case does not call refreshVisibility. lifecycleRefreshes goes back to 0 after a session replacement and after a scope-only community switch. - ChannelsPage.tabs, real session: the DM's hide reaches the writer but publish fails, so it is unconfirmed. The replica lacks the 30622. Refresh channels makes the session's visibility snapshot hide the DM. - Existing tests that assumed replica-routed preflights now expect strong preflight reads: confirms-while-replicas-lag (4 cases), exact coordinates and owner-agent profile reads (2). Confirmation-read holds now also wait for publication. The 39001 ChannelsPage test no longer edits the replica: only the writer has the demotion, so the preflight produces the toast by reading the writer. Without the change: with both production files at 0e74fa3b51, 13 of the 259 tests in channel-lifecycle, ChannelNavigationState and ChannelsPage.tabs fail. Reverting each piece on its own also fails: - preflight without strong: 10 (both new authorize cases, the 39001 ChannelsPage test, 4 confirms cases, exact coordinates, 2 owner-agent) - strong not passed to the visibility read: 2 (the strong refresh test, the ChannelsPage Hide test) - strong joining a replica refresh in flight: 1 - the replica refresh not aborted: 1 - the toast without the Hide reread: 2 (the ChannelNavigationState and ChannelsPage Hide tests) - the scope check dropped, or the counter carried across session replacement: 1 each The reset test passes at 0e74fa3b51 too: the reset already worked, and this test guards it. Checked: tsc --noEmit clean. biome check clean on the 5 touched source and test files. git diff --check clean. vitest, 10 files, 414 passed: channel-lifecycle 217, ChannelLifecycleActions 22, ChannelLifecycleMenu 36, ChannelNavigationState 13, ChannelSettingsPanel 32, ChannelsPage 10, ChannelsPage.tabs 29, ChannelsPage.solo 50, ChannelsPage.conversion 4, ChannelsPage.icon 1. The other refreshVisibility consumers (ChannelInventory, SearchResults, NewMessage.recovery, reauthorization): 7 files, 379 passed. tests/browser/channel-lifecycle.spec.mjs in Chromium (--no-deps): 10 passed. Without --no-deps the run stopped at an unrelated webkit-measurements failure in scroll.spec.mjs (cursor paging), and the lifecycle spec did not run. Not changed: the outbox's fixed workflow copy ("refresh the saved configuration") is still deferred. Co-Authored-By: Claude Opus 5.5 Signed-off-by: mtoohey Signed-off-by: Matt Toohey --- .../channels/ChannelsPage.tabs.test.tsx | 61 ++++++++++++ .../ChannelNavigationState.test.tsx | 76 ++++++++++++++- .../ChannelNavigationState.tsx | 8 ++ src/features/relay/channel-lifecycle.test.ts | 95 +++++++++++++++++-- src/features/relay/channel-lifecycle.ts | 75 +++++++++------ 5 files changed, 280 insertions(+), 35 deletions(-) diff --git a/src/bundled/channels/ChannelsPage.tabs.test.tsx b/src/bundled/channels/ChannelsPage.tabs.test.tsx index 67b0219c1c..e515da86ed 100644 --- a/src/bundled/channels/ChannelsPage.tabs.test.tsx +++ b/src/bundled/channels/ChannelsPage.tabs.test.tsx @@ -804,6 +804,67 @@ it("a refreshed roster that demotes the viewer retires Archive and Delete in Cha expect(publish).not.toHaveBeenCalled(); }); +it("Refresh channels after an unconfirmed Hide rereads DM visibility from the writer", async () => { + const viewer = keypair(), + authority = keypair(), + alice = keypair(); + const id = "22222222-2222-4222-8222-222222222222"; + const events = [ + signed(authority, { + kind: 39000, + content: "", + tags: [["d", id], ["t", "dm"], ["hidden"]], + }), + signed(authority, { kind: 39001, content: "", tags: [["d", id]] }), + roster(authority, id, [viewer.pubkey, alice.pubkey]), + ]; + const replica = [...events]; + // The relay hides the DM, but its reply is lost: the outcome is uncertain. + const publish = vi.fn(async () => { + events.push( + signed(authority, { + kind: 30622, + content: "", + tags: [ + ["d", viewer.pubkey], + ["p", viewer.pubkey], + ["h", id], + ], + }), + ); + throw new Error("Relay connection lost"); + }); + const { owner } = workspace(events, viewer, authority, { + lifecycle: publish, + handoff: true, + replica, + }); + await screen.findByRole("textbox", { name: /^Message / }); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "Channel actions" })); + await user.click( + await screen.findByRole("menuitem", { name: "Hide conversation" }), + ); + const confirm = await screen.findByRole("dialog", { + name: /^Hide conversation: /, + }); + await user.click( + within(confirm).getByRole("button", { name: "Hide conversation" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Hide conversation failed", + }); + expect(owner.session.channelLifecycle.snapshot().hidden).toEqual([]); + fireEvent.click( + within(toast).getByRole("button", { name: "Refresh channels" }), + ); + // Only the writer has the hide; the replica still predates it. + await vi.waitFor(() => + expect(owner.session.channelLifecycle.snapshot().hidden).toEqual([id]), + ); + expect(publish).toHaveBeenCalledOnce(); +}); + it("selects a default channel the relay adds after the page opened", async () => { const events: RelayEvent[] = []; const { owner, viewer, authority } = workspace(events); diff --git a/src/features/channel-navigation/ChannelNavigationState.test.tsx b/src/features/channel-navigation/ChannelNavigationState.test.tsx index c8fdc86182..4fdc48bb6c 100644 --- a/src/features/channel-navigation/ChannelNavigationState.test.tsx +++ b/src/features/channel-navigation/ChannelNavigationState.test.tsx @@ -16,7 +16,10 @@ import { ToastProvider } from "../../shared/design-system/ui/Toast"; import { ApiPaused } from "../relay/http-admission"; import type { RelayData, RelaySnapshot } from "../relay/service"; import type { RelaySession } from "../relay/session"; -import { ChannelLifecycleStale } from "../relay/channel-lifecycle"; +import { + ChannelLifecycleStale, + ChannelLifecycleUnconfirmed, +} from "../relay/channel-lifecycle"; import { PanelWorkspace } from "../panels/PanelWorkspace"; import { ChannelNavigationProvider, @@ -45,6 +48,7 @@ function fixture( return listed.list; }; const refreshList = vi.fn(); + const refreshVisibility = vi.fn(async () => {}); const session = () => ({ channels: { @@ -53,7 +57,7 @@ function fixture( refreshList, }, sidebarPreferences: { setMute: async () => [] }, - channelLifecycle: { run }, + channelLifecycle: { run, refreshVisibility }, }) as unknown as RelaySession; let snapshot: RelaySnapshot = { status: "ready", @@ -75,6 +79,7 @@ function fixture( return { relay, refreshList, + refreshVisibility, roster: (next: string[]) => { ids = next; }, @@ -86,6 +91,10 @@ function fixture( }; for (const listener of listeners) listener(); }, + switchScope(scope: string) { + snapshot = { ...snapshot, scope }; + for (const listener of listeners) listener(); + }, }; } function mount(relay: RelayData, toasts = false) { @@ -468,6 +477,7 @@ it("offers Refresh channels when a lifecycle action failed on stale state", asyn }); // Settings reads its channel actions again on each one. expect(view.result.current.lifecycleRefreshes).toBe(1); + expect(h.refreshVisibility).not.toHaveBeenCalled(); await waitFor(() => expect( screen.queryByRole("dialog", { name: "Archive channel failed" }), @@ -475,6 +485,68 @@ it("offers Refresh channels when a lifecycle action failed on stale state", asyn ); }); +it("also rereads DM visibility from the writer after an unconfirmed Hide", async () => { + const unconfirmed = new ChannelLifecycleUnconfirmed( + new Error("Relay connection lost"), + ); + const h = fixture(async () => { + throw unconfirmed; + }); + const view = mount(h.relay, true); + act(() => + view.result.current.openLifecycle({ id: "dm", name: "Alice" }, "hide"), + ); + fireEvent.click( + await screen.findByRole("button", { name: "Hide conversation" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Hide conversation failed", + }); + expect(toast).toHaveAccessibleDescription(unconfirmed.message); + fireEvent.click( + within(toast).getByRole("button", { name: "Refresh channels" }), + ); + expect(h.refreshList).toHaveBeenCalledExactlyOnceWith({ + consistency: "strong", + }); + // Whether the DM was hidden is in its visibility, not the channel list. + expect(h.refreshVisibility).toHaveBeenCalledExactlyOnceWith(undefined, { + consistency: "strong", + }); +}); + +it("resets lifecycle refreshes on session replacement and community switch", async () => { + const h = fixture(async () => { + throw new ChannelLifecycleStale("This action is no longer permitted."); + }); + const view = mount(h.relay, true); + const refresh = async () => { + act(() => + view.result.current.openLifecycle( + { id: "channel", name: "Channel" }, + "archive", + ), + ); + fireEvent.click( + await screen.findByRole("button", { name: "Archive channel" }), + ); + const toast = await screen.findByRole("dialog", { + name: "Archive channel failed", + }); + fireEvent.click( + within(toast).getByRole("button", { name: "Refresh channels" }), + ); + }; + await refresh(); + expect(view.result.current.lifecycleRefreshes).toBe(1); + act(() => h.replace()); + expect(view.result.current.lifecycleRefreshes).toBe(0); + await refresh(); + expect(view.result.current.lifecycleRefreshes).toBe(1); + act(() => h.switchScope("community:other")); + expect(view.result.current.lifecycleRefreshes).toBe(0); +}); + it("keeps other lifecycle failures' toasts to Dismiss", async () => { const h = fixture(async () => { throw new Error("Archive check unavailable. Try again."); diff --git a/src/features/channel-navigation/ChannelNavigationState.tsx b/src/features/channel-navigation/ChannelNavigationState.tsx index e340077f4c..dd3e3150dd 100644 --- a/src/features/channel-navigation/ChannelNavigationState.tsx +++ b/src/features/channel-navigation/ChannelNavigationState.tsx @@ -182,6 +182,7 @@ export function ChannelNavigationProvider({ title: string; message: string; refresh: boolean; + action: ChannelLifecycleAction | undefined; }>(); const activityThread = useRef(undefined); const activityAgent = useRef(undefined); @@ -489,6 +490,7 @@ export function ChannelNavigationProvider({ ? `${state.lifecycleDialog?.channel.name}: ${message}` : message, refresh, + action: state.lifecycleDialog?.action, }); endLifecycle(state.lifecycleDialog, unconfirmed); }} @@ -509,6 +511,12 @@ export function ChannelNavigationProvider({ connection.session.channels.refreshList?.({ consistency: "strong", }); + // Hide's effect is DM visibility, which the list does not read. + if (failure.action === "hide") + void connection.session.channelLifecycle.refreshVisibility( + undefined, + { consistency: "strong" }, + ); update((previous) => ({ ...previous, lifecycleRefreshes: previous.lifecycleRefreshes + 1, diff --git a/src/features/relay/channel-lifecycle.test.ts b/src/features/relay/channel-lifecycle.test.ts index c4ab334f57..2a120662c4 100644 --- a/src/features/relay/channel-lifecycle.test.ts +++ b/src/features/relay/channel-lifecycle.test.ts @@ -353,6 +353,41 @@ describe("bounded visibility recovery", () => { }, ); + it("a strong refresh reads the writer instead of joining a replica-backed one", async () => { + const h = harness("owner", "dm"); + h.setVisible([ + h.record(30622, [ + ["d", viewer], + ["p", viewer], + ["h", id], + ]), + ]); + // The replica-backed read predates the hide. + const replica = deferred(); + h.read.mockImplementationOnce(() => replica.promise); + const ordinary = h.owner.capability.refreshVisibility(); + await vi.advanceTimersByTimeAsync(0); + const strong = h.owner.capability.refreshVisibility(undefined, { + consistency: "strong", + }); + expect(strong).not.toBe(ordinary); + expect(h.read.mock.calls[0]?.[1]?.signal?.aborted).toBe(true); + // A later ordinary request joins the writer-backed refresh. + expect(h.owner.capability.refreshVisibility()).toBe(strong); + await strong; + expect(h.read.mock.calls.map(([filters]) => filters)).toEqual([ + [expect.not.objectContaining({ consistency: expect.anything() })], + [expect.objectContaining({ kinds: [30622], consistency: "strong" })], + ]); + replica.resolve([]); + await ordinary; + expect(h.owner.capability.snapshot()).toEqual({ + status: "ready", + hidden: [id], + }); + h.owner.dispose(); + }); + it.each(["caller", "cancel", "clear", "dispose"] as const)( "%s cancels backoff without a terminal error or another read", async (action) => { @@ -440,9 +475,9 @@ it.each(["archive", "delete", "leave", "hide"] as const)( await h.owner.capability.refreshVisibility(); expect(h.read.mock.calls[0]?.[0][0]).not.toHaveProperty("consistency"); await h.owner.capability.run(action, id); + // The permission preflight, before signing and before publishing. for (const [filters] of h.read.mock.calls.slice(1, 3)) - for (const filter of filters) - expect(filter).not.toHaveProperty("consistency"); + for (const filter of filters) expect(filter.consistency).toBe("strong"); expect(h.publish).toHaveBeenCalledOnce(); expect(h.read.mock.calls.at(-1)?.[0][0]?.consistency).toBe("strong"); if (action === "hide") @@ -689,6 +724,43 @@ it("rereads authority after signing; a removed admin cannot publish", async () = expect(h.publish).not.toHaveBeenCalled(); h.owner.dispose(); }); +it.each(["a direct role", "owner-agent evidence"] as const)( + "authorizes from the writer when a replica predates %s", + async (grant) => { + const h = + grant === "a direct role" ? harness("admin") : ownedAgent("member"); + const [metadata, , members] = h.getEvents(); + assert(metadata && members); + const replica = + grant === "a direct role" + ? [metadata, h.roles("member"), members] + : h.getEvents().filter((event) => event.kind !== 0); + const currentRead = h.read.getMockImplementation(); + assert(currentRead); + h.read.mockImplementation(async (filters, options) => + filters.every((filter) => filter.consistency === "strong") + ? currentRead(filters, options) + : replica.filter((event) => + filters.some( + (filter) => + filter.kinds?.includes(event.kind) && + filter.authors?.includes(event.pubkey), + ), + ), + ); + try { + // Ordinary reads, as Settings makes before a refresh, deny Archive. + expect(await h.owner.capability.load(id)).toMatchObject({ + canArchive: false, + }); + await h.owner.capability.run("archive", id); + expect(h.publish).toHaveBeenCalledOnce(); + expect(h.acceptDiscovery).toHaveBeenCalledOnce(); + } finally { + h.owner.dispose(); + } + }, +); it("fences access loss during signing and rejects a changed timestamp", async () => { const h = harness(); h.sign.mockImplementationOnce(async (event) => { @@ -1257,7 +1329,12 @@ it.each( assert(currentRead); let held = false; h.read.mockImplementation(async (filters, options) => { - if (held || !filters.every((filter) => filter.consistency === "strong")) + // The preflight also reads the writer; confirmation follows publication. + if ( + held || + !h.publish.mock.calls.length || + !filters.every((filter) => filter.consistency === "strong") + ) return currentRead(filters, options); held = true; started.resolve(); @@ -1319,7 +1396,10 @@ it.each(["after a macrotask", "without a macrotask"] as const)( let retired = 0; let unyielded = 0; h.read.mockImplementation(async (filters, options) => { - if (!filters.every((filter) => filter.consistency === "strong")) + if ( + !h.publish.mock.calls.length || + !filters.every((filter) => filter.consistency === "strong") + ) return currentRead(filters, options); retired++; // A reread that never yields starves the clock; fail it rather than @@ -1362,11 +1442,12 @@ it.each(["after a macrotask", "without a macrotask"] as const)( } }, ); -it("reads exact relay-owned coordinates fresh both before sign and before publish", async () => { +it("reads exact relay-owned coordinates fresh from the writer both before sign and before publish", async () => { const h = harness(); await h.owner.capability.run("delete", id); const expected = [39000, 39001, 39002].map((kind) => ({ kinds: [kind], + consistency: "strong", authors: [relayAuthor], "#d": [id], limit: 1, @@ -1461,7 +1542,9 @@ describe("channel owner-agent Archive and Delete eligibility", () => { ); expect(ownershipReads).toHaveLength(2); for (const [filters, options] of ownershipReads) { - expect(filters).toEqual([{ kinds: [0], authors: [other], limit: 1 }]); + expect(filters).toEqual([ + { kinds: [0], consistency: "strong", authors: [other], limit: 1 }, + ]); expect(options).toMatchObject({ fresh: true, priority: "foreground" }); } expect(h.removed).toHaveBeenCalledWith(id); diff --git a/src/features/relay/channel-lifecycle.ts b/src/features/relay/channel-lifecycle.ts index a61fc1545e..639d6a6456 100644 --- a/src/features/relay/channel-lifecycle.ts +++ b/src/features/relay/channel-lifecycle.ts @@ -46,6 +46,12 @@ export type DmVisibility = Readonly<{ hidden: readonly string[]; error?: string; }>; +export type RefreshVisibilityOptions = Readonly<{ + ifStale?: boolean; + trailing?: boolean; + strong?: boolean; + consistency?: ReadFilter["consistency"]; +}>; export interface ChannelLifecycleCapability { readonly available: boolean; load( @@ -69,11 +75,12 @@ export interface ChannelLifecycleCapability { /** `ifStale` lets a read that succeeded within `FRESH_FOR` answer, for * triggers that only suggest visibility may have changed. `trailing` needs * a read that starts after this call: repeated calls during a pending read - * share one more read after it. `strong` reads from the relay's writer, for - * a trigger that follows a relay write the read must see. */ + * share one more read after it. `strong` or `consistency: "strong"` reads + * the writer. An immediate strong refresh replaces a replica-backed one; + * a trailing strong refresh waits for it and reads the writer afterward. */ refreshVisibility( signal?: AbortSignal, - options?: { ifStale?: boolean; trailing?: boolean; strong?: boolean }, + options?: RefreshVisibilityOptions, ): Promise; observeRemoval(listener: (channelId: string) => void): () => void; } @@ -121,6 +128,7 @@ export function createChannelLifecycle({ let trailingStrong = false; // When this epoch's last visibility refresh succeeded. let refreshedAt: number | undefined; + let refreshStrong = false; const available = !!reader && !!writer; const emit = (next: DmVisibility) => { snapshot = Object.freeze(next); @@ -345,29 +353,37 @@ export function createChannelLifecycle({ }, refreshVisibility( caller?: AbortSignal, - options?: { ifStale?: boolean; trailing?: boolean; strong?: boolean }, + options?: RefreshVisibilityOptions, ) { if (!reader || closed || caller?.aborted) return Promise.resolve(); + const strong = + options?.strong === true || options?.consistency === "strong"; if (refresh && !refreshSignal?.aborted) { - if (!options?.trailing) return refresh; - // The pending read may predate this call. - if (options.strong) trailingStrong = true; - if (!trailing) { - const started = epoch; - const next: Promise = refresh.then(() => { - // A clear retired this read; its shared state is a newer one's. - if (trailing !== next || started !== epoch) return; - trailing = undefined; - const strong = trailingStrong; - trailingStrong = false; - return capability.refreshVisibility( - caller, - strong ? { strong } : undefined, - ); - }); - trailing = next; + // A replica-backed refresh can predate the write a strong one + // checks; retire it instead of joining it. + if (strong && !refreshStrong && !options?.trailing) + refreshController?.abort(); + else { + if (!options?.trailing) return refresh; + // The pending read may predate this call. + if (strong) trailingStrong = true; + if (!trailing) { + const started = epoch; + const next: Promise = refresh.then(() => { + // A clear retired this read; its shared state is a newer one's. + if (trailing !== next || started !== epoch) return; + trailing = undefined; + const strong = trailingStrong; + trailingStrong = false; + return capability.refreshVisibility( + caller, + strong ? { strong } : undefined, + ); + }); + trailing = next; + } + return trailing; } - return trailing; } if ( options?.ifStale && @@ -384,14 +400,15 @@ export function createChannelLifecycle({ ...(caller ? [caller] : []), ]); refreshSignal = signal; + refreshStrong = strong; emit({ status: "loading", hidden: snapshot.hidden }); // Exhausted errors omit `transient`, so session recovery cannot restart // them. A read retired by another channel's access change (`cancelled`) // retries within the same budget. const operation = retryRead( async () => { - await owned({ caller: signal }, (read) => - readVisibility(read, options?.strong), + await owned({ caller: signal }, (signal) => + readVisibility(signal, strong), ); if (started === epoch) refreshedAt = Date.now(); }, @@ -431,11 +448,11 @@ export function createChannelLifecycle({ options?: Pick, ) { const id = lifecycleChannelId(value); - const strong = options?.consistency === "strong"; + const strong = + options?.strong === true || options?.consistency === "strong"; return owned({ id, caller }, (signal) => retryRead( - () => - reread(signal, () => load(id, signal, "any", records, strong)), + () => reread(signal, () => load(id, signal, "any", records, strong)), signal, ), ); @@ -499,6 +516,8 @@ export function createChannelLifecycle({ if (action === "join") return joined(); if (action === "auto-join-on" || action === "auto-join-off") return flaggable(); + // Read the writer: a refusal that sends the viewer to Refresh + // channels must not come from a replica older than that refresh. const settings = await load( id, signal, @@ -507,6 +526,8 @@ export function createChannelLifecycle({ action === "delete" ? action : false, + undefined, + true, ); if (settings.deleteUnavailable) throw new Error( From 416f452e70bfc1706854cb2da7ac8269f03df029 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:14 +1100 Subject: [PATCH 07/12] fix(channels): show the relay's sign-in refusal on the starter channel switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses kalvinnchau's review comment on PR 2778 (PRRT_kwDOUVULN860dV2P, against 24cb6709e; still present at 5529a67db). When an owner or admin turned "Starter channel for new members" on or off and the HTTP publish came back 401 with `auth-required: authentication required`, the switch said "Only community owners and admins can change this." That prefix is kept for writers to match on, so relayRefusal returned undefined and the PublishRejected fell through to the permission copy. Before this branch the switch showed the raw `auth-required: authentication required`. - outbox: new authRefusal(error). For a sent PublishRejected whose `reason` starts with `auth-required:`, it returns the relay's words without the prefix and capitalized, clipped to the same 256 characters as relayRefusal. A 401 with NIP-FI's missing-evidence text now reads "Authentication required". That is the readable form transport's refusalMessage gives every non-kept prefix, and the same form this switch already shows for NIP-FI's 403 `restricted: authorization denied` ("Authorization denied"). The app has no shared copy for relay `auth-required:` refusals. The sign-in copy in CommunitySignIn maps native sign-in codes, and live-recovery and artifact-sync only classify the prefix. isRelayRefusal and relayRefusal are unchanged. - ChannelSettingsPanel AutoJoinSetting: tries authRefusal after relayRefusal. The permission copy now covers only rejections without relay words. The other relayRefusal callers don't have this problem. On an `auth-required:` refusal the emoji directory says "Failed to add emoji." and the workflow outbox keeps its fixed "Workflow command rejected…" copy. Neither claims a missing role, so both are unchanged. Tests: - ChannelSettingsPanel: the row that expected the permission copy for a kept prefix now expects "Authentication required" for the transport-shaped `auth-required: authentication required` refusal. With the authRefusal call removed from the panel, it fails with "Only community owners and admins can change this." - transport: a real 401 `auth-required: authentication required` through acceptPublish keeps its raw message and reason, is not a relayRefusal, and reads "Authentication required" from authRefusal. A 1000-character one is clipped to 256. - outbox: authRefusal returns nothing for an `auth-required:` refusal with no words, another relay refusal, or a write that was not sent. Checked: tsc --noEmit clean (exit 0). biome check clean on the 5 touched files. vitest for ChannelSettingsPanel, outbox and transport: 3 files, 155 tests passed. Not changed: a 409 conflict (client text, no reason) still shows the permission copy on this switch, as it did before this branch. `rate-limited:` and `conflict:` relay text don't reach this path with a reason: rate limits come back as 429, which isn't a kept refusal status, and 409 drops the relay text. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matt Toohey --- .../channels/ChannelSettingsPanel.test.tsx | 11 ++++++-- src/bundled/channels/ChannelSettingsPanel.tsx | 3 ++ src/features/relay/outbox.test.ts | 28 +++++++++++++++++++ src/features/relay/outbox.ts | 17 +++++++++++ src/features/relay/transport.test.ts | 13 +++++++++ 5 files changed, 69 insertions(+), 3 deletions(-) diff --git a/src/bundled/channels/ChannelSettingsPanel.test.tsx b/src/bundled/channels/ChannelSettingsPanel.test.tsx index 825a506d24..c83ff46b05 100644 --- a/src/bundled/channels/ChannelSettingsPanel.test.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.test.tsx @@ -654,10 +654,15 @@ it.each([ ), "Only community owners and admins can change this.", ], + // `auth-required:` stays prefixed for writers to match on; it refuses the + // sign-in, so an owner is not told they lack the role. [ - "the default reason for a machine prefix", - new PublishRejected("auth-required: sign in", "auth-required: sign in"), - "Only community owners and admins can change this.", + "the relay's sign-in refusal", + new PublishRejected( + "auth-required: authentication required", + "auth-required: authentication required", + ), + "Authentication required", ], [ "a retry for an unconfirmed outcome", diff --git a/src/bundled/channels/ChannelSettingsPanel.tsx b/src/bundled/channels/ChannelSettingsPanel.tsx index be7eef3ae9..44d21e0174 100644 --- a/src/bundled/channels/ChannelSettingsPanel.tsx +++ b/src/bundled/channels/ChannelSettingsPanel.tsx @@ -15,6 +15,7 @@ import { type ChannelLifecycleCapability, } from "../../features/relay/channel-lifecycle"; import { + authRefusal, PublishNotSent, PublishRejected, relayRefusal, @@ -355,6 +356,8 @@ function AutoJoinSetting({ error instanceof PublishNotSent ? "Not sent. Try again." : (relayRefusal(error) ?? + // A refused sign-in, which says nothing about the role. + authRefusal(error) ?? (error instanceof PublishRejected ? "Only community owners and admins can change this." : error instanceof Error diff --git a/src/features/relay/outbox.test.ts b/src/features/relay/outbox.test.ts index bc76e99de9..ebe5476db3 100644 --- a/src/features/relay/outbox.test.ts +++ b/src/features/relay/outbox.test.ts @@ -4,6 +4,7 @@ import { HELD_RETRY_REFUSED, PublishNotSent, PublishRejected, + authRefusal, createOutbox, isRelayRefusal, relayRefusal, @@ -1858,3 +1859,30 @@ it.each([ expect(isRelayRefusal(error)).toBe(refused); expect(relayRefusal(error)).toBe(refused ? error.message : undefined); }); +it.each([ + [ + "a refused sign-in", + new PublishRejected("auth-required: sign in", "auth-required: sign in"), + "Sign in", + ], + [ + "a sign-in refusal without words", + new PublishRejected("auth-required: ", "auth-required: "), + undefined, + ], + [ + "another relay refusal", + new PublishRejected("Bad tag", "invalid: bad tag"), + undefined, + ], + [ + "a write that was not sent", + new PublishNotSent("auth-required: sign in", "auth-required: sign in"), + undefined, + ], +])( + "shows the relay's sign-in words only for its sign-in refusal: %s", + (_, error, words) => { + expect(authRefusal(error)).toBe(words); + }, +); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index eabaebd0f8..d4f472b149 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -205,6 +205,23 @@ export function relayRefusal(error: unknown): string | undefined { return isRelayRefusal(error) ? clip(error.message) : undefined; } +/** The relay's words, without their prefix and clipped like relayRefusal, + * when it refuses the sign-in rather than the write: a sent `auth-required:` + * refusal. That prefix is kept for writers to match on, so it is never a + * relayRefusal. */ +export function authRefusal(error: unknown): string | undefined { + if (!(error instanceof PublishRejected) || error instanceof PublishNotSent) + return undefined; + const prefix = NIP01_PREFIX.exec(error.reason ?? ""); + const words = + prefix?.[1] === "auth-required" + ? error.reason?.slice(prefix[0].length).trim() + : undefined; + return words + ? clip(words.charAt(0).toUpperCase() + words.slice(1)) + : undefined; +} + export { browserOutboxStorage } from "./outbox-storage"; /** The desktop host's answer to a retry the relay would refuse as too old, * when the event cannot be read back. */ diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index 231999afa5..d892b07f63 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -11,6 +11,7 @@ import { READ_STATE_TIMESTAMP_REFUSAL, } from "./read-state-host"; import { + authRefusal, isRelayRefusal, PublishNotSent, PublishRejected, @@ -393,6 +394,18 @@ it("keeps a long refusal's whole reason but clips its display words", async () = expect(result).toMatchObject({ reason: error }); expect(relayRefusal(result)).toBe(`X${"x".repeat(255)}`); }); +it("reads a 401 sign-in refusal as the relay's words, clipped, never as a refusal of the write", async () => { + // NIP-FI's missing-evidence denial on an HTTP publish. + const error = "auth-required: authentication required"; + const result = await refusal(401, { error }); + expect(result).toMatchObject({ message: error, reason: error }); + expect(relayRefusal(result)).toBeUndefined(); + expect(authRefusal(result)).toBe("Authentication required"); + const long = await refusal(401, { + error: `auth-required: ${"x".repeat(1000)}`, + }); + expect(authRefusal(long)).toBe(`X${"x".repeat(255)}`); +}); it("keeps the conflict refusal and the raw reason for classifying writers", async () => { const conflict = await refusal(409, { error: "invalid: whatever" }); expect(conflict).toHaveProperty( From e314013aea6265a989c247c85c17e4d98039ca74 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 20 Nov 2026 11:05:14 +1100 Subject: [PATCH 08/12] fix(channels): keep focus in Settings when Refresh channels retires the action Addresses kalvinnchau's review comment on PR 2778 (PRRT_kwDOUVULN860dV2L, against 24cb6709e; still present at de63146db). An owner opened Channel settings, another owner demoted them, and they chose the Archive action Settings still offered. The "no longer permitted" toast then offered Refresh channels. Pressing Enter on it removed the focused button with no handoff, and the refresh then removed Archive and Delete. Focus ended on BODY, so the next Tab went to global chrome instead of the Settings pane. - ChannelNavigationState: the failure keeps the failed action's trigger and fallback. Refresh channels returns focus to the trigger, or to the fallback if the trigger is gone, the same way finalFocus does. It does this only when focus is still on the button or was lost, so it never pulls focus from somewhere else. The mute toast's buttons hand focus back to their row in the same way. - ChannelLifecycleActions: when a refresh or a live role change removes a focused Leave, Archive/Unarchive or Delete button, focus moves to the pane's fallback: the Settings-tab close control. A ref cleanup sees the focus before the button detaches. A microtask then moves it, but only if focus would otherwise sit on BODY. This is the pattern ActivityGroupActions uses for its retired Stop buttons. - ChannelLifecycleDialog: lifecycleFocusFallback holds the fallback lookup that openLifecycle used inline, so both owners share it. finalFocus uses the same focusOrigin helper as the toast. - docs/channels.md: one sentence on where focus goes after Refresh channels. Dismiss on this toast doesn't lose focus, so it is unchanged. Keyboard Dismiss returns focus to Archive both before and after this change. Sonner's fallback restores the element focused before the toast, and Dismiss doesn't refresh anything, so Archive stays. Tests: - ChannelsPage.tabs, real session: the demotion recovery test now focuses Refresh channels and presses Enter. A new `hold` option on the workspace fixture keeps the refresh read pending while the test checks that focus is back on Archive. After release, Leave replaces Archive and Delete, and focus settles on Close Channel settings tab. - ChannelLifecycleActions: a role change that removes a focused Archive moves focus to the pane's first button. If focus had moved to another control first, it stays there. Fail-before: - With all production files as at de63146db, the ChannelsPage test fails on the toHaveFocus check right after Enter. - With only the Refresh handoff removed, it fails at the same check. - With only the retirement handoff removed, it fails at the final check. A throwaway probe in that state showed focus settled on BODY. - In the ChannelLifecycleActions test, removing the refs fails the first half, and removing both focus guards fails the second. Checked: tsc --noEmit exits 0. biome check is clean on the 5 touched source and test files. git diff --check is clean. vitest, 8 files, 278 tests passed: ChannelsPage.tabs, ChannelLifecycleActions, ChannelNavigationState, ChannelLifecycleMenu, ChannelSettingsPanel, ChannelsPage, ChannelsPage.solo, ChannelInventory. tests/browser/channel-lifecycle.spec.mjs in Chromium (--no-deps): 10 passed. That spec has no demotion recovery journey, so it is a regression check only. Not checked: the reviewer's flow in a real Chromium or WebKit build. jsdom covers the focus logic but not each engine's focus fixup when a node is removed. Not changed: the unused lifecycleRefreshes counter. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matt Toohey --- .../channels/ChannelLifecycleActions.test.tsx | 29 ++++++++ .../channels/ChannelLifecycleActions.tsx | 28 +++++++- .../channels/ChannelLifecycleDialog.tsx | 12 ++++ .../channels/ChannelsPage.tabs.test.tsx | 66 ++++++++++++++----- .../ChannelNavigationState.tsx | 45 +++++++------ 5 files changed, 141 insertions(+), 39 deletions(-) diff --git a/src/bundled/channels/ChannelLifecycleActions.test.tsx b/src/bundled/channels/ChannelLifecycleActions.test.tsx index ce8814b44f..3d4eb6f8d9 100644 --- a/src/bundled/channels/ChannelLifecycleActions.test.tsx +++ b/src/bundled/channels/ChannelLifecycleActions.test.tsx @@ -121,6 +121,35 @@ it("replaces Archive with Unarchive when the live channel is archived", () => { screen.getByRole("button", { name: "Unarchive channel" }), ).toBeVisible(); }); +it("keeps focus in the pane when a role change retires the focused action, unless it moved", async () => { + const host = session(); + const pane = (role: ChannelSummary["viewerRole"]) => ( + <> + + + + ); + const view = render(pane("admin")); + screen.getByRole("button", { name: "Archive channel" }).focus(); + view.rerender(pane("member")); + expect(screen.queryByRole("button", { name: "Archive channel" })).toBeNull(); + await vi.waitFor(() => + expect(screen.getByRole("button", { name: "Settings tab" })).toHaveFocus(), + ); + view.rerender(pane("admin")); + screen.getByRole("button", { name: "Archive channel" }).focus(); + screen.getByRole("textbox", { name: "Elsewhere" }).focus(); + view.rerender(pane("member")); + await Promise.resolve(); + expect(screen.getByRole("textbox", { name: "Elsewhere" })).toHaveFocus(); +}); it("explains an unsupported host without a lookup or write", () => { const host = session(false); render( diff --git a/src/bundled/channels/ChannelLifecycleActions.tsx b/src/bundled/channels/ChannelLifecycleActions.tsx index e8e991c976..f545ba5e3b 100644 --- a/src/bundled/channels/ChannelLifecycleActions.tsx +++ b/src/bundled/channels/ChannelLifecycleActions.tsx @@ -1,3 +1,4 @@ +import { useCallback } from "react"; import type { ChannelSummary } from "../../features/relay/contracts"; import type { ChannelLifecycleAction } from "../../features/relay/channel-lifecycle-protocol"; import { Button } from "../../shared/design-system/ui/Button"; @@ -6,7 +7,10 @@ import { SignOutIcon, TrashIcon, } from "../../shared/design-system/icons"; -import type { LifecycleNoun } from "./ChannelLifecycleDialog"; +import { + lifecycleFocusFallback, + type LifecycleNoun, +} from "./ChannelLifecycleDialog"; import { useLifecycleOffer, type LifecycleSession } from "./useLifecycleOffer"; /** The archived footer uses the same live permissions as Settings. */ @@ -48,18 +52,37 @@ export function ChannelLifecycleActions({ noun?: LifecycleNoun; }) { const permissions = useLifecycleOffer(session, channel); + // A refreshed or live role can retire the focused action. Ref cleanup runs + // before its button detaches, while it still owns focus; keep focus in the + // pane unless something else took it meanwhile. + const retire = useCallback((node: HTMLButtonElement | null) => { + if (!node) return; + return () => { + const document = node.ownerDocument; + if (document.activeElement !== node) return; + const fallback = lifecycleFocusFallback(node); + queueMicrotask(() => { + if (!node.isConnected && document.activeElement === document.body) + fallback?.focus({ preventScroll: true }); + }); + }; + }, []); if (!session.channelLifecycle.available) return

Channel actions unavailable on this connection

; return ( <> {permissions?.canLeave && ( - )} {(permissions?.canArchive || permissions?.canUnarchive) && (