From 6965584e4a9ab37ac6df2884f443dd1950cfd853 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Aug 2025 11:08:10 -0400 Subject: [PATCH] feat: idempotency key --- docs/command-line-flags.md | 21 +++++ src/commands/remote.test.ts | 154 ++++++++++++++++++++++++++++++++++++ src/commands/remote.ts | 17 ++-- src/index.ts | 4 + 4 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 src/commands/remote.test.ts diff --git a/docs/command-line-flags.md b/docs/command-line-flags.md index 319eea188..647831209 100644 --- a/docs/command-line-flags.md +++ b/docs/command-line-flags.md @@ -68,8 +68,29 @@ cn serve --timeout 600 # 10 minute timeout ```bash cn remote "help debug this" # Create new remote environment cn remote --url https://my-server.com "work" # Connect to existing server +cn remote --idempotency-key my-session "work" # Resume or create idempotent session ``` +### Idempotent Sessions + +Use `--idempotency-key` to create resumable remote sessions: + +```bash +# First time - creates new session +cn remote --idempotency-key "project-review" "start code review" + +# Later - resumes same session if it exists +cn remote --idempotency-key "project-review" "continue where we left off" + +# Different key - creates separate session +cn remote --idempotency-key "feature-dev" "work on new feature" +``` + +The backend manages session lifecycle based on the idempotency key: +- New key = new remote environment +- Existing key = connect to existing session +- Sessions may expire based on backend configuration + ## Common Examples ```bash diff --git a/src/commands/remote.test.ts b/src/commands/remote.test.ts new file mode 100644 index 000000000..d10ace629 --- /dev/null +++ b/src/commands/remote.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { remote } from "./remote.js"; + +// Mock dependencies +vi.mock("../auth/workos.js"); +vi.mock("../env.js"); +vi.mock("../telemetry/telemetryService.js"); +vi.mock("../ui/index.js"); +vi.mock("../util/logger.js"); + +const mockWorkos = vi.mocked( + await import("../auth/workos.js") +); +const mockEnv = vi.mocked(await import("../env.js")); +const mockStartRemoteTUIChat = vi.mocked( + await import("../ui/index.js") +); + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch as any; + +// Mock console methods +const mockConsoleInfo = vi.fn(); +const mockConsoleError = vi.fn(); +global.console = { + ...global.console, + info: mockConsoleInfo, + error: mockConsoleError, +}; + +describe("remote command", () => { + beforeEach(() => { + vi.clearAllMocks(); + + // Setup default mocks + mockWorkos.loadAuthConfig.mockReturnValue({ + userId: "test-user-id", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh-token", + expiresAt: Date.now() + 3600000, + organizationId: null, + }); + + mockWorkos.isAuthenticatedConfig.mockReturnValue(true); + mockWorkos.getAccessToken.mockReturnValue("test-token"); + + mockEnv.env = { + apiBase: "https://api.example.com", + workOsClientId: "test-client-id", + appUrl: "https://test.example.com", + }; + + mockFetch.mockResolvedValue({ + ok: true, + json: async () => ({ + url: "ws://test-url.com", + port: 8080, + }), + }); + + mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any); + }); + + it("should include idempotency key in request body when provided", async () => { + const testIdempotencyKey = "test-idempotency-key-123"; + + await remote("test prompt", { idempotencyKey: testIdempotencyKey }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents/devboxes", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.stringContaining(`"idempotencyKey":"${testIdempotencyKey}"`), + }) + ); + }); + + it("should not include idempotency key in request body when not provided", async () => { + await remote("test prompt", {}); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents/devboxes", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.not.stringContaining("idempotencyKey"), + }) + ); + }); + + it("should display idempotency key in console when provided", async () => { + const testIdempotencyKey = "test-key-456"; + + await remote("test prompt", { idempotencyKey: testIdempotencyKey }); + + expect(mockConsoleInfo).toHaveBeenCalledWith( + expect.stringContaining(`Using idempotency key: ${testIdempotencyKey}`) + ); + }); + + it("should not display idempotency key message when not provided", async () => { + await remote("test prompt", {}); + + expect(mockConsoleInfo).not.toHaveBeenCalledWith( + expect.stringContaining("Using idempotency key:") + ); + }); + + it("should work with direct URL connection and idempotency key", async () => { + const testUrl = "ws://direct-url.com"; + const testIdempotencyKey = "direct-key-789"; + + await remote("test prompt", { + url: testUrl, + idempotencyKey: testIdempotencyKey + }); + + // Should not make POST request when connecting directly to URL + expect(mockFetch).not.toHaveBeenCalled(); + + // Should connect directly to the provided URL + expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( + testUrl, + "test prompt" + ); + }); + + it("should handle proper request body structure with all fields", async () => { + const testIdempotencyKey = "structured-test-key"; + + await remote("test prompt", { idempotencyKey: testIdempotencyKey }); + + const fetchCall = mockFetch.mock.calls[0]; + const requestBody = JSON.parse(fetchCall[1].body); + + expect(requestBody).toEqual({ + cUserId: "test-user-id", + repoUrl: "https://github.com/continuedev/amplified.dev", + name: expect.stringMatching(/^devbox-\d+$/), + prompt: "test prompt", + idempotencyKey: testIdempotencyKey, + }); + }); +}); \ No newline at end of file diff --git a/src/commands/remote.ts b/src/commands/remote.ts index 8f4f42c3d..0b0b829b8 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -12,7 +12,7 @@ import { logger } from "../util/logger.js"; export async function remote( prompt: string | undefined, - options: { url?: string } = {} + options: { url?: string; idempotencyKey?: string } = {} ) { // If --url is provided, connect directly to that URL if (options.url) { @@ -47,18 +47,21 @@ export async function remote( const accessToken = getAccessToken(authConfig); + const requestBody = { + cUserId: authConfig.userId, + repoUrl: "https://github.com/continuedev/amplified.dev", // getRepoUrl(), + name: `devbox-${Date.now()}`, + prompt: prompt, + idempotencyKey: options.idempotencyKey, + }; + const response = await fetch(new URL("agents/devboxes", env.apiBase), { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, - body: JSON.stringify({ - cUserId: authConfig.userId, - repoUrl: "https://github.com/continuedev/amplified.dev", // getRepoUrl(), - name: `devbox-${Date.now()}`, - prompt: prompt, - }), + body: JSON.stringify(requestBody), }); if (!response.ok) { diff --git a/src/index.ts b/src/index.ts index 884b1d490..1ab7a66e6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -156,6 +156,10 @@ program "--url ", "Connect directly to the specified URL instead of creating a new remote environment" ) + .option( + "--idempotency-key ", + "Idempotency key for session management - allows resuming existing sessions" + ) .action(async (prompt: string | undefined, options) => { await remote(prompt, options); });