From 1beb46d29a98fa79f4d54e5461e2293a0ae7e500 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:41:41 +0530 Subject: [PATCH 01/13] fix(mailbox): reload mailboxes after an account switch bugs-mailbox-provider-no-refetch The provider's fetch effect ran once; on an account switch the reset handler set isLoading=true and never refetched, leaving the skeleton and an empty mailbox until a hard reload. No test: the fix lives in a React provider effect and the repo has no component test harness; verified by tsc and by tracing the reset path. Co-Authored-By: Claude Opus 5.5 --- src/components/mailbox-provider.tsx | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/components/mailbox-provider.tsx b/src/components/mailbox-provider.tsx index 8a16d0e86..b7e866ee5 100644 --- a/src/components/mailbox-provider.tsx +++ b/src/components/mailbox-provider.tsx @@ -5,6 +5,7 @@ import { useCallback, useContext, useEffect, + useRef, useState, } from "react"; import type { ReactNode } from "react"; @@ -20,6 +21,7 @@ import { } from "@/lib/auth/client"; import { PROFILE_NAME_CHANGED_EVENT } from "@/lib/profile/name-client"; import { PROFILE_AVATAR_CHANGED_EVENT } from "@/lib/profile/avatar-client"; +import type { AuthSessionChangedDetail } from "@/lib/auth/client-types"; import type { ProfileNameChangedDetail } from "@/lib/profile/types"; export type MailboxOption = { @@ -59,13 +61,16 @@ export function MailboxProvider({ children }: { children: ReactNode }) { const [selectedMailbox, setSelectedMailboxState] = useState(null); const [isLoading, setIsLoading] = useState(true); - useEffect(() => { - let cancelled = false; + const loadId = useRef(0); + + const loadMailboxes = useCallback(() => { + const id = ++loadId.current; const sessionToken = getClientSessionToken(); + const isCurrent = () => id === loadId.current && sessionToken === getClientSessionToken(); fetchMailboxOptions() .then((items) => { - if (cancelled || sessionToken !== getClientSessionToken()) return; + if (!isCurrent()) return; setMailboxes(items); const storedId = localStorage.getItem(SELECTED_MAILBOX_STORAGE_KEY); @@ -85,24 +90,32 @@ export function MailboxProvider({ children }: { children: ReactNode }) { }) .catch(() => {}) .finally(() => { - if (!cancelled && sessionToken === getClientSessionToken()) setIsLoading(false); + if (isCurrent()) setIsLoading(false); }); + }, []); + useEffect(() => { + loadMailboxes(); return () => { - cancelled = true; + // Invalidate any request still in flight. + loadId.current += 1; }; - }, []); + }, [loadMailboxes]); useEffect(() => { - function resetMailboxState() { + function resetMailboxState(event: Event) { setMailboxes([]); setSelectedMailboxState(null); setIsLoading(true); + // Signing out has no mailboxes to load. + if ((event as CustomEvent).detail?.authenticated === false) return; + // The provider outlives an account switch, so load the new account's mailboxes. + loadMailboxes(); } window.addEventListener(AUTH_SESSION_CHANGED_EVENT, resetMailboxState); return () => window.removeEventListener(AUTH_SESSION_CHANGED_EVENT, resetMailboxState); - }, []); + }, [loadMailboxes]); useEffect(() => { function updatePersonalMailboxNames(event: Event) { From 06e73d34f396f12936274b5d9e777a5e70359797 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:42:02 +0530 Subject: [PATCH 02/13] fix(drive): clear cached listings on session change bugs-drive-cache-not-cleared-on-session-change Sign-out or account switch does not reload the page, so /drive could render a stale cached listing. Clear it on AUTH_SESSION_CHANGED_EVENT like the other caches. Test: tests/drive-cache.test.mjs Co-Authored-By: Claude Opus 5.5 --- src/app/(drive)/drive-cache.ts | 6 ++++++ tests/drive-cache.test.mjs | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 tests/drive-cache.test.mjs diff --git a/src/app/(drive)/drive-cache.ts b/src/app/(drive)/drive-cache.ts index 4508e113b..0f1d29b54 100644 --- a/src/app/(drive)/drive-cache.ts +++ b/src/app/(drive)/drive-cache.ts @@ -1,3 +1,4 @@ +import { AUTH_SESSION_CHANGED_EVENT } from "@/lib/auth/client"; import type { DriveCrumb, DriveItemDto, DriveRole } from "@/lib/drive/types"; export type DriveListing = { items: DriveItemDto[]; path: DriveCrumb[]; role: DriveRole; storageUsed: number; storageLimit: number | null }; @@ -21,3 +22,8 @@ export function saveDriveListing(key: string, listing: DriveListing) { export function clearDriveListings() { listings.clear(); } + +// A listing belongs to the account that fetched it; sign-out and account switches do not reload the page. +if (typeof window !== "undefined") { + window.addEventListener(AUTH_SESSION_CHANGED_EVENT, clearDriveListings); +} diff --git a/tests/drive-cache.test.mjs b/tests/drive-cache.test.mjs new file mode 100644 index 000000000..625615a30 --- /dev/null +++ b/tests/drive-cache.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "drive-cache-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/app/(drive)/drive-cache.ts")], + outfile: join(directory, "drive-cache.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ + contents: `export const AUTH_SESSION_CHANGED_EVENT = "auth-changed";`, + loader: "js", + })); + } }], +}); +const cacheUrl = pathToFileURL(join(directory, "drive-cache.mjs")).href; + +test("drive listings are dropped when the session changes", async () => { + const dom = new JSDOM(""); + globalThis.window = dom.window; + try { + const cache = await import(`${cacheUrl}?run=${Math.random()}`); + const listing = { items: [{ id: "a" }], path: [], role: "owner", storageUsed: 1, storageLimit: null }; + cache.saveDriveListing("my|||", listing); + assert.equal(cache.readDriveListing("my|||"), listing); + window.dispatchEvent(new window.Event("auth-changed")); + assert.equal(cache.readDriveListing("my|||"), undefined); + } finally { + dom.window.close(); + delete globalThis.window; + } +}); From 984b4e06fa2de13b6eb285eff803a7aa102636c5 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:42:21 +0530 Subject: [PATCH 03/13] fix(messages): do not cache or paint error responses as a message list bugs-message-list-caches-error-response A JSON 4xx/5xx from /api/messages was cached as the list and blanked the open folder to 'no messages' on every remount. fetchMessageList now rejects non-OK responses without caching, and useMessages keeps the list already shown. Sidebar counts are unchanged: a failed counts request is not cached, and keeping the previous mailbox's counts after a mailbox switch would be wrong. Test: tests/message-list-cache.test.mjs Co-Authored-By: Claude Opus 5.5 --- src/hooks/use-messages.ts | 2 ++ src/hooks/utils.ts | 7 ++++- tests/message-list-cache.test.mjs | 47 +++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 tests/message-list-cache.test.mjs diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts index 484137341..4a931c602 100644 --- a/src/hooks/use-messages.ts +++ b/src/hooks/use-messages.ts @@ -46,6 +46,8 @@ export function useMessages( setLimit(data.limit ?? filters?.limit ?? 25); setOffset(data.offset ?? filters?.offset ?? 0); } + } catch { + // Keep the list already on screen when a refresh fails. } finally { if (!cancelled && currentRequest === requestNumber) setIsLoading(false); } diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index a5af295b4..7f907d43b 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -176,7 +176,12 @@ export async function fetchMessageList(params: URLSearchParams, force = false): if (!force && messageListRequests.has(key)) return messageListRequests.get(key) ?? {}; const requestGeneration = messageCacheGeneration; const request = authFetch(`/api/messages?${key}`) - .then((res) => res.json()) + .then(async (res) => { + const data = await res.json(); + // An error body is not a message list; do not cache it or paint it as an empty folder. + if (!res.ok) throw new Error((data as { error?: string }).error ?? "Could not load messages"); + return data; + }) .then((data) => { const response = data as MessageListResponse; if (requestGeneration === messageCacheGeneration) { diff --git a/tests/message-list-cache.test.mjs b/tests/message-list-cache.test.mjs new file mode 100644 index 000000000..79a5ca105 --- /dev/null +++ b/tests/message-list-cache.test.mjs @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "message-list-cache-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/hooks/utils.ts")], + outfile: join(directory, "utils.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ + contents: `export const AUTH_SESSION_CHANGED_EVENT = "auth-changed"; export function getClientSessionToken(){return null;} export function authFetch(...args){return globalThis.listFetch(...args);}`, + loader: "js", + })); + } }], +}); +const utilsUrl = pathToFileURL(join(directory, "utils.mjs")).href; + +async function setup() { + const dom = new JSDOM(""); + globalThis.window = dom.window; + return { dom, utils: await import(`${utilsUrl}?run=${Math.random()}`) }; +} +function cleanup(dom) { + dom.window.close(); + delete globalThis.window; + delete globalThis.listFetch; +} + +test("an error response is rejected and not cached as a message list", async () => { + const { dom, utils } = await setup(); + try { + const params = new URLSearchParams("folder=inbox"); + globalThis.listFetch = async () => ({ ok: false, status: 404, json: async () => ({ error: "Mailbox not found" }) }); + await assert.rejects(utils.fetchMessageList(params), /Mailbox not found/); + assert.equal(utils.peekMessageList(params), undefined); + globalThis.listFetch = async () => ({ ok: true, status: 200, json: async () => ({ messages: [{ id: "m1" }], total: 1 }) }); + assert.equal((await utils.fetchMessageList(params)).total, 1); + assert.equal(utils.peekMessageList(params).total, 1); + } finally { cleanup(dom); } +}); From 93e8bbdd6b1d1e059ff829fc734b4c3842dbd04e Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:44:05 +0530 Subject: [PATCH 04/13] fix(settings): saving the recovery email no longer rewrites the profile name bugs-profile-recovery-stale-name The recovery form re-sent the name loaded when the page opened, so renaming and then saving the recovery email reverted the name (user, primary mailbox, self contacts). name is now optional on PATCH /api/settings/profile and the recovery save omits it. Test: tests/profile-schema.test.mjs Co-Authored-By: Claude Opus 5.5 --- src/app/api/settings/profile/route.ts | 14 +++++----- src/components/settings/account-settings.tsx | 1 - src/components/settings/profile-form.tsx | 7 +++-- src/components/settings/types.d.ts | 1 - src/lib/validators.ts | 3 ++- tests/profile-schema.test.mjs | 28 ++++++++++++++++++++ 6 files changed, 41 insertions(+), 13 deletions(-) create mode 100644 tests/profile-schema.test.mjs diff --git a/src/app/api/settings/profile/route.ts b/src/app/api/settings/profile/route.ts index 0e7350f42..61fa8b0a8 100644 --- a/src/app/api/settings/profile/route.ts +++ b/src/app/api/settings/profile/route.ts @@ -29,11 +29,13 @@ export async function PATCH(request: Request) { return NextResponse.json({ error: "A Pro or Team license is required for email forwarding" }, { status: 403 }); } const forwardingEmail = parsed.forwardingEmail === undefined ? user.forwardingEmail : parsed.forwardingEmail; - await syncPersonalIdentity(db, { - userId: user.id, - name: parsed.name, - avatarKey: user.avatarKey, - }); + if (parsed.name !== undefined) { + await syncPersonalIdentity(db, { + userId: user.id, + name: parsed.name, + avatarKey: user.avatarKey, + }); + } await db .update(users) .set({ resetEmail: parsed.resetEmail, forwardingEmail }) @@ -43,7 +45,7 @@ export async function PATCH(request: Request) { user: { id: user.id, email: user.email, - name: parsed.name, + name: parsed.name ?? user.name, resetEmail: parsed.resetEmail, forwardingEmail, canForwardEmail, diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsx index c0840aec5..c71470481 100644 --- a/src/components/settings/account-settings.tsx +++ b/src/components/settings/account-settings.tsx @@ -59,7 +59,6 @@ export function AccountSettings() {
diff --git a/src/components/settings/profile-form.tsx b/src/components/settings/profile-form.tsx index a4dce6616..95243e95d 100644 --- a/src/components/settings/profile-form.tsx +++ b/src/components/settings/profile-form.tsx @@ -14,7 +14,6 @@ import type { ProfileFormProps, ProfileFormResponse } from "./types"; import { getMailboxAddress, updateCurrentMailboxName } from "./utils"; export function ProfileForm({ - accountName, initialResetEmail, }: ProfileFormProps) { const { t } = useLanguage(); @@ -42,12 +41,12 @@ export function ProfileForm({ // account itself, so the recovery email applies to it alone. const isPrimary = !!selectedMailbox?.isPrimary && selectedMailbox.type === "personal"; - async function saveProfile(nextName: string, nextResetEmail: string) { + async function saveProfile(nextResetEmail: string) { try { const res = await authFetch("/api/settings/profile", { method: "PATCH", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name: nextName, resetEmail: nextResetEmail }), + body: JSON.stringify({ resetEmail: nextResetEmail }), }); const data = (await res.json()) as ProfileFormResponse; @@ -96,7 +95,7 @@ export function ProfileForm({ setSavingRecovery(true); setRecoveryStatus(null); try { - await saveProfile(accountName, resetEmail); + await saveProfile(resetEmail); setRecoveryStatus(t("common.saved")); } catch (error) { setRecoveryStatus( diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.ts index 5bd54ead3..df783c5f6 100644 --- a/src/components/settings/types.d.ts +++ b/src/components/settings/types.d.ts @@ -1,5 +1,4 @@ export type ProfileFormProps = { - accountName: string; initialResetEmail: string; }; diff --git a/src/lib/validators.ts b/src/lib/validators.ts index c274a90d5..78dbe21a4 100644 --- a/src/lib/validators.ts +++ b/src/lib/validators.ts @@ -320,7 +320,8 @@ export const folderSchema = z.object({ }); export const updateProfileSchema = z.object({ - name: z.string().trim().min(1).max(100), + // Optional so a recovery-email-only save leaves the name alone instead of writing back a stale one. + name: z.string().trim().min(1).max(100).optional(), resetEmail: z.preprocess( (value) => (typeof value === "string" ? value.trim() : value), z.string().email().or(z.literal("")).transform((value) => value || null), diff --git a/tests/profile-schema.test.mjs b/tests/profile-schema.test.mjs new file mode 100644 index 000000000..9f06af456 --- /dev/null +++ b/tests/profile-schema.test.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-profile-schema-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + stdin: { contents: `export { updateProfileSchema } from "./src/lib/validators.ts";`, resolveDir: root, sourcefile: "profile-schema-entry.ts" }, + outfile: join(directory, "entry.mjs"), + bundle: true, platform: "node", format: "esm", target: "node24", + tsconfig: join(root, "tsconfig.json"), packages: "external", logLevel: "silent", +}); +const { updateProfileSchema } = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +test("a recovery-email-only save carries no name", () => { + const parsed = updateProfileSchema.parse({ resetEmail: "me@example.com" }); + assert.equal(parsed.name, undefined); + assert.equal(parsed.resetEmail, "me@example.com"); +}); + +test("a supplied name is still trimmed and validated", () => { + assert.equal(updateProfileSchema.parse({ name: " Alex ", resetEmail: "" }).name, "Alex"); + assert.throws(() => updateProfileSchema.parse({ name: " ", resetEmail: "" })); +}); From 0b043d78d495d9f94ab3674af5a741647d44f56d Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:44:20 +0530 Subject: [PATCH 05/13] fix(import): reject the upload when the response is not JSON or the request aborts bugs-import-upload-hangs-non-json A proxy HTML 413/502 made JSON.parse throw inside onload, so the promise never settled and the import button stayed on 'Importing'. Parse defensively and reject on abort/timeout. Test: tests/import-upload-response.test.mjs Co-Authored-By: Claude Opus 5.5 --- .../settings/import-messages-utils.ts | 14 +++++- tests/import-upload-response.test.mjs | 46 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 tests/import-upload-response.test.mjs diff --git a/src/components/settings/import-messages-utils.ts b/src/components/settings/import-messages-utils.ts index 727519367..3b1955274 100644 --- a/src/components/settings/import-messages-utils.ts +++ b/src/components/settings/import-messages-utils.ts @@ -23,8 +23,11 @@ export async function importMessageFiles( if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100)); }; request.onerror = () => reject(new Error("Import upload failed")); + request.onabort = () => reject(new Error("Import upload cancelled")); + request.ontimeout = () => reject(new Error("Import upload timed out")); request.onload = () => { - const data = JSON.parse(request.responseText || "{}") as ImportMessagesResult; + // A proxy can answer with an HTML error page; fall through to the status check. + const data = parseImportResponse(request.responseText); if (request.status < 200 || request.status >= 300) { reject(new Error(data.error ?? "Import failed")); return; @@ -34,3 +37,12 @@ export async function importMessageFiles( request.send(form); }); } + +function parseImportResponse(text: string): ImportMessagesResult { + try { + const data: unknown = JSON.parse(text || "{}"); + return data && typeof data === "object" ? (data as ImportMessagesResult) : {}; + } catch { + return {}; + } +} diff --git a/tests/import-upload-response.test.mjs b/tests/import-upload-response.test.mjs new file mode 100644 index 000000000..a5df94f1b --- /dev/null +++ b/tests/import-upload-response.test.mjs @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "import-upload-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/components/settings/import-messages-utils.ts")], + outfile: join(directory, "utils.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ contents: `export function getAuthHeaders(){return new Headers();}`, loader: "js" })); + } }], +}); +const utils = await import(pathToFileURL(join(directory, "utils.mjs")).href); + +function stubXhr(finish) { + globalThis.FormData = class { set() {} append() {} }; + globalThis.XMLHttpRequest = class { + upload = {}; + open() {} + setRequestHeader() {} + send() { queueMicrotask(() => finish(this)); } + }; +} + +test("a non-JSON error page rejects instead of hanging", async () => { + stubXhr((x) => { x.status = 502; x.responseText = "Bad gateway"; x.onload(); }); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /Import failed/); +}); + +test("abort and timeout reject", async () => { + stubXhr((x) => x.onabort()); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /cancelled/); + stubXhr((x) => x.ontimeout()); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /timed out/); +}); + +test("a JSON success still resolves", async () => { + stubXhr((x) => { x.status = 202; x.responseText = JSON.stringify({ job: { id: "j1" } }); x.onload(); }); + assert.deepEqual(await utils.importMessageFiles("mb", [], "inbox"), { job: { id: "j1" } }); +}); From dfbc7866db6cc0207500e6c928ccbf532cb27b83 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:47:32 +0530 Subject: [PATCH 06/13] fix(setup): reset loading state when a register or onboarding request fails bugs-setup-forms-stuck-loading A dropped connection or an HTML 5xx during first-run setup made fetch or res.json() reject before setLoading(false)/setDomainChecking(false) ran, leaving the button disabled with no error. Handlers now use try/catch/finally with auth.serverUnreachable, and the setup utils tolerate non-JSON bodies via readResponseJson. Test: tests/response-json.test.mjs (body parsing); the handlers are React event handlers with no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- .../(auth)/onboarding/onboarding-client.tsx | 105 +++++++------ src/app/(auth)/onboarding/utils.ts | 9 +- src/app/(auth)/register/register-client.tsx | 138 ++++++++++-------- src/app/(auth)/register/utils.ts | 13 +- src/lib/http/response.ts | 13 ++ tests/response-json.test.mjs | 25 ++++ 6 files changed, 187 insertions(+), 116 deletions(-) create mode 100644 src/lib/http/response.ts create mode 100644 tests/response-json.test.mjs diff --git a/src/app/(auth)/onboarding/onboarding-client.tsx b/src/app/(auth)/onboarding/onboarding-client.tsx index dc9e57803..8900f550c 100644 --- a/src/app/(auth)/onboarding/onboarding-client.tsx +++ b/src/app/(auth)/onboarding/onboarding-client.tsx @@ -43,43 +43,46 @@ export function OnboardingClient() { setLoading(true); setError(null); - const normalized = hostname.toLowerCase().trim(); - let checkedDomain = domainCheck; - let sendingRequested = enableSending; - if (skipDns) { - checkedDomain = { hostname: normalized, zone: { id: "manual", name: normalized } }; - } else if (checkedDomain?.hostname !== normalized) { - const result = await checkDomain(normalized); - if (!result.ok || !result.domain) { - setLoading(false); - setError(result.error ?? t("onboarding.domainCheckFailed")); + try { + const normalized = hostname.toLowerCase().trim(); + let checkedDomain = domainCheck; + let sendingRequested = enableSending; + if (skipDns) { + checkedDomain = { hostname: normalized, zone: { id: "manual", name: normalized } }; + } else if (checkedDomain?.hostname !== normalized) { + const result = await checkDomain(normalized); + if (!result.ok || !result.domain) { + setError(result.error ?? t("onboarding.domainCheckFailed")); + return; + } + checkedDomain = result.domain; + sendingRequested = false; + setDomainCheck(result.domain); + setEnableSending(sendingRequested); + } + if (!checkedDomain) { + setError(t("onboarding.domainCheckFailed")); return; } - checkedDomain = result.domain; - sendingRequested = false; - setDomainCheck(result.domain); - setEnableSending(sendingRequested); - } - if (!checkedDomain) { - setLoading(false); - setError(t("onboarding.domainCheckFailed")); - return; - } - const { ok, data } = await createDomain(checkedDomain.hostname, skipDns ? true : sendingRequested, replaceMxRecords, skipDns); - setLoading(false); - if (!ok || !data.domain) { - if (data.code === "MX_RECORDS_CONFLICT") { - setMxConflict(true); - setError(null); + const { ok, data } = await createDomain(checkedDomain.hostname, skipDns ? true : sendingRequested, replaceMxRecords, skipDns); + if (!ok || !data.domain) { + if (data.code === "MX_RECORDS_CONFLICT") { + setMxConflict(true); + setError(null); + return; + } + setError(data.error ?? t("onboarding.addDomainFailed")); return; } - setError(data.error ?? t("onboarding.addDomainFailed")); - return; + setMxConflict(false); + setDomainId(data.domain.id); + setStep(2); + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - setMxConflict(false); - setDomainId(data.domain.id); - setStep(2); } async function inspectDomain() { @@ -89,30 +92,42 @@ export function OnboardingClient() { setDomainChecking(true); setError(null); setMxConflict(false); - const result = await checkDomain(normalized); - setDomainChecking(false); - if (!result.ok || !result.domain) { + try { + const result = await checkDomain(normalized); + if (!result.ok || !result.domain) { + setDomainCheck(null); + setEnableSending(false); + setError(result.error ?? t("onboarding.domainCheckFailed")); + return; + } + + setDomainCheck(result.domain); + setEnableSending(false); + } catch { setDomainCheck(null); setEnableSending(false); - setError(result.error ?? t("onboarding.domainCheckFailed")); - return; + setError(t("auth.serverUnreachable")); + } finally { + setDomainChecking(false); } - - setDomainCheck(result.domain); - setEnableSending(false); } async function addMailbox() { setLoading(true); setError(null); - const { ok, data } = await createMailbox(domainId, localPart); - setLoading(false); - if (!ok) { - setError(data.error ?? t("onboarding.createMailboxFailed")); - return; + try { + const { ok, data } = await createMailbox(domainId, localPart); + if (!ok) { + setError(data.error ?? t("onboarding.createMailboxFailed")); + return; + } + router.push("/inbox"); + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - router.push("/inbox"); } return ( diff --git a/src/app/(auth)/onboarding/utils.ts b/src/app/(auth)/onboarding/utils.ts index 2c65b0405..46a194770 100644 --- a/src/app/(auth)/onboarding/utils.ts +++ b/src/app/(auth)/onboarding/utils.ts @@ -1,3 +1,4 @@ +import { readResponseJson } from "@/lib/http/response"; import { authFetch } from "@/lib/auth/client"; import type { DomainCreateResult, @@ -8,7 +9,7 @@ import type { export async function getDomains(): Promise { const res = await authFetch("/api/domains"); - return (await res.json()) as DomainListResult; + return (await readResponseJson(res)) as DomainListResult; } export async function checkDomain(hostname: string): Promise { @@ -17,7 +18,7 @@ export async function checkDomain(hostname: string): Promise; + const data = (await readResponseJson(res)) as Omit; return { ok: res.ok, ...data }; } @@ -35,7 +36,7 @@ export async function createDomain( return { ok: res.ok, - data: (await res.json()) as DomainCreateResult, + data: (await readResponseJson(res)) as DomainCreateResult, }; } @@ -51,6 +52,6 @@ export async function createMailbox( return { ok: res.ok, - data: (await res.json()) as MailboxCreateResult, + data: (await readResponseJson(res)) as MailboxCreateResult, }; } diff --git a/src/app/(auth)/register/register-client.tsx b/src/app/(auth)/register/register-client.tsx index fea648a14..3288596b4 100644 --- a/src/app/(auth)/register/register-client.tsx +++ b/src/app/(auth)/register/register-client.tsx @@ -132,36 +132,40 @@ export function RegisterClient() { setLoading(true); setError(null); - const hostname = String(new FormData(e.currentTarget).get("domain") ?? "").toLowerCase().trim(); - if (skipDns) { - const { ok, data } = await submitPrimaryDomain(hostname, true); - setLoading(false); + try { + const hostname = String(new FormData(e.currentTarget).get("domain") ?? "").toLowerCase().trim(); + if (skipDns) { + const { ok, data } = await submitPrimaryDomain(hostname, true); + if (!ok || !data.domain) { + setError(typeof data.error === "string" ? data.error : t("setup.domainFailed")); + return; + } + setSetupDomain(data.domain.hostname); + setSetupEnableSending(true); + setSetupSkipDns(true); + setStep(3); + return; + } + setSetupSkipDns(false); + const usedCachedCheck = domainCheck?.hostname === hostname; + const result: { ok: boolean; data: DomainSetupResult } = usedCachedCheck + ? { ok: true, data: { domain: domainCheck } } + : await submitPrimaryDomain(hostname); + const { ok, data } = result; if (!ok || !data.domain) { - setError(typeof data.error === "string" ? data.error : t("setup.domainFailed")); + setError( + typeof data.error === "string" ? data.error : t("setup.domainFailed"), + ); return; } setSetupDomain(data.domain.hostname); - setSetupEnableSending(true); - setSetupSkipDns(true); + setSetupEnableSending(usedCachedCheck ? enableSending : false); setStep(3); - return; - } - setSetupSkipDns(false); - const usedCachedCheck = domainCheck?.hostname === hostname; - const result: { ok: boolean; data: DomainSetupResult } = usedCachedCheck - ? { ok: true, data: { domain: domainCheck } } - : await submitPrimaryDomain(hostname); - const { ok, data } = result; - setLoading(false); - if (!ok || !data.domain) { - setError( - typeof data.error === "string" ? data.error : t("setup.domainFailed"), - ); - return; + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - setSetupDomain(data.domain.hostname); - setSetupEnableSending(usedCachedCheck ? enableSending : false); - setStep(3); } async function onDomainBlur(e: React.FocusEvent) { @@ -170,17 +174,24 @@ export function RegisterClient() { setDomainChecking(true); setError(null); - const { ok, data } = await submitPrimaryDomain(hostname); - setDomainChecking(false); - if (!ok || !data.domain) { + try { + const { ok, data } = await submitPrimaryDomain(hostname); + if (!ok || !data.domain) { + setDomainCheck(null); + setEnableSending(false); + setError(typeof data.error === "string" ? data.error : t("setup.domainCheckFailed")); + return; + } + + setDomainCheck(data.domain); + setEnableSending(false); + } catch { setDomainCheck(null); setEnableSending(false); - setError(typeof data.error === "string" ? data.error : t("setup.domainCheckFailed")); - return; + setError(t("auth.serverUnreachable")); + } finally { + setDomainChecking(false); } - - setDomainCheck(data.domain); - setEnableSending(false); } async function onSubmit(e: React.FormEvent) { @@ -188,41 +199,46 @@ export function RegisterClient() { setLoading(true); setError(null); - const form = new FormData(e.currentTarget); - const domain = setupDomain ?? primaryDomain; - if (!domain) { - setLoading(false); - setError(t("setup.domainIncomplete")); - return; - } + try { + const form = new FormData(e.currentTarget); + const domain = setupDomain ?? primaryDomain; + if (!domain) { + setError(t("setup.domainIncomplete")); + return; + } - const { ok, data } = await submitRegistration(form, { - firstRun: true, - domain, - enableSending: setupDomain - ? setupEnableSending - : primaryDomainSendingRequested ?? undefined, - replaceMxRecords, - skipDns: setupDomain ? setupSkipDns : undefined, - }); - setLoading(false); - if (!ok) { - if (data.code === "MX_RECORDS_CONFLICT") { - setMxRecordsExist(true); - setReplaceMxRecords(false); - setError(null); + const { ok, data } = await submitRegistration(form, { + firstRun: true, + domain, + enableSending: setupDomain + ? setupEnableSending + : primaryDomainSendingRequested ?? undefined, + replaceMxRecords, + skipDns: setupDomain ? setupSkipDns : undefined, + }); + if (!ok) { + if (data.code === "MX_RECORDS_CONFLICT") { + setMxRecordsExist(true); + setReplaceMxRecords(false); + setError(null); + setTurnstileReset((value) => value + 1); + return; + } + setError( + data.code === "passkey_unavailable" + ? t("authError.passkeyUnavailable") + : typeof data.error === "string" ? data.error : t("setup.registrationFailed"), + ); setTurnstileReset((value) => value + 1); return; } - setError( - data.code === "passkey_unavailable" - ? t("authError.passkeyUnavailable") - : typeof data.error === "string" ? data.error : t("setup.registrationFailed"), - ); + window.location.assign(data.redirect ?? "/login"); + } catch { + setError(t("auth.serverUnreachable")); setTurnstileReset((value) => value + 1); - return; + } finally { + setLoading(false); } - window.location.assign(data.redirect ?? "/login"); } const showDomainStep = hasPrimaryDomain === false && step === 2; diff --git a/src/app/(auth)/register/utils.ts b/src/app/(auth)/register/utils.ts index ba1eb890f..b7675c377 100644 --- a/src/app/(auth)/register/utils.ts +++ b/src/app/(auth)/register/utils.ts @@ -1,3 +1,4 @@ +import { readResponseJson } from "@/lib/http/response"; import { clearClientSessionToken } from "@/lib/auth/client"; import type { DomainSetupResult, @@ -11,14 +12,14 @@ export async function prepareSetup(): Promise<{ ok: boolean; data: SetupPreparat const res = await fetch("/api/setup/prepare", { method: "POST" }); return { ok: res.ok, - data: (await res.json()) as SetupPreparationResult, + data: (await readResponseJson(res)) as SetupPreparationResult, }; } export async function getSetupStatus(): Promise { const res = await fetch("/api/setup/status"); - const data = (await res.json()) as SetupStatus; - if (!res.ok) throw new Error(data.error ?? "Could not load setup status"); + const data = (await readResponseJson(res)) as SetupStatus; + if (!res.ok || typeof data.hasAdminAccount !== "boolean") throw new Error(data.error ?? "Could not load setup status"); return data; } @@ -31,7 +32,7 @@ export async function submitPrimaryDomain(hostname: string, skipDns = false): Pr return { ok: res.ok, - data: (await res.json()) as DomainSetupResult, + data: (await readResponseJson(res)) as DomainSetupResult, }; } @@ -44,7 +45,7 @@ export async function checkExistingMx(hostname: string): Promise<{ ok: boolean; return { ok: res.ok, - data: (await res.json()) as MxCheckResult, + data: (await readResponseJson(res)) as MxCheckResult, }; } @@ -78,7 +79,7 @@ export async function submitRegistration( ), }); - const data = (await res.json()) as RegisterResult; + const data = (await readResponseJson(res)) as RegisterResult; if (res.ok) clearClientSessionToken(); return { ok: res.ok, data }; } diff --git a/src/lib/http/response.ts b/src/lib/http/response.ts new file mode 100644 index 000000000..38f27d2ce --- /dev/null +++ b/src/lib/http/response.ts @@ -0,0 +1,13 @@ +/** + * Parse a response body as a JSON object, or `{}` when it is not JSON (for + * example an HTML 502 page from a proxy). Callers then fall through to their + * own `res.ok` handling and fallback message. + */ +export async function readResponseJson(res: Response): Promise { + try { + const data: unknown = await res.json(); + return (data && typeof data === "object" ? data : {}) as T; + } catch { + return {} as T; + } +} diff --git a/tests/response-json.test.mjs b/tests/response-json.test.mjs new file mode 100644 index 000000000..2e4b9422e --- /dev/null +++ b/tests/response-json.test.mjs @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-response-json-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(root, "src/lib/http/response.ts")], + outfile: join(directory, "response.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", +}); +const { readResponseJson } = await import(pathToFileURL(join(directory, "response.mjs")).href); + +test("JSON objects pass through", async () => { + assert.deepEqual(await readResponseJson(new Response('{"error":"x"}')), { error: "x" }); +}); + +test("an HTML error page or empty body becomes an empty object", async () => { + assert.deepEqual(await readResponseJson(new Response("502", { status: 502 })), {}); + assert.deepEqual(await readResponseJson(new Response("")), {}); + assert.deepEqual(await readResponseJson(new Response("null")), {}); +}); From d4aa776319bef6a3bcf36776126e651f9ecd07af Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:47:42 +0530 Subject: [PATCH 07/13] fix(contacts): track the photo flag while editing a contact bugs-contact-edit-stale-avatar-flag The edit dialog read hasAvatar from the contact snapshot taken on open, so after uploading a photo 'Remove' never appeared, and after removing one it still did (a second remove errored). No test: React state in a dialog form; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/components/contacts/contact-edit-dialog.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/components/contacts/contact-edit-dialog.tsx b/src/components/contacts/contact-edit-dialog.tsx index 2dbef5a0c..72e90e3fd 100644 --- a/src/components/contacts/contact-edit-dialog.tsx +++ b/src/components/contacts/contact-edit-dialog.tsx @@ -63,6 +63,8 @@ function ContactEditForm({ const editing = contact !== null; const [email, setEmail] = useState(contact?.email ?? ""); const [displayName, setDisplayName] = useState(contact?.displayName ?? ""); + // `contact` is the snapshot taken when the dialog opened, so the photo flag is tracked here. + const [hasAvatar, setHasAvatar] = useState(contact?.hasAvatar ?? false); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); @@ -97,8 +99,11 @@ function ContactEditForm({ mailboxId={mailboxId} address={contact.email} name={displayName} - hasAvatar={contact.hasAvatar} - onAvatarChange={(hasAvatar) => onSaved({ ...contact, hasAvatar })} + hasAvatar={hasAvatar} + onAvatarChange={(next) => { + setHasAvatar(next); + onSaved({ ...contact, hasAvatar: next }); + }} /> )}
From 898c1f8e2cec8c0429906e18f45ea51283f61918 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:47:50 +0530 Subject: [PATCH 08/13] fix(follow-ups): ignore out-of-order responses bugs-stale-response-loaders After switching mailbox or message, a slow response for the previous id could land last and show its reminders/status (and act on the new id). Only the newest request now sets state. No test: effect-local request counter in React components; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/components/follow-ups/due-follow-ups.tsx | 10 ++++++++-- src/components/follow-ups/message-follow-up-status.tsx | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/components/follow-ups/due-follow-ups.tsx b/src/components/follow-ups/due-follow-ups.tsx index e95060a1b..9d3d5bc49 100644 --- a/src/components/follow-ups/due-follow-ups.tsx +++ b/src/components/follow-ups/due-follow-ups.tsx @@ -1,7 +1,7 @@ "use client"; import Link from "next/link"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { BellRing, Check } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; import { Tooltip } from "@/components/ui/tooltip"; @@ -19,8 +19,14 @@ export function DueFollowUps({ mailboxId }: { mailboxId?: string | null }) { const [items, setItems] = useState([]); const [failed, setFailed] = useState(false); + const latestRequest = useRef(0); + const load = useCallback(() => { - void fetchDueFollowUps(mailboxId).then(setItems).catch(() => undefined); + // Only the newest request may set state, so a slow response for a previous mailbox is dropped. + const request = ++latestRequest.current; + void fetchDueFollowUps(mailboxId) + .then((next) => { if (request === latestRequest.current) setItems(next); }) + .catch(() => undefined); }, [mailboxId]); useEffect(() => { diff --git a/src/components/follow-ups/message-follow-up-status.tsx b/src/components/follow-ups/message-follow-up-status.tsx index 2496640cc..b5b16a8f7 100644 --- a/src/components/follow-ups/message-follow-up-status.tsx +++ b/src/components/follow-ups/message-follow-up-status.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { BellRing, Check } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; import type { MessageFollowUp } from "@/lib/follow-ups/types"; @@ -17,8 +17,14 @@ export function MessageFollowUpStatus({ messageId }: { messageId: string }) { const [followUp, setFollowUp] = useState(undefined); const [failed, setFailed] = useState(false); + const latestRequest = useRef(0); + const load = useCallback(() => { - void fetchMessageFollowUp(messageId).then(setFollowUp).catch(() => setFollowUp(null)); + // Only the newest request may set state, so a slow response for another message is dropped. + const request = ++latestRequest.current; + void fetchMessageFollowUp(messageId) + .then((next) => { if (request === latestRequest.current) setFollowUp(next); }) + .catch(() => { if (request === latestRequest.current) setFollowUp(null); }); }, [messageId]); useEffect(() => { From 48e85bf5d6d30de2b55e6ff59008dd2764320beb Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:54:49 +0530 Subject: [PATCH 09/13] fix(drive): ignore a late share response for a previous item bugs-drive-share-stale-response Opening Share on a second item while the first item's response was slow showed the first item's people and public link in the second dialog (and 'Disable link' then posted to the second item). Responses are now dropped once the item changes, and a network failure shows the existing error toast instead of an unhandled rejection. No test: effect cleanup in a React dialog; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/app/(drive)/drive-share-dialog.tsx | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/app/(drive)/drive-share-dialog.tsx b/src/app/(drive)/drive-share-dialog.tsx index c37c4d3d2..e562b61a2 100644 --- a/src/app/(drive)/drive-share-dialog.tsx +++ b/src/app/(drive)/drive-share-dialog.tsx @@ -31,12 +31,21 @@ export function DriveShareDialog({ item, onClose, onChanged }: { item: DriveItem useEffect(() => { if (!id) return; + // A slow response for an earlier item must not fill in the item shown now. + let active = true; void authFetch(`/api/drive/items/${id}/shares`).then(async (response) => { - if (!response.ok) return toast.error(t("drive.shareFailed")); + if (!response.ok) { + if (active) toast.error(t("drive.shareFailed")); + return; + } const data = await response.json() as { shares: DriveShareDto[]; linkToken: string | null }; + if (!active) return; setShares(data.shares); setLinkToken(data.linkToken); + }).catch(() => { + if (active) toast.error(t("drive.shareFailed")); }); + return () => { active = false; }; }, [id, t]); async function request(input: string, init: RequestInit) { From 0195b95c1fa83102244501fc491ae4c8d107aac6 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:54:49 +0530 Subject: [PATCH 10/13] fix(branding): clear the icon preview and file input after saving bugs-branding-preview-leak After saving, the preview object URL stayed alive and the file input kept its value, so choosing the same file again fired no change event. The preview is now revoked and the input cleared after a save, and the URL is revoked on unmount. No test: browser object-URL and file-input handling in a React page; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/app/(admin)/branding/page.tsx | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/app/(admin)/branding/page.tsx b/src/app/(admin)/branding/page.tsx index b31774f67..797063d3d 100644 --- a/src/app/(admin)/branding/page.tsx +++ b/src/app/(admin)/branding/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import Link from "next/link"; import { ArrowRight, ExternalLink, ImagePlus, LockKeyhole, Palette } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; @@ -20,6 +20,7 @@ export default function BrandingPage() { const [status, setStatus] = useState(null); const [saving, setSaving] = useState(false); const inputRef = useRef(null); + const previewRef = useRef(null); const [syncedAppName, setSyncedAppName] = useState(branding.appName); // Reset the field whenever the saved name changes. @@ -28,6 +29,11 @@ export default function BrandingPage() { setAppName(branding.appName); } + // Free the preview's object URL when leaving the page. + useEffect(() => () => { + if (previewRef.current) URL.revokeObjectURL(previewRef.current); + }, []); + if (!branding.canCustomizeBranding) { return (
@@ -52,8 +58,13 @@ export default function BrandingPage() { function pickIcon(file: File | null) { setIcon(file); - if (preview) URL.revokeObjectURL(preview); - setPreview(file ? URL.createObjectURL(file) : null); + setPreviewUrl(file ? URL.createObjectURL(file) : null); + } + + function setPreviewUrl(url: string | null) { + if (previewRef.current) URL.revokeObjectURL(previewRef.current); + previewRef.current = url; + setPreview(url); } async function submit(event: React.FormEvent) { @@ -64,6 +75,9 @@ export default function BrandingPage() { await saveBranding(appName.trim(), icon); await branding.refreshBranding(); setIcon(null); + // Drop the preview and the file input's value so the same file can be chosen again. + setPreviewUrl(null); + if (inputRef.current) inputRef.current.value = ""; setStatus(t("branding.updated")); } catch (error) { setStatus(error instanceof Error ? error.message : t("branding.saveFailed")); From 23c878b6e14bbc0ccbc7fb369c8b11825bbb096f Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:54:49 +0530 Subject: [PATCH 11/13] fix(auth): recover when the Turnstile script fails to load bugs-turnstile-loader-failure A blocked script stayed in the DOM, so a second mount waited on its load event forever and the first caller raised an unhandled rejection. The failed script is now removed, waiters also reject on error, and the loader call has a catch so a later mount retries. No test: DOM script loading in a client component; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/components/auth/turnstile.tsx | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/components/auth/turnstile.tsx b/src/components/auth/turnstile.tsx index 975ea03c9..9fee61aa9 100644 --- a/src/components/auth/turnstile.tsx +++ b/src/components/auth/turnstile.tsx @@ -26,7 +26,10 @@ function loadTurnstileScript(): Promise { if (existing) { return existing.dataset.loaded === "true" ? Promise.resolve() - : new Promise((resolve) => existing.addEventListener("load", () => resolve(), { once: true })); + : new Promise((resolve, reject) => { + existing.addEventListener("load", () => resolve(), { once: true }); + existing.addEventListener("error", () => reject(new Error("Turnstile failed to load")), { once: true }); + }); } return new Promise((resolve, reject) => { @@ -39,7 +42,11 @@ function loadTurnstileScript(): Promise { script.dataset.loaded = "true"; resolve(); }); - script.addEventListener("error", () => reject(new Error("Turnstile failed to load"))); + script.addEventListener("error", () => { + // Leave no dead script behind, or later mounts would wait on it forever. + script.remove(); + reject(new Error("Turnstile failed to load")); + }); document.head.appendChild(script); }); } @@ -69,6 +76,8 @@ export function TurnstileField({ "expired-callback": () => setToken(""), "error-callback": () => setToken(""), }); + }).catch(() => { + // The widget stays empty; a later mount retries the load. }); return () => { From bd8f5ff8a0500c0b8f10447bb29d80b8fd9ed5eb Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:55:19 +0530 Subject: [PATCH 12/13] fix(import): stop the Takeout import when the page unmounts bugs-takeout-continues-after-unmount Navigating away mid-import left the upload loop running with no progress UI or Stop button, and a second import could then run concurrently. The controller is now aborted on unmount; progress is already saved for resuming. No test: effect cleanup in a React component; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/components/settings/takeout-import.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/components/settings/takeout-import.tsx b/src/components/settings/takeout-import.tsx index 979a290e1..87915e8af 100644 --- a/src/components/settings/takeout-import.tsx +++ b/src/components/settings/takeout-import.tsx @@ -71,6 +71,9 @@ export function TakeoutImport() { }; }, [running]); + // Leaving the page must stop the upload loop; progress is saved, so the import can be resumed later. + useEffect(() => () => controllerRef.current?.abort(), []); + function destinationLabel(key: string): string { const [type, ...rest] = key.split(":"); const value = rest.join(":"); From b91f520b255c3fafb3b45ce7e034a1719b069780 Mon Sep 17 00:00:00 2001 From: bobmcdonald0 <266144304+bobmcdonald0@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:48:53 +0530 Subject: [PATCH 13/13] perf(icons): create the Forward icon once perf-forward-icon-recreated-each-render Forward called createIcon (forwardRef) on every render, a new component type each time, so React remounted the SVG on every parent render (message actions, rules rows). Hoisted to module scope; className now goes through cn() instead of rendering 'undefined scale-x-[-1]'. No test: JSX icon wrapper; no component harness in the repo. Co-Authored-By: Claude Opus 5.5 --- src/components/icons.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/components/icons.tsx b/src/components/icons.tsx index daf42c1cc..c8220607f 100644 --- a/src/components/icons.tsx +++ b/src/components/icons.tsx @@ -1,4 +1,5 @@ import { createElement, forwardRef, type ComponentType, type SVGProps } from "react"; +import { cn } from "@/lib/utils"; import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react"; import { ActivityIcon as HugeActivityIcon, @@ -244,9 +245,10 @@ export const FileWarning = createIcon(HugeFileExclamationPointIcon, "FileWarning export const Folder = createIcon(HugeFolderIcon, "Folder"); export const FolderInput = createIcon(HugeFolderInputIcon, "FolderInput"); export const FolderPlus = createIcon(HugeFolderPlusIcon, "FolderPlus"); -export const Forward = function (props) { - return createElement(createIcon(HugeReplyIcon, "Forward"), {...props, className: `${props.className} scale-x-[-1]`}); -} +// Created once: building the icon component inside render gives React a new type every time and remounts the SVG. +const ForwardBase = createIcon(HugeReplyIcon, "Forward"); +export const Forward: LucideIcon = (props) => + createElement(ForwardBase, { ...props, className: cn(props.className, "scale-x-[-1]") }); export const Globe2 = createIcon(HugeGlobeIcon, "Globe2"); export const HardDrive = createIcon(HugeHardDriveIcon, "HardDrive"); export const HelpCircle = createIcon(HugeHelpCircleIcon, "HelpCircle");