Skip to content

Commit f2595b8

Browse files
delkcGoose
andauthored
Add community leave and device removal settings (#954)
Signed-off-by: Clay Delk <[email protected]> Co-authored-by: Goose <[email protected]>
1 parent e2d3b3d commit f2595b8

14 files changed

Lines changed: 1141 additions & 79 deletions

‎src/app/App.tsx‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ import { AgentsContext } from "../features/agents/react";
77
import { ToastProvider } from "../shared/design-system/ui/Toast";
88
import { Button } from "../shared/design-system/ui/Button";
99
import { UpdateNotice } from "../features/updates/UpdateNotice";
10-
import { useEffect, useRef, useSyncExternalStore } from "react";
10+
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
1111
import { registerAppShortcuts } from "./shortcuts";
1212
import type { AppServices } from "./services";
1313
import { Settings } from "./Settings";
1414
import { SettingsSidebar } from "./SettingsSidebar";
1515
import { RecoveryScreen } from "./RecoveryScreen";
1616
import { PageView } from "../features/pages/PageView";
17-
import { useAppNavigation } from "./navigation";
17+
import { useAppNavigation, type PendingSettingsDeparture } from "./navigation";
1818
import { NavigationControls } from "./shell/NavigationControls";
1919
import { registerNavigationShortcuts } from "./shortcuts";
2020
import { AppShell } from "./shell/AppShell";
@@ -58,7 +58,10 @@ export function App({ services }: { services: AppServices }) {
5858
function ConnectedApp({ services }: { services: AppServices }) {
5959
const { plugins } = services;
6060
const startup = useSyncExternalStore(plugins.subscribe, plugins.startup);
61-
const route = useAppNavigation(services);
61+
const [departure, setDeparture] = useState<PendingSettingsDeparture | null>(
62+
null,
63+
);
64+
const route = useAppNavigation(services, departure);
6265
const launcher = usePanelLauncher(services.panels, startup === "ready");
6366
const client = useSyncExternalStore(
6467
services.communities.subscribe,
@@ -93,6 +96,15 @@ function ConnectedApp({ services }: { services: AppServices }) {
9396
document.getElementById("main-content")?.focus({ preventScroll: true });
9497
retryFocus.current = undefined;
9598
}, [restoring, settings, route.state.attempt]);
99+
useEffect(() => {
100+
if (
101+
departure &&
102+
(departure.attempt !== route.state.attempt ||
103+
departure.viewer !== client.viewer ||
104+
(client.selected !== null && client.selected !== departure.communityId))
105+
)
106+
setDeparture(null);
107+
}, [client.selected, client.viewer, departure, route.state.attempt]);
96108
const terminal =
97109
startup === "recovery" ||
98110
route.state.status === "failed" ||
@@ -297,6 +309,20 @@ function ConnectedApp({ services }: { services: AppServices }) {
297309
updates={services.updates}
298310
navigation={route.request}
299311
navigationPane
312+
onDeparturePending={(pending) => {
313+
const client = services.communities.snapshot();
314+
const attempt = route.state.attempt;
315+
if (pending && client.viewer && client.selected)
316+
setDeparture({
317+
attempt,
318+
viewer: client.viewer,
319+
communityId: client.selected,
320+
});
321+
else if (!pending)
322+
setDeparture((current) =>
323+
current?.attempt === attempt ? null : current,
324+
);
325+
}}
300326
onSection={(section) => {
301327
const client = services.communities.snapshot();
302328
void services.navigation.open({
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
// @vitest-environment jsdom
2+
import "@testing-library/jest-dom/vitest";
3+
import {
4+
act,
5+
cleanup,
6+
render,
7+
screen,
8+
waitFor,
9+
within,
10+
} from "@testing-library/react";
11+
import userEvent from "@testing-library/user-event";
12+
import { afterEach, expect, it, vi } from "vitest";
13+
import type { Communities } from "../features/communities/service";
14+
import { ToastProvider } from "../shared/design-system/ui/Toast";
15+
import { CommunityDepartureSettings } from "./CommunityDepartureSettings";
16+
17+
const api = vi.hoisted(() => ({ requestLeave: vi.fn() }));
18+
vi.mock("../features/communities/api", async (actual) => ({
19+
...(await actual<typeof import("../features/communities/api")>()),
20+
requestLeave: api.requestLeave,
21+
}));
22+
23+
const community = { id: "https://acme.example", name: "Acme" };
24+
function harness() {
25+
let selected: string | null = community.id;
26+
const leave = vi.fn(async () => {
27+
selected = null;
28+
return [];
29+
});
30+
return {
31+
communities: {
32+
snapshot: () => ({ selected, memberships: [community] }),
33+
leave,
34+
} as unknown as Communities,
35+
leave,
36+
};
37+
}
38+
39+
function setup() {
40+
const owner = harness();
41+
const onRemoved = vi.fn();
42+
const view = render(
43+
<ToastProvider>
44+
<CommunityDepartureSettings
45+
communities={owner.communities}
46+
community={community}
47+
onRemoved={onRemoved}
48+
/>
49+
</ToastProvider>,
50+
);
51+
return { ...owner, ...view, onRemoved, user: userEvent.setup() };
52+
}
53+
54+
afterEach(() => {
55+
cleanup();
56+
api.requestLeave.mockReset();
57+
});
58+
59+
it("removes the community from this device without contacting the relay", async () => {
60+
const { user, leave, onRemoved } = setup();
61+
await user.click(
62+
screen.getByRole("button", { name: "Remove from this device" }),
63+
);
64+
const dialog = screen.getByRole("alertdialog", {
65+
name: "Remove Acme from this device?",
66+
});
67+
expect(dialog).toHaveTextContent(
68+
"The community connection and any saved drafts or data will be removed from Buzz on this device.",
69+
);
70+
await user.click(
71+
within(dialog).getByRole("button", { name: "Remove from this device" }),
72+
);
73+
await screen.findByText(
74+
"Acme was removed from this device. Your membership wasn’t changed. You can add it again later.",
75+
);
76+
expect(api.requestLeave).not.toHaveBeenCalled();
77+
expect(leave).toHaveBeenCalledWith(community.id, { purge: true });
78+
expect(onRemoved).toHaveBeenCalledOnce();
79+
});
80+
81+
it("leaves through the relay before removing the local community", async () => {
82+
api.requestLeave.mockResolvedValue("left");
83+
const { user, leave, onRemoved } = setup();
84+
const [openLeave] = screen.getAllByRole("button", {
85+
name: "Leave community",
86+
});
87+
expect(openLeave).toBeDefined();
88+
if (!openLeave) throw new Error("Leave action is missing");
89+
await user.click(openLeave);
90+
const dialog = screen.getByRole("alertdialog", { name: "Leave Acme?" });
91+
await user.click(
92+
within(dialog).getByRole("button", { name: "Leave community" }),
93+
);
94+
await screen.findByText("Left Acme.");
95+
expect(api.requestLeave).toHaveBeenCalledWith(community.id);
96+
expect(leave).toHaveBeenCalledWith(community.id, { purge: true });
97+
expect(api.requestLeave.mock.invocationCallOrder[0]).toBeLessThan(
98+
leave.mock.invocationCallOrder[0] ?? 0,
99+
);
100+
expect(onRemoved).toHaveBeenCalledOnce();
101+
});
102+
103+
it("keeps both actions available after a relay refusal", async () => {
104+
api.requestLeave.mockRejectedValue(
105+
new Error("invalid: relay owner cannot leave"),
106+
);
107+
const { user, leave, onRemoved } = setup();
108+
const [openLeave] = screen.getAllByRole("button", {
109+
name: "Leave community",
110+
});
111+
expect(openLeave).toBeDefined();
112+
if (!openLeave) throw new Error("Leave action is missing");
113+
await user.click(openLeave);
114+
await user.click(
115+
within(screen.getByRole("alertdialog")).getByRole("button", {
116+
name: "Leave community",
117+
}),
118+
);
119+
await screen.findByText("The relay owner can’t leave Acme.");
120+
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
121+
expect(leave).not.toHaveBeenCalled();
122+
expect(onRemoved).not.toHaveBeenCalled();
123+
expect(
124+
screen.getByRole("button", { name: "Remove from this device" }),
125+
).toBeEnabled();
126+
});
127+
128+
function deferred<T>() {
129+
let resolve!: (value: T) => void;
130+
let reject!: (reason: unknown) => void;
131+
const promise = new Promise<T>((yes, no) => {
132+
resolve = yes;
133+
reject = no;
134+
});
135+
return { promise, resolve, reject };
136+
}
137+
138+
it("locks confirmation while departure is pending and recovers after failure", async () => {
139+
const request = deferred<string>();
140+
api.requestLeave.mockReturnValue(request.promise);
141+
const { user, leave, onRemoved } = setup();
142+
await user.click(screen.getByRole("button", { name: "Leave community" }));
143+
const dialog = screen.getByRole("alertdialog");
144+
try {
145+
await user.click(
146+
within(dialog).getByRole("button", {
147+
name: "Leave community",
148+
}),
149+
);
150+
await waitFor(() => expect(api.requestLeave).toHaveBeenCalledOnce());
151+
expect(
152+
within(dialog).getByRole("button", { name: "Cancel" }),
153+
).toBeDisabled();
154+
await user.keyboard("{Escape}");
155+
expect(dialog).toBeVisible();
156+
expect(leave).not.toHaveBeenCalled();
157+
} finally {
158+
await act(async () => request.reject(new Error("offline")));
159+
}
160+
await screen.findByText(
161+
"Couldn’t leave Acme. Check your connection and try again.",
162+
);
163+
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
164+
expect(screen.getByRole("button", { name: "Leave community" })).toBeEnabled();
165+
expect(onRemoved).not.toHaveBeenCalled();
166+
});
167+
168+
it("does not navigate a replacement surface after an in-flight departure", async () => {
169+
const request = deferred<string>();
170+
api.requestLeave.mockReturnValue(request.promise);
171+
const { user, leave, onRemoved, unmount } = setup();
172+
await user.click(screen.getByRole("button", { name: "Leave community" }));
173+
await user.click(
174+
within(screen.getByRole("alertdialog")).getByRole("button", {
175+
name: "Leave community",
176+
}),
177+
);
178+
await waitFor(() => expect(api.requestLeave).toHaveBeenCalledOnce());
179+
unmount();
180+
await act(async () => request.resolve("left"));
181+
expect(leave).toHaveBeenCalledWith(community.id, { purge: true });
182+
expect(onRemoved).not.toHaveBeenCalled();
183+
});
184+
185+
it("cancels without removing local state or contacting the relay", async () => {
186+
const { user, leave, onRemoved } = setup();
187+
await user.click(
188+
screen.getByRole("button", { name: "Remove from this device" }),
189+
);
190+
await user.click(
191+
within(screen.getByRole("alertdialog")).getByRole("button", {
192+
name: "Cancel",
193+
}),
194+
);
195+
expect(screen.queryByRole("alertdialog")).toBeNull();
196+
expect(api.requestLeave).not.toHaveBeenCalled();
197+
expect(leave).not.toHaveBeenCalled();
198+
expect(onRemoved).not.toHaveBeenCalled();
199+
});
200+
201+
it.each(["relay", "device"])(
202+
"reports a %s failure after the departure page unmounts",
203+
async (phase) => {
204+
const request = deferred<string>();
205+
api.requestLeave.mockReturnValue(request.promise);
206+
const { user, leave, onRemoved, rerender } = setup();
207+
if (phase === "device")
208+
leave.mockRejectedValueOnce(new Error("storage unavailable"));
209+
await user.click(screen.getByRole("button", { name: "Leave community" }));
210+
await user.click(
211+
within(screen.getByRole("alertdialog")).getByRole("button", {
212+
name: "Leave community",
213+
}),
214+
);
215+
await waitFor(() => expect(api.requestLeave).toHaveBeenCalledOnce());
216+
// Navigation retires the page, not the app-owned toast provider.
217+
rerender(
218+
<ToastProvider>
219+
<p>Replacement destination</p>
220+
</ToastProvider>,
221+
);
222+
await act(async () => {
223+
if (phase === "relay") request.reject(new Error("offline"));
224+
else request.resolve("left");
225+
});
226+
await screen.findByText(
227+
phase === "relay"
228+
? "Couldn’t leave Acme. Check your connection and try again."
229+
: "Left Acme, but this device couldn’t finish cleaning up (storage unavailable). Leave it again to finish.",
230+
);
231+
expect(screen.getByText("Replacement destination")).toBeVisible();
232+
expect(onRemoved).not.toHaveBeenCalled();
233+
if (phase === "relay") expect(leave).not.toHaveBeenCalled();
234+
else expect(leave).toHaveBeenCalledWith(community.id, { purge: true });
235+
},
236+
);

0 commit comments

Comments
 (0)