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
72 changes: 72 additions & 0 deletions lib/sandbox/__tests__/createSandboxPostHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { NextResponse } from "next/server";
import { createSandboxPostHandler } from "../createSandboxPostHandler";
import { validateSandboxBody } from "@/lib/sandbox/validateSandboxBody";
import { createSandbox } from "@/lib/sandbox/createSandbox";
import { insertAccountSandbox } from "@/lib/supabase/account_sandboxes/insertAccountSandbox";

vi.mock("@/lib/sandbox/validateSandboxBody", () => ({
validateSandboxBody: vi.fn(),
Expand All @@ -14,6 +15,10 @@ vi.mock("@/lib/sandbox/createSandbox", () => ({
createSandbox: vi.fn(),
}));

vi.mock("@/lib/supabase/account_sandboxes/insertAccountSandbox", () => ({
insertAccountSandbox: vi.fn(),
}));

/**
* Creates a mock NextRequest for testing.
*
Expand Down Expand Up @@ -54,6 +59,15 @@ describe("createSandboxPostHandler", () => {
timeout: 600000,
createdAt: "2024-01-01T00:00:00.000Z",
});
vi.mocked(insertAccountSandbox).mockResolvedValue({
data: {
id: "record_123",
account_id: "acc_123",
sandbox_id: "sbx_123",
created_at: "2024-01-01T00:00:00.000Z",
},
error: null,
});

const request = createMockRequest();
const response = await createSandboxPostHandler(request);
Expand All @@ -73,6 +87,38 @@ describe("createSandboxPostHandler", () => {
});
});

it("calls insertAccountSandbox with correct account_id and sandbox_id", async () => {
vi.mocked(validateSandboxBody).mockResolvedValue({
accountId: "acc_123",
orgId: null,
authToken: "token",
prompt: "tell me hello",
});
vi.mocked(createSandbox).mockResolvedValue({
sandboxId: "sbx_456",
sandboxStatus: "running",
timeout: 600000,
createdAt: "2024-01-01T00:00:00.000Z",
});
vi.mocked(insertAccountSandbox).mockResolvedValue({
data: {
id: "record_123",
account_id: "acc_123",
sandbox_id: "sbx_456",
created_at: "2024-01-01T00:00:00.000Z",
},
error: null,
});

const request = createMockRequest();
await createSandboxPostHandler(request);

expect(insertAccountSandbox).toHaveBeenCalledWith({
account_id: "acc_123",
sandbox_id: "sbx_456",
});
});

it("returns 400 with error status when createSandbox throws", async () => {
vi.mocked(validateSandboxBody).mockResolvedValue({
accountId: "acc_123",
Expand All @@ -92,4 +138,30 @@ describe("createSandboxPostHandler", () => {
error: "Sandbox creation failed",
});
});

it("returns 400 with error status when insertAccountSandbox throws", async () => {
vi.mocked(validateSandboxBody).mockResolvedValue({
accountId: "acc_123",
orgId: null,
authToken: "token",
prompt: "tell me hello",
});
vi.mocked(createSandbox).mockResolvedValue({
sandboxId: "sbx_123",
sandboxStatus: "running",
timeout: 600000,
createdAt: "2024-01-01T00:00:00.000Z",
});
vi.mocked(insertAccountSandbox).mockRejectedValue(new Error("Database insert failed"));

const request = createMockRequest();
const response = await createSandboxPostHandler(request);

expect(response.status).toBe(400);
const json = await response.json();
expect(json).toEqual({
status: "error",
error: "Database insert failed",
});
});
});
7 changes: 7 additions & 0 deletions lib/sandbox/createSandboxPostHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { createSandbox } from "@/lib/sandbox/createSandbox";
import { validateSandboxBody } from "@/lib/sandbox/validateSandboxBody";
import { insertAccountSandbox } from "@/lib/supabase/account_sandboxes/insertAccountSandbox";

/**
* Handler for POST /api/sandboxes.
*
* Creates a Vercel Sandbox with Claude's Agent SDK pre-installed and executes a prompt.
* Requires authentication via x-api-key header or Authorization Bearer token.
* Saves sandbox info to the account_sandboxes table.
*
* @param request - The request object
* @returns A NextResponse with sandbox creation result or error
Expand All @@ -22,6 +24,11 @@ export async function createSandboxPostHandler(request: NextRequest): Promise<Ne
try {
const result = await createSandbox(validated.prompt);

await insertAccountSandbox({
account_id: validated.accountId,
sandbox_id: result.sandboxId,
});

return NextResponse.json(
{ status: "success", sandboxes: [result] },
{ status: 200, headers: getCorsHeaders() },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { describe, it, expect, vi, beforeEach } from "vitest";

const mockFrom = vi.fn();
const mockInsert = vi.fn();
const mockSelect = vi.fn();
const mockSingle = vi.fn();

vi.mock("@/lib/supabase/serverClient", () => ({
default: {
from: (...args: unknown[]) => mockFrom(...args),
},
}));

import { insertAccountSandbox } from "../insertAccountSandbox";

describe("insertAccountSandbox", () => {
beforeEach(() => {
vi.clearAllMocks();
mockFrom.mockReturnValue({ insert: mockInsert });
mockInsert.mockReturnValue({ select: mockSelect });
mockSelect.mockReturnValue({ single: mockSingle });
});

it("inserts an account sandbox record and returns data on success", async () => {
const mockData = {
id: "sandbox-record-123",
account_id: "account-456",
sandbox_id: "sbx_789",
created_at: "2024-01-01T00:00:00.000Z",
};
mockSingle.mockResolvedValue({ data: mockData, error: null });

const result = await insertAccountSandbox({
account_id: "account-456",
sandbox_id: "sbx_789",
});

expect(mockFrom).toHaveBeenCalledWith("account_sandboxes");
expect(mockInsert).toHaveBeenCalledWith({
account_id: "account-456",
sandbox_id: "sbx_789",
});
expect(result).toEqual({ data: mockData, error: null });
});

it("returns error when insert fails", async () => {
const mockError = { message: "Insert failed", code: "23505" };
mockSingle.mockResolvedValue({ data: null, error: mockError });

const result = await insertAccountSandbox({
account_id: "account-456",
sandbox_id: "sbx_789",
});

expect(mockFrom).toHaveBeenCalledWith("account_sandboxes");
expect(result).toEqual({ data: null, error: mockError });
});

it("returns error when account_id foreign key constraint fails", async () => {
const mockError = {
message: 'insert or update on table "account_sandboxes" violates foreign key constraint',
code: "23503",
};
mockSingle.mockResolvedValue({ data: null, error: mockError });

const result = await insertAccountSandbox({
account_id: "non-existent-account",
sandbox_id: "sbx_789",
});

expect(result).toEqual({ data: null, error: mockError });
});
});
33 changes: 33 additions & 0 deletions lib/supabase/account_sandboxes/insertAccountSandbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { PostgrestError } from "@supabase/supabase-js";
import supabase from "../serverClient";
import type { Tables, TablesInsert } from "@/types/database.types";

type InsertAccountSandboxResult =
| { data: Tables<"account_sandboxes">; error: null }
| { data: null; error: PostgrestError };

/**
* Inserts an account sandbox record into the database.
*
* @param input - The input object containing account_id and sandbox_id
* @param input.account_id - The account UUID
* @param input.sandbox_id - The sandbox identifier from Vercel
* @returns The inserted account sandbox record or error
*/
export async function insertAccountSandbox({
account_id,
sandbox_id,
}: TablesInsert<"account_sandboxes">): Promise<InsertAccountSandboxResult> {
const { data, error } = await supabase
.from("account_sandboxes")
.insert({
account_id,
sandbox_id,
})
.select()
.single();

if (error) return { data: null, error };

return { data, error: null };
}
29 changes: 29 additions & 0 deletions types/database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,35 @@ export type Database = {
},
]
}
account_sandboxes: {
Row: {
account_id: string
created_at: string
id: string
sandbox_id: string
}
Insert: {
account_id: string
created_at?: string
id?: string
sandbox_id: string
}
Update: {
account_id?: string
created_at?: string
id?: string
sandbox_id?: string
}
Relationships: [
{
foreignKeyName: "account_sandboxes_account_id_fkey"
columns: ["account_id"]
isOneToOne: false
referencedRelation: "accounts"
referencedColumns: ["id"]
},
]
}
account_socials: {
Row: {
account_id: string | null
Expand Down