Skip to content

Commit ac3315b

Browse files
matt2eclaude
andcommitted
fix(communities): settle leave edges after the relay has answered
Follow-up to Leave community in the rail menu (ca92ffe), addressing the review's three warnings and three suggestions. - A relay that answers "blocked: you are banned from this community" has already severed access at authentication, before any leave handler runs, so no retry could ever succeed. `requestLeave` now resolves it as `access-revoked` alongside `already-absent` (both via a new `settledRefusal()` in the shared protocol module), and the rail removes the community from this device with an informational toast saying access was revoked, instead of keeping a membership the viewer could never remove. - Failures before and after the relay accepted the leave read differently. A pre-publish failure keeps the connection-oriented retry message. Once `requestLeave` has resolved, a failing `communities.leave` reports that the community was left but this device couldn't finish cleaning up, and that leaving it again finishes (through the not-a-member answer). To keep that promise accurate, the service's required save is now the only step that throws, before anything changes; a session that will not dispose is reported rather than thrown, since the membership is already gone by then. - When the left community was the selected one, the rail routes the fallback to Personal space through the host's `onSelect` callback after the service has updated the store, so the leave gets the same channels navigation and ingress-recovery check as clicking Personal space and the viewer is not left on a Settings card scoped to a gone community. - After leaving an inactive community, focus follows the selection: the still-selected community's button, or Personal space only where a left selection actually landed. Focus still returns to the community itself after a cancel or a failure that kept it. - Purge failures are no longer discarded. `purgeCommunityDeviceState` names each store, logs every failure with `console.warn` including the store and origin, and `communities.leave` returns the list so the rail appends "Some saved data couldn't be cleared." to the success toast when any occurred. - Removing a session scope guards the `indexOf` result, so a miss can never splice another community's scope off the teardown list. Tests: the rail test gains the banned answer in the settled-refusal table, a post-publish device failure that shows the cleanup message and not the connection one, host selection of Personal space for a left selection (and none for an inactive one), the residual-data toast line, and the inactive-leave case now expects focus on the still-selected community. The device-state and service tests assert the named, console-warned failures; the native adapter test covers the banned classification. Each new or adjusted test was checked to fail against the previous sources. The communities and shell docs describe the settled answers, the two failure messages, the host-routed fallback and focus placement. Typecheck, lint and the full unit suite (421 files, 5132 tests) pass. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent ca92ffe commit ac3315b

11 files changed

Lines changed: 360 additions & 85 deletions

‎docs/communities.md‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,17 @@ owns or administers the selected community and this build can mint invites. Copy
7777
Community settings and Leave work on inactive communities without opening their
7878
sessions. Leave asks for confirmation, then sends a signed NIP-43 leave request
7979
(kind 28936) to that community's relay before the device forgets it: the relay
80-
accepting, or answering that the viewer is not a member, removes the community
81-
here and clears its drafts, reading positions and other device state; any other
82-
refusal or an unreachable relay keeps the membership and reports the failure so
83-
Leave can be tried again. A left community that was selected lands on Personal
84-
space. Messages shows an intentional
80+
accepting, answering that the viewer is not a member, or answering that the
81+
viewer is banned (access is already severed, so no retry could do more) removes
82+
the community here and clears its drafts, reading positions and other device
83+
state; any other refusal or an unreachable relay keeps the membership and
84+
reports the failure so Leave can be tried again. Once the relay has answered,
85+
only this device can still fail: a device record that will not save keeps the
86+
community in the rail and says so, and leaving it again finishes through the
87+
not-a-member answer; a store that will not clear is logged by name and the
88+
success notice says some saved data remains. A left community that was selected
89+
lands on Personal space through the host's selection path, exactly as clicking
90+
Personal space would. Messages shows an intentional
8591
empty state there. Try drafting in A, switching to B, then returning to A.
8692
Selected channels, drafts and reading offsets are partitioned by the canonical
8793
community origin and viewer; channel IDs alone are not sufficient keys.
@@ -199,12 +205,16 @@ backup; same-origin plugin JavaScript is trusted and can invoke that IPC too.
199205
`src/features/communities/service.test.ts` covers no-community initialization,
200206
local profiles, scoped view intent, session retention, selective restoration and
201207
leaving (membership removal, Personal space fallback, session disposal, purged
202-
device state and the last community). `CommunityRail.test.tsx` covers the leave
203-
flow end to end against the broker route: confirm, publish, then remove; cancel;
204-
refusals and timeouts that keep the membership; the already-absent answer; the
205-
in-flight state; and that no inactive session is acquired. `device-state.test.ts`
206-
covers the per-origin purge. The broker and native adapter tests sign the exact
207-
leave shape and pass through only the relay's known refusals.
208+
device state, the last community and a purge that leaves named failures).
209+
`CommunityRail.test.tsx` covers the leave flow end to end against the broker
210+
route: confirm, publish, then remove; cancel; refusals and timeouts that keep the
211+
membership; the not-a-member and banned answers; a device record that will not
212+
save after the relay answered; residual saved data; the host selection of
213+
Personal space for a left selection; focus placement; the in-flight state; and
214+
that no inactive session is acquired. `device-state.test.ts` covers the
215+
per-origin purge and its per-store failure report. The broker and native adapter
216+
tests sign the exact leave shape and pass through only the relay's known
217+
refusals.
208218
`broker.test.ts` runs real localhost HTTP with signed fixture events to verify
209219
multi-community routing, profile publication, invite claims, and a captured send
210220
after opening another community. `destination.test.ts` checks normalization and

