Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
c107840
feat(sessions): enhance session patching with sandbox state management
ahmednahima0-beep May 21, 2026
5c682b0
test(sessions): enhance session route tests with sandbox management m…
ahmednahima0-beep May 21, 2026
a496aaf
refactor(tests): simplify mock implementation for session route tests
ahmednahima0-beep May 21, 2026
cc48342
fix(sessions): improve error handling in stopSandboxOnArchive function
ahmednahima0-beep May 21, 2026
2c110cd
fix(sessions): enhance error handling in stopSandboxOnArchive function
ahmednahima0-beep May 21, 2026
b16d185
fix(sessions): refine unarchive condition for sandbox state management
ahmednahima0-beep May 21, 2026
0cdec95
fix(sessions): further refine unarchive condition for sandbox state m…
ahmednahima0-beep May 21, 2026
04790ee
fix(sessions): add session status check before stopping sandbox on ar…
ahmednahima0-beep May 21, 2026
cd8782b
fix(sessions): optimize session state update in stopSandboxOnArchive
ahmednahima0-beep May 21, 2026
de9729b
Merge branch 'test' into feat/patch-session-archive-side-effects
ahmednahima0-beep May 22, 2026
07ea801
Merge branch 'test' into feat/patch-session-archive-side-effects
ahmednahima0-beep May 26, 2026
8b1e349
Enhance session patching and sandbox state management
ahmednahima0-beep May 26, 2026
4c2a791
Merge branch 'feat/patch-session-archive-side-effects' of https://git…
ahmednahima0-beep May 26, 2026
5a2ce3c
Refactor file path resolution in agent tools
ahmednahima0-beep May 26, 2026
bfda13a
Merge branch 'test' into feat/patch-session-archive-side-effects
ahmednahima0-beep May 27, 2026
7fefdaa
Refactor credit deduction and path handling
ahmednahima0-beep May 27, 2026
4cc3a16
Merge branch 'feat/patch-session-archive-side-effects' of https://git…
ahmednahima0-beep May 27, 2026
925c011
Refactor sandbox path handling in agent tools
ahmednahima0-beep May 27, 2026
a141f48
Enhance path comparison in isPathWithinSandboxDirectory for Windows c…
ahmednahima0-beep May 27, 2026
8ca5866
refactor(agent/tools): revert sandbox path helpers to native path module
ahmednahima0-beep May 27, 2026
eec2fff
chore(pr-578): remove all scope creep
ahmednahima0-beep May 27, 2026
40e7a2e
refactor(sessions): extract isSandboxPausing into lib/sandbox
ahmednahima0-beep May 27, 2026
1b021b0
fix(sessions): preserve snapshot as fallback until stop succeeds; cle…
ahmednahima0-beep May 27, 2026
83af7dd
refactor(sessions): extract isUnarchiveConflict predicate into lib
ahmednahima0-beep May 27, 2026
ecf407a
refactor(sessions): simplify lifecycle state updates in patchSessionB…
ahmednahima0-beep May 27, 2026
d6a924e
refactor(sessions): format imports for lifecycle state patches in pat…
ahmednahima0-beep May 27, 2026
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
14 changes: 14 additions & 0 deletions app/api/sessions/[sessionId]/__tests__/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import type { Tables } from "@/types/database.types";

type SessionRow = Tables<"sessions">;

vi.mock("next/server", async importOriginal => {
const actual = await importOriginal<typeof import("next/server")>();
return { ...actual, after: vi.fn() };
});

vi.mock("@/lib/sessions/stopSandboxOnArchive", () => ({
stopSandboxOnArchive: vi.fn(),
}));

vi.mock("@/lib/supabase/sessions/selectSessions", () => ({
selectSessions: vi.fn(),
}));
Expand Down Expand Up @@ -352,6 +361,11 @@ describe("PATCH /api/sessions/[sessionId]", () => {
expect(updateSession).toHaveBeenCalledWith("sess_1", {
title: "Renamed session",
status: "archived",
lifecycle_state: "archived",
lifecycle_error: null,
lifecycle_run_id: null,
sandbox_expires_at: null,
hibernate_after: null,
});
});

Expand Down
21 changes: 21 additions & 0 deletions lib/sandbox/isSandboxPausing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { hasRuntimeSandboxState } from "@/lib/sandbox/hasRuntimeSandboxState";

/**
* Returns true when a sandbox is actively being paused — i.e. it has
* live runtime state but has not yet reached a terminal lifecycle state
* (`hibernated` or `archived`).
*
* Used by `PATCH /api/sessions/{sessionId}` to guard unarchive requests:
* if the sandbox is still pausing the request returns 409 so the caller
* can retry once the sandbox has settled.
*/
export function isSandboxPausing(row: {
sandbox_state: unknown;
lifecycle_state: string | null;
}): boolean {
return (
hasRuntimeSandboxState(row.sandbox_state) &&
row.lifecycle_state !== "hibernated" &&
row.lifecycle_state !== "archived"
);
}
16 changes: 16 additions & 0 deletions lib/sessions/isUnarchiveConflict.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { isSandboxPausing } from "@/lib/sandbox/isSandboxPausing";

/**
* Returns true when an unarchive request should be rejected with 409:
* the sandbox has no snapshot to restore from and is still actively pausing.
*
* Without a snapshot, the sandbox cannot be unarchived until the pause
* completes; callers should retry after the sandbox settles.
*/
export function isUnarchiveConflict(row: {
sandbox_state: unknown;
lifecycle_state: string | null;
snapshot_url: string | null;
}): boolean {
return !row.snapshot_url && isSandboxPausing(row);
}
21 changes: 21 additions & 0 deletions lib/sessions/lifecycleStatePatches.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Lifecycle fields applied synchronously when a session is archived via
* `PATCH /api/sessions/{sessionId}`. Sandbox stop and snapshot clearing
* run afterward via `stopSandboxOnArchive`.
*/
export const ARCHIVE_LIFECYCLE_PATCH = {
lifecycle_state: "archived",
lifecycle_error: null,
lifecycle_run_id: null,
sandbox_expires_at: null,
hibernate_after: null,
} as const;

/**
* Lifecycle fields applied synchronously when a session is unarchived via
* `PATCH /api/sessions/{sessionId}`.
*/
export const UNARCHIVE_LIFECYCLE_PATCH = {
lifecycle_state: null,
lifecycle_error: null,
} as const;
23 changes: 23 additions & 0 deletions lib/sessions/patchSessionByIdHandler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { after } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { isUnarchiveConflict } from "@/lib/sessions/isUnarchiveConflict";
import {
ARCHIVE_LIFECYCLE_PATCH,
UNARCHIVE_LIFECYCLE_PATCH,
} from "@/lib/sessions/lifecycleStatePatches";
import { validatePatchSessionBody } from "@/lib/sessions/validatePatchSessionBody";
import { stopSandboxOnArchive } from "@/lib/sessions/stopSandboxOnArchive";
import { selectSessions } from "@/lib/supabase/sessions/selectSessions";
import { updateSession } from "@/lib/supabase/sessions/updateSession";
import { toSessionResponse } from "@/lib/sessions/toSessionResponse";
Expand Down Expand Up @@ -56,11 +63,23 @@ export async function patchSessionByIdHandler(
);
}

const shouldArchive = body.status === "archived" && row.status !== "archived";
const shouldUnarchive = body.status === "running" && row.status === "archived";

if (shouldUnarchive && isUnarchiveConflict(row)) {
return NextResponse.json(
{ status: "error", error: "Sandbox is still being paused, try again in a few seconds." },
{ status: 409, headers: getCorsHeaders() },
);
}
Comment on lines +66 to +74

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OCP

  • actual: net new code added inline
  • required: new lib for the net new code additions


const updates = {
...(body.title !== undefined && { title: body.title }),
...(body.status !== undefined && { status: body.status }),
...(body.linesAdded !== undefined && { lines_added: body.linesAdded }),
...(body.linesRemoved !== undefined && { lines_removed: body.linesRemoved }),
...(shouldArchive && ARCHIVE_LIFECYCLE_PATCH),
...(shouldUnarchive && UNARCHIVE_LIFECYCLE_PATCH),
};

if (Object.keys(updates).length === 0) {
Expand All @@ -79,6 +98,10 @@ export async function patchSessionByIdHandler(
);
}

if (shouldArchive) {
after(() => stopSandboxOnArchive(row));
}

return NextResponse.json(
{ session: toSessionResponse(updated) },
{ status: 200, headers: getCorsHeaders() },
Expand Down
68 changes: 68 additions & 0 deletions lib/sessions/stopSandboxOnArchive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { connectSandbox, type SandboxState } from "@/lib/sandbox/factory";
import { clearSandboxState } from "@/lib/sandbox/clearSandboxState";
import { hasRuntimeSandboxState } from "@/lib/sandbox/hasRuntimeSandboxState";
import { selectSessions } from "@/lib/supabase/sessions/selectSessions";
import { updateSession } from "@/lib/supabase/sessions/updateSession";
import type { Tables } from "@/types/database.types";
import type { Json } from "@/types/database.types";

/**
* Fire-and-forget sandbox teardown for newly-archived sessions.
*
* Stops the running sandbox then clears its runtime state so the
* auto-hibernate workflow ignores the row. When the stop fails, persists
* a `lifecycle_error` and — if the row has no snapshot to fall back to —
* clears the runtime sandbox state so future unarchive attempts are not
* blocked forever by the 409 guard.
*
* Must be scheduled via `after()` so the HTTP response is not blocked.
* No-ops immediately when the session has no runtime sandbox.
*
* @param session - The session row as it existed before archiving.
*/
export async function stopSandboxOnArchive(session: Tables<"sessions">): Promise<void> {
if (!hasRuntimeSandboxState(session.sandbox_state)) return;

let stopError: unknown;

try {
const sandbox = await connectSandbox(session.sandbox_state as unknown as SandboxState);
await sandbox.stop();
} catch (error) {
stopError = error;
console.error(`[stopSandboxOnArchive] stop failed for session ${session.id}:`, error);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
}

try {
const rows = await selectSessions({ id: session.id });
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
const current = rows?.[0] ?? null;

if (!current || current.status !== "archived") return;

if (stopError !== undefined) {
const message = stopError instanceof Error ? stopError.message : String(stopError);
const shouldClearState =
!current.snapshot_url && hasRuntimeSandboxState(current.sandbox_state);

await updateSession(session.id, {
lifecycle_error: `Archive finalization failed: ${message}`,
lifecycle_state: "archived",
lifecycle_run_id: null,
sandbox_expires_at: null,
hibernate_after: null,
...(shouldClearState && {
sandbox_state: clearSandboxState(current.sandbox_state) as unknown as Json,
}),
});
return;
}

await updateSession(session.id, {
snapshot_url: null,
snapshot_created_at: null,
sandbox_state: clearSandboxState(session.sandbox_state) as unknown as Json,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
} catch (error) {
console.error(`[stopSandboxOnArchive] state update failed for session ${session.id}:`, error);
}
}
Loading