From 8d1e6e6c208458b86f0d86521645633280bad194 Mon Sep 17 00:00:00 2001 From: Cosmo Date: Sun, 25 Oct 2026 02:42:25 +0200 Subject: [PATCH 1/4] fix: keep Files and attachments in the selected account scope --- components/Sandboxes/SandboxDeleteButton.tsx | 9 +- components/Sandboxes/SandboxFileTree.tsx | 14 +- components/Sandboxes/SandboxFileWorkspace.tsx | 11 + .../SandboxFileTree.override.test.tsx | 32 +++ .../__tests__/guardedJourney.mocks.tsx | 6 +- hooks/__tests__/guardedReplacement.fixture.ts | 6 +- hooks/__tests__/sandboxAccount.fixture.tsx | 69 ++++++ .../__tests__/sandboxWrites.account.test.tsx | 209 +++++++++++++++++ .../useSandboxFileContent.account.test.tsx | 124 ++++++++++ hooks/__tests__/useSandboxes.account.test.tsx | 158 +++++++++++++ .../useVercelChat.fileScope.test.tsx | 217 ++++++++++++++++++ hooks/useDeleteSandbox.ts | 14 ++ hooks/useGuardedFileReplacement.ts | 14 ++ hooks/useSandboxAccountScope.ts | 38 +++ hooks/useSandboxFileContent.ts | 12 +- hooks/useSandboxFileDrop.ts | 21 +- hooks/useSandboxFileQuery.ts | 38 ++- hooks/useSandboxes.ts | 27 ++- hooks/useVercelChat.ts | 80 ++++++- lib/sandboxes/__tests__/accountScope.test.ts | 95 ++++++++ lib/sandboxes/getFileContents.ts | 29 ++- lib/sandboxes/getSandboxes.ts | 12 +- lib/sandboxes/guarded-replacement.md | 8 + lib/sandboxes/uploadSandboxFiles.ts | 4 + providers/AccountOverrideProvider.tsx | 73 ++++-- .../AccountOverrideProvider.test.tsx | 205 +++++++++++++++++ 26 files changed, 1450 insertions(+), 75 deletions(-) create mode 100644 components/Sandboxes/__tests__/SandboxFileTree.override.test.tsx create mode 100644 hooks/__tests__/sandboxAccount.fixture.tsx create mode 100644 hooks/__tests__/sandboxWrites.account.test.tsx create mode 100644 hooks/__tests__/useSandboxFileContent.account.test.tsx create mode 100644 hooks/__tests__/useSandboxes.account.test.tsx create mode 100644 hooks/__tests__/useVercelChat.fileScope.test.tsx create mode 100644 hooks/useSandboxAccountScope.ts create mode 100644 lib/sandboxes/__tests__/accountScope.test.ts create mode 100644 providers/__tests__/AccountOverrideProvider.test.tsx diff --git a/components/Sandboxes/SandboxDeleteButton.tsx b/components/Sandboxes/SandboxDeleteButton.tsx index 889d17447..66bf38a8a 100644 --- a/components/Sandboxes/SandboxDeleteButton.tsx +++ b/components/Sandboxes/SandboxDeleteButton.tsx @@ -23,7 +23,7 @@ interface SandboxDeleteButtonProps { export default function SandboxDeleteButton({ onSuccess, }: SandboxDeleteButtonProps) { - const { deleteSandbox, isDeleting } = useDeleteSandbox(); + const { deleteSandbox, isDeleting, readOnly } = useDeleteSandbox(); const handleDelete = async () => { await deleteSandbox(); @@ -34,7 +34,11 @@ export default function SandboxDeleteButton({ return ( - , ); + if (readOnly) + return listing.filetree.length ? ( + + ) : ( + withPreview(

No files yet.

) + ); if (!listing.filetree.length) return withPreview(); return ( diff --git a/components/Sandboxes/__tests__/SandboxFileTree.override.test.tsx b/components/Sandboxes/__tests__/SandboxFileTree.override.test.tsx new file mode 100644 index 000000000..963a3ae0a --- /dev/null +++ b/components/Sandboxes/__tests__/SandboxFileTree.override.test.tsx @@ -0,0 +1,32 @@ +// @vitest-environment jsdom +import React from "react"; +import { expect, it, vi } from "vitest"; +import { + fixture, + render, + screen, + fireEvent, + SandboxFileTree, +} from "./guardedJourney.fixture"; + +vi.mock("@/providers/AccountOverrideProvider", () => ({ + useAccountOverride: () => ({ accountIdOverride: "selected-b", email: null }), +})); + +it("shows read-only files without upload controls for a selected account", () => { + render(); + expect(screen.getByText(/selected account are read-only/)).toBeDefined(); + expect(screen.getByText("Opened draft")).toBeDefined(); + expect(screen.queryByText("Drop replacement")).toBeNull(); + const protect = screen.getByRole("checkbox") as HTMLInputElement; + expect(protect.disabled).toBe(true); + fireEvent.click(protect); + expect(fixture.legacy).not.toHaveBeenCalled(); +}); + +it("does not offer uploads for an empty selected account", () => { + fixture.empty = true; + render(); + expect(screen.getByText("No files yet.")).toBeDefined(); + expect(screen.queryByLabelText("Upload files")).toBeNull(); +}); diff --git a/components/Sandboxes/__tests__/guardedJourney.mocks.tsx b/components/Sandboxes/__tests__/guardedJourney.mocks.tsx index 4e7261747..aff964913 100644 --- a/components/Sandboxes/__tests__/guardedJourney.mocks.tsx +++ b/components/Sandboxes/__tests__/guardedJourney.mocks.tsx @@ -3,7 +3,11 @@ import { cleanup } from "@testing-library/react"; import { beforeEach, afterEach, vi } from "vitest"; import { fixture, file, opened } from "./guardedJourney.data"; vi.mock("@privy-io/react-auth", () => ({ - usePrivy: () => ({ getAccessToken: async () => "synthetic-token" }), + usePrivy: () => ({ + getAccessToken: async () => "synthetic-token", + authenticated: true, + user: { id: fixture.actor }, + }), })); vi.mock("@/lib/sandboxes/uploadSandboxFiles", () => ({ uploadSandboxFiles: vi.fn(), diff --git a/hooks/__tests__/guardedReplacement.fixture.ts b/hooks/__tests__/guardedReplacement.fixture.ts index 03a43468a..edf87662e 100644 --- a/hooks/__tests__/guardedReplacement.fixture.ts +++ b/hooks/__tests__/guardedReplacement.fixture.ts @@ -7,7 +7,11 @@ import { SandboxFileConflictError } from "@/lib/sandboxes/SandboxFileConflictErr const token = vi.fn(async (): Promise => "synthetic-token"); vi.mock("@privy-io/react-auth", () => ({ - usePrivy: () => ({ getAccessToken: token }), + usePrivy: () => ({ + getAccessToken: token, + authenticated: true, + user: { id: "actor-a" }, + }), })); vi.mock("@/lib/sandboxes/uploadSandboxFiles", () => ({ uploadSandboxFiles: vi.fn(), diff --git a/hooks/__tests__/sandboxAccount.fixture.tsx b/hooks/__tests__/sandboxAccount.fixture.tsx new file mode 100644 index 000000000..6b123e6e2 --- /dev/null +++ b/hooks/__tests__/sandboxAccount.fixture.tsx @@ -0,0 +1,69 @@ +// @vitest-environment jsdom +import React from "react"; +import { cleanup } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, vi } from "vitest"; + +const context = vi.hoisted(() => ({ + actor: "actor-a" as string | null, + authenticated: true, + account: null as string | null, + email: null as string | null, + origin: "https://api-synthetic-recoup.vercel.app", +})); +const token = vi.hoisted(() => vi.fn(async () => "synthetic-token")); +vi.mock("@privy-io/react-auth", () => ({ + usePrivy: () => ({ + user: context.actor ? { id: context.actor } : null, + authenticated: context.authenticated && Boolean(context.actor), + getAccessToken: token, + }), +})); +vi.mock("@/providers/AccountOverrideProvider", () => ({ + useAccountOverride: () => ({ + accountIdOverride: context.account, + email: context.email, + }), +})); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => context.origin, +})); +vi.mock("sonner", () => ({ + toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() }, +})); +export const fetchMock = vi.fn(); +export let client: QueryClient; +export const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} +); +export function response(data: object) { + return { + ok: true, + status: 200, + json: async () => ({ status: "success", ...data }), + } as Response; +} +beforeEach(() => { + context.actor = "actor-a"; + context.authenticated = true; + context.account = null; + context.email = null; + context.origin = "https://api-synthetic-recoup.vercel.app"; + token.mockReset().mockResolvedValue("synthetic-token"); + fetchMock + .mockReset() + .mockRejectedValue(new Error("Unexpected network request")); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("NEXT_PUBLIC_GUARDED_GIT_API_ORIGIN", context.origin); + client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); +}); +afterEach(() => { + cleanup(); + client.clear(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +export { context, token }; diff --git a/hooks/__tests__/sandboxWrites.account.test.tsx b/hooks/__tests__/sandboxWrites.account.test.tsx new file mode 100644 index 000000000..97f2685ea --- /dev/null +++ b/hooks/__tests__/sandboxWrites.account.test.tsx @@ -0,0 +1,209 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from "@testing-library/react"; +import { expect, it, vi, beforeEach } from "vitest"; +import { + context, + token, + fetchMock, + wrapper, + response, +} from "./sandboxAccount.fixture"; +import { useSandboxFileDrop } from "../useSandboxFileDrop"; +import useDeleteSandbox from "../useDeleteSandbox"; +import { useGuardedFileReplacement } from "../useGuardedFileReplacement"; +import { stageSandboxFiles } from "@/lib/sandboxes/stageSandboxFiles"; + +vi.mock("@/lib/sandboxes/stageSandboxFiles", () => ({ + stageSandboxFiles: vi.fn(), +})); +const files = [new File(["replacement"], "draft.txt")]; +const dropOptions = { selectedPath: "notes", filetree: [], refetch: vi.fn() }; +beforeEach(() => { + vi.mocked(stageSandboxFiles) + .mockReset() + .mockResolvedValue({ + blobFiles: [{ name: "draft.txt", url: "https://blob.example/draft.txt" }], + blobErrors: [], + }); + fetchMock.mockResolvedValue( + response({ uploaded: [{ path: "notes/draft.txt", sha: "b".repeat(40) }] }), + ); +}); + +it("blocks upload and delete before obtaining credentials when reading another account", async () => { + context.account = "selected-b"; + const drop = renderHook(() => useSandboxFileDrop(dropOptions), { wrapper }); + const deletion = renderHook(() => useDeleteSandbox(), { wrapper }); + act(() => drop.result.current.handleFilesDropped(files)); + await act(async () => { + await expect(deletion.result.current.deleteSandbox()).rejects.toThrow( + /read.only/i, + ); + }); + await waitFor(() => expect(drop.result.current.uploading).toBe(false)); + expect(token).not.toHaveBeenCalled(); + expect(stageSandboxFiles).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("blocks a pending upload if account selection changes while obtaining credentials", async () => { + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileDrop(dropOptions), + { wrapper }, + ); + act(() => result.current.handleFilesDropped(files)); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await act(async () => release("old-token")); + await waitFor(() => expect(result.current.uploading).toBe(false)); + expect(stageSandboxFiles).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("blocks pending uploads when authentication is lost without clearing the user id", async () => { + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileDrop(dropOptions), + { wrapper }, + ); + act(() => result.current.handleFilesDropped(files)); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.authenticated = false; + rerender(); + await act(async () => release("old-token")); + await waitFor(() => expect(result.current.uploading).toBe(false)); + expect(stageSandboxFiles).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("blocks the commit if selection changes after blob staging begins", async () => { + let release!: (value: Awaited>) => void; + vi.mocked(stageSandboxFiles).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileDrop(dropOptions), + { wrapper }, + ); + act(() => result.current.handleFilesDropped(files)); + await waitFor(() => expect(stageSandboxFiles).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await act(async () => release({ blobFiles: [], blobErrors: [] })); + await waitFor(() => expect(result.current.uploading).toBe(false)); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("blocks a pending deletion after switching account", async () => { + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useDeleteSandbox(), { + wrapper, + }); + let deletion!: Promise; + act(() => { + deletion = result.current.deleteSandbox(); + }); + const rejected = expect(deletion).rejects.toThrow(/changed|read.only/i); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await act(async () => { + release("old-token"); + await rejected; + }); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("does not accept a protected replacement while an override is active", async () => { + context.account = "selected-b"; + const { result } = renderHook(() => + useGuardedFileReplacement({ + enabled: true, + opened: { + path: "notes/draft.txt", + sha: "a".repeat(40), + apiBaseUrl: context.origin, + scopeKey: "actor-a", + }, + scopeKey: "actor-a", + selectedPath: "notes/draft.txt", + onSaved: vi.fn(), + }), + ); + await act(async () => result.current.replace(files)); + expect(stageSandboxFiles).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("retains a protected replacement without committing after an override switch", async () => { + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const options = { + enabled: true, + opened: { + path: "notes/draft.txt", + sha: "a".repeat(40), + apiBaseUrl: context.origin, + scopeKey: "actor-a", + }, + scopeKey: "actor-a", + selectedPath: "notes/draft.txt", + onSaved: vi.fn(), + }; + const { result, rerender } = renderHook(() => + useGuardedFileReplacement({ + ...options, + scopeKey: context.account ? "selected-b-scope" : options.scopeKey, + }), + ); + let replacement!: Promise; + act(() => { + replacement = result.current.replace(files); + }); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await act(async () => { + release("old-token"); + await replacement; + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(stageSandboxFiles).not.toHaveBeenCalled(); + expect(result.current.pending).toBeNull(); + expect(result.current.hasPending).toBe(true); + context.account = null; + rerender(); + expect(result.current.pending?.file).toBe(files[0]); +}); + +it("preserves normal-account upload and deletion", async () => { + const drop = renderHook(() => useSandboxFileDrop(dropOptions), { wrapper }); + act(() => drop.result.current.handleFilesDropped(files)); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + const deletion = renderHook(() => useDeleteSandbox(), { wrapper }); + await act(async () => deletion.result.current.deleteSandbox()); + expect(fetchMock).toHaveBeenCalledTimes(2); +}); diff --git a/hooks/__tests__/useSandboxFileContent.account.test.tsx b/hooks/__tests__/useSandboxFileContent.account.test.tsx new file mode 100644 index 000000000..df94c1b58 --- /dev/null +++ b/hooks/__tests__/useSandboxFileContent.account.test.tsx @@ -0,0 +1,124 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from "@testing-library/react"; +import { expect, it } from "vitest"; +import { + context, + token, + fetchMock, + wrapper, + response, +} from "./sandboxAccount.fixture"; +import useSandboxFileContent from "../useSandboxFileContent"; + +it("hides a cached revision on authentication loss even if Privy retains the user id", async () => { + fetchMock.mockResolvedValue( + response({ content: "private A", sha: "a".repeat(40) }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileContent({ path: "draft.txt", includeRevision: true }), + { wrapper }, + ); + await waitFor(() => expect(result.current.openedRevision).toBeDefined()); + context.authenticated = false; + rerender(); + expect(result.current.content).toBeNull(); + expect(result.current.openedRevision).toBeUndefined(); +}); + +it("scopes previews to the selected account and never grants an override a writable revision", async () => { + fetchMock.mockImplementation(async (url: string) => + response({ + account_id: new URL(url).searchParams.get("account_id"), + content: new URL(url).searchParams.get("account_id") ?? "self", + sha: "a".repeat(40), + }), + ); + const { result, rerender } = renderHook( + () => + useSandboxFileContent({ path: "notes/a b.txt", includeRevision: true }), + { wrapper }, + ); + await waitFor(() => expect(result.current.openedRevision).toBeDefined()); + const oldScope = result.current.scopeKey; + context.account = "selected-b"; + rerender(); + expect(result.current.content).toBeNull(); + expect(result.current.openedRevision).toBeUndefined(); + await waitFor(() => expect(result.current.content).toBe("selected-b")); + expect(result.current.scopeKey).not.toBe(oldScope); + expect(result.current.openedRevision).toBeUndefined(); + const url = new URL(fetchMock.mock.calls.at(-1)![0]); + expect(url.searchParams.get("path")).toBe("notes/a b.txt"); + expect(url.searchParams.has("include_revision")).toBe(false); +}); + +it("rejects a late token acquired for a different override", async () => { + context.account = "selected-a"; + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + fetchMock.mockResolvedValue( + response({ account_id: "selected-b", content: "B" }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileContent({ path: "draft.txt" }), + { wrapper }, + ); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await waitFor(() => expect(result.current.content).toBe("B")); + await act(async () => release("old-token")); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +it("does not leak late preview content into the newly selected account", async () => { + let release!: (response: Response) => void; + fetchMock.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileContent({ path: "draft.txt" }), + { wrapper }, + ); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + fetchMock.mockResolvedValue( + response({ account_id: "selected-b", content: "B" }), + ); + rerender(); + await waitFor(() => expect(result.current.content).toBe("B")); + await act(async () => release(response({ content: "private A" }))); + expect(result.current.content).toBe("B"); +}); + +it("restarts a pending preview after switching away and back", async () => { + let release!: (value: Response) => void; + fetchMock.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook( + () => useSandboxFileContent({ path: "draft.txt" }), + { wrapper }, + ); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + fetchMock.mockResolvedValueOnce( + response({ account_id: "selected-b", content: "B" }), + ); + rerender(); + await waitFor(() => expect(result.current.content).toBe("B")); + context.account = null; + fetchMock.mockResolvedValue(response({ content: "fresh" })); + rerender(); + await waitFor(() => expect(result.current.content).toBe("fresh")); + await act(async () => release(response({ content: "old" }))); + expect(result.current.content).toBe("fresh"); +}); diff --git a/hooks/__tests__/useSandboxes.account.test.tsx b/hooks/__tests__/useSandboxes.account.test.tsx new file mode 100644 index 000000000..f05c67536 --- /dev/null +++ b/hooks/__tests__/useSandboxes.account.test.tsx @@ -0,0 +1,158 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from "@testing-library/react"; +import { expect, it } from "vitest"; +import { + context, + token, + fetchMock, + wrapper, + response, + client, +} from "./sandboxAccount.fixture"; +import useSandboxes from "../useSandboxes"; + +it("propagates the selected account and never reuses another account's listing", async () => { + fetchMock.mockImplementation(async (url: string) => + response({ + account_id: new URL(url).searchParams.get("account_id"), + sandboxes: [ + { sandboxId: new URL(url).searchParams.get("account_id") ?? "self" }, + ], + filetree: [], + }), + ); + const { result, rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => + expect(result.current.sandboxes[0]?.sandboxId).toBe("self"), + ); + context.account = "selected-b"; + rerender(); + expect(result.current.sandboxes).toEqual([]); + await waitFor(() => + expect(result.current.sandboxes[0]?.sandboxId).toBe("selected-b"), + ); + context.account = "selected-c"; + rerender(); + expect(result.current.sandboxes).toEqual([]); + await waitFor(() => + expect(result.current.sandboxes[0]?.sandboxId).toBe("selected-c"), + ); +}); + +it.each(["actor", "origin"] as const)( + "isolates cached listings when %s changes", + async (field) => { + fetchMock.mockResolvedValue( + response({ sandboxes: [{ sandboxId: "first" }], filetree: [] }), + ); + const { result, rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => expect(result.current.sandboxes).toHaveLength(1)); + fetchMock.mockResolvedValue( + response({ sandboxes: [{ sandboxId: "second" }], filetree: [] }), + ); + context[field] = field === "actor" ? "actor-b" : "https://other.example"; + rerender(); + expect(result.current.sandboxes).toEqual([]); + await waitFor(() => + expect(result.current.sandboxes[0]?.sandboxId).toBe("second"), + ); + }, +); + +it("does not issue a stale request when the account changes during token acquisition", async () => { + let release!: (token: string) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + fetchMock.mockResolvedValue( + response({ account_id: "selected-b", sandboxes: [], filetree: [] }), + ); + const { rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await act(async () => release("old-token")); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +it("discards a response that arrives after selecting a different account", async () => { + let release!: (response: Response) => void; + fetchMock.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + fetchMock.mockResolvedValue( + response({ + account_id: "selected-b", + sandboxes: [{ sandboxId: "b" }], + filetree: [], + }), + ); + rerender(); + await waitFor(() => expect(result.current.sandboxes[0]?.sandboxId).toBe("b")); + await act(async () => + release(response({ sandboxes: [{ sandboxId: "old" }], filetree: [] })), + ); + expect(result.current.sandboxes[0]?.sandboxId).toBe("b"); + expect( + client + .getQueryCache() + .findAll() + .some((q) => (JSON.stringify(q.state.data) ?? "").includes('"old"')), + ).toBe(false); +}); + +it("does not fall back to the signed-in account while an email override resolves", async () => { + context.email = "selected@example.test"; + const { result } = renderHook(() => useSandboxes(), { wrapper }); + await act(async () => {}); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result.current.sandboxes).toEqual([]); +}); + +it("hides the previous listing on sign-out", async () => { + fetchMock.mockResolvedValue( + response({ sandboxes: [{ sandboxId: "private" }], filetree: [] }), + ); + const { result, rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => expect(result.current.sandboxes).toHaveLength(1)); + context.actor = null; + rerender(); + expect(result.current.sandboxes).toEqual([]); +}); + +it("restarts a pending listing after switching away and back", async () => { + let release!: (value: Response) => void; + fetchMock.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useSandboxes(), { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + context.account = "selected-b"; + fetchMock.mockResolvedValueOnce( + response({ account_id: "selected-b", sandboxes: [], filetree: [] }), + ); + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + context.account = null; + fetchMock.mockResolvedValue( + response({ sandboxes: [{ sandboxId: "fresh" }], filetree: [] }), + ); + rerender(); + await waitFor(() => + expect(result.current.sandboxes[0]?.sandboxId).toBe("fresh"), + ); + await act(async () => + release(response({ sandboxes: [{ sandboxId: "old" }], filetree: [] })), + ); + expect(result.current.sandboxes[0]?.sandboxId).toBe("fresh"); +}); diff --git a/hooks/__tests__/useVercelChat.fileScope.test.tsx b/hooks/__tests__/useVercelChat.fileScope.test.tsx new file mode 100644 index 000000000..03174f0d9 --- /dev/null +++ b/hooks/__tests__/useVercelChat.fileScope.test.tsx @@ -0,0 +1,217 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { beforeEach, afterEach, expect, it, vi } from "vitest"; +import { useVercelChat } from "../useVercelChat"; + +const ext = vi.hoisted(() => ({ + account: "selected-b" as string | null, + email: "b@example.test" as string | null, + origin: "https://api.example.test", + token: vi.fn(async () => "synthetic-token"), + headers: vi.fn(async () => ({ Authorization: "Bearer synthetic-token" })), + send: vi.fn(), + files: [{ id: "draft.txt", path: "draft.txt", mime_type: "text/plain" }], + messages: [], + lifecycle: { cancelAll: vi.fn() }, + snapshots: { captureSendIntent: () => () => true }, +})); +vi.mock("@privy-io/react-auth", () => ({ + usePrivy: () => ({ + authenticated: true, + user: { id: "actor" }, + getAccessToken: ext.token, + }), +})); +vi.mock("@/providers/UserProvder", () => ({ + useUserProvider: () => ({ userData: { account_id: "self-a" } }), +})); +vi.mock("@/providers/ArtistProvider", () => ({ + useArtistProvider: () => ({ selectedArtist: null }), +})); +vi.mock("@/providers/OrganizationProvider", () => ({ + useOrganization: () => ({ selectedOrgId: null, isInitialized: true }), +})); +vi.mock("@/providers/AccountOverrideProvider", () => ({ + useAccountOverride: () => ({ + accountIdOverride: ext.account, + email: ext.email, + }), +})); +vi.mock("@/providers/PaymentProvider", () => ({ + usePaymentProvider: () => ({ refetchCredits: vi.fn() }), +})); +vi.mock("@/providers/ConversationsProvider", () => ({ + useConversationsProvider: () => ({ addOptimisticConversation: vi.fn() }), +})); +vi.mock("@/hooks/useAvailableModels", () => ({ + default: () => ({ data: [] }), +})); +vi.mock("@/hooks/useArtistFilesForMentions", () => ({ + default: () => ({ files: ext.files }), +})); +vi.mock("@/hooks/useMessageLoader", () => ({ + useMessageLoader: () => ({ isLoading: false, hasError: false }), +})); +vi.mock("@/hooks/usePersistSelectedModel", () => ({ + usePersistSelectedModel: () => async () => {}, +})); +vi.mock("@/hooks/useDeleteTrailingMessages", () => ({ + useDeleteTrailingMessages: () => ({ deleteTrailingMessages: vi.fn() }), +})); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => ext.origin, +})); +vi.mock("next/navigation", () => ({ useParams: () => ({ chatId: "chat" }) })); +vi.mock("@ai-sdk/react", () => ({ + useChat: () => ({ + messages: ext.messages, + status: "ready", + sendMessage: ext.send, + regenerate: vi.fn(), + setMessages: vi.fn(), + stop: vi.fn(), + }), +})); +vi.mock("@/hooks/useChatTransport", () => ({ + useChatTransport: () => ({ + transport: {}, + getHeaders: ext.headers, + snapshotConsumer: ext.snapshots, + requestLifecycle: ext.lifecycle, + }), +})); +const fetchMock = vi.fn(); +const submit = { preventDefault() {} } as React.FormEvent; +const mount = () => + renderHook(() => useVercelChat({ id: "chat", sessionId: "session" })); +const response = (account: string | null, content: string) => + Response.json({ + status: "success", + ...(account && { account_id: account }), + content, + }); +beforeEach(() => { + ext.account = "selected-b"; + ext.email = "b@example.test"; + ext.origin = "https://api.example.test"; + ext.token.mockReset().mockResolvedValue("synthetic-token"); + ext.headers + .mockReset() + .mockResolvedValue({ Authorization: "Bearer synthetic-token" }); + ext.send + .mockReset() + .mockImplementation(async (_message, request) => + request.metadata.onAccepted({ chatId: "chat", sessionId: "session" }), + ); + fetchMock.mockReset().mockImplementation(async (url) => { + const account = new URL(url).searchParams.get("account_id"); + return response(account, account ?? "private-self-a"); + }); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("NEXT_PUBLIC_RECOUP_INTELLIGENT_UI_CHAT", "false"); + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +it("attaches the selected account's file bytes, not the same path from self", async () => { + const { result } = mount(); + act(() => result.current.setInput("Use @[Draft](draft.txt)")); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(result.current.isLoadingSignedUrls).toBe(false)); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect( + new URL(fetchMock.mock.calls[0][0]).searchParams.get("account_id"), + ).toBe("selected-b"); + expect(ext.send).toHaveBeenCalledTimes(1); + expect(JSON.stringify(ext.send.mock.calls[0][0])).toContain("selected-b"); + expect(JSON.stringify(ext.send.mock.calls[0][0])).not.toContain( + "private-self-a", + ); + expect(ext.send.mock.calls[0][1].body.accountId).toBe("selected-b"); +}); + +it("blocks plain sends and captured self intents while a selected email is unresolved", async () => { + ext.account = null; + ext.email = null; + const { result, rerender } = mount(); + const oldIntent = result.current.captureSendIntent(); + const oldSend = result.current.handleSendMessage; + act(() => result.current.setInput("Keep this draft")); + ext.email = "waiting@example.test"; + rerender(); + expect(oldIntent()).toBe(false); + await act(async () => { + await oldSend(submit); + await result.current.handleSendMessage(submit); + }); + expect(ext.send).not.toHaveBeenCalled(); + expect(ext.headers).not.toHaveBeenCalled(); + expect(result.current.input).toBe("Keep this draft"); +}); + +it("blocks attachment submission when an older API does not acknowledge the target", async () => { + fetchMock.mockResolvedValue(response(null, "private-self-a")); + const { result } = mount(); + act(() => result.current.setInput("Use @[Draft](draft.txt)")); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(result.current.isLoadingSignedUrls).toBe(false)); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).not.toHaveBeenCalled(); + expect(result.current.input).toContain("Draft"); +}); + +it("cannot submit old mention bytes during a new account's pending read", async () => { + const { result, rerender } = mount(); + act(() => result.current.setInput("Use @[Draft](draft.txt)")); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(result.current.isLoadingSignedUrls).toBe(false)); + let resolve!: (value: Response) => void; + fetchMock.mockReturnValueOnce( + new Promise((done) => { + resolve = done; + }), + ); + ext.account = "selected-c"; + ext.email = "c@example.test"; + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).not.toHaveBeenCalled(); + await act(async () => resolve(response("selected-c", "selected-c"))); + await waitFor(() => expect(result.current.isLoadingSignedUrls).toBe(false)); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(JSON.stringify(ext.send.mock.calls[0][0])).toContain("selected-c"); + expect(JSON.stringify(ext.send.mock.calls[0][0])).not.toContain("selected-b"); +}); + +it("keeps the deep-link send pending until the selected account resolves", async () => { + ext.account = null; + const initialMessages = [ + { + id: "query", + role: "user" as const, + parts: [{ type: "text" as const, text: "Deep link draft" }], + }, + ]; + const { result, rerender } = renderHook(() => + useVercelChat({ id: "chat", sessionId: "session", initialMessages }), + ); + await waitFor(() => expect(result.current.input).toBe("Deep link draft")); + expect(ext.send).not.toHaveBeenCalled(); + ext.account = "selected-b"; + rerender(); + await waitFor(() => expect(ext.send).toHaveBeenCalledTimes(1)); + expect(ext.send.mock.calls[0][1].body.accountId).toBe("selected-b"); +}); diff --git a/hooks/useDeleteSandbox.ts b/hooks/useDeleteSandbox.ts index 79e38c562..964605c55 100644 --- a/hooks/useDeleteSandbox.ts +++ b/hooks/useDeleteSandbox.ts @@ -2,22 +2,35 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { usePrivy } from "@privy-io/react-auth"; import { toast } from "sonner"; import { deleteSandbox } from "@/lib/sandboxes/deleteSandbox"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; interface UseDeleteSandboxReturn { deleteSandbox: () => Promise; isDeleting: boolean; + readOnly: boolean; } export default function useDeleteSandbox(): UseDeleteSandboxReturn { const { getAccessToken } = usePrivy(); + const scope = useSandboxAccountScope(); const queryClient = useQueryClient(); const mutation = useMutation({ mutationFn: async () => { + if (!scope.ready) + throw new Error( + "Please sign in and select an account to delete files.", + ); + if (scope.readOnly) + throw new Error("Files for a selected account are read-only."); + if (!scope.isCurrent()) + throw new Error("The account or connection changed. Try again."); const accessToken = await getAccessToken(); if (!accessToken) { throw new Error("Please sign in to delete sandbox"); } + if (!scope.isCurrent()) + throw new Error("The account or connection changed. Try again."); return deleteSandbox(accessToken); }, onSuccess: () => { @@ -35,5 +48,6 @@ export default function useDeleteSandbox(): UseDeleteSandboxReturn { return { deleteSandbox: deleteSandboxHandler, isDeleting: mutation.isPending, + readOnly: scope.readOnly, }; } diff --git a/hooks/useGuardedFileReplacement.ts b/hooks/useGuardedFileReplacement.ts index 817b20c67..9874907ff 100644 --- a/hooks/useGuardedFileReplacement.ts +++ b/hooks/useGuardedFileReplacement.ts @@ -2,6 +2,7 @@ import { useLayoutEffect, useRef, useState } from "react"; import { usePrivy } from "@privy-io/react-auth"; import { saveOpenedFileReplacement } from "@/lib/sandboxes/saveOpenedFileReplacement"; import { isOpenedRevisionCurrent } from "@/lib/sandboxes/isOpenedRevisionCurrent"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; import type { GuardedReplacementOptions, PendingFileReplacement, @@ -9,6 +10,7 @@ import type { } from "@/lib/sandboxes/guardedFileTypes"; export function useGuardedFileReplacement(options: GuardedReplacementOptions) { const { getAccessToken } = usePrivy(); + const accountScope = useSandboxAccountScope(); const latest = useRef(options); const mounted = useRef(false); useLayoutEffect(() => { @@ -26,6 +28,17 @@ export function useGuardedFileReplacement(options: GuardedReplacementOptions) { const replace = async (files: File[]) => { if (inFlight.current) return; + if ( + !accountScope.ready || + accountScope.readOnly || + !accountScope.isCurrent() + ) { + setFailure({ + scope: options.scopeKey, + message: "Files for a selected account are read-only.", + }); + return; + } const { opened, scopeKey, selectedPath, enabled } = latest.current; if (retained.current) { setFailure({ @@ -60,6 +73,7 @@ export function useGuardedFileReplacement(options: GuardedReplacementOptions) { setSaving(true); const isCurrent = () => mounted.current && + accountScope.isCurrent() && isOpenedRevisionCurrent(latest.current, original.opened); try { await saveOpenedFileReplacement(getAccessToken, original, isCurrent); diff --git a/hooks/useSandboxAccountScope.ts b/hooks/useSandboxAccountScope.ts new file mode 100644 index 000000000..db00eb93e --- /dev/null +++ b/hooks/useSandboxAccountScope.ts @@ -0,0 +1,38 @@ +import { useCallback, useLayoutEffect, useMemo, useRef } from "react"; +import { usePrivy } from "@privy-io/react-auth"; +import { useAccountOverride } from "@/providers/AccountOverrideProvider"; +import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; + +/** Reads can target an override; existing write endpoints only target self. */ +export function useSandboxAccountScope() { + const { user, authenticated } = usePrivy(); + const { accountIdOverride, email } = useAccountOverride(); + const actor = authenticated === false ? "" : (user?.id ?? ""); + const apiBaseUrl = getClientApiBaseUrl(); + const context = useMemo( + () => ({ actor, accountIdOverride, email, apiBaseUrl }), + [actor, accountIdOverride, email, apiBaseUrl], + ); + const current = useRef(context); + useLayoutEffect(() => { + current.current = context; + return () => { + current.current = null; + }; + }, [context]); + const isCurrent = useCallback( + () => current.current === context && getClientApiBaseUrl() === apiBaseUrl, + [context, apiBaseUrl], + ); + return { + accountId: accountIdOverride, + apiBaseUrl, + scopeKey: + accountIdOverride || email + ? JSON.stringify([actor, accountIdOverride, email]) + : actor, + ready: Boolean(actor && (!email || accountIdOverride)), + readOnly: Boolean(accountIdOverride || email), + isCurrent, + }; +} diff --git a/hooks/useSandboxFileContent.ts b/hooks/useSandboxFileContent.ts index 6e8530be1..d54474239 100644 --- a/hooks/useSandboxFileContent.ts +++ b/hooks/useSandboxFileContent.ts @@ -29,7 +29,7 @@ export default function useSandboxFileContent( const effectivePath = options?.path ?? selectedPath; const enabled = options?.enabled ?? true; - const { query, scopeKey, reopen } = useSandboxFileQuery( + const { query, scopeKey, reopen, ready } = useSandboxFileQuery( effectivePath, enabled, options?.includeRevision ?? false, @@ -45,13 +45,15 @@ export default function useSandboxFileContent( return { selectedPath: effectivePath, - content: query.error ? null : (query.data?.content ?? null), - imageUrl: query.error ? null : (query.data?.imageUrl ?? null), - loading: query.isLoading || query.isFetching, + content: !ready || query.error ? null : (query.data?.content ?? null), + imageUrl: !ready || query.error ? null : (query.data?.imageUrl ?? null), + loading: ready && (query.isLoading || query.isFetching), error: query.error?.message ?? null, select, openedRevision: - query.error || query.isFetching ? undefined : query.data?.openedRevision, + !ready || query.error || query.isFetching + ? undefined + : query.data?.openedRevision, scopeKey, reopen: select, }; diff --git a/hooks/useSandboxFileDrop.ts b/hooks/useSandboxFileDrop.ts index f64a8b835..21c16e772 100644 --- a/hooks/useSandboxFileDrop.ts +++ b/hooks/useSandboxFileDrop.ts @@ -4,6 +4,7 @@ import { uploadSandboxFiles } from "@/lib/sandboxes/uploadSandboxFiles"; import { findFileNode } from "@/lib/sandboxes/findFileNode"; import { toast } from "sonner"; import type { FileNode } from "@/lib/sandboxes/parseFileTree"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; /** * Hook that handles sandbox file upload logic using useMutation. @@ -18,13 +19,28 @@ export function useSandboxFileDrop({ refetch: () => void; }) { const { getAccessToken } = usePrivy(); + const scope = useSandboxAccountScope(); const mutation = useMutation({ mutationFn: async (files: File[]) => { + const assertCurrent = () => { + if (!scope.ready) + throw new Error( + "Please sign in and select an account to upload files.", + ); + if (scope.readOnly) + throw new Error("Files for a selected account are read-only."); + if (!scope.isCurrent()) + throw new Error( + "The account or connection changed. Select the upload again.", + ); + }; + assertCurrent(); const accessToken = await getAccessToken(); if (!accessToken) { throw new Error("Please sign in to upload files"); } + assertCurrent(); let targetPath: string | undefined; if (selectedPath) { @@ -37,13 +53,16 @@ export function useSandboxFileDrop({ } } - return uploadSandboxFiles({ + const result = await uploadSandboxFiles({ accessToken, files, path: targetPath, + assertCurrent, }); + return { ...result, isCurrent: scope.isCurrent }; }, onSuccess: (result) => { + if (!result.isCurrent()) return; if (result.errors?.length) { toast.warning( `Uploaded ${result.uploaded.length} files, ${result.errors.length} failed`, diff --git a/hooks/useSandboxFileQuery.ts b/hooks/useSandboxFileQuery.ts index 00da3b215..7950d0b5b 100644 --- a/hooks/useSandboxFileQuery.ts +++ b/hooks/useSandboxFileQuery.ts @@ -1,49 +1,45 @@ -import { useCallback, useLayoutEffect, useRef } from "react"; +import { useCallback } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { usePrivy } from "@privy-io/react-auth"; import { getFileContents } from "@/lib/sandboxes/getFileContents"; -import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; import type { OpenedFileRevision } from "@/lib/sandboxes/guardedFileTypes"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; export function useSandboxFileQuery( path: string | undefined, enabled: boolean, includeRevision: boolean, ) { - const { getAccessToken, user } = usePrivy(); - const scopeKey = user?.id ?? ""; - const apiBaseUrl = getClientApiBaseUrl(); + const { getAccessToken } = usePrivy(); + const scope = useSandboxAccountScope(); + const { scopeKey, apiBaseUrl } = scope; const client = useQueryClient(); - const current = useRef({ scopeKey, apiBaseUrl }); - useLayoutEffect(() => { - current.current = { scopeKey, apiBaseUrl }; - }, [scopeKey, apiBaseUrl]); + const writableRevision = includeRevision && !scope.readOnly; const prefix = ["sandbox-file-content", apiBaseUrl, scopeKey]; const query = useQuery({ queryKey: [...prefix, path, includeRevision], - enabled: Boolean(enabled && path), - queryFn: async () => { + enabled: Boolean(enabled && path && scope.ready), + queryFn: async ({ signal }) => { if (!path) throw new Error("Select a file to open."); + if (!scope.ready || signal.aborted || !scope.isCurrent()) + throw new Error("Select an account to view files."); const accessToken = await getAccessToken(); if (!accessToken) throw new Error("Please sign in to view file contents"); - const sameScope = () => - current.current.scopeKey === scopeKey && - current.current.apiBaseUrl === apiBaseUrl && - getClientApiBaseUrl() === apiBaseUrl; - if (!sameScope()) + if (signal.aborted || !scope.isCurrent()) throw new Error("The account or connection changed. Reopen this file."); const result = await getFileContents(accessToken, path, { - includeRevision, + includeRevision: writableRevision, + accountId: scope.accountId, }); - if (!sameScope()) + if (signal.aborted || !scope.isCurrent()) throw new Error("The account or connection changed. Reopen this file."); const openedRevision: OpenedFileRevision | undefined = - includeRevision && result.sha && scopeKey + writableRevision && result.sha && scopeKey ? { path, sha: result.sha, apiBaseUrl, scopeKey } : undefined; return { ...result, openedRevision }; }, - ...(includeRevision && { + ...(writableRevision && { staleTime: Infinity, refetchOnWindowFocus: false, refetchOnReconnect: false, @@ -58,5 +54,5 @@ export function useSandboxFileQuery( }, [client, apiBaseUrl, scopeKey], ); - return { query, scopeKey, reopen }; + return { query, scopeKey, reopen, ready: scope.ready }; } diff --git a/hooks/useSandboxes.ts b/hooks/useSandboxes.ts index 0deff6d7f..fc3e54877 100644 --- a/hooks/useSandboxes.ts +++ b/hooks/useSandboxes.ts @@ -6,6 +6,7 @@ import { convertFileTreeEntries } from "@/lib/sandboxes/convertFileTreeEntries"; import getSubtreeAtPath from "@/lib/sandboxes/getSubtreeAtPath"; import type { Sandbox } from "@/lib/sandboxes/createSandbox"; import type { FileNode } from "@/lib/sandboxes/parseFileTree"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; interface UseSandboxesReturn { sandboxes: Sandbox[]; @@ -17,27 +18,37 @@ interface UseSandboxesReturn { export default function useSandboxes(): UseSandboxesReturn { const { getAccessToken, authenticated } = usePrivy(); + const scope = useSandboxAccountScope(); + const enabled = authenticated && scope.ready; const query = useQuery({ - queryKey: ["sandboxes"], - queryFn: async () => { + queryKey: ["sandboxes", scope.apiBaseUrl, scope.scopeKey], + queryFn: async ({ signal }) => { + if (!enabled || signal.aborted || !scope.isCurrent()) + throw new Error("Select an account to view files."); const accessToken = await getAccessToken(); if (!accessToken) { throw new Error("Please sign in to view sandboxes"); } - return getSandboxes(accessToken); + if (signal.aborted || !scope.isCurrent()) + throw new Error("The account or connection changed. Reload the files."); + const result = await getSandboxes(accessToken, scope.accountId); + if (signal.aborted || !scope.isCurrent()) + throw new Error("The account or connection changed. Reload the files."); + return result; }, - enabled: authenticated, + enabled, }); + const entries = enabled && !query.error ? query.data?.filetree : undefined; const filetree = useMemo(() => { - if (!query.data?.filetree) return []; - const tree = convertFileTreeEntries(query.data.filetree); + if (!entries) return []; + const tree = convertFileTreeEntries(entries); return getSubtreeAtPath(tree); - }, [query.data?.filetree]); + }, [entries]); return { - sandboxes: query.data?.sandboxes || [], + sandboxes: enabled && !query.error ? query.data?.sandboxes || [] : [], filetree, isLoading: query.isLoading, error: query.error, diff --git a/hooks/useVercelChat.ts b/hooks/useVercelChat.ts index 83590f988..a0b566b18 100644 --- a/hooks/useVercelChat.ts +++ b/hooks/useVercelChat.ts @@ -30,6 +30,7 @@ import { usePaymentProvider } from "@/providers/PaymentProvider"; import useArtistFilesForMentions from "@/hooks/useArtistFilesForMentions"; import { useChatTransport } from "./useChatTransport"; import { usePrivy } from "@privy-io/react-auth"; +import { useSandboxAccountScope } from "./useSandboxAccountScope"; import { TextAttachment } from "@/types/textAttachment"; import { formatTextAttachments } from "@/lib/chat/formatTextAttachments"; import { useDeleteTrailingMessages } from "./useDeleteTrailingMessages"; @@ -106,7 +107,15 @@ export function useVercelChat({ const userId = userData?.account_id || userData?.id; // Use account_id if available, fallback to id const { accountIdOverride } = useAccountOverride(); - const effectiveAccountId = accountIdOverride ?? userId; + const { + scopeKey: fileScopeKey, + apiBaseUrl: fileApiBaseUrl, + ready: fileScopeReady, + isCurrent: isFileScopeCurrent, + } = useSandboxAccountScope(); + const effectiveAccountId = fileScopeReady + ? (accountIdOverride ?? userId) + : undefined; const catalogHost = getChatCatalogHost({ catalogId, catalogQuery, @@ -205,6 +214,9 @@ export function useVercelChat({ isNewChatBootstrap, authenticatedUser?.id, effectiveAccountId, + fileScopeKey, + fileApiBaseUrl, + fileScopeReady, organizationId, artistId, catalogHost.kind === "catalog" @@ -316,12 +328,16 @@ export function useVercelChat({ ); const coordinateHistory = isChatIntelligentUIEnabled(); const captureSendIntent = useCallback(() => { - if (!isActionCurrent()) return () => false; + if (!isActionCurrent() || !fileScopeReady || !isFileScopeCurrent()) + return () => false; const epoch = intentEpoch.current; const snapshotCurrent = snapshotConsumer.captureSendIntent(); return () => - isActionCurrent() && epoch === intentEpoch.current && snapshotCurrent(); - }, [snapshotConsumer, isActionCurrent]); + isActionCurrent() && + isFileScopeCurrent() && + epoch === intentEpoch.current && + snapshotCurrent(); + }, [snapshotConsumer, isActionCurrent, fileScopeReady, isFileScopeCurrent]); const historyLoadScope = coordinateHistory ? JSON.stringify([ authenticatedUser?.id, @@ -386,10 +402,22 @@ export function useVercelChat({ ); const [mentionTextContext, setMentionTextContext] = useState(""); const [isLoadingSignedUrls, setIsLoadingSignedUrls] = useState(false); + const mentionRequestScope = JSON.stringify([ + fileScopeKey, + fileApiBaseUrl, + fileScopeReady, + selectedFileIds, + allArtistFiles.map((file) => [file.id, file.path]), + ]); + const [resolvedMentionScope, setResolvedMentionScope] = useState< + string | null + >(null); useEffect(() => { let cancelled = false; const run = async () => { + setResolvedMentionScope(null); + if (!fileScopeReady || !isFileScopeCurrent()) return; if (!selectedFileIds.length) { if (!cancelled) setMentionAttachments((prev) => (prev.length ? [] : prev)); @@ -412,13 +440,16 @@ export function useVercelChat({ if (!cancelled) setIsLoadingSignedUrls(true); const accessToken = await getAccessToken(); + if (cancelled || !isFileScopeCurrent()) return; if (!accessToken) { throw new Error("Please sign in to attach mentioned files"); } const results = await Promise.all( selected.map(async (f) => { - const fileResult = await getFileContents(accessToken, f.path); + const fileResult = await getFileContents(accessToken, f.path, { + accountId: accountIdOverride, + }); const mimeType = f.mime_type || getMimeFromPath(f.path); return { path: f.path, @@ -428,6 +459,7 @@ export function useVercelChat({ }; }), ); + if (cancelled || !isFileScopeCurrent()) return; const nextAttachments: FileUIPart[] = []; const textBlocks: string[] = []; @@ -458,6 +490,7 @@ export function useVercelChat({ textBlocks.length ? textBlocks.join("\n\n") : "", ); if (!cancelled) setIsLoadingSignedUrls(false); + if (!cancelled) setResolvedMentionScope(mentionRequestScope); } catch (e) { console.error(e); if (!cancelled) @@ -470,7 +503,15 @@ export function useVercelChat({ return () => { cancelled = true; }; - }, [selectedFileIds, allArtistFiles, getAccessToken]); + }, [ + selectedFileIds, + allArtistFiles, + getAccessToken, + accountIdOverride, + fileScopeReady, + isFileScopeCurrent, + mentionRequestScope, + ]); const chatRequestBody = useMemo( () => ({ @@ -500,6 +541,7 @@ export function useVercelChat({ // 401s/404s on every cold load and surfaces as an error toast // (chat#1949 F4a). resume: + fileScopeReady && shouldResumeStream({ authenticated, routeChatId: chatId }) && (!coordinateHistory || (historyReadiness?.scopeKey === historyLoadScope && @@ -908,7 +950,7 @@ export function useVercelChat({ // is already typing into while provisioning resolves. const { isLoading: isMessagesLoading, hasError } = useMessageLoader( sessionId, - chatId && (coordinateHistory || messages.length === 0) + fileScopeReady && chatId && (coordinateHistory || messages.length === 0) ? transportChatId : undefined, userId, @@ -945,6 +987,24 @@ export function useVercelChat({ retryDraft?: SubmittedChatDraft, ) => { event.preventDefault(); + if (!fileScopeReady || !isFileScopeCurrent()) { + if (isActionCurrent()) + setSendError( + "Wait for the selected account to resolve, or clear the account selection.", + ); + return false; + } + if ( + !retryDraft && + selectedFileIds.length && + resolvedMentionScope !== mentionRequestScope + ) { + if (isActionCurrent()) + setSendError( + "Mentioned files are not ready for this account. Wait for them to load, or remove the file mentions.", + ); + return false; + } if ( (isGeneratingResponse && !retryDraft) || preparing || @@ -1043,7 +1103,11 @@ export function useVercelChat({ // lives entirely in this hook — extend it there, not here (chat#1847). useInitialMessageAutoSend({ initialMessages, - autoSendCancelled: initialAutoSendCancelled, + autoSendCancelled: + initialAutoSendCancelled || + !fileScopeReady || + (selectedFileIds.length > 0 && + resolvedMentionScope !== mentionRequestScope), status, messagesLength: messages.length, sessionId, diff --git a/lib/sandboxes/__tests__/accountScope.test.ts b/lib/sandboxes/__tests__/accountScope.test.ts new file mode 100644 index 000000000..7e7229091 --- /dev/null +++ b/lib/sandboxes/__tests__/accountScope.test.ts @@ -0,0 +1,95 @@ +import { beforeEach, afterEach, expect, it, vi } from "vitest"; +import { getSandboxes } from "../getSandboxes"; +import { getFileContents } from "../getFileContents"; + +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => "https://api.example.test", +})); +const fetchMock = vi.fn(); +beforeEach(() => { + fetchMock.mockReset(); + vi.stubGlobal("fetch", fetchMock); +}); +afterEach(() => vi.unstubAllGlobals()); + +it.each([undefined, "wrong-account"])( + "rejects overridden listing and contents when the API echoes %s", + async (account_id) => { + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + status: "success", + account_id, + content: "wrong account", + sandboxes: [], + filetree: [], + }), + }); + await expect(getSandboxes("token", "selected-b")).rejects.toThrow( + /selected account/i, + ); + await expect( + getFileContents("token", "path.txt", { accountId: "selected-b" }), + ).rejects.toThrow(/selected account/i); + }, +); + +it("encodes the override/path and accepts only the matching response account", async () => { + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + status: "success", + account_id: "selected-b", + content: "B", + sandboxes: [], + filetree: [], + }), + }); + await expect(getSandboxes("token", "selected-b")).resolves.toEqual({ + sandboxes: [], + filetree: [], + }); + await expect( + getFileContents("token", "a & b.txt", { accountId: "selected-b" }), + ).resolves.toEqual({ content: "B", imageUrl: null }); + const urls = fetchMock.mock.calls.map(([url]) => new URL(url)); + expect( + urls.every((url) => url.searchParams.get("account_id") === "selected-b"), + ).toBe(true); + expect(urls[1].searchParams.get("path")).toBe("a & b.txt"); +}); + +it("never fetches a writable revision for an override", async () => { + await expect( + getFileContents("token", "path.txt", { + accountId: "selected-b", + includeRevision: true, + }), + ).rejects.toThrow(/read.only/i); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("keeps normal self-account response shapes compatible", async () => { + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + status: "success", + content: "self", + sandboxes: [], + filetree: [], + }), + }); + await expect(getSandboxes("token")).resolves.toEqual({ + sandboxes: [], + filetree: [], + }); + await expect(getFileContents("token", "path.txt")).resolves.toEqual({ + content: "self", + imageUrl: null, + }); + expect( + fetchMock.mock.calls.every( + ([url]) => !new URL(url).searchParams.has("account_id"), + ), + ).toBe(true); +}); diff --git a/lib/sandboxes/getFileContents.ts b/lib/sandboxes/getFileContents.ts index 729069ec9..ade0cb9da 100644 --- a/lib/sandboxes/getFileContents.ts +++ b/lib/sandboxes/getFileContents.ts @@ -8,6 +8,7 @@ interface GetFileContentsResponse { encoding?: "base64"; error?: string; sha?: string; + account_id?: string; } interface FileContentsResult { @@ -24,8 +25,10 @@ interface FileContentsResult { export async function getFileContents( accessToken: string, path: string, - options?: { includeRevision?: boolean }, + options?: { includeRevision?: boolean; accountId?: string | null }, ): Promise { + if (options?.includeRevision && options.accountId) + throw new Error("Files for a selected account are read-only."); const apiBaseUrl = options?.includeRevision ? getGuardedGitApiBaseUrl() : getClientApiBaseUrl(); @@ -33,16 +36,18 @@ export async function getFileContents( throw new Error( "Protected replacement is not enabled for this connection.", ); - const response = await fetch( - `${apiBaseUrl}/api/sandboxes/file?path=${encodeURIComponent(path)}${options?.includeRevision ? "&include_revision=true" : ""}`, - { - method: "GET", - headers: { - Authorization: `Bearer ${accessToken}`, - }, - cache: "no-store", + const url = new URL(`${apiBaseUrl}/api/sandboxes/file`); + url.searchParams.set("path", path); + if (options?.includeRevision) + url.searchParams.set("include_revision", "true"); + if (options?.accountId) url.searchParams.set("account_id", options.accountId); + const response = await fetch(url.toString(), { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, }, - ); + cache: "no-store", + }); const data: GetFileContentsResponse = await response.json(); @@ -58,6 +63,10 @@ export async function getFileContents( "This connection did not return an opened file revision. Replacement is blocked.", ); } + if (options?.accountId && data.account_id !== options.accountId) + throw new Error( + "This connection did not confirm the selected account. Files are unavailable.", + ); const revision = options?.includeRevision ? { sha: data.sha } : {}; if (data.encoding === "base64") { diff --git a/lib/sandboxes/getSandboxes.ts b/lib/sandboxes/getSandboxes.ts index d5b776d4d..0c9bec090 100644 --- a/lib/sandboxes/getSandboxes.ts +++ b/lib/sandboxes/getSandboxes.ts @@ -7,6 +7,7 @@ interface GetSandboxesResponse { sandboxes?: Sandbox[]; filetree?: FileTreeEntry[]; error?: string; + account_id?: string; } export interface GetSandboxesResult { @@ -15,9 +16,12 @@ export interface GetSandboxesResult { } export async function getSandboxes( - accessToken: string + accessToken: string, + accountId?: string | null, ): Promise { - const response = await fetch(`${getClientApiBaseUrl()}/api/sandboxes`, { + const url = new URL(`${getClientApiBaseUrl()}/api/sandboxes`); + if (accountId) url.searchParams.set("account_id", accountId); + const response = await fetch(url.toString(), { method: "GET", headers: { Authorization: `Bearer ${accessToken}`, @@ -29,6 +33,10 @@ export async function getSandboxes( if (!response.ok || data.status === "error") { throw new Error(data.error || "Failed to fetch sandboxes"); } + if (accountId && data.account_id !== accountId) + throw new Error( + "This connection did not confirm the selected account. Files are unavailable.", + ); return { sandboxes: data.sandboxes || [], diff --git a/lib/sandboxes/guarded-replacement.md b/lib/sandboxes/guarded-replacement.md index f5eb93c20..28ad10cea 100644 --- a/lib/sandboxes/guarded-replacement.md +++ b/lib/sandboxes/guarded-replacement.md @@ -26,6 +26,14 @@ This narrow immutable-target gate matters because predecessor APIs ignore unknow Replacement retention is in memory for this mounted Files view; it is not a new persistent draft store. Keep a copy before navigating away/closing the tab. A prior account's retained replacement is withheld when the identity changes, and no operation is resumed automatically. +## Selected-account reads + +The Files account-selection companion depends on [API #1131](https://github.com/recoupable/api/pull/1131), reviewed source `b6ee204c`. Deploy that API change before this App change. Explicit `account_id` reads of `/api/sandboxes` and `/api/sandboxes/file` require the response to confirm the same authorized `account_id`; an older or mismatched API origin fails closed instead of showing the signed-in account's files. Default self-account reads retain their existing response shape. + +Listing, preview and mentioned-file reads follow the selected account and isolate their cache/results by authenticated identity, selection and API origin. Pending email resolution never falls back to self. Superseded lookups and responses cannot persist a different account's selection or content, including when switching away and back while a request is pending. + +Every explicit account override is **read-only**, including an override naming the current account: the existing upload and deletion endpoints target the authenticated account, not an override. Upload, delete and protected replacement remain unavailable until returning to the default account. No writable opened revision is created for an override, and an account/authentication/origin change blocks a pending write before staging or commit. This does not enable cross-account writes or alter the default-off protected-replacement gate above. No hosted write or production permission/configuration change is established by these source and regression checks. + ## Tests and remaining limits Synthetic tests exercise the actual upload/read helpers, revision query, replacement controller and Files UI. They cover a disabled/mismatched gate with no guarded request or staged upload; predecessor read without a SHA; unchanged SHA forwarding; conflict without retry; success receipt; uncertain outcome; context change after staging; retained File/original revision after viewing newer data; duplicate-drop suppression; empty text; identity changes during authentication; explicit reopen; and the unchanged legacy upload branch. Provider/auth boundaries are fixtures, not hosted mutation evidence. diff --git a/lib/sandboxes/uploadSandboxFiles.ts b/lib/sandboxes/uploadSandboxFiles.ts index 54051ed94..013a5d22a 100644 --- a/lib/sandboxes/uploadSandboxFiles.ts +++ b/lib/sandboxes/uploadSandboxFiles.ts @@ -35,13 +35,16 @@ export async function uploadSandboxFiles({ path, message, guard, + assertCurrent, }: { accessToken: string; files: File[]; path?: string; message?: string; guard?: FileReplacementGuard; + assertCurrent?: () => void; }): Promise<{ uploaded: UploadedFile[]; errors?: string[] }> { + assertCurrent?.(); if (guard) assertFileReplacementGuard(guard, files, path); const apiBaseUrl = guard?.opened.apiBaseUrl ?? getClientApiBaseUrl(); const { blobFiles, blobErrors } = await stageSandboxFiles( @@ -51,6 +54,7 @@ export async function uploadSandboxFiles({ guard?.opened.sha, ); + assertCurrent?.(); if (guard) assertFileReplacementGuard(guard, files, path); const response = await fetch(`${apiBaseUrl}/api/sandboxes/files`, { method: "POST", diff --git a/providers/AccountOverrideProvider.tsx b/providers/AccountOverrideProvider.tsx index 02117f27e..017972fc6 100644 --- a/providers/AccountOverrideProvider.tsx +++ b/providers/AccountOverrideProvider.tsx @@ -1,6 +1,15 @@ "use client"; -import { createContext, useContext, useState, useCallback, ReactNode } from "react"; +import { + createContext, + useContext, + useState, + useCallback, + useMemo, + useLayoutEffect, + useRef, + ReactNode, +} from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { usePrivy } from "@privy-io/react-auth"; import { useQuery } from "@tanstack/react-query"; @@ -8,6 +17,7 @@ import { fetchAccountIdByEmail } from "@/lib/accounts/fetchAccountIdByEmail"; import { getStoredAccountOverride } from "@/lib/accounts/override/getStoredAccountOverride"; import { setStoredAccountOverride } from "@/lib/accounts/override/setStoredAccountOverride"; import { clearStoredAccountOverride } from "@/lib/accounts/override/clearStoredAccountOverride"; +import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; interface AccountOverrideContextType { accountIdOverride: string | null; @@ -30,37 +40,70 @@ const AccountOverrideContext = createContext({ export function AccountOverrideProvider({ children }: { children: ReactNode }) { const searchParams = useSearchParams(); const router = useRouter(); - const { getAccessToken } = usePrivy(); + const { getAccessToken, user, authenticated } = usePrivy(); const emailParam = searchParams.get("email"); const [stored, setStored] = useState(getStoredAccountOverride); - const email = emailParam || stored.email; - const isClear = emailParam === "clear"; + const [clearRequest, setClearRequest] = useState({ + emailParam, + active: false, + }); + if (clearRequest.emailParam !== emailParam) { + setClearRequest({ emailParam, active: false }); + } + const isClear = + emailParam === "clear" || + (clearRequest.emailParam === emailParam && clearRequest.active); + const email = isClear ? null : emailParam || stored.email; + const actor = authenticated ? user?.id : undefined; + const apiBaseUrl = getClientApiBaseUrl(); + const selection = useMemo( + () => ({ actor, apiBaseUrl, email, isClear }), + [actor, apiBaseUrl, email, isClear], + ); + const current = useRef(selection); + useLayoutEffect(() => { + current.current = selection; + return () => { + current.current = null; + }; + }, [selection]); const { data: resolvedAccountId } = useQuery({ - queryKey: ["accountOverride", email], - queryFn: async () => { + queryKey: ["accountOverride", apiBaseUrl, actor, email, isClear], + queryFn: async ({ signal }) => { if (isClear) { clearStoredAccountOverride(); setStored({ accountId: null, email: null }); return null; } + const isCurrent = () => + !signal.aborted && + current.current === selection && + getClientApiBaseUrl() === apiBaseUrl; + if (!actor || !email || !isCurrent()) return null; const accessToken = await getAccessToken(); - if (!accessToken) return null; - const accountId = await fetchAccountIdByEmail(email!, accessToken); - if (accountId && email) { + if (!accessToken || !isCurrent()) return null; + const accountId = await fetchAccountIdByEmail(email, accessToken); + if (!isCurrent()) return null; + if (accountId) { setStoredAccountOverride(accountId, email); setStored({ accountId, email }); } return accountId; }, - enabled: (!!email || isClear) && !stored.accountId, - staleTime: Infinity, + enabled: isClear || Boolean(actor && email), + staleTime: isClear ? 0 : Infinity, }); - const accountIdOverride = stored.accountId || resolvedAccountId || null; + // Stored IDs may belong to a previous URL, actor or API origin. Resolve the + // selected email in the current authenticated context before exposing an ID. + const accountIdOverride = + actor && !isClear ? (resolvedAccountId ?? null) : null; const clear = useCallback(() => { + current.current = null; + setClearRequest({ emailParam, active: true }); clearStoredAccountOverride(); setStored({ accountId: null, email: null }); const params = new URLSearchParams(searchParams.toString()); @@ -69,10 +112,12 @@ export function AccountOverrideProvider({ children }: { children: ReactNode }) { ? `${window.location.pathname}?${params.toString()}` : window.location.pathname; router.replace(newPath); - }, [searchParams, router]); + }, [searchParams, router, emailParam]); return ( - + {children} ); diff --git a/providers/__tests__/AccountOverrideProvider.test.tsx b/providers/__tests__/AccountOverrideProvider.test.tsx new file mode 100644 index 000000000..8db8c4569 --- /dev/null +++ b/providers/__tests__/AccountOverrideProvider.test.tsx @@ -0,0 +1,205 @@ +// @vitest-environment jsdom +import React from "react"; +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { beforeEach, afterEach, expect, it, vi } from "vitest"; +import { + AccountOverrideProvider, + useAccountOverride, +} from "../AccountOverrideProvider"; +import { fetchAccountIdByEmail } from "@/lib/accounts/fetchAccountIdByEmail"; +import { setStoredAccountOverride } from "@/lib/accounts/override/setStoredAccountOverride"; +import { getStoredAccountOverride } from "@/lib/accounts/override/getStoredAccountOverride"; + +const state = vi.hoisted(() => ({ + email: "b@example.test" as string | null, + actor: "actor-a", + authenticated: true, + origin: "https://api.example.test", +})); +const token = vi.hoisted(() => vi.fn(async () => "synthetic-token")); +const replace = vi.hoisted(() => vi.fn()); +vi.mock("next/navigation", () => ({ + useSearchParams: () => + new URLSearchParams(state.email ? { email: state.email } : {}), + useRouter: () => ({ replace }), +})); +vi.mock("@privy-io/react-auth", () => ({ + usePrivy: () => ({ + user: { id: state.actor }, + authenticated: state.authenticated, + getAccessToken: token, + }), +})); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => state.origin, +})); +vi.mock("@/lib/accounts/fetchAccountIdByEmail", () => ({ + fetchAccountIdByEmail: vi.fn(), +})); +let client: QueryClient; +const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + +); +beforeEach(() => { + state.email = "b@example.test"; + state.actor = "actor-a"; + state.authenticated = true; + state.origin = "https://api.example.test"; + window.sessionStorage.clear(); + token.mockReset().mockResolvedValue("synthetic-token"); + replace.mockReset(); + vi.mocked(fetchAccountIdByEmail) + .mockReset() + .mockImplementation(async (email) => + email === "b@example.test" ? "account-b" : "account-c", + ); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); +}); +afterEach(() => { + cleanup(); + client.clear(); + window.sessionStorage.clear(); +}); + +it("resolves a new URL email instead of pairing it with the previously stored account", async () => { + setStoredAccountOverride("account-b", "b@example.test"); + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); + state.email = "c@example.test"; + rerender(); + expect(result.current.email).toBe("c@example.test"); + expect(result.current.accountIdOverride).toBeNull(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-c"), + ); + expect(getStoredAccountOverride()).toEqual({ + accountId: "account-c", + email: "c@example.test", + }); +}); + +it("never persists an obsolete lookup after selecting another email", async () => { + let release!: (account: string) => void; + vi.mocked(fetchAccountIdByEmail).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1)); + state.email = "c@example.test"; + rerender(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-c"), + ); + await act(async () => release("account-b")); + expect(result.current.accountIdOverride).toBe("account-c"); + expect(getStoredAccountOverride()).toEqual({ + accountId: "account-c", + email: "c@example.test", + }); +}); + +it("restarts an abandoned lookup when returning to the same email before it finishes", async () => { + let release!: (account: string) => void; + vi.mocked(fetchAccountIdByEmail).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1)); + state.email = "c@example.test"; + rerender(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-c"), + ); + state.email = "b@example.test"; + rerender(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); + await act(async () => release("obsolete-b")); + expect(result.current.accountIdOverride).toBe("account-b"); + expect(getStoredAccountOverride().accountId).toBe("account-b"); +}); + +it.each(["actor", "origin"] as const)( + "does not reuse account resolution across a different %s", + async (field) => { + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); + vi.mocked(fetchAccountIdByEmail).mockResolvedValue(null); + state[field] = field === "actor" ? "actor-b" : "https://other.example.test"; + rerender(); + expect(result.current.accountIdOverride).toBeNull(); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(2)); + expect(result.current.accountIdOverride).toBeNull(); + }, +); + +it("hides the override on authentication loss and prevents late persistence", async () => { + let release!: (account: string) => void; + vi.mocked(fetchAccountIdByEmail).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1)); + state.authenticated = false; + rerender(); + await act(async () => release("account-b")); + expect(result.current.accountIdOverride).toBeNull(); + expect(getStoredAccountOverride().accountId).toBeNull(); +}); + +it("clears a stored override through the URL and does not resurrect it on return to default", async () => { + setStoredAccountOverride("account-b", "b@example.test"); + state.email = "clear"; + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => expect(getStoredAccountOverride().accountId).toBeNull()); + expect(result.current.accountIdOverride).toBeNull(); + state.email = null; + rerender(); + expect(result.current.email).toBeNull(); + expect(result.current.accountIdOverride).toBeNull(); +}); + +it("clears immediately and permits selecting the same email again later", async () => { + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); + act(() => result.current.clear()); + expect(result.current.accountIdOverride).toBeNull(); + expect(result.current.email).toBeNull(); + state.email = null; + rerender(); + state.email = "b@example.test"; + rerender(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); +}); From 8ea8e4727e82f66fa43b39703cb04375fa55b5d9 Mon Sep 17 00:00:00 2001 From: Cosmo Date: Sun, 25 Oct 2026 02:47:07 +0200 Subject: [PATCH 2/4] test: assert signed-out catalog requests remain blocked --- .../chats/[chatId]/__tests__/catalogHost.test.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/app/sessions/[sessionId]/chats/[chatId]/__tests__/catalogHost.test.tsx b/app/sessions/[sessionId]/chats/[chatId]/__tests__/catalogHost.test.tsx index aece882fb..6dfa01b02 100644 --- a/app/sessions/[sessionId]/chats/[chatId]/__tests__/catalogHost.test.tsx +++ b/app/sessions/[sessionId]/chats/[chatId]/__tests__/catalogHost.test.tsx @@ -698,7 +698,7 @@ it.each([ }, ); -it.each(["workspace", "personal-account", "signed-out"] as const)( +it.each(["workspace", "personal-account"] as const)( "does not bind incomplete %s catalog context", async (incomplete) => { if (incomplete === "workspace") @@ -707,7 +707,6 @@ it.each(["workspace", "personal-account", "signed-out"] as const)( external.organization = null; external.account = "account-label"; } - if (incomplete === "signed-out") external.authenticated = false; const fetch = mockFetch(); await mount(); expect(current.intelligentUI).toBeUndefined(); @@ -721,6 +720,17 @@ it.each(["workspace", "personal-account", "signed-out"] as const)( }, ); +it("does not load, resume, or send catalog chat while signed out", async () => { + external.authenticated = false; + const fetch = mockFetch(); + await mount(); + expect(current.intelligentUI).toBeUndefined(); + await send(); + expect(external.getAccessToken).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + expect(screen.queryByText("Catalog response.")).toBeNull(); +}); + it("replaces artist admission with an explicit catalog subject without inferring a relationship", async () => { external.artist = ids.artist; const artistPart = part(1, "Historical artist answer."); From a76ee1878906ec1f977d2ee9935e95df48dc5e6f Mon Sep 17 00:00:00 2001 From: Cosmo Date: Sun, 25 Oct 2026 02:11:49 +0100 Subject: [PATCH 3/4] fix: keep unresolved account selections clearable --- components/AccountOverrideBadge.tsx | 6 +- .../__tests__/AccountOverrideBadge.test.tsx | 196 ++++++++++++++++++ 2 files changed, 199 insertions(+), 3 deletions(-) create mode 100644 components/__tests__/AccountOverrideBadge.test.tsx diff --git a/components/AccountOverrideBadge.tsx b/components/AccountOverrideBadge.tsx index f36f2d8df..9cb1c73d9 100644 --- a/components/AccountOverrideBadge.tsx +++ b/components/AccountOverrideBadge.tsx @@ -4,17 +4,17 @@ import { X } from "lucide-react"; import { useAccountOverride } from "@/providers/AccountOverrideProvider"; /** - * Displays a pill badge when an account override is active. + * Keeps an explicit account selection clearable even when resolution fails. * Reads from AccountOverrideProvider context. */ export default function AccountOverrideBadge() { const { email, accountIdOverride, clear } = useAccountOverride(); - if (!accountIdOverride || !email) return null; + if (!email) return null; return (
- Viewing as + {accountIdOverride ? "Viewing as" : "Selected account"} {email} + ); +} +function renderSelection() { + return render( + + + + + + , + ); +} +function expectBlockedSelection() { + expect(screen.getByText("selected@example.test")).toBeDefined(); + expect(screen.getByText("Selected account")).toBeDefined(); + expect(screen.queryByText("Viewing as")).toBeNull(); + expect( + ( + screen.getByRole("button", { + name: "Default files ready", + }) as HTMLButtonElement + ).disabled, + ).toBe(true); + expect( + screen.getByRole("button", { name: "Clear account override" }), + ).toBeDefined(); +} +function clearAndExpectDefault() { + fireEvent.click( + screen.getByRole("button", { name: "Clear account override" }), + ); + expect( + screen.queryByRole("button", { name: "Clear account override" }), + ).toBeNull(); + expect( + ( + screen.getByRole("button", { + name: "Default files ready", + }) as HTMLButtonElement + ).disabled, + ).toBe(false); + expect(getStoredAccountOverride()).toEqual({ accountId: null, email: null }); + expect(replace).toHaveBeenCalledWith(window.location.pathname); +} + +beforeEach(() => { + state.email = "selected@example.test"; + window.sessionStorage.clear(); + token.mockReset().mockResolvedValue("synthetic-token"); + replace.mockReset(); + vi.mocked(fetchAccountIdByEmail).mockReset(); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); +}); +afterEach(() => { + cleanup(); + client.clear(); + window.sessionStorage.clear(); +}); + +it("allows clearing a pending selection and does not revive it after the lookup finishes", async () => { + let release!: (account: string) => void; + vi.mocked(fetchAccountIdByEmail).mockReturnValue( + new Promise((resolve) => { + release = resolve; + }), + ); + renderSelection(); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1)); + expectBlockedSelection(); + clearAndExpectDefault(); + await act(async () => release("selected-account")); + expect(screen.queryByText("selected@example.test")).toBeNull(); + expect(getStoredAccountOverride().accountId).toBeNull(); + expect( + ( + screen.getByRole("button", { + name: "Default files ready", + }) as HTMLButtonElement + ).disabled, + ).toBe(false); +}); + +it("keeps an unresolved persisted selection blocked until the user clears it", async () => { + state.email = null; + setStoredAccountOverride("old-account", "selected@example.test"); + vi.mocked(fetchAccountIdByEmail).mockResolvedValue(null); + renderSelection(); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1); + expectBlockedSelection(); + clearAndExpectDefault(); +}); + +it("offers explicit recovery when the account lookup rejects", async () => { + vi.mocked(fetchAccountIdByEmail).mockRejectedValue( + new Error("Account lookup failed: 403"), + ); + renderSelection(); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1); + expectBlockedSelection(); + clearAndExpectDefault(); +}); + +it("offers explicit recovery when no access token is available", async () => { + token.mockResolvedValue(null); + renderSelection(); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expect(token).toHaveBeenCalled(); + expect(fetchAccountIdByEmail).not.toHaveBeenCalled(); + expectBlockedSelection(); + clearAndExpectDefault(); +}); + +it("preserves the resolved badge and its clear action", async () => { + vi.mocked(fetchAccountIdByEmail).mockResolvedValue("selected-account"); + renderSelection(); + await waitFor(() => expect(screen.getByText("Viewing as")).toBeDefined()); + expect(screen.getByText("selected@example.test")).toBeDefined(); + expect( + ( + screen.getByRole("button", { + name: "Selected files ready", + }) as HTMLButtonElement + ).disabled, + ).toBe(false); + clearAndExpectDefault(); +}); + +it("does not show an override badge for the default account", () => { + state.email = null; + renderSelection(); + expect( + screen.queryByRole("button", { name: "Clear account override" }), + ).toBeNull(); + expect( + ( + screen.getByRole("button", { + name: "Default files ready", + }) as HTMLButtonElement + ).disabled, + ).toBe(false); + expect(fetchAccountIdByEmail).not.toHaveBeenCalled(); +}); From 997c5b7dd197e9bfa8e7f1fde9bdc674c03e1fe7 Mon Sep 17 00:00:00 2001 From: Cosmo Date: Sun, 25 Oct 2026 02:25:48 +0100 Subject: [PATCH 4/4] fix(files): preserve account recovery and complete selected mentions --- components/Sandboxes/SandboxFileWorkspace.tsx | 8 ++ .../SandboxAccountReadiness.test.tsx | 131 ++++++++++++++++++ .../__tests__/guardedJourney.mocks.tsx | 1 + .../useVercelChat.fileScope.test.tsx | 70 ++++++++++ hooks/useSandboxes.ts | 2 + hooks/useVercelChat.ts | 3 +- providers/AccountOverrideProvider.tsx | 3 +- .../AccountOverrideProvider.test.tsx | 64 ++++++++- 8 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 components/Sandboxes/__tests__/SandboxAccountReadiness.test.tsx diff --git a/components/Sandboxes/SandboxFileWorkspace.tsx b/components/Sandboxes/SandboxFileWorkspace.tsx index 09229704b..b4b5c364e 100644 --- a/components/Sandboxes/SandboxFileWorkspace.tsx +++ b/components/Sandboxes/SandboxFileWorkspace.tsx @@ -27,6 +27,14 @@ export default function SandboxFileWorkspace({ ); + if (!listing.scopeReady) + return withPreview( +

+ {readOnly + ? "The selected account is not ready. Clear the account selection using the badge above to return to your account." + : "Sign in to view files."} +

, + ); if (listing.isLoading) return withPreview(
diff --git a/components/Sandboxes/__tests__/SandboxAccountReadiness.test.tsx b/components/Sandboxes/__tests__/SandboxAccountReadiness.test.tsx new file mode 100644 index 000000000..776285a68 --- /dev/null +++ b/components/Sandboxes/__tests__/SandboxAccountReadiness.test.tsx @@ -0,0 +1,131 @@ +// @vitest-environment jsdom +import React from "react"; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import SandboxFileTree from "../SandboxFileTree"; +import AccountOverrideBadge from "@/components/AccountOverrideBadge"; +import { AccountOverrideProvider } from "@/providers/AccountOverrideProvider"; +import { fetchAccountIdByEmail } from "@/lib/accounts/fetchAccountIdByEmail"; + +vi.mock("next/navigation", () => ({ + useSearchParams: () => + new URLSearchParams({ email: "selected@example.test" }), + useRouter: () => ({ replace: vi.fn() }), +})); +vi.mock("@privy-io/react-auth", () => ({ + usePrivy: () => ({ + user: { id: "actor-a" }, + authenticated: true, + getAccessToken: async () => "synthetic-token", + }), +})); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => "https://api.example.test", +})); +vi.mock("@/lib/accounts/fetchAccountIdByEmail", () => ({ + fetchAccountIdByEmail: vi.fn(), +})); +const fetchMock = vi.fn(); +let client: QueryClient; +function renderFiles() { + return render( + + + + + + , + ); +} +function expectUnresolvedFiles() { + expect(screen.getByText(/selected account is not ready/i)).toBeDefined(); + expect(screen.getByText(/clear.*account.*above/i)).toBeDefined(); + expect(screen.queryByText(/No files yet/)).toBeNull(); + expect(screen.queryByText("Loading files...")).toBeNull(); + expect( + screen.getByRole("button", { name: "Clear account override" }), + ).toBeDefined(); + expect(fetchMock).not.toHaveBeenCalled(); +} +beforeEach(() => { + window.sessionStorage.clear(); + vi.mocked(fetchAccountIdByEmail).mockReset(); + fetchMock.mockReset().mockImplementation(async (url: string) => { + const request = new URL(url); + if (request.pathname !== "/api/sandboxes") + throw new Error("Unexpected request"); + return { + ok: true, + json: async () => ({ + status: "success", + account_id: request.searchParams.get("account_id"), + sandboxes: [], + filetree: [], + }), + }; + }); + vi.stubGlobal("fetch", fetchMock); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); +}); +afterEach(() => { + cleanup(); + client.clear(); + window.sessionStorage.clear(); + vi.unstubAllGlobals(); +}); + +it("does not label a pending account as empty and returns to default only on clear", async () => { + let release!: (value: string) => void; + vi.mocked(fetchAccountIdByEmail).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + renderFiles(); + await waitFor(() => expect(fetchAccountIdByEmail).toHaveBeenCalledTimes(1)); + expectUnresolvedFiles(); + fireEvent.click( + screen.getByRole("button", { name: "Clear account override" }), + ); + await waitFor(() => expect(screen.getByText(/No files yet/)).toBeDefined()); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect( + new URL(fetchMock.mock.calls[0][0]).searchParams.has("account_id"), + ).toBe(false); + await act(async () => release("selected-account")); + expect(screen.queryByText(/selected account is not ready/i)).toBeNull(); +}); + +it.each(["missing", "failed"])( + "distinguishes a %s account lookup from a settled empty account", + async (kind) => { + if (kind === "missing") + vi.mocked(fetchAccountIdByEmail).mockResolvedValue(null); + else + vi.mocked(fetchAccountIdByEmail).mockRejectedValue( + new Error("Account lookup failed"), + ); + renderFiles(); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expectUnresolvedFiles(); + }, +); + +it("shows the real empty state after the selected account is resolved and its list loads", async () => { + vi.mocked(fetchAccountIdByEmail).mockResolvedValue("selected-account"); + renderFiles(); + await waitFor(() => expect(screen.getByText("No files yet.")).toBeDefined()); + expect(screen.queryByText(/selected account is not ready/i)).toBeNull(); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect( + new URL(fetchMock.mock.calls[0][0]).searchParams.get("account_id"), + ).toBe("selected-account"); +}); diff --git a/components/Sandboxes/__tests__/guardedJourney.mocks.tsx b/components/Sandboxes/__tests__/guardedJourney.mocks.tsx index aff964913..3b23eff74 100644 --- a/components/Sandboxes/__tests__/guardedJourney.mocks.tsx +++ b/components/Sandboxes/__tests__/guardedJourney.mocks.tsx @@ -22,6 +22,7 @@ vi.mock("@/hooks/useSandboxes", () => ({ ? [] : [{ name: "draft.txt", path: "notes/draft.txt", type: "file" }], isLoading: fixture.loading, + scopeReady: true, error: fixture.listingError, refetch: fixture.refetch, }), diff --git a/hooks/__tests__/useVercelChat.fileScope.test.tsx b/hooks/__tests__/useVercelChat.fileScope.test.tsx index 03174f0d9..aeeab73db 100644 --- a/hooks/__tests__/useVercelChat.fileScope.test.tsx +++ b/hooks/__tests__/useVercelChat.fileScope.test.tsx @@ -94,6 +94,7 @@ beforeEach(() => { ext.account = "selected-b"; ext.email = "b@example.test"; ext.origin = "https://api.example.test"; + ext.files = [{ id: "draft.txt", path: "draft.txt", mime_type: "text/plain" }]; ext.token.mockReset().mockResolvedValue("synthetic-token"); ext.headers .mockReset() @@ -215,3 +216,72 @@ it("keeps the deep-link send pending until the selected account resolves", async await waitFor(() => expect(ext.send).toHaveBeenCalledTimes(1)); expect(ext.send.mock.calls[0][1].body.accountId).toBe("selected-b"); }); + +it("does not silently omit one unavailable file from a multi-file mention", async () => { + const { result, rerender } = mount(); + await act(async () => { + result.current.setInput("Use @[Draft](draft.txt) and @[Notes](notes.txt)"); + }); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result.current.input).toContain("@[Notes](notes.txt)"); + + ext.files = [ + ...ext.files, + { id: "notes.txt", path: "notes.txt", mime_type: "text/plain" }, + ]; + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(result.current.isLoadingSignedUrls).toBe(false)); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).toHaveBeenCalledTimes(1); + const submitted = JSON.stringify(ext.send.mock.calls[0][0]); + expect(submitted).toContain("[Mentioned File: draft.txt]"); + expect(submitted).toContain("[Mentioned File: notes.txt]"); +}); + +it("requires removing an unavailable mention before sending without that file", async () => { + ext.files = []; + const { result } = mount(); + await act(async () => result.current.setInput("Use @[Missing](missing.txt)")); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).not.toHaveBeenCalled(); + expect(result.current.sendError).toContain("remove the file mentions"); + await act(async () => result.current.setInput("Use the text instead")); + await act(async () => { + await result.current.handleSendMessage(submit); + }); + expect(ext.send).toHaveBeenCalledTimes(1); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +it("waits for deep-link mentioned files instead of sending without attachments", async () => { + ext.files = []; + const initialMessages = [ + { + id: "query", + role: "user" as const, + parts: [{ type: "text" as const, text: "Use @[Draft](draft.txt)" }], + }, + ]; + const { result, rerender } = renderHook(() => + useVercelChat({ id: "chat", sessionId: "session", initialMessages }), + ); + await waitFor(() => + expect(result.current.input).toBe("Use @[Draft](draft.txt)"), + ); + expect(ext.send).not.toHaveBeenCalled(); + ext.files = [{ id: "draft.txt", path: "draft.txt", mime_type: "text/plain" }]; + rerender(); + await waitFor(() => expect(ext.send).toHaveBeenCalledTimes(1)); + expect(JSON.stringify(ext.send.mock.calls[0][0])).toContain( + "[Mentioned File: draft.txt]", + ); +}); diff --git a/hooks/useSandboxes.ts b/hooks/useSandboxes.ts index fc3e54877..264f70552 100644 --- a/hooks/useSandboxes.ts +++ b/hooks/useSandboxes.ts @@ -12,6 +12,7 @@ interface UseSandboxesReturn { sandboxes: Sandbox[]; filetree: FileNode[]; isLoading: boolean; + scopeReady: boolean; error: Error | null; refetch: () => void; } @@ -51,6 +52,7 @@ export default function useSandboxes(): UseSandboxesReturn { sandboxes: enabled && !query.error ? query.data?.sandboxes || [] : [], filetree, isLoading: query.isLoading, + scopeReady: enabled, error: query.error, refetch: query.refetch, }; diff --git a/hooks/useVercelChat.ts b/hooks/useVercelChat.ts index a0b566b18..bb990382f 100644 --- a/hooks/useVercelChat.ts +++ b/hooks/useVercelChat.ts @@ -428,7 +428,8 @@ export function useVercelChat({ const idSet = new Set(selectedFileIds); const selected = allArtistFiles.filter((f) => idSet.has(f.id)); - if (selected.length === 0) { + // Never silently omit an unavailable file from the selected mentions. + if (selected.length !== selectedFileIds.length) { if (!cancelled) setMentionAttachments((prev) => (prev.length ? [] : prev)); if (!cancelled) setMentionTextContext((prev) => (prev ? "" : prev)); diff --git a/providers/AccountOverrideProvider.tsx b/providers/AccountOverrideProvider.tsx index 017972fc6..c1f684d11 100644 --- a/providers/AccountOverrideProvider.tsx +++ b/providers/AccountOverrideProvider.tsx @@ -83,7 +83,8 @@ export function AccountOverrideProvider({ children }: { children: ReactNode }) { getClientApiBaseUrl() === apiBaseUrl; if (!actor || !email || !isCurrent()) return null; const accessToken = await getAccessToken(); - if (!accessToken || !isCurrent()) return null; + if (!isCurrent()) return null; + if (!accessToken) throw new Error("Please sign in to select an account."); const accountId = await fetchAccountIdByEmail(email, accessToken); if (!isCurrent()) return null; if (accountId) { diff --git a/providers/__tests__/AccountOverrideProvider.test.tsx b/providers/__tests__/AccountOverrideProvider.test.tsx index 8db8c4569..3a3bee0c6 100644 --- a/providers/__tests__/AccountOverrideProvider.test.tsx +++ b/providers/__tests__/AccountOverrideProvider.test.tsx @@ -17,7 +17,9 @@ const state = vi.hoisted(() => ({ authenticated: true, origin: "https://api.example.test", })); -const token = vi.hoisted(() => vi.fn(async () => "synthetic-token")); +const token = vi.hoisted(() => + vi.fn(async (): Promise => "synthetic-token"), +); const replace = vi.hoisted(() => vi.fn()); vi.mock("next/navigation", () => ({ useSearchParams: () => @@ -203,3 +205,63 @@ it("clears immediately and permits selecting the same email again later", async expect(result.current.accountIdOverride).toBe("account-b"), ); }); + +it("retries a transient missing token when the same email is explicitly reselected", async () => { + token.mockResolvedValue(null); + const { result, rerender } = renderHook(() => useAccountOverride(), { + wrapper, + }); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expect(token).toHaveBeenCalledTimes(1); + expect(fetchAccountIdByEmail).not.toHaveBeenCalled(); + expect(result.current.email).toBe("b@example.test"); + expect(result.current.accountIdOverride).toBeNull(); + act(() => result.current.clear()); + state.email = null; + rerender(); + token.mockResolvedValue("available-token"); + state.email = "b@example.test"; + rerender(); + await waitFor(() => + expect(result.current.accountIdOverride).toBe("account-b"), + ); + expect(fetchAccountIdByEmail).toHaveBeenCalledWith( + "b@example.test", + "available-token", + ); +}); + +it("does not infinitely cache a missing token across a provider remount", async () => { + token.mockResolvedValue(null); + const first = renderHook(() => useAccountOverride(), { wrapper }); + await waitFor(() => expect(client.isFetching()).toBe(0)); + expect(first.result.current.accountIdOverride).toBeNull(); + expect(fetchAccountIdByEmail).not.toHaveBeenCalled(); + first.unmount(); + token.mockResolvedValue("available-token"); + const second = renderHook(() => useAccountOverride(), { wrapper }); + await waitFor(() => + expect(second.result.current.accountIdOverride).toBe("account-b"), + ); + expect(fetchAccountIdByEmail).toHaveBeenCalledWith( + "b@example.test", + "available-token", + ); +}); + +it("discards an obsolete missing token after explicit clear", async () => { + let release!: (value: null) => void; + token.mockReturnValueOnce( + new Promise((resolve) => { + release = resolve; + }), + ); + const { result } = renderHook(() => useAccountOverride(), { wrapper }); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + act(() => result.current.clear()); + await act(async () => release(null)); + expect(result.current.email).toBeNull(); + expect(result.current.accountIdOverride).toBeNull(); + expect(fetchAccountIdByEmail).not.toHaveBeenCalled(); + expect(getStoredAccountOverride()).toEqual({ accountId: null, email: null }); +});