‎docs/shell-design.md‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,19 @@ dialog owned by the rail (“Leave <name>?”) whose destructive confirm shows a
132132
pending state while the request runs; the menu item itself is disabled and reads
133133
“Leaving…” for that community until the relay answers. The rail publishes the
134134
NIP-43 leave request to the community's relay by origin, then asks the
135-
communities service to forget it; the relay's acceptance or its "not a member"
136-
answer removes the community and reports through the toast stack, while any
137-
other failure keeps the membership and reports the reason. Focus returns to the
138-
community when it is still saved and to Personal space once it is gone. Closing
139-
a menu opened from the keyboard returns focus to
135+
communities service to forget it; the relay's acceptance, its "not a member"
136+
answer or its banned answer removes the community and reports through the toast
137+
stack, while any other refusal or an unreachable relay keeps the membership and
138+
reports the reason. A failure after the relay has answered is the device's own
139+
and reads that way: the community was left but this device could not finish
140+
cleaning up, and leaving it again finishes. Saved data the purge could not clear
141+
is logged by store and adds a line to the success notice. When the left
142+
community was selected, the rail routes the fallback to Personal space through
143+
the host's selection callback so navigation and ingress recovery match a click
144+
on Personal space, rather than leaving a page scoped to a gone community. Focus
145+
returns to the community when it is still saved; once it is gone, focus follows
146+
the selection, to the still-selected community or to Personal space where a
147+
left selection now lands. Closing a menu opened from the keyboard returns focus to
140148
that community; closing one opened by pointer restores whatever had focus
141149
before, so a right-click while typing does not move the caret to the rail.
142150
Opening a menu or running any item never acquires an inactive session, and the

‎src/features/communities/CommunityRail.test.tsx‎

Lines changed: 132 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type { UnreadCapability } from "../relay/unread";
1818
import { ToastProvider } from "../../shared/design-system/ui/Toast";
1919
import { CommunityRail } from "./CommunityRail";
2020
import { INVITES_SECTION } from "./CommunityRailItem";
21+
import type { PurgeFailure } from "./device-state";
2122
import { MEMBERSHIP_KIND, type Role } from "./roster";
2223
import {
2324
createCommunities,
@@ -53,6 +54,10 @@ function harness({
5354
: never,
5455
/** What the community's relay answers to the broker leave route. */
5556
leaveResponse = accepted as () => Response | Promise<Response>,
57+
/** Stores the service could not clear after forgetting the community. */
58+
leaveResidue = [] as PurgeFailure[],
59+
/** The service's own failure to save the device record, before it changes. */
60+
leaveError = undefined as Error | undefined,
5661
} = {}) {
5762
let snapshot: ClientSnapshot = {
5863
status: "ready",
@@ -74,14 +79,17 @@ function harness({
7479
notify();
7580
});
7681
// Mirrors the service: the membership goes, and a left selection lands on
77-
// Personal space without the rail selecting anything.
82+
// Personal space without the rail selecting anything. Only the save can
83+
// throw, and it does so before anything changes.
7884
const leave = vi.fn(async (id: string) => {
85+
if (leaveError) throw leaveError;
7986
snapshot = {
8087
...snapshot,
8188
memberships: snapshot.memberships.filter((m) => m.id !== id),
8289
selected: snapshot.selected === id ? null : snapshot.selected,
8390
};
8491
notify();
92+
return leaveResidue;
8593
});
8694
const read = vi.fn(async () => [
8795
{
@@ -136,6 +144,8 @@ function harness({
136144
});
137145
vi.stubGlobal("fetch", fetch);
138146
const onOpenTarget = vi.fn();
147+
// The host's selection path: selects through the service, then navigates.
148+
const onSelect = vi.fn((id: string | null) => select(id));
139149
return {
140150
communities,
141151
select,
@@ -144,6 +154,7 @@ function harness({
144154
fetch,
145155
markAllChannelsRead,
146156
onOpenTarget,
157+
onSelect,
147158
leaveRequests: () =>
148159
fetch.mock.calls
149160
.map(([url]) => String(url))
@@ -547,12 +558,61 @@ it("leaves an inactive community after confirming: the relay releases it before
547558
expect(sessionRequests(h.fetch)).toEqual([]);
548559
expect(h.read).not.toHaveBeenCalled();
549560
expect(h.select).not.toHaveBeenCalled();
561+
expect(h.onSelect).not.toHaveBeenCalled();
550562
expect(button("Primary")).toHaveAttribute("aria-current", "true");
551-
await waitFor(() =>
552-
expect(
553-
screen.getByRole("button", { name: "Personal space" }),
554-
).toHaveFocus(),
563+
// Focus follows the selection, which stayed put; Personal space is only
564+
// right when a left selection actually landed there.
565+
await waitFor(() => expect(button("Primary")).toHaveFocus());
566+
expect(
567+
screen.getByRole("button", { name: "Personal space" }),
568+
).not.toHaveFocus();
569+
});
570+
571+
it("leaving the selected community tells the host to select Personal space; an inactive one does not", async () => {
572+
const user = userEvent.setup();
573+
const h = harness();
574+
render(<CommunityRail communities={h.communities} onSelect={h.onSelect} />);
575+
let dialog = await askToLeave(user, "Primary");
576+
await user.click(confirmLeave(dialog));
577+
await screen.findByText("Left Primary.");
578+
// The service owns the store state; the host adds the navigation and ingress
579+
// recovery that clicking Personal space would, so a Settings card scoped to
580+
// the gone community is not left open.
581+
expect(h.leave).toHaveBeenCalledWith(primary);
582+
expect(h.onSelect).toHaveBeenCalledTimes(1);
583+
expect(h.onSelect).toHaveBeenCalledWith(null);
584+
expect(h.leave.mock.invocationCallOrder[0]).toBeLessThan(
585+
h.onSelect.mock.invocationCallOrder[0] ?? 0,
555586
);
587+
const personal = screen.getByRole("button", { name: "Personal space" });
588+
expect(personal).toHaveAttribute("aria-current", "true");
589+
await waitFor(() => expect(personal).toHaveFocus());
590+
591+
h.update({ selected: secondary });
592+
dialog = await askToLeave(user, "Secondary");
593+
await user.click(confirmLeave(dialog));
594+
await screen.findByText("Left Secondary.");
595+
expect(h.onSelect).toHaveBeenCalledTimes(2);
596+
expect(h.onSelect).toHaveBeenLastCalledWith(null);
597+
598+
// Leaving a community that is not selected changes nothing about selection.
599+
h.update({
600+
memberships: [
601+
{ id: primary, name: "Primary" },
602+
{ id: secondary, name: "Secondary" },
603+
],
604+
selected: primary,
605+
});
606+
dialog = await askToLeave(user, "Secondary");
607+
await user.click(confirmLeave(dialog));
608+
// The earlier "Left Secondary." toast is still showing, so wait on the
609+
// leave itself rather than on a second copy of the same text.
610+
await waitFor(() => expect(h.leave).toHaveBeenCalledTimes(3));
611+
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
612+
expect(await screen.findAllByText("Left Secondary.")).toHaveLength(2);
613+
expect(h.onSelect).toHaveBeenCalledTimes(2);
614+
expect(button("Primary")).toHaveAttribute("aria-current", "true");
615+
await waitFor(() => expect(button("Primary")).toHaveFocus());
556616
});
557617

558618
it("cancelling the confirmation keeps the membership and returns focus to the community", async () => {
@@ -628,28 +688,87 @@ it.each([
628688
},
629689
);
630690

691+
const absent =
692+
"You were no longer a member of Secondary, so it was removed from this device.";
631693
it.each([
632-
"invalid: you are not a relay member",
633-
"invalid: relay membership is not enabled",
634-
])("forgets a community whose relay answers %j and says so", async (error) => {
694+
{ error: "invalid: you are not a relay member", toast: absent },
695+
{ error: "invalid: relay membership is not enabled", toast: absent },
696+
{
697+
// The relay refuses a banned identity before any leave handler runs, so
698+
// there is nothing a retry could achieve: access is already severed.
699+
error: "blocked: you are banned from this community",
700+
toast:
701+
"Your access to Secondary was revoked, so it was removed from this device.",
702+
},
703+
])(
704+
"forgets a community whose relay answers $error and says so",
705+
async ({ error, toast }) => {
706+
const user = userEvent.setup();
707+
const h = harness({
708+
leaveResponse: () => Response.json({ error }, { status: 400 }),
709+
});
710+
render(<CommunityRail communities={h.communities} />);
711+
const dialog = await askToLeave(user, "Secondary");
712+
await user.click(confirmLeave(dialog));
713+
const notice = await screen.findByText(toast);
714+
expect(notice.closest(".buzz-toast")).not.toBeNull();
715+
expect(notice.closest(".buzz-toast")).toHaveAttribute("data-type", "info");
716+
expect(h.leave).toHaveBeenCalledWith(secondary);
717+
await waitFor(() =>
718+
expect(
719+
screen.queryByRole("button", { name: "Switch to Secondary" }),
720+
).toBeNull(),
721+
);
722+
expect(sessionRequests(h.fetch)).toEqual([]);
723+
},
724+
);
725+
726+
it("reports a device that could not finish forgetting a left community without blaming the connection", async () => {
635727
const user = userEvent.setup();
636728
const h = harness({
637-
leaveResponse: () => Response.json({ error }, { status: 400 }),
729+
leaveError: new Error(
730+
"Could not save this community on this device. Try again.",
731+
),
638732
});
639-
render(<CommunityRail communities={h.communities} />);
733+
render(<CommunityRail communities={h.communities} onSelect={h.onSelect} />);
640734
const dialog = await askToLeave(user, "Secondary");
641735
await user.click(confirmLeave(dialog));
642736
const notice = await screen.findByText(
643-
"You were no longer a member of Secondary, so it was removed from this device.",
737+
"Left Secondary, but this device couldn’t finish cleaning up. Leave it again to finish.",
644738
);
645-
expect(notice.closest(".buzz-toast")).not.toBeNull();
739+
expect(notice.closest(".buzz-toast")).toHaveAttribute("data-type", "error");
740+
expect(
741+
screen.queryByText(
742+
"Couldn’t leave Secondary. Check your connection and try again.",
743+
),
744+
).toBeNull();
745+
// The relay released the membership; only the device record failed, so the
746+
// community stays in the rail for the retry that reaches the absent path.
747+
expect(h.leaveRequests()).toHaveLength(1);
646748
expect(h.leave).toHaveBeenCalledWith(secondary);
749+
expect(h.onSelect).not.toHaveBeenCalled();
750+
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
751+
expect(button("Secondary")).toBeInTheDocument();
752+
await waitFor(() => expect(button("Secondary")).toHaveFocus());
753+
});
754+
755+
it("says when some saved data outlived the purge", async () => {
756+
const user = userEvent.setup();
757+
const h = harness({
758+
leaveResidue: [{ store: "outbox", error: new Error("blocked") }],
759+
});
760+
render(<CommunityRail communities={h.communities} />);
761+
const dialog = await askToLeave(user, "Secondary");
762+
await user.click(confirmLeave(dialog));
763+
const notice = await screen.findByText(
764+
"Left Secondary. Some saved data couldn’t be cleared.",
765+
);
766+
expect(notice.closest(".buzz-toast")).toHaveAttribute("data-type", "success");
647767
await waitFor(() =>
648768
expect(
649769
screen.queryByRole("button", { name: "Switch to Secondary" }),
650770
).toBeNull(),
651771
);
652-
expect(sessionRequests(h.fetch)).toEqual([]);
653772
});
654773

655774
it("shows the leave in flight on the dialog and the menu item until the relay answers", async () => {

0 commit comments

Comments
 (0)