Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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();
Expand All @@ -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.");
Expand Down
6 changes: 3 additions & 3 deletions components/AccountOverrideBadge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<div className="fixed top-3 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 bg-amber-500 dark:bg-amber-400 text-black px-4 py-2 rounded-full shadow-lg text-sm font-medium">
<span>Viewing as</span>
<span>{accountIdOverride ? "Viewing as" : "Selected account"}</span>
<span className="font-bold">{email}</span>
<button
onClick={clear}
Expand Down
9 changes: 7 additions & 2 deletions components/Sandboxes/SandboxDeleteButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -34,7 +34,11 @@ export default function SandboxDeleteButton({
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive" size="icon" disabled={isDeleting}>
<Button
variant="destructive"
size="icon"
disabled={isDeleting || readOnly}
>
{isDeleting ? (
<Loader className="h-4 w-4 animate-spin" />
) : (
Expand All @@ -53,6 +57,7 @@ export default function SandboxDeleteButton({
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
disabled={isDeleting || readOnly}
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Expand Down
14 changes: 12 additions & 2 deletions components/Sandboxes/SandboxFileTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { useState } from "react";
import { getGuardedGitApiBaseUrl } from "@/lib/sandboxes/getGuardedGitApiBaseUrl";
import { useGuardedFileReplacement } from "@/hooks/useGuardedFileReplacement";
import GuardedFileReplacementNotice from "./GuardedFileReplacementNotice";
import { useSandboxAccountScope } from "@/hooks/useSandboxAccountScope";

export default function SandboxFileTree() {
const { readOnly } = useSandboxAccountScope();
const listing = useSandboxes();
const { filetree, refetch } = listing;
const [protectReplacement, setProtectReplacement] = useState(false);
Expand All @@ -23,7 +25,7 @@ export default function SandboxFileTree() {
refetch,
});
const guarded = useGuardedFileReplacement({
enabled: protectReplacement,
enabled: protectReplacement && !readOnly,
opened: fileContent.openedRevision,
selectedPath: fileContent.selectedPath,
scopeKey: fileContent.scopeKey,
Expand All @@ -35,18 +37,25 @@ export default function SandboxFileTree() {
});
const busy = uploading || guarded.saving;
const onDrop = (files: File[]) => {
if (readOnly) return;
if (protectReplacement || guarded.hasPending) void guarded.replace(files);
else handleFilesDropped(files);
};

return (
<div className="space-y-4">
{readOnly && (
<p className="text-sm text-muted-foreground">
Files for the selected account are read-only. Return to your account
to upload or replace files.
</p>
)}
{(available || protectReplacement || guarded.hasPending) && (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={protectReplacement || guarded.hasPending}
disabled={busy || guarded.hasPending}
disabled={busy || guarded.hasPending || readOnly}
onChange={(event) => setProtectReplacement(event.target.checked)}
/>
Protect replacement of the opened file
Expand All @@ -67,6 +76,7 @@ export default function SandboxFileTree() {
fileContent={fileContent}
onDrop={onDrop}
busy={busy}
readOnly={readOnly}
/>
</div>
);
Expand Down
19 changes: 19 additions & 0 deletions components/Sandboxes/SandboxFileWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,28 @@ export default function SandboxFileWorkspace({
fileContent,
onDrop,
busy,
readOnly = false,
}: {
listing: ReturnType<typeof useSandboxes>;
fileContent: ReturnType<typeof useSandboxFileContent>;
onDrop: (files: File[]) => void;
busy: boolean;
readOnly?: boolean;
}) {
const withPreview = (status: ReactNode) => (
<>
{status}
<SandboxSelectedFilePreview fileContent={fileContent} />
</>
);
if (!listing.scopeReady)
return withPreview(
<p className="text-sm text-muted-foreground">
{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."}
</p>,
);
if (listing.isLoading)
return withPreview(
<div className="flex items-center gap-2 text-muted-foreground">
Expand All @@ -44,6 +54,15 @@ export default function SandboxFileWorkspace({
</button>
</div>,
);
if (readOnly)
return listing.filetree.length ? (
<SandboxFileBrowser
filetree={listing.filetree}
fileContent={fileContent}
/>
) : (
withPreview(<p>No files yet.</p>)
);
Comment thread
sidneyswift marked this conversation as resolved.
Resolved
if (!listing.filetree.length)
return withPreview(<NoSandboxFiles onDrop={onDrop} disabled={busy} />);
return (
Expand Down
131 changes: 131 additions & 0 deletions components/Sandboxes/__tests__/SandboxAccountReadiness.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<QueryClientProvider client={client}>
<AccountOverrideProvider>
<AccountOverrideBadge />
<SandboxFileTree />
</AccountOverrideProvider>
</QueryClientProvider>,
);
}
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");
});
Original file line number Diff line number Diff line change
@@ -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(<SandboxFileTree />);
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(<SandboxFileTree />);
expect(screen.getByText("No files yet.")).toBeDefined();
expect(screen.queryByLabelText("Upload files")).toBeNull();
});
7 changes: 6 additions & 1 deletion components/Sandboxes/__tests__/guardedJourney.mocks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -18,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,
}),
Expand Down
Loading
Loading