-
Notifications
You must be signed in to change notification settings - Fork 9
feat(sandbox): port POST /api/sandbox + GET /api/sandbox/status from open-agents #522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
65927e2
feat(sandbox): port POST /api/sandbox + GET /api/sandbox/status from …
sweetmantech f77e5c3
fix(sandbox): treat type-stub sandbox_state as no_sandbox in /status
sweetmantech e0a2b97
refactor(sandbox): SRP/KISS extractions + Tier 1 correctness fixes
sweetmantech 5b1cca4
refactor(sandbox): drop branch from POST /api/sandbox contract
sweetmantech File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { describe, it, expect, vi } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { POST } from "@/app/api/sandbox/route"; | ||
| import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler"; | ||
|
|
||
| vi.mock("@/lib/sandbox/createSandboxHandler", () => ({ | ||
| createSandboxHandler: vi.fn(async () => NextResponse.json({ ok: true }, { status: 200 })), | ||
| })); | ||
|
|
||
| describe("POST /api/sandbox route shell", () => { | ||
| it("delegates to createSandboxHandler", async () => { | ||
| const req = new NextRequest("http://localhost/api/sandbox", { method: "POST" }); | ||
| const res = await POST(req); | ||
|
|
||
| expect(createSandboxHandler).toHaveBeenCalledWith(req); | ||
| expect(res.status).toBe(200); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler"; | ||
|
|
||
| /** | ||
| * OPTIONS handler for CORS preflight requests. | ||
| * | ||
| * @returns A NextResponse with CORS headers. | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { | ||
| status: 204, | ||
| headers: getCorsHeaders(), | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * `POST /api/sandbox` — provision (or resume) a Sandbox bound to a session. | ||
| * | ||
| * @param request - The incoming request. | ||
| * @returns A NextResponse with `{ createdAt, timeout, currentBranch, mode, timing }` on 200, or an error. | ||
| */ | ||
| export async function POST(request: NextRequest) { | ||
| return createSandboxHandler(request); | ||
| } | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
| export const fetchCache = "force-no-store"; | ||
| export const revalidate = 0; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { describe, it, expect, vi } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { GET } from "@/app/api/sandbox/status/route"; | ||
| import { getSandboxStatusHandler } from "@/lib/sandbox/getSandboxStatusHandler"; | ||
|
|
||
| vi.mock("@/lib/sandbox/getSandboxStatusHandler", () => ({ | ||
| getSandboxStatusHandler: vi.fn(async () => NextResponse.json({ ok: true }, { status: 200 })), | ||
| })); | ||
|
|
||
| describe("GET /api/sandbox/status route shell", () => { | ||
| it("delegates to getSandboxStatusHandler", async () => { | ||
| const req = new NextRequest("http://localhost/api/sandbox/status?sessionId=s", { | ||
| method: "GET", | ||
| }); | ||
| const res = await GET(req); | ||
|
|
||
| expect(getSandboxStatusHandler).toHaveBeenCalledWith(req); | ||
| expect(res.status).toBe(200); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { getSandboxStatusHandler } from "@/lib/sandbox/getSandboxStatusHandler"; | ||
|
|
||
| /** | ||
| * OPTIONS handler for CORS preflight requests. | ||
| * | ||
| * @returns A NextResponse with CORS headers. | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { | ||
| status: 204, | ||
| headers: getCorsHeaders(), | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * `GET /api/sandbox/status?sessionId=...` — current lifecycle/runtime state for the sandbox bound to a session. | ||
| * | ||
| * @param request - The incoming request. | ||
| * @returns A NextResponse with `{ status, hasSnapshot, lifecycleVersion, lifecycle }` on 200, or an error. | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| return getSandboxStatusHandler(request); | ||
| } | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
| export const fetchCache = "force-no-store"; | ||
| export const revalidate = 0; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { describe, it, expect, beforeEach, afterEach } from "vitest"; | ||
| import { getServiceGithubToken } from "@/lib/github/getServiceGithubToken"; | ||
|
|
||
| const ORIGINAL = process.env.GITHUB_TOKEN; | ||
|
|
||
| beforeEach(() => { | ||
| delete process.env.GITHUB_TOKEN; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| if (ORIGINAL === undefined) { | ||
| delete process.env.GITHUB_TOKEN; | ||
| } else { | ||
| process.env.GITHUB_TOKEN = ORIGINAL; | ||
| } | ||
| }); | ||
|
|
||
| describe("getServiceGithubToken", () => { | ||
| it("returns undefined when GITHUB_TOKEN is unset", () => { | ||
| expect(getServiceGithubToken()).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined when GITHUB_TOKEN is the empty string", () => { | ||
| process.env.GITHUB_TOKEN = ""; | ||
| expect(getServiceGithubToken()).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns the token when set", () => { | ||
| process.env.GITHUB_TOKEN = "ghs_secret"; | ||
| expect(getServiceGithubToken()).toBe("ghs_secret"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| /** | ||
| * Returns the service-account GitHub token used for cloning private | ||
| * repositories into sandboxes. Returns undefined when the env var is | ||
| * unset or empty so callers can fall back to public-repo behavior | ||
| * without crashing. | ||
| * | ||
| * @returns The token string, or undefined. | ||
| */ | ||
| export function getServiceGithubToken(): string | undefined { | ||
| const token = process.env.GITHUB_TOKEN; | ||
| return token && token.length > 0 ? token : undefined; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { describe, it, expect } from "vitest"; | ||
| import { buildLifecycle } from "@/lib/sandbox/buildLifecycle"; | ||
|
|
||
| const ISO = "2030-01-01T00:00:00.000Z"; | ||
| const EPOCH = Date.parse(ISO); | ||
|
|
||
| describe("buildLifecycle", () => { | ||
| it("converts every ISO timestamp on the row to epoch ms and sets serverTime", () => { | ||
| const row = { | ||
| lifecycle_state: "active", | ||
| last_activity_at: ISO, | ||
| hibernate_after: ISO, | ||
| sandbox_expires_at: ISO, | ||
| } as any; | ||
|
|
||
| const result = buildLifecycle(row); | ||
|
|
||
| expect(result).toEqual({ | ||
| serverTime: expect.any(Number), | ||
| state: "active", | ||
| lastActivityAt: EPOCH, | ||
| hibernateAfter: EPOCH, | ||
| sandboxExpiresAt: EPOCH, | ||
| }); | ||
| }); | ||
|
|
||
| it("preserves null fields and a null lifecycle_state as-is", () => { | ||
| const row = { | ||
| lifecycle_state: null, | ||
| last_activity_at: null, | ||
| hibernate_after: null, | ||
| sandbox_expires_at: null, | ||
| } as any; | ||
|
|
||
| const result = buildLifecycle(row); | ||
|
|
||
| expect(result.state).toBeNull(); | ||
| expect(result.lastActivityAt).toBeNull(); | ||
| expect(result.hibernateAfter).toBeNull(); | ||
| expect(result.sandboxExpiresAt).toBeNull(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler"; | ||
| import { validateCreateSandboxBody } from "@/lib/sandbox/validateCreateSandboxBody"; | ||
| import { selectSessions } from "@/lib/supabase/sessions/selectSessions"; | ||
| import { connectSandbox } from "@/lib/sandbox/factory"; | ||
| import { updateSession } from "@/lib/supabase/sessions/updateSession"; | ||
|
|
||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: () => ({ "Access-Control-Allow-Origin": "*" }), | ||
| })); | ||
| vi.mock("@/lib/sandbox/validateCreateSandboxBody", () => ({ | ||
| validateCreateSandboxBody: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/supabase/sessions/selectSessions", () => ({ | ||
| selectSessions: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/sandbox/factory", () => ({ | ||
| connectSandbox: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/supabase/sessions/updateSession", () => ({ | ||
| updateSession: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/github/getServiceGithubToken", () => ({ | ||
| getServiceGithubToken: vi.fn(() => "ghs_test_token"), | ||
| })); | ||
|
|
||
| const ACCOUNT_ID = "acc-1"; | ||
|
|
||
| function makeReq(): NextRequest { | ||
| return new NextRequest("http://localhost/api/sandbox", { method: "POST" }); | ||
| } | ||
|
|
||
| function fakeSandbox(overrides: Partial<Record<string, unknown>> = {}) { | ||
| return { | ||
| timeout: 1_800_000, | ||
| expiresAt: Date.parse("2030-01-01T00:00:00.000Z"), | ||
| currentBranch: "main", | ||
| getState: () => ({ type: "vercel", sandboxName: "session-sess-1" }), | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| describe("createSandboxHandler", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(validateCreateSandboxBody).mockResolvedValue({ | ||
| body: { | ||
| repoUrl: "https://github.com/o/r", | ||
| sessionId: "sess-1", | ||
| }, | ||
| auth: { accountId: ACCOUNT_ID, orgId: null, authToken: "k" }, | ||
| }); | ||
| vi.mocked(selectSessions).mockResolvedValue([{ id: "sess-1", account_id: ACCOUNT_ID } as any]); | ||
| vi.mocked(connectSandbox).mockResolvedValue( | ||
| fakeSandbox() as unknown as Awaited<ReturnType<typeof connectSandbox>>, | ||
| ); | ||
| vi.mocked(updateSession).mockResolvedValue({} as any); | ||
| }); | ||
|
|
||
| it("short-circuits with the validator's response on validation failure", async () => { | ||
| const fail = NextResponse.json({ status: "error", error: "bad" }, { status: 400 }); | ||
| vi.mocked(validateCreateSandboxBody).mockResolvedValueOnce(fail); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res).toBe(fail); | ||
| expect(connectSandbox).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 404 when sessionId is provided but the session does not exist", async () => { | ||
| vi.mocked(selectSessions).mockResolvedValueOnce([]); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res.status).toBe(404); | ||
| expect(connectSandbox).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 403 when the session is not owned by the authenticated account", async () => { | ||
| vi.mocked(selectSessions).mockResolvedValueOnce([ | ||
| { id: "sess-1", account_id: "someone-else" } as any, | ||
| ]); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res.status).toBe(403); | ||
| expect(connectSandbox).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 502 when the sandbox provider throws", async () => { | ||
| vi.mocked(connectSandbox).mockRejectedValueOnce(new Error("vercel down")); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res.status).toBe(502); | ||
| }); | ||
|
|
||
| it("returns 200 with the documented response shape on success", async () => { | ||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| const body = await res.json(); | ||
| expect(body).toMatchObject({ | ||
| timeout: 1_800_000, | ||
| currentBranch: "main", | ||
| mode: "vercel", | ||
| }); | ||
| expect(typeof body.createdAt).toBe("number"); | ||
| expect(typeof body.timing.readyMs).toBe("number"); | ||
| }); | ||
|
|
||
| it("reports currentBranch from the sandbox handle (not request input)", async () => { | ||
| vi.mocked(connectSandbox).mockResolvedValueOnce( | ||
| fakeSandbox({ currentBranch: "release/v2" }) as unknown as Awaited< | ||
| ReturnType<typeof connectSandbox> | ||
| >, | ||
| ); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| const body = await res.json(); | ||
| expect(body.currentBranch).toBe("release/v2"); | ||
| }); | ||
|
|
||
| it("persists sandbox state and clears stale snapshot fields on the session row", async () => { | ||
| await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(updateSession).toHaveBeenCalledWith( | ||
| "sess-1", | ||
| expect.objectContaining({ | ||
| sandbox_state: { type: "vercel", sandboxName: "session-sess-1" }, | ||
| lifecycle_state: "active", | ||
| snapshot_url: null, | ||
| snapshot_created_at: null, | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it("plumbs the service github token into connectSandbox options", async () => { | ||
| await createSandboxHandler(makeReq()); | ||
|
|
||
| const arg = vi.mocked(connectSandbox).mock.calls[0]?.[0]; | ||
| expect(arg).toBeDefined(); | ||
| if (!arg || !("options" in arg)) throw new Error("expected new-API config shape"); | ||
| expect(arg.options?.githubToken).toBe("ghs_test_token"); | ||
| }); | ||
|
|
||
| it("skips the session-row write when no sessionId is provided", async () => { | ||
| vi.mocked(validateCreateSandboxBody).mockResolvedValueOnce({ | ||
| body: { repoUrl: "https://github.com/o/r" }, | ||
| auth: { accountId: ACCOUNT_ID, orgId: null, authToken: "k" }, | ||
| }); | ||
|
|
||
| const res = await createSandboxHandler(makeReq()); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(updateSession).not.toHaveBeenCalled(); | ||
| expect(selectSessions).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Custom agent: Enforce Clear Code Style and Maintainability Practices
New test file exceeds the 100-line file-size limit required by the maintainability rule.
Prompt for AI agents