Merge pull request #170 from continuedev/idempotency-key

feat: idempotency key
This commit is contained in:
Nate Sesti 2025-08-09 06:20:18 -07:00 • committed by GitHub
commit 9100a37cfb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 337 additions and 9 deletions

View file

@ -68,8 +68,40 @@ 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
### Repository Detection
The `cn remote` command automatically detects your repository URL:
- **GitHub Actions**: Uses `GITHUB_REPOSITORY` and `GITHUB_SERVER_URL` environment variables
- **Git Repository**: Uses `git remote get-url origin`
- **Fallback**: Uses current working directory path
This ensures the remote environment is created with the correct repository context.
## Common Examples
```bash

170
src/commands/remote.test.ts Normal file
View file

@ -0,0 +1,170 @@
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/git.js");
vi.mock("../util/logger.js");
const mockWorkos = vi.mocked(
await import("../auth/workos.js")
);
const mockEnv = vi.mocked(await import("../env.js"));
const mockGit = vi.mocked(await import("../util/git.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();
// Clear GitHub Actions environment variables
delete process.env.GITHUB_ACTIONS;
delete process.env.GITHUB_REPOSITORY;
delete process.env.GITHUB_SERVER_URL;
// 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",
};
mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git");
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 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/user/test-repo.git",
name: expect.stringMatching(/^devbox-\d+$/),
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
});
});
it("should call getRepoUrl to get the current repository URL", async () => {
await remote("test prompt", {});
expect(mockGit.getRepoUrl).toHaveBeenCalled();
});
it("should work correctly in GitHub Actions environment", async () => {
// Simulate GitHub Actions environment
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "myorg/myrepo";
// Mock getRepoUrl to return the GitHub Actions URL
mockGit.getRepoUrl.mockReturnValue("https://github.com/myorg/myrepo.git");
await remote("test prompt", { idempotencyKey: "github-actions-key" });
const fetchCall = mockFetch.mock.calls[0];
const requestBody = JSON.parse(fetchCall[1].body);
expect(requestBody.repoUrl).toBe("https://github.com/myorg/myrepo.git");
expect(requestBody.idempotencyKey).toBe("github-actions-key");
});
});

View file

@ -8,11 +8,12 @@ import {
import { env } from "../env.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import { getRepoUrl } from "../util/git.js";
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 +48,21 @@ export async function remote(
const accessToken = getAccessToken(authConfig);
const requestBody: any = {
cUserId: authConfig.userId,
repoUrl: 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) {

View file

@ -156,6 +156,10 @@ program
"--url <url>",
"Connect directly to the specified URL instead of creating a new remote environment",
)
.option(
"--idempotency-key <key>",
"Idempotency key for session management - allows resuming existing sessions",
)
.action(async (prompt: string | undefined, options) => {
await remote(prompt, options);
});

78
src/util/git.test.ts Normal file
View file

@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
getGitHubActionsRepoUrl,
isGitHubActions,
} from "./git.js";
describe("git utilities - GitHub Actions detection", () => {
beforeEach(() => {
// Clear environment variables
delete process.env.GITHUB_ACTIONS;
delete process.env.GITHUB_REPOSITORY;
delete process.env.GITHUB_SERVER_URL;
});
describe("isGitHubActions", () => {
it("should return true when GITHUB_ACTIONS is 'true'", () => {
process.env.GITHUB_ACTIONS = "true";
expect(isGitHubActions()).toBe(true);
});
it("should return false when GITHUB_ACTIONS is not set", () => {
expect(isGitHubActions()).toBe(false);
});
it("should return false when GITHUB_ACTIONS is set to other values", () => {
process.env.GITHUB_ACTIONS = "false";
expect(isGitHubActions()).toBe(false);
});
});
describe("getGitHubActionsRepoUrl", () => {
it("should return null when not in GitHub Actions", () => {
expect(getGitHubActionsRepoUrl()).toBeNull();
});
it("should return null when GITHUB_REPOSITORY is not set", () => {
process.env.GITHUB_ACTIONS = "true";
expect(getGitHubActionsRepoUrl()).toBeNull();
});
it("should return GitHub URL with default server", () => {
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "owner/repo";
expect(getGitHubActionsRepoUrl()).toBe("https://github.com/owner/repo.git");
});
it("should return GitHub URL with custom server", () => {
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "owner/repo";
process.env.GITHUB_SERVER_URL = "https://github.enterprise.com";
expect(getGitHubActionsRepoUrl()).toBe("https://github.enterprise.com/owner/repo.git");
});
});
describe("getRepoUrl - GitHub Actions priority", () => {
it("should prioritize GitHub Actions environment variables", () => {
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "owner/repo";
// Since we can't easily mock git commands, we'll rely on the fact that
// GitHub Actions detection should take priority and return immediately
const result = getGitHubActionsRepoUrl();
expect(result).toBe("https://github.com/owner/repo.git");
});
it("should work with GitHub Enterprise Server", () => {
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "enterprise/repo";
process.env.GITHUB_SERVER_URL = "https://git.company.com";
const result = getGitHubActionsRepoUrl();
expect(result).toBe("https://git.company.com/enterprise/repo.git");
});
});
});

View file

@ -34,14 +34,54 @@ export function isGitRepo(): boolean {
}
/**
* Get the current repository URL, falling back to local path if not a git repo
* @returns Git remote URL or local path
* Check if running in GitHub Actions
*/
export function isGitHubActions(): boolean {
return process.env.GITHUB_ACTIONS === "true";
}
/**
* Get repository URL from GitHub Actions environment variables
* @returns GitHub repository URL or null if not available
*/
export function getGitHubActionsRepoUrl(): string | null {
if (!isGitHubActions()) {
return null;
}
// GITHUB_REPOSITORY is in format "owner/repo"
const githubRepository = process.env.GITHUB_REPOSITORY;
if (!githubRepository) {
return null;
}
// GITHUB_SERVER_URL defaults to https://github.com but can be different for GitHub Enterprise
const serverUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
return `${serverUrl}/${githubRepository}.git`;
}
/**
* Get the current repository URL with enhanced detection for CI environments
* Priority order:
* 1. GitHub Actions environment variables (if running in GitHub Actions)
* 2. Git remote URL (if in a git repository)
* 3. Current working directory (fallback)
* @returns Repository URL or local path
*/
export function getRepoUrl(): string {
// First, check if we're in GitHub Actions and can get repo URL from env vars
const githubActionsUrl = getGitHubActionsRepoUrl();
if (githubActionsUrl) {
return githubActionsUrl;
}
// Then check if we're in a git repository
if (!isGitRepo()) {
return process.cwd();
}
// Try to get the remote URL from git
const remoteUrl = getGitRemoteUrl();
return remoteUrl || process.cwd();
}