refactor: remove login/logout/remote commands and fix CLI tests
- Remove login, logout, whoami CLI commands and slash commands - Remove remote command (used api.continue.dev) - Fix 41 failing CLI tests for Hub removal and Local→Main Config rename Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
bb2a478472
commit
d04d4e6ca0
25 changed files with 212 additions and 1952 deletions
|
|
@ -1,222 +1,39 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
// Mock auth functions
|
||||
vi.mock("./auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn(),
|
||||
getAccessToken: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getAccessToken, loadAuthConfig } from "./auth/workos.js";
|
||||
import { processRule as processPromptOrRule } from "./hubLoader.js";
|
||||
describe("processPromptOrRule (loadRuleFromHub integration)", () => {
|
||||
// Mock fetch for hub tests
|
||||
const originalFetch = global.fetch;
|
||||
const mockFetch = vi.fn() as any;
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = mockFetch;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch.mockClear();
|
||||
// Reset auth mocks to not authenticated state
|
||||
(loadAuthConfig as any).mockReturnValue(null);
|
||||
(getAccessToken as any).mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe("loadRuleFromHub", () => {
|
||||
it("should successfully load a rule from the Continue Hub", async () => {
|
||||
// Create a mock zip file containing a markdown rule
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const ruleContent =
|
||||
"# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
|
||||
zip.file("rule.md", ruleContent);
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
// Mock successful fetch response
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processPromptOrRule("continuedev/sentry-nextjs");
|
||||
|
||||
expect(result).toBe(ruleContent);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL(
|
||||
"v0/continuedev/sentry-nextjs/latest/download",
|
||||
"https://api.continue.dev/",
|
||||
),
|
||||
{ headers: {} },
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle HTTP errors when loading from hub", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
} as Response);
|
||||
|
||||
await expect(
|
||||
processPromptOrRule("continuedev/nonexistent-rule"),
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found',
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle network errors when loading from hub", async () => {
|
||||
mockFetch.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
await expect(
|
||||
processPromptOrRule("continuedev/sentry-nextjs"),
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/sentry-nextjs": Network error',
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle invalid slug format", async () => {
|
||||
// "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
|
||||
// Let's test with a slug that has wrong format but contains "/"
|
||||
await expect(
|
||||
processPromptOrRule("invalid/slug/too/many/parts"),
|
||||
).rejects.toThrow(
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts',
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle empty zip file", async () => {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(
|
||||
processPromptOrRule("continuedev/empty-rule"),
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file',
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle zip with only directories", async () => {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
zip.folder("docs"); // Create a directory but no files
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(
|
||||
processPromptOrRule("continuedev/directory-only"),
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file',
|
||||
);
|
||||
});
|
||||
|
||||
it("should prefer markdown files and ignore other file types", async () => {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const mdContent = "# Main Rule\n\nThis is the markdown rule content.";
|
||||
const txtContent = "This is just a text file.";
|
||||
|
||||
zip.file("README.txt", txtContent);
|
||||
zip.file("rule.md", mdContent);
|
||||
zip.file("package.json", '{"name": "test"}');
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processPromptOrRule("continuedev/mixed-files");
|
||||
|
||||
expect(result).toBe(mdContent);
|
||||
});
|
||||
|
||||
it("should handle multiple markdown files and use the first one", async () => {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const rule1Content = "# First Rule\n\nThis is the first rule.";
|
||||
const rule2Content = "# Second Rule\n\nThis is the second rule.";
|
||||
|
||||
zip.file("rule1.md", rule1Content);
|
||||
zip.file("rule2.md", rule2Content);
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processPromptOrRule("continuedev/multiple-rules");
|
||||
|
||||
// Should use the first markdown file found (alphabetically)
|
||||
expect(result).toBe(rule1Content);
|
||||
});
|
||||
|
||||
it("should handle malformed zip files", async () => {
|
||||
const invalidZipBuffer = new ArrayBuffer(10);
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(invalidZipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(
|
||||
processPromptOrRule("continuedev/corrupted-zip"),
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/corrupted-zip"',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("processPromptOrRule logic", () => {
|
||||
it("should identify hub slugs correctly", async () => {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
zip.file("rule.md", "# Hub Rule");
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processPromptOrRule("owner/package");
|
||||
expect(result).toBe("# Hub Rule");
|
||||
expect(mockFetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should treat direct strings as content", async () => {
|
||||
describe("processPromptOrRule (rule processing)", () => {
|
||||
describe("direct content", () => {
|
||||
it("should treat simple strings as direct content", async () => {
|
||||
const directContent = "This is direct rule content";
|
||||
const result = await processPromptOrRule(directContent);
|
||||
expect(result).toBe(directContent);
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should distinguish between hub slugs and file paths", async () => {
|
||||
// This would be treated as a file path, not a hub slug
|
||||
// since it starts with "."
|
||||
it("should treat hub-slug-like strings as direct content (hub loading removed)", async () => {
|
||||
// Hub loading has been removed, so "owner/package" is treated as direct content
|
||||
const result = await processPromptOrRule("continuedev/sentry-nextjs");
|
||||
expect(result).toBe("continuedev/sentry-nextjs");
|
||||
});
|
||||
|
||||
it("should treat multiline strings as direct content", async () => {
|
||||
const multiline = "# Rule\n\nThis is a multiline rule.";
|
||||
const result = await processPromptOrRule(multiline);
|
||||
expect(result).toBe(multiline);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file paths", () => {
|
||||
it("should throw for non-existent file paths starting with ./", async () => {
|
||||
await expect(processPromptOrRule("./owner/package")).rejects.toThrow(
|
||||
'Failed to read rule file "./owner/package": Rule file not found',
|
||||
);
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should throw for non-existent file paths starting with /", async () => {
|
||||
await expect(processPromptOrRule("/nonexistent/rule.md")).rejects.toThrow(
|
||||
'Failed to read rule file "/nonexistent/rule.md"',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -25,10 +25,6 @@ describe("Slash Commands Integration", () => {
|
|||
expect(commandNames).toContain("help");
|
||||
expect(commandNames).toContain("clear");
|
||||
expect(commandNames).toContain("exit");
|
||||
expect(commandNames).toContain("login");
|
||||
expect(commandNames).toContain("logout");
|
||||
expect(commandNames).toContain("whoami");
|
||||
|
||||
expect(commandNames).toContain("model");
|
||||
expect(commandNames).toContain("config");
|
||||
});
|
||||
|
|
@ -43,16 +39,7 @@ describe("Slash Commands Integration", () => {
|
|||
it("should categorize system commands correctly", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
const systemCommands = commands.filter((cmd) =>
|
||||
[
|
||||
"help",
|
||||
"clear",
|
||||
"exit",
|
||||
"login",
|
||||
"logout",
|
||||
"whoami",
|
||||
"model",
|
||||
"config",
|
||||
].includes(cmd.name),
|
||||
["help", "clear", "exit", "model", "config"].includes(cmd.name),
|
||||
);
|
||||
|
||||
systemCommands.forEach((cmd) => {
|
||||
|
|
@ -70,18 +57,5 @@ describe("Slash Commands Integration", () => {
|
|||
expect(cmd.category).toBe("assistant");
|
||||
});
|
||||
});
|
||||
|
||||
it("should only show remote mode commands in remote mode", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant, {
|
||||
isRemoteMode: true,
|
||||
});
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
// In remote mode, only remote commands should be available
|
||||
expect(commandNames).toContain("exit");
|
||||
expect(commandNames).toContain("diff");
|
||||
expect(commandNames).toContain("apply");
|
||||
expect(commandNames).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,10 +2,7 @@ import { type AssistantConfig } from "@continuedev/sdk";
|
|||
|
||||
// Export command functions
|
||||
export { chat } from "./chat.js";
|
||||
export { login } from "./login.js";
|
||||
export { logout } from "./logout.js";
|
||||
export { listSessionsCommand } from "./ls.js";
|
||||
export { remote } from "./remote.js";
|
||||
export { review } from "./review.js";
|
||||
export { serve } from "./serve.js";
|
||||
|
||||
|
|
@ -31,26 +28,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
description: "Clear the chat history",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "login",
|
||||
description: "Authenticate with your account",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "logout",
|
||||
description: "Sign out of your current session",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
description: "Update the Continue CLI",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "whoami",
|
||||
description: "Check who you're currently logged in as",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "info",
|
||||
description: "Show session information",
|
||||
|
|
@ -63,7 +45,7 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
},
|
||||
{
|
||||
name: "config",
|
||||
description: "Switch configuration or organization",
|
||||
description: "Switch configuration",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
|
|
@ -113,39 +95,12 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
},
|
||||
];
|
||||
|
||||
// Remote mode specific commands
|
||||
export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
|
||||
{
|
||||
name: "exit",
|
||||
description: "Exit the remote environment",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "diff",
|
||||
description: "Show the current diff from the remote environment",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "apply",
|
||||
description: "Apply the current diff to the local working tree",
|
||||
category: "system",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get all available slash commands including system commands and assistant prompts
|
||||
*/
|
||||
export function getAllSlashCommands(
|
||||
assistant: AssistantConfig,
|
||||
options: { isRemoteMode?: boolean } = {},
|
||||
): SlashCommand[] {
|
||||
const { isRemoteMode = false } = options;
|
||||
|
||||
// In remote mode, only show the exit command
|
||||
if (isRemoteMode) {
|
||||
return REMOTE_MODE_SLASH_COMMANDS;
|
||||
}
|
||||
|
||||
// All system commands are available
|
||||
const systemCommands = SYSTEM_SLASH_COMMANDS;
|
||||
|
||||
|
|
|
|||
|
|
@ -3,11 +3,9 @@ import React from "react";
|
|||
|
||||
import { listSessions, loadSessionById } from "../session.js";
|
||||
import { SessionSelector } from "../ui/SessionSelector.js";
|
||||
import { ApiRequestError, post } from "../util/apiClient.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { chat } from "./chat.js";
|
||||
import { remote } from "./remote.js";
|
||||
|
||||
interface ListSessionsOptions {
|
||||
format?: "json";
|
||||
|
|
@ -25,22 +23,6 @@ function setSessionId(sessionId: string): void {
|
|||
);
|
||||
}
|
||||
|
||||
export async function getTunnelForAgent(agentId: string): Promise<string> {
|
||||
try {
|
||||
const response = await post<{ url: string }>(
|
||||
`agents/${encodeURIComponent(agentId)}/tunnel`,
|
||||
);
|
||||
return response.data.url;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List recent chat sessions and allow selection
|
||||
*/
|
||||
|
|
@ -87,37 +69,25 @@ export async function listSessionsCommand(
|
|||
try {
|
||||
app.unmount();
|
||||
|
||||
// Find the selected session to check if it's remote
|
||||
const selectedSession = sessions.find((s) => s.sessionId === sessionId);
|
||||
|
||||
if (selectedSession?.isRemote && selectedSession.remoteId) {
|
||||
// Handle remote session - use the remote command with the agent URL
|
||||
logger.info(`Opening remote session: ${selectedSession.remoteId}`);
|
||||
|
||||
const tunnelUrl = await getTunnelForAgent(selectedSession.remoteId);
|
||||
|
||||
await remote(undefined, { url: tunnelUrl });
|
||||
} else {
|
||||
// Handle local session
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
logger.error(`Session ${sessionId} could not be loaded.`);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`Loading session: ${sessionId}`);
|
||||
|
||||
// Set the session ID so that when chat() runs, it will load this session
|
||||
setSessionId(sessionId);
|
||||
|
||||
// Start chat with resume flag to load the selected session
|
||||
await chat(undefined, {
|
||||
resume: true,
|
||||
headless: false,
|
||||
});
|
||||
// Handle local session
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
logger.error(`Session ${sessionId} could not be loaded.`);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`Loading session: ${sessionId}`);
|
||||
|
||||
// Set the session ID so that when chat() runs, it will load this session
|
||||
setSessionId(sessionId);
|
||||
|
||||
// Start chat with resume flag to load the selected session
|
||||
await chat(undefined, {
|
||||
resume: true,
|
||||
headless: false,
|
||||
});
|
||||
|
||||
resolve();
|
||||
} catch (error) {
|
||||
logger.error("Error loading session:", error);
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startRemoteTUIChat } from "../ui/index.js";
|
||||
import { gracefulExit } from "../util/exit.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
export async function remoteTest(
|
||||
prompt?: string,
|
||||
url: string = "http://localhost:8000",
|
||||
) {
|
||||
console.info(chalk.white(`Connecting to remote environment at ${url}...`));
|
||||
|
||||
try {
|
||||
// Record session start
|
||||
telemetryService.recordSessionStart();
|
||||
telemetryService.startActiveTime();
|
||||
|
||||
try {
|
||||
// Start the TUI in remote mode
|
||||
await startRemoteTUIChat(url, prompt);
|
||||
} finally {
|
||||
telemetryService.stopActiveTime();
|
||||
}
|
||||
} catch (error: any) {
|
||||
logger.error(
|
||||
chalk.red(`Failed to connect to remote environment: ${error.message}`),
|
||||
);
|
||||
await gracefulExit(1);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,520 +0,0 @@
|
|||
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/exit.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"));
|
||||
const mockExit = vi.mocked(await import("../util/exit.js"));
|
||||
|
||||
// Mock fetch globally
|
||||
const mockFetch = vi.fn();
|
||||
global.fetch = mockFetch as any;
|
||||
|
||||
// Mock console methods
|
||||
const mockConsoleInfo = vi.fn();
|
||||
const mockConsoleError = vi.fn();
|
||||
const mockConsoleLog = vi.fn();
|
||||
global.console = {
|
||||
...global.console,
|
||||
info: mockConsoleInfo,
|
||||
error: mockConsoleError,
|
||||
log: mockConsoleLog,
|
||||
};
|
||||
|
||||
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",
|
||||
continueHome: "/tmp/test-continue-home",
|
||||
};
|
||||
|
||||
mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git");
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({
|
||||
id: "test-agent-id",
|
||||
url: "ws://test-url.com",
|
||||
port: 8080,
|
||||
}),
|
||||
});
|
||||
|
||||
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
|
||||
|
||||
// Mock gracefulExit to prevent process.exit during tests
|
||||
mockExit.gracefulExit.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
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", 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", 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 ignore --start flag when --url is provided without --start", async () => {
|
||||
const testUrl = "ws://direct-url.com";
|
||||
|
||||
await remote("test prompt", { url: testUrl });
|
||||
|
||||
// Should not make POST request when connecting directly to URL
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
|
||||
// Should connect directly to the provided URL and start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
|
||||
testUrl,
|
||||
"test prompt",
|
||||
);
|
||||
|
||||
// Should not output JSON
|
||||
expect(mockConsoleLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should fetch tunnel and connect when id option is provided", async () => {
|
||||
const agentId = "agent-789";
|
||||
|
||||
mockFetch
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }),
|
||||
})
|
||||
.mockResolvedValue({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({
|
||||
id: "test-agent-id",
|
||||
url: "ws://test-url.com",
|
||||
port: 8080,
|
||||
}),
|
||||
});
|
||||
|
||||
await remote("test prompt", { id: agentId });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
|
||||
"ws://tunnel-url.com",
|
||||
"test prompt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should output JSON without starting TUI when using --id with --start", async () => {
|
||||
const agentId = "agent-456";
|
||||
const tunnelResponse = { url: "ws://existing-tunnel.com", port: 7070 };
|
||||
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => tunnelResponse,
|
||||
});
|
||||
|
||||
await remote("test prompt", { id: agentId, start: true });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote agent tunnel connection details",
|
||||
url: tunnelResponse.url,
|
||||
containerPort: tunnelResponse.port,
|
||||
agentId,
|
||||
mode: "existing_agent",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
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({
|
||||
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");
|
||||
});
|
||||
|
||||
it("should include branchName in request body when branch option is provided", async () => {
|
||||
const testBranch = "feature/new-feature";
|
||||
|
||||
await remote("test prompt", { branch: testBranch });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"branchName":"${testBranch}"`),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should not include branchName in request body when branch option is not provided", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.not.stringContaining("branchName"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with branch field", async () => {
|
||||
const testBranch = "main";
|
||||
const testIdempotencyKey = "test-with-branch";
|
||||
|
||||
await remote("test prompt", {
|
||||
branch: testBranch,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
branchName: testBranch,
|
||||
agent: undefined,
|
||||
config: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("should include config in request body when config option is provided", async () => {
|
||||
const testConfig = "test-config-path";
|
||||
|
||||
await remote("test prompt", { config: testConfig });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"config":"${testConfig}"`),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
body: expect.stringContaining(`"config":"${testConfig}"`),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should include agent in request body when agent option is provided", async () => {
|
||||
const testAgent = "test-agent";
|
||||
|
||||
await remote("test prompt", { agent: testAgent });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"agent":"${testAgent}"`),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
body: expect.stringContaining(`"agent":"${testAgent}"`),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with config field", async () => {
|
||||
const testConfig = "my-agent-config";
|
||||
const testIdempotencyKey = "test-with-config";
|
||||
|
||||
await remote("test prompt", {
|
||||
config: testConfig,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
config: testConfig,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with agent field", async () => {
|
||||
const testAgent = "my-agent";
|
||||
const testIdempotencyKey = "test-with-config";
|
||||
|
||||
await remote("test prompt", {
|
||||
agent: testAgent,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
agent: testAgent,
|
||||
});
|
||||
});
|
||||
|
||||
it("should not include config in request body when config option is not provided", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
agent: undefined,
|
||||
config: undefined,
|
||||
});
|
||||
expect(requestBody).not.toHaveProperty("idempotencyKey");
|
||||
});
|
||||
|
||||
describe("start mode (-s / --start flag)", () => {
|
||||
it("should output JSON and exit without starting TUI when using --start with direct URL", async () => {
|
||||
const testUrl = "ws://test-url.com";
|
||||
|
||||
await remote("test prompt", { url: testUrl, start: true });
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
// Should not make POST request
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
|
||||
// Should output JSON
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote environment connection details",
|
||||
url: testUrl,
|
||||
mode: "direct_url",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should create remote environment, output JSON, and exit without starting TUI when using --start", async () => {
|
||||
await remote("test prompt", { start: true });
|
||||
|
||||
// Should make POST request to create environment
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
// Should output JSON with environment details
|
||||
const consoleLogCall = mockConsoleLog.mock.calls[0][0];
|
||||
const outputJson = JSON.parse(consoleLogCall);
|
||||
|
||||
expect(outputJson).toEqual({
|
||||
status: "success",
|
||||
message: "Remote development environment created successfully",
|
||||
url: "https://test.example.com/agents/test-agent-id",
|
||||
containerUrl: "ws://test-url.com",
|
||||
containerPort: 8080,
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
mode: "new_environment",
|
||||
});
|
||||
});
|
||||
|
||||
it("should work with start mode and idempotency key", async () => {
|
||||
const testIdempotencyKey = "start-mode-key";
|
||||
|
||||
await remote("test prompt", {
|
||||
start: true,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
// Should include idempotency key in request
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
expect(requestBody.idempotencyKey).toBe(testIdempotencyKey);
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
// Should output JSON
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
expect.stringContaining('"status":"success"'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,227 +0,0 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { env } from "../env.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startRemoteTUIChat } from "../ui/index.js";
|
||||
import {
|
||||
ApiRequestError,
|
||||
AuthenticationRequiredError,
|
||||
post,
|
||||
} from "../util/apiClient.js";
|
||||
import { gracefulExit } from "../util/exit.js";
|
||||
import { getRepoUrl } from "../util/git.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import { readStdinSync } from "../util/stdin.js";
|
||||
|
||||
type RemoteCommandOptions = {
|
||||
url?: string;
|
||||
id?: string;
|
||||
idempotencyKey?: string;
|
||||
start?: boolean;
|
||||
branch?: string;
|
||||
repo?: string;
|
||||
config?: string;
|
||||
agent?: string;
|
||||
};
|
||||
|
||||
type TunnelResponse = {
|
||||
url: string;
|
||||
port?: number;
|
||||
};
|
||||
|
||||
type AgentCreationResponse = TunnelResponse & {
|
||||
id: string;
|
||||
};
|
||||
|
||||
export async function remote(
|
||||
prompt: string | undefined,
|
||||
options: RemoteCommandOptions = {},
|
||||
) {
|
||||
const actualPrompt = resolvePrompt(prompt);
|
||||
|
||||
try {
|
||||
if (options.url) {
|
||||
await connectToRemoteUrl(options.url, actualPrompt, options.start);
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.id) {
|
||||
await connectExistingAgent(options.id, actualPrompt, options.start);
|
||||
return;
|
||||
}
|
||||
|
||||
await createAndConnectRemoteEnvironment(actualPrompt, options);
|
||||
} catch (error) {
|
||||
await handleRemoteError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePrompt(prompt: string | undefined): string | undefined {
|
||||
const stdinInput = readStdinSync();
|
||||
|
||||
if (!stdinInput) {
|
||||
return prompt;
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
return stdinInput;
|
||||
}
|
||||
|
||||
return `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`;
|
||||
}
|
||||
|
||||
async function connectToRemoteUrl(
|
||||
remoteUrl: string,
|
||||
prompt: string | undefined,
|
||||
startOnly?: boolean,
|
||||
) {
|
||||
if (startOnly) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote environment connection details",
|
||||
url: remoteUrl,
|
||||
mode: "direct_url",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
|
||||
);
|
||||
await launchRemoteTUI(remoteUrl, prompt);
|
||||
}
|
||||
|
||||
async function connectExistingAgent(
|
||||
agentId: string,
|
||||
prompt: string | undefined,
|
||||
startOnly?: boolean,
|
||||
) {
|
||||
const tunnel = await fetchAgentTunnel(agentId);
|
||||
|
||||
if (startOnly) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote agent tunnel connection details",
|
||||
url: tunnel.url,
|
||||
containerPort: tunnel.port,
|
||||
agentId,
|
||||
mode: "existing_agent",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote agent tunnel at: ${tunnel.url}`),
|
||||
);
|
||||
await launchRemoteTUI(tunnel.url, prompt);
|
||||
}
|
||||
|
||||
async function createAndConnectRemoteEnvironment(
|
||||
prompt: string | undefined,
|
||||
options: RemoteCommandOptions,
|
||||
) {
|
||||
const requestBody = buildAgentRequestBody(options, prompt);
|
||||
|
||||
let result: AgentCreationResponse;
|
||||
try {
|
||||
const response = await post<AgentCreationResponse>("agents", requestBody);
|
||||
result = response.data;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to create remote environment: ${error.status} ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (options.start) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote development environment created successfully",
|
||||
url: `https://continue.dev/agents/${result.id}`,
|
||||
containerUrl: result.url,
|
||||
containerPort: result.port,
|
||||
name: requestBody.name,
|
||||
mode: "new_environment",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.green("✅ Remote development environment created successfully!"),
|
||||
);
|
||||
|
||||
if (!result.url) {
|
||||
throw new Error("No URL returned from remote environment creation");
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${result.url}`),
|
||||
);
|
||||
await launchRemoteTUI(result.url, prompt);
|
||||
}
|
||||
|
||||
function buildAgentRequestBody(
|
||||
options: RemoteCommandOptions,
|
||||
prompt: string | undefined,
|
||||
) {
|
||||
const body: Record<string, unknown> = {
|
||||
repoUrl: options.repo ?? getRepoUrl(),
|
||||
name: `devbox-${Date.now()}`,
|
||||
prompt,
|
||||
agent: options.agent,
|
||||
config: options.config,
|
||||
};
|
||||
|
||||
if (options.idempotencyKey) {
|
||||
body.idempotencyKey = options.idempotencyKey;
|
||||
}
|
||||
|
||||
if (options.branch) {
|
||||
body.branchName = options.branch;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
async function fetchAgentTunnel(agentId: string) {
|
||||
try {
|
||||
const response = await post<TunnelResponse>(`agents/${agentId}/tunnel`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) {
|
||||
telemetryService.recordSessionStart();
|
||||
telemetryService.startActiveTime();
|
||||
|
||||
try {
|
||||
await startRemoteTUIChat(remoteUrl, prompt);
|
||||
} finally {
|
||||
telemetryService.stopActiveTime();
|
||||
}
|
||||
}
|
||||
|
||||
function printStartJson(payload: Record<string, unknown>) {
|
||||
console.log(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
async function handleRemoteError(error: unknown) {
|
||||
if (error instanceof AuthenticationRequiredError) {
|
||||
logger.error(chalk.red(error.message));
|
||||
} else if (error instanceof Error) {
|
||||
logger.error(chalk.red(error.message));
|
||||
} else {
|
||||
logger.error(chalk.red("An unknown error occurred while starting remote"));
|
||||
}
|
||||
|
||||
await gracefulExit(1);
|
||||
}
|
||||
|
|
@ -7,11 +7,7 @@ import { Command } from "commander";
|
|||
|
||||
import { chat } from "./commands/chat.js";
|
||||
import { checks } from "./commands/checks.js";
|
||||
import { login } from "./commands/login.js";
|
||||
import { logout } from "./commands/logout.js";
|
||||
import { listSessionsCommand } from "./commands/ls.js";
|
||||
import { remoteTest } from "./commands/remote-test.js";
|
||||
import { remote } from "./commands/remote.js";
|
||||
import { review } from "./commands/review.js";
|
||||
import { serve } from "./commands/serve.js";
|
||||
import {
|
||||
|
|
@ -300,22 +296,6 @@ addCommonOptions(program)
|
|||
await chat(prompt, options);
|
||||
});
|
||||
|
||||
// Login subcommand
|
||||
program
|
||||
.command("login")
|
||||
.description("Authenticate with Continue")
|
||||
.action(async () => {
|
||||
await login();
|
||||
});
|
||||
|
||||
// Logout subcommand
|
||||
program
|
||||
.command("logout")
|
||||
.description("Log out from Continue")
|
||||
.action(async () => {
|
||||
await logout();
|
||||
});
|
||||
|
||||
// List sessions subcommand
|
||||
program
|
||||
.command("ls")
|
||||
|
|
@ -327,40 +307,6 @@ program
|
|||
});
|
||||
});
|
||||
|
||||
// Remote subcommand
|
||||
addCommonOptions(
|
||||
program
|
||||
.command("remote [prompt]", { hidden: true })
|
||||
.description("Launch a remote instance of the cn agent"),
|
||||
)
|
||||
.option(
|
||||
"--url <url>",
|
||||
"Connect directly to the specified URL instead of creating a new remote environment",
|
||||
)
|
||||
.option(
|
||||
"--id <id>",
|
||||
"Connect to an existing remote agent by id and establish a tunnel",
|
||||
)
|
||||
.option(
|
||||
"--idempotency-key <key>",
|
||||
"Idempotency key for session management - allows resuming existing sessions",
|
||||
)
|
||||
.option(
|
||||
"-s, --start",
|
||||
"Create remote environment and print connection details without starting TUI",
|
||||
)
|
||||
.option(
|
||||
"--branch <branch>",
|
||||
"Specify the git branch name to use in the remote environment",
|
||||
)
|
||||
.option(
|
||||
"--repo <url>",
|
||||
"Specify the repository URL to use in the remote environment",
|
||||
)
|
||||
.action(async (prompt: string | undefined, options) => {
|
||||
await remote(prompt, options);
|
||||
});
|
||||
|
||||
// Serve subcommand
|
||||
program
|
||||
.command("serve [prompt]", { hidden: true })
|
||||
|
|
@ -391,15 +337,6 @@ program
|
|||
await serve(prompt, mergedOptions);
|
||||
});
|
||||
|
||||
// Remote test subcommand (for development)
|
||||
program
|
||||
.command("remote-test [prompt]")
|
||||
.description("Test remote TUI mode with a local server")
|
||||
.option("--url <url>", "Server URL (default: http://localhost:8000)")
|
||||
.action(async (prompt: string | undefined, options) => {
|
||||
await remoteTest(prompt, options.url);
|
||||
});
|
||||
|
||||
// Checks subcommand
|
||||
program
|
||||
.command("checks [action] [pr-url]")
|
||||
|
|
|
|||
|
|
@ -5,14 +5,7 @@ import * as path from "path";
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos.js";
|
||||
|
||||
import {
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { getModelName, updateModelName } from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
import { ModelService } from "../services/ModelService.js";
|
||||
import { persistModelName } from "../util/modelPersistence.js";
|
||||
|
|
@ -24,7 +17,6 @@ describe("Model Persistence End-to-End", () => {
|
|||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthenticatedConfig;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -66,15 +58,6 @@ describe("Model Persistence End-to-End", () => {
|
|||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000, // 1 hour from now
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
// Setup default mock behavior
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
|
|
@ -84,6 +67,9 @@ describe("Model Persistence End-to-End", () => {
|
|||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clear persisted model to avoid cross-test contamination
|
||||
persistModelName(null);
|
||||
|
||||
// Cleanup
|
||||
if (fs.existsSync(testDir)) {
|
||||
fs.rmSync(testDir, { recursive: true });
|
||||
|
|
@ -95,51 +81,28 @@ describe("Model Persistence End-to-End", () => {
|
|||
}
|
||||
});
|
||||
|
||||
test("should restore model selection after restart", async () => {
|
||||
// Step 1: Initial session - user starts with default model (GPT-4)
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
let service = new ModelService();
|
||||
let state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
console.log("Initial model:", state.model?.name);
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
|
||||
// Step 2: User switches to Claude 3.5 Sonnet (index 1)
|
||||
await service.switchModel(1);
|
||||
state = service.getState();
|
||||
|
||||
console.log("After switch:", state.model?.name);
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Step 3: Persist the model choice (this should happen in useModelSelector)
|
||||
test("should restore model selection after switch and restart", async () => {
|
||||
// Step 1: Persist the model choice via updateModelName (uses GlobalContext)
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it was saved to auth.json
|
||||
const savedConfig = loadAuthConfig();
|
||||
console.log("Saved model name:", getModelName(savedConfig));
|
||||
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
// Verify it was saved
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Step 4: Simulate restart - create new service instance
|
||||
// Load fresh auth config from disk (this is what the real code does)
|
||||
const freshAuthConfig = loadAuthConfig();
|
||||
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
|
||||
// Step 2: Create a new service (simulating restart) - should restore persisted model
|
||||
const service = new ModelService();
|
||||
const state = await service.initialize(mockAssistant, null);
|
||||
|
||||
service = new ModelService();
|
||||
state = await service.initialize(mockAssistant, freshAuthConfig);
|
||||
|
||||
// Step 5: Verify the persisted model is restored
|
||||
console.log("After restart:", state.model?.name);
|
||||
// Verify the persisted model is restored
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
expect(state.model?.provider).toBe("anthropic");
|
||||
});
|
||||
|
||||
test("should handle model name mismatch gracefully", async () => {
|
||||
// Save auth config with a model that doesn't exist
|
||||
mockAuthConfig.modelName = "Non-existent Model";
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
// Save a model name that doesn't exist in the assistant
|
||||
updateModelName("Non-existent Model");
|
||||
|
||||
const service = new ModelService();
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
const state = await service.initialize(mockAssistant, null);
|
||||
|
||||
// Should fall back to first available model (GPT-4)
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
|
|
@ -167,40 +130,34 @@ describe("Model Persistence End-to-End", () => {
|
|||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig.modelName = "claude-3-5-sonnet-20241022";
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
updateModelName("claude-3-5-sonnet-20241022");
|
||||
|
||||
const service = new ModelService();
|
||||
const state = await service.initialize(
|
||||
assistantWithModelField,
|
||||
mockAuthConfig,
|
||||
);
|
||||
const state = await service.initialize(assistantWithModelField, null);
|
||||
|
||||
// Should match by model field
|
||||
expect(state.model?.model).toBe("claude-3-5-sonnet-20241022");
|
||||
});
|
||||
|
||||
test("should persist model through multiple switches", async () => {
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
const service = new ModelService();
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
// Clear any persisted model first
|
||||
persistModelName(null);
|
||||
await service.initialize(mockAssistant, null);
|
||||
|
||||
// Switch to Claude 3.5 Sonnet
|
||||
await service.switchModel(1);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet");
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Switch to Claude 3 Opus
|
||||
await service.switchModel(2);
|
||||
updateModelName("Claude 3 Opus");
|
||||
expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus");
|
||||
expect(getModelName(null)).toBe("Claude 3 Opus");
|
||||
|
||||
// Restart and verify last selection
|
||||
const freshAuthConfig = loadAuthConfig();
|
||||
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
|
||||
|
||||
const newService = new ModelService();
|
||||
const state = await newService.initialize(mockAssistant, freshAuthConfig);
|
||||
const state = await newService.initialize(mockAssistant, null);
|
||||
expect(state.model?.name).toBe("Claude 3 Opus");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,11 +5,7 @@ import * as path from "path";
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { getModelName, updateModelName } from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
import { ModelService } from "../services/ModelService.js";
|
||||
import {
|
||||
|
|
@ -20,7 +16,7 @@ import {
|
|||
// Mock the config module
|
||||
vi.mock("../config.js");
|
||||
|
||||
describe("Model Persistence for Unauthenticated Users", () => {
|
||||
describe("Model Persistence (Hub auth removed)", () => {
|
||||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
|
|
@ -85,12 +81,8 @@ describe("Model Persistence for Unauthenticated Users", () => {
|
|||
}
|
||||
});
|
||||
|
||||
test("should persist model selection for logged-out users", () => {
|
||||
// User is logged out (no auth config)
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).toBeNull();
|
||||
|
||||
// User switches model
|
||||
test("should persist model selection via GlobalContext", () => {
|
||||
// Auth is always null now
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it was saved to GlobalContext
|
||||
|
|
@ -101,38 +93,27 @@ describe("Model Persistence for Unauthenticated Users", () => {
|
|||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should restore model selection on next session for logged-out users", async () => {
|
||||
// Session 1: User is logged out and switches model
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).toBeNull();
|
||||
|
||||
test("should restore model selection on next session", async () => {
|
||||
// Session 1: User switches model
|
||||
const modelService = new ModelService();
|
||||
await modelService.initialize(mockAssistant, authConfig);
|
||||
await modelService.initialize(mockAssistant, null);
|
||||
|
||||
await modelService.switchModel(1);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Session 2: User reopens CLI (still logged out)
|
||||
const newAuthConfig = loadAuthConfig();
|
||||
expect(newAuthConfig).toBeNull();
|
||||
|
||||
// Session 2: User reopens CLI
|
||||
const newModelService = new ModelService();
|
||||
const state = await newModelService.initialize(
|
||||
mockAssistant,
|
||||
newAuthConfig,
|
||||
);
|
||||
const state = await newModelService.initialize(mockAssistant, null);
|
||||
|
||||
// Should restore Claude 3.5 Sonnet
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should handle multiple model switches for logged-out users", () => {
|
||||
test("should handle multiple model switches and persist last one", () => {
|
||||
// Perform multiple switches - only verify the final state
|
||||
// to avoid race conditions with concurrent test files using the same GlobalContext
|
||||
updateModelName("GPT-4");
|
||||
expect(getModelName(null)).toBe("GPT-4");
|
||||
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
updateModelName("Claude 3 Opus");
|
||||
expect(getModelName(null)).toBe("Claude 3 Opus");
|
||||
});
|
||||
|
|
@ -145,87 +126,7 @@ describe("Model Persistence for Unauthenticated Users", () => {
|
|||
expect(getModelName(null)).toBeNull();
|
||||
});
|
||||
|
||||
test("should preserve GlobalContext model when user logs in", () => {
|
||||
// User is logged out with a persisted model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// User logs in (simulated by having auth.json)
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
}),
|
||||
);
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).not.toBeNull();
|
||||
|
||||
// GlobalContext model should still exist
|
||||
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// When auth config has no modelName, it should fall back to GlobalContext
|
||||
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should use auth config model when both exist", () => {
|
||||
// Clear previous state
|
||||
updateModelName(null);
|
||||
|
||||
// Set GlobalContext model
|
||||
updateModelName("GPT-4");
|
||||
expect(getPersistedModelName()).toBe("GPT-4");
|
||||
|
||||
// Create auth config with different model
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "Claude 3.5 Sonnet",
|
||||
}),
|
||||
);
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
// Auth config should take precedence
|
||||
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should not save to GlobalContext when using CONTINUE_API_KEY", () => {
|
||||
// Clear any existing model
|
||||
updateModelName(null);
|
||||
expect(getPersistedModelName()).toBeNull();
|
||||
|
||||
// Capture original value to restore after test
|
||||
const originalApiKey = process.env.CONTINUE_API_KEY;
|
||||
process.env.CONTINUE_API_KEY = "test-api-key";
|
||||
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Should not be saved to GlobalContext
|
||||
expect(getPersistedModelName()).toBeNull();
|
||||
|
||||
// Restore original value
|
||||
if (originalApiKey === undefined) {
|
||||
delete process.env.CONTINUE_API_KEY;
|
||||
} else {
|
||||
process.env.CONTINUE_API_KEY = originalApiKey;
|
||||
}
|
||||
});
|
||||
|
||||
test("should work across config changes for logged-out users", async () => {
|
||||
test("should work across config changes", async () => {
|
||||
// User switches model with one config
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
|
|
|
|||
|
|
@ -5,16 +5,10 @@ import * as path from "path";
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos.js";
|
||||
import { AuthService } from "src/services/AuthService.js";
|
||||
|
||||
import {
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
} from "../auth/workos.js";
|
||||
import { getModelName, updateModelName } from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
import { ModelService } from "../services/ModelService.js";
|
||||
import { persistModelName } from "../util/modelPersistence.js";
|
||||
|
||||
// Mock the config module
|
||||
vi.mock("../config.js");
|
||||
|
|
@ -23,7 +17,6 @@ describe("Model Persistence User Flow", () => {
|
|||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthenticatedConfig;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(async () => {
|
||||
|
|
@ -34,6 +27,9 @@ describe("Model Persistence User Flow", () => {
|
|||
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
|
||||
process.env.CONTINUE_GLOBAL_DIR = testDir;
|
||||
|
||||
// Clear GlobalContext for clean test state
|
||||
persistModelName(null);
|
||||
|
||||
mockAssistant = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
|
|
@ -62,16 +58,6 @@ describe("Model Persistence User Flow", () => {
|
|||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000, // 1 hour from now
|
||||
organizationId: "test-org",
|
||||
modelName: "GPT-4",
|
||||
};
|
||||
|
||||
// Setup default mock behavior
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
|
|
@ -93,63 +79,32 @@ describe("Model Persistence User Flow", () => {
|
|||
});
|
||||
|
||||
test("should persist model choice exactly as user experiences it", async () => {
|
||||
console.log("\n=== SESSION 1: User opens cn and switches model ===");
|
||||
|
||||
// Session 1: User starts CLI
|
||||
// Save initial auth config (what happens after login)
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
console.log("1. Initial auth.json saved");
|
||||
// Auth is always null now (Hub removed)
|
||||
|
||||
// Initialize ModelService (what happens on CLI start)
|
||||
const modelService = new ModelService();
|
||||
const state = await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
console.log("2. Initial model:", state.model?.name);
|
||||
const state = await modelService.initialize(mockAssistant, null);
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
|
||||
// User switches to Claude 3.5 Sonnet via UI
|
||||
await modelService.switchModel(1);
|
||||
const modelInfo = modelService.getModelInfo();
|
||||
console.log("3. User switched to:", modelInfo?.name);
|
||||
expect(modelInfo?.name).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// useModelSelector calls updateModelName
|
||||
const { updateModelName } = await import("../auth/workos.js");
|
||||
const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet");
|
||||
console.log("4. Model name persisted to disk");
|
||||
// updateModelName persists via GlobalContext
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it was saved
|
||||
const savedConfig = loadAuthConfig();
|
||||
console.log("5. Read back from disk:", getModelName(savedConfig));
|
||||
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// User closes CLI
|
||||
console.log("6. User exits CLI\n");
|
||||
|
||||
console.log("=== SESSION 2: User reopens cn ===");
|
||||
|
||||
// Session 2: User restarts CLI
|
||||
// Initialize AuthService (loads from disk)
|
||||
const authService = new AuthService();
|
||||
const authState = await authService.initialize();
|
||||
console.log(
|
||||
"7. AuthService loaded, modelName in auth:",
|
||||
getModelName(authState.authConfig),
|
||||
);
|
||||
|
||||
// Initialize ModelService with fresh auth state
|
||||
// Session 2: User reopens CLI
|
||||
// Initialize ModelService with fresh state (auth is always null)
|
||||
const newModelService = new ModelService();
|
||||
const newState = await newModelService.initialize(
|
||||
mockAssistant,
|
||||
authState.authConfig,
|
||||
);
|
||||
console.log(
|
||||
"8. ModelService initialized with model:",
|
||||
newState.model?.name,
|
||||
);
|
||||
const newState = await newModelService.initialize(mockAssistant, null);
|
||||
|
||||
// EXPECTATION: Should restore Claude 3.5 Sonnet
|
||||
expect(newState.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
expect(newState.model?.provider).toBe("anthropic");
|
||||
console.log("✅ Model persisted correctly!\n");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,15 +4,11 @@ import * as path from "path";
|
|||
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos.js";
|
||||
|
||||
import { getModelName, updateModelName } from "../auth/workos.js";
|
||||
import {
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { persistModelName } from "../util/modelPersistence.js";
|
||||
getPersistedModelName,
|
||||
persistModelName,
|
||||
} from "../util/modelPersistence.js";
|
||||
|
||||
describe("Model Persistence Integration", () => {
|
||||
let testDir: string;
|
||||
|
|
@ -41,155 +37,50 @@ describe("Model Persistence Integration", () => {
|
|||
});
|
||||
|
||||
test("should persist model name when user selects a model", () => {
|
||||
// Create initial auth config without model name
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// User selects a model
|
||||
// User selects a model (auth is always null now)
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify model name is persisted
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
// Verify model name is persisted via GlobalContext
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should update model name when user switches models", () => {
|
||||
// Create initial auth config with a model
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "GPT-4",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
// Set initial model
|
||||
updateModelName("GPT-4");
|
||||
expect(getModelName(null)).toBe("GPT-4");
|
||||
|
||||
// User switches to a different model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify new model name
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should preserve other auth config fields when updating model", () => {
|
||||
// Create initial auth config
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
configUri: "slug://owner/my-config",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// Update model name
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify all fields are preserved
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(loadedConfig).toMatchObject({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
organizationId: "test-org",
|
||||
configUri: "slug://owner/my-config",
|
||||
modelName: "Claude 3.5 Sonnet",
|
||||
});
|
||||
// Verify new model name
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should clear model name when set to null", () => {
|
||||
// Create initial auth config with a model
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "GPT-4",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
// Set a model
|
||||
updateModelName("GPT-4");
|
||||
expect(getModelName(null)).toBe("GPT-4");
|
||||
|
||||
// Clear model name
|
||||
updateModelName(null);
|
||||
|
||||
// Load config and verify model name is cleared
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
// Verify model name is cleared
|
||||
expect(getModelName(null)).toBeNull();
|
||||
});
|
||||
|
||||
test("should return null for model name when not authenticated and no GlobalContext", () => {
|
||||
// No auth config exists and no GlobalContext model
|
||||
test("should return null for model name when no model persisted", () => {
|
||||
// No model persisted and no auth config
|
||||
persistModelName(null); // Ensure GlobalContext is clear
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
expect(getModelName(null)).toBeNull();
|
||||
});
|
||||
|
||||
test("should not persist model name when using CONTINUE_API_KEY", () => {
|
||||
// Clear GlobalContext first
|
||||
persistModelName(null);
|
||||
|
||||
// Capture original value to restore after test
|
||||
const originalApiKey = process.env.CONTINUE_API_KEY;
|
||||
// Set environment variable
|
||||
process.env.CONTINUE_API_KEY = "test-api-key";
|
||||
|
||||
// Try to update model name
|
||||
test("should persist model name via GlobalContext", () => {
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config - should be environment auth config without model name
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
// Verify via getPersistedModelName
|
||||
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Restore original value
|
||||
if (originalApiKey === undefined) {
|
||||
delete process.env.CONTINUE_API_KEY;
|
||||
} else {
|
||||
process.env.CONTINUE_API_KEY = originalApiKey;
|
||||
}
|
||||
});
|
||||
|
||||
test("should persist model name in auth.json file with correct format", () => {
|
||||
// Create and save auth config
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Read the raw file content
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
const rawContent = fs.readFileSync(authPath, "utf8");
|
||||
const parsedContent = JSON.parse(rawContent);
|
||||
|
||||
// Verify the file structure
|
||||
expect(parsedContent).toHaveProperty("userId", "test-user");
|
||||
expect(parsedContent).toHaveProperty("userEmail", "test@example.com");
|
||||
expect(parsedContent).toHaveProperty("organizationId", "test-org");
|
||||
expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it's pretty-printed (has indentation)
|
||||
expect(rawContent).toContain("\n ");
|
||||
// Verify via getModelName (which reads from GlobalContext)
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,23 +10,13 @@ describe("--mcp flag integration", () => {
|
|||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should validate MCP slug format", async () => {
|
||||
// Test that invalid slug formats are rejected
|
||||
it("should reject all hub loading since hub has been removed", async () => {
|
||||
await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid-slug',
|
||||
"Hub package loading has been removed.",
|
||||
);
|
||||
|
||||
// Valid format should not throw during validation step
|
||||
const mockFetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
});
|
||||
global.fetch = mockFetch;
|
||||
|
||||
// This will fail at the HTTP level, not validation level
|
||||
await expect(loadMcpFromHub("valid/slug")).rejects.toThrow(
|
||||
'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found',
|
||||
"Hub package loading has been removed.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,56 +21,48 @@ describe("ApiClientService", () => {
|
|||
});
|
||||
|
||||
describe("State Management", () => {
|
||||
test("should initialize with null api client", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
|
||||
const state = await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("should initialize with api client when token provided", async () => {
|
||||
test("should initialize with api client", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
|
||||
const state = await service.initialize({
|
||||
accessToken: "test-token",
|
||||
} as any);
|
||||
// Auth is always null now; doInitialize ignores the parameter
|
||||
const state = await service.initialize(null);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient,
|
||||
});
|
||||
expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith("test-token");
|
||||
// Should be called with undefined (no auth token)
|
||||
expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update()", () => {
|
||||
test("should update api client with new auth config", async () => {
|
||||
test("should update api client", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
// Update with new token
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
const state = await service.update({ accessToken: "new-token" } as any);
|
||||
await service.initialize(null);
|
||||
|
||||
// Update
|
||||
const newMockApiClient = { ...mockApiClient, extra: true };
|
||||
vi.mocked(config.getApiClient).mockReturnValue(newMockApiClient as any);
|
||||
const state = await service.update(null);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient,
|
||||
apiClient: newMockApiClient,
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test("should handle update errors", async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize(null);
|
||||
|
||||
vi.mocked(config.getApiClient).mockImplementation(() => {
|
||||
throw new Error("Failed to create client");
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.update({ accessToken: "bad-token" } as any),
|
||||
).rejects.toThrow("Failed to create client");
|
||||
await expect(service.update(null)).rejects.toThrow(
|
||||
"Failed to create client",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -79,16 +71,9 @@ describe("ApiClientService", () => {
|
|||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test("should return false when api client is null", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test("should return true when api client exists", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize({ accessToken: "token" } as any);
|
||||
await service.initialize(null);
|
||||
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
|
@ -102,23 +87,25 @@ describe("ApiClientService", () => {
|
|||
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged on update", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize(null);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.update({ accessToken: "new-token" } as any);
|
||||
const newMockApiClient = { ...mockApiClient, extra: true };
|
||||
vi.mocked(config.getApiClient).mockReturnValue(newMockApiClient as any);
|
||||
await service.update(null);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ apiClient: newMockApiClient }),
|
||||
expect.objectContaining({ apiClient: mockApiClient }),
|
||||
expect.objectContaining({ apiClient: null }),
|
||||
);
|
||||
});
|
||||
|
||||
test("should emit error on update failure", async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize(null);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on("error", errorListener);
|
||||
|
|
@ -128,9 +115,7 @@ describe("ApiClientService", () => {
|
|||
throw error;
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.update({ accessToken: "bad" } as any),
|
||||
).rejects.toThrow();
|
||||
await expect(service.update(null)).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import * as configLoader from "../configLoader.js";
|
|||
|
||||
import { ConfigService } from "./ConfigService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { ToolPermissionServiceState } from "./ToolPermissionService.js";
|
||||
import { AgentFileServiceState, SERVICE_NAMES } from "./types.js";
|
||||
vi.mock("../auth/workos.js");
|
||||
vi.mock("../configLoader.js", () => ({
|
||||
|
|
@ -82,7 +83,7 @@ describe("ConfigService", () => {
|
|||
});
|
||||
|
||||
const state = await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/path/to/config.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -111,7 +112,7 @@ describe("ConfigService", () => {
|
|||
});
|
||||
|
||||
const state = await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: undefined,
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -137,7 +138,7 @@ describe("ConfigService", () => {
|
|||
vi.mocked(mergeUnrolledAssistants).mockReturnValue(expectedConfig);
|
||||
|
||||
const state = await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/config.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -168,7 +169,7 @@ describe("ConfigService", () => {
|
|||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -183,7 +184,7 @@ describe("ConfigService", () => {
|
|||
vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig);
|
||||
|
||||
const state = await service.switchConfig({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/new.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -198,7 +199,7 @@ describe("ConfigService", () => {
|
|||
|
||||
test("should handle switch config errors", async () => {
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -210,7 +211,7 @@ describe("ConfigService", () => {
|
|||
|
||||
await expect(
|
||||
service.switchConfig({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/bad.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -227,7 +228,7 @@ describe("ConfigService", () => {
|
|||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/config.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -242,7 +243,7 @@ describe("ConfigService", () => {
|
|||
vi.mocked(mergeUnrolledAssistants).mockReturnValue(updatedConfig);
|
||||
|
||||
const state = await service.reload({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
});
|
||||
|
|
@ -260,7 +261,7 @@ describe("ConfigService", () => {
|
|||
source: { type: "remote-default-config" } as any,
|
||||
});
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: undefined,
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -268,7 +269,7 @@ describe("ConfigService", () => {
|
|||
|
||||
await expect(
|
||||
service.reload({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
}),
|
||||
|
|
@ -284,21 +285,20 @@ describe("ConfigService", () => {
|
|||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
});
|
||||
|
||||
// Mock service container
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue({
|
||||
accessToken: "token",
|
||||
organizationId: "org-123",
|
||||
} as any);
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(serviceContainer.get)
|
||||
.mockResolvedValueOnce({ apiClient: mockApiClient })
|
||||
.mockResolvedValueOnce(mockAgentFileState)
|
||||
.mockResolvedValueOnce({ isHeadless: false });
|
||||
.mockResolvedValueOnce({
|
||||
isHeadless: false,
|
||||
} as ToolPermissionServiceState);
|
||||
|
||||
// Mock new config load
|
||||
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
|
||||
|
|
@ -328,16 +328,13 @@ describe("ConfigService", () => {
|
|||
|
||||
test("should handle missing API client", async () => {
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
});
|
||||
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue({
|
||||
accessToken: "token",
|
||||
organizationId: "org-123",
|
||||
} as any);
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(serviceContainer.get).mockResolvedValue({
|
||||
apiClient: null,
|
||||
});
|
||||
|
|
@ -442,7 +439,7 @@ describe("ConfigService", () => {
|
|||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -459,7 +456,7 @@ describe("ConfigService", () => {
|
|||
vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig);
|
||||
|
||||
await service.switchConfig({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/new.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -476,7 +473,7 @@ describe("ConfigService", () => {
|
|||
|
||||
test("should emit error on switch failure", async () => {
|
||||
await service.doInitialize({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/old.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -490,7 +487,7 @@ describe("ConfigService", () => {
|
|||
|
||||
await expect(
|
||||
service.switchConfig({
|
||||
authConfig: { accessToken: "token" } as any,
|
||||
authConfig: null,
|
||||
configPath: "/bad.yaml",
|
||||
apiClient: mockApiClient as any,
|
||||
agentFileState: mockAgentFileState,
|
||||
|
|
@ -526,7 +523,7 @@ describe("ConfigService", () => {
|
|||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(
|
||||
|
|
@ -542,7 +539,7 @@ describe("ConfigService", () => {
|
|||
},
|
||||
},
|
||||
],
|
||||
"token",
|
||||
null,
|
||||
null,
|
||||
mockApiClient,
|
||||
);
|
||||
|
|
@ -567,7 +564,7 @@ describe("ConfigService", () => {
|
|||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
);
|
||||
|
||||
// Should not call the unroll function since chat model exists
|
||||
|
|
@ -593,7 +590,7 @@ describe("ConfigService", () => {
|
|||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(
|
||||
|
|
@ -620,7 +617,7 @@ describe("ConfigService", () => {
|
|||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(1);
|
||||
|
|
@ -645,7 +642,7 @@ describe("ConfigService", () => {
|
|||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(1);
|
||||
|
|
@ -668,7 +665,7 @@ describe("ConfigService", () => {
|
|||
service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
true,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
|
|
@ -696,7 +693,7 @@ describe("ConfigService", () => {
|
|||
service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
null,
|
||||
true,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
|
|
|
|||
|
|
@ -1,13 +1,11 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import * as workosModule from "./auth/workos.js";
|
||||
import { services } from "./services/index.js";
|
||||
import * as sessionModule from "./session.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
import * as versionModule from "./version.js";
|
||||
|
||||
// Mock all dependencies
|
||||
vi.mock("./auth/workos.js");
|
||||
vi.mock("./version.js", () => ({
|
||||
getVersion: vi.fn(() => "1.2.3"),
|
||||
getLatestVersion: vi.fn(() => Promise.resolve(null)),
|
||||
|
|
@ -51,9 +49,6 @@ describe("handleSlashCommands - /info", () => {
|
|||
});
|
||||
|
||||
it("should include version and working directory in output", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
|
|
@ -78,15 +73,7 @@ describe("handleSlashCommands - /info", () => {
|
|||
expect(result?.exit).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle authenticated user info", async () => {
|
||||
// Mock auth as authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(true);
|
||||
vi.mocked(workosModule.loadAuthConfig).mockReturnValue({
|
||||
userEmail: "test@example.com",
|
||||
userId: "test-user",
|
||||
} as any);
|
||||
vi.mocked(workosModule.isAuthenticatedConfig).mockReturnValue(true);
|
||||
|
||||
it("should show model info in configuration section", async () => {
|
||||
// Mock config service
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
|
|
@ -100,15 +87,10 @@ describe("handleSlashCommands - /info", () => {
|
|||
|
||||
const result = await handleSlashCommands("/info", mockAssistant as any);
|
||||
|
||||
expect(result?.output).toContain("Authentication:");
|
||||
expect(result?.output).toContain("Email: test@example.com");
|
||||
expect(result?.output).toContain("Model: claude-3-sonnet");
|
||||
});
|
||||
|
||||
it("should handle missing model info gracefully", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service with no model info
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
|
|
@ -123,9 +105,6 @@ describe("handleSlashCommands - /info", () => {
|
|||
});
|
||||
|
||||
it("should handle config service error", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service throwing error
|
||||
vi.mocked(services.config.getState).mockImplementation(() => {
|
||||
throw new Error("Service not available");
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
|
||||
describe("Remote mode slash commands", () => {
|
||||
const mockAssistant = {
|
||||
name: "test",
|
||||
version: "1.0.0",
|
||||
prompts: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("/diff and /apply commands", () => {
|
||||
it("should not be handled by handleSlashCommands - these are handled by TUI layer", async () => {
|
||||
// /diff and /apply are handled by handleSpecialCommands in useChat.helpers.ts,
|
||||
// not by the general slash command system. These commands are intercepted
|
||||
// at the TUI layer before reaching handleSlashCommands, so handleSlashCommands
|
||||
// should return null (no match) for these commands.
|
||||
|
||||
const diffResult = await handleSlashCommands("/diff", mockAssistant);
|
||||
expect(diffResult).toBe(null);
|
||||
|
||||
const applyResult = await handleSlashCommands("/apply", mockAssistant);
|
||||
expect(applyResult).toBe(null);
|
||||
});
|
||||
|
||||
it("should return unknown command for remote commands when called directly", async () => {
|
||||
// When called directly (bypassing handleSpecialCommands), /diff and /apply
|
||||
// should return "Unknown command" because they're listed in REMOTE_MODE_SLASH_COMMANDS
|
||||
// for UI display but not implemented as handlers.
|
||||
|
||||
const diffResult = await handleSlashCommands("/diff", mockAssistant, {
|
||||
remoteUrl: "http://localhost:3000",
|
||||
isRemoteMode: true,
|
||||
});
|
||||
expect(diffResult).toEqual({
|
||||
output: "Unknown command: diff",
|
||||
});
|
||||
|
||||
const applyResult = await handleSlashCommands("/apply", mockAssistant, {
|
||||
remoteUrl: "http://localhost:3000",
|
||||
isRemoteMode: true,
|
||||
});
|
||||
expect(applyResult).toEqual({
|
||||
output: "Unknown command: apply",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -8,8 +8,6 @@ import {
|
|||
type MockedFunction,
|
||||
} from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "./auth/workos.js";
|
||||
import type { AuthConfig } from "./auth/workos.js";
|
||||
import type { ConfigServiceState } from "./services/types.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
|
||||
|
|
@ -19,6 +17,9 @@ vi.mock("./services/index.js", () => ({
|
|||
config: {
|
||||
getState: vi.fn(),
|
||||
},
|
||||
model: {
|
||||
getModelInfo: vi.fn(),
|
||||
},
|
||||
},
|
||||
reloadService: vi.fn(),
|
||||
SERVICE_NAMES: {
|
||||
|
|
@ -26,13 +27,6 @@ vi.mock("./services/index.js", () => ({
|
|||
},
|
||||
}));
|
||||
|
||||
// Mock auth functions
|
||||
vi.mock("./auth/workos.js", () => ({
|
||||
isAuthenticated: vi.fn(),
|
||||
isAuthenticatedConfig: vi.fn(),
|
||||
loadAuthConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock commands
|
||||
vi.mock("./commands/commands.js", () => ({
|
||||
getAllSlashCommands: vi.fn(() => []),
|
||||
|
|
@ -99,7 +93,7 @@ describe("slashCommands", () => {
|
|||
expect(result).toBeDefined();
|
||||
expect(result?.output).toContain("Keyboard Shortcuts:");
|
||||
expect(result?.output).toContain("Navigation:");
|
||||
expect(result?.output).toContain("↑/↓");
|
||||
expect(result?.output).toContain("\u2191/\u2193");
|
||||
expect(result?.output).toContain("Tab");
|
||||
expect(result?.output).toContain("Enter");
|
||||
expect(result?.output).toContain("Shift+Enter");
|
||||
|
|
@ -115,13 +109,9 @@ describe("slashCommands", () => {
|
|||
expect(result?.exit).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle /info command when not authenticated", async () => {
|
||||
const { isAuthenticated } = await import("./auth/workos.js");
|
||||
it("should handle /info command and show config info", async () => {
|
||||
const { services } = await import("./services/index.js");
|
||||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -134,8 +124,6 @@ describe("slashCommands", () => {
|
|||
const result = await handleSlashCommands("/info", mockAssistant);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.output).toContain("Authentication:");
|
||||
expect(result?.output).toContain("Not logged in");
|
||||
expect(result?.output).toContain("Configuration:");
|
||||
expect(result?.output).toContain("/test/config.yaml");
|
||||
expect(result?.output).toContain("Session:");
|
||||
|
|
@ -143,18 +131,9 @@ describe("slashCommands", () => {
|
|||
expect(result?.exit).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle /info command when authenticated via environment", async () => {
|
||||
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
|
||||
await import("./auth/workos.js");
|
||||
it("should handle /info command when config not found", async () => {
|
||||
const { services } = await import("./services/index.js");
|
||||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockResolvedValue(true);
|
||||
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
|
||||
{} as AuthConfig,
|
||||
);
|
||||
(isAuthenticatedConfig as any).mockReturnValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -167,36 +146,14 @@ describe("slashCommands", () => {
|
|||
const result = await handleSlashCommands("/info", mockAssistant);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.output).toContain("Authentication:");
|
||||
expect(result?.output).toContain(
|
||||
"Authenticated via environment variable",
|
||||
);
|
||||
expect(result?.output).toContain("Configuration:");
|
||||
expect(result?.output).toContain("Config not found");
|
||||
expect(result?.exit).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle /info command when authenticated with user config", async () => {
|
||||
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
|
||||
await import("./auth/workos.js");
|
||||
it("should handle /info command with config path", async () => {
|
||||
const { services } = await import("./services/index.js");
|
||||
|
||||
const mockAuthConfig: AuthenticatedConfig = {
|
||||
userId: "test-user-id",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh-token",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org-id",
|
||||
};
|
||||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockResolvedValue(true);
|
||||
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
|
||||
mockAuthConfig,
|
||||
);
|
||||
(isAuthenticatedConfig as any).mockReturnValue(true);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -209,21 +166,14 @@ describe("slashCommands", () => {
|
|||
const result = await handleSlashCommands("/info", mockAssistant);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.output).toContain("Authentication:");
|
||||
expect(result?.output).toContain("test@example.com");
|
||||
expect(result?.output).toContain("test-org-id");
|
||||
expect(result?.output).toContain("Configuration:");
|
||||
expect(result?.output).toContain("/custom/config.yaml");
|
||||
expect(result?.exit).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle config service errors gracefully", async () => {
|
||||
const { isAuthenticated } = await import("./auth/workos.js");
|
||||
const { services } = await import("./services/index.js");
|
||||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -239,7 +189,6 @@ describe("slashCommands", () => {
|
|||
});
|
||||
|
||||
it("should use test session directory when in test mode", async () => {
|
||||
const { isAuthenticated } = await import("./auth/workos.js");
|
||||
const { services } = await import("./services/index.js");
|
||||
const { getSessionFilePath, getCurrentSession } = await import(
|
||||
"./session.js"
|
||||
|
|
@ -254,9 +203,6 @@ describe("slashCommands", () => {
|
|||
title: "Test Session",
|
||||
});
|
||||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
|
|||
|
|
@ -12,8 +12,6 @@ import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
|
|||
type CommandHandler = (
|
||||
args: string[],
|
||||
assistant: AssistantConfig,
|
||||
remoteUrl?: string,
|
||||
options?: { isRemoteMode?: boolean },
|
||||
) => Promise<SlashCommandResult> | SlashCommandResult;
|
||||
|
||||
async function handleHelp(_args: string[], _assistant: AssistantConfig) {
|
||||
|
|
@ -47,27 +45,6 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
|
|||
return { output: helpMessage };
|
||||
}
|
||||
|
||||
async function handleLogin() {
|
||||
return {
|
||||
exit: false,
|
||||
output: "Login is not available. Hub authentication has been removed.",
|
||||
};
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
return {
|
||||
exit: false,
|
||||
output: "Logout is not available. Hub authentication has been removed.",
|
||||
};
|
||||
}
|
||||
|
||||
async function handleWhoami() {
|
||||
return {
|
||||
exit: false,
|
||||
output: "Not logged in. Hub authentication has been removed.",
|
||||
};
|
||||
}
|
||||
|
||||
async function handleFork() {
|
||||
try {
|
||||
const currentSession = getCurrentSession();
|
||||
|
|
@ -138,9 +115,6 @@ const commandHandlers: Record<string, CommandHandler> = {
|
|||
config: () => {
|
||||
return { openConfigSelector: true };
|
||||
},
|
||||
login: handleLogin,
|
||||
logout: handleLogout,
|
||||
whoami: handleWhoami,
|
||||
info: handleInfoSlashCommand,
|
||||
model: () => ({ openModelSelector: true }),
|
||||
compact: () => {
|
||||
|
|
@ -168,7 +142,6 @@ const commandHandlers: Record<string, CommandHandler> = {
|
|||
export async function handleSlashCommands(
|
||||
input: string,
|
||||
assistant: AssistantConfig,
|
||||
options?: { remoteUrl?: string; isRemoteMode?: boolean },
|
||||
): Promise<SlashCommandResult | null> {
|
||||
// Only trigger slash commands if slash is the very first character
|
||||
if (!input.startsWith("/") || !input.trim().startsWith("/")) {
|
||||
|
|
@ -181,7 +154,7 @@ export async function handleSlashCommands(
|
|||
|
||||
const handler = commandHandlers[command];
|
||||
if (handler) {
|
||||
return await handler(args, assistant, options?.remoteUrl, options);
|
||||
return await handler(args, assistant);
|
||||
}
|
||||
|
||||
// Check for custom assistant prompts
|
||||
|
|
@ -209,9 +182,7 @@ export async function handleSlashCommands(
|
|||
}
|
||||
|
||||
// Check if this command would match any available commands (same logic as UI)
|
||||
const allCommands = getAllSlashCommands(assistant, {
|
||||
isRemoteMode: options?.isRemoteMode,
|
||||
});
|
||||
const allCommands = getAllSlashCommands(assistant);
|
||||
const hasMatches = allCommands.some((cmd) =>
|
||||
cmd.name.toLowerCase().includes(command.toLowerCase()),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -20,21 +20,17 @@ interface SlashCommandUIProps {
|
|||
assistant?: AssistantConfig;
|
||||
filter: string;
|
||||
selectedIndex: number;
|
||||
isRemoteMode?: boolean;
|
||||
}
|
||||
|
||||
const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
|
||||
assistant,
|
||||
filter,
|
||||
selectedIndex,
|
||||
isRemoteMode = false,
|
||||
}) => {
|
||||
// Memoize the slash commands to prevent excessive re-renders
|
||||
const allCommands = useMemo(() => {
|
||||
if (assistant || isRemoteMode) {
|
||||
return getAllSlashCommands(assistant || ({} as AssistantConfig), {
|
||||
isRemoteMode,
|
||||
});
|
||||
if (assistant) {
|
||||
return getAllSlashCommands(assistant);
|
||||
}
|
||||
|
||||
// Fallback - basic commands without assistant
|
||||
|
|
@ -43,7 +39,7 @@ const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
|
|||
{ name: "clear", description: "Clear the chat history" },
|
||||
{ name: "exit", description: "Exit the chat" },
|
||||
];
|
||||
}, [isRemoteMode, assistant?.prompts, assistant?.rules]);
|
||||
}, [assistant?.prompts, assistant?.rules]);
|
||||
|
||||
// Filter commands based on the current filter
|
||||
const filteredCommands = allCommands
|
||||
|
|
|
|||
|
|
@ -55,14 +55,12 @@ const SlashCommandsMaybe: React.FC<{
|
|||
filter,
|
||||
selectedIndex,
|
||||
}) => {
|
||||
if (!show || !inputMode || hideNormalUI || !(isRemoteMode || assistant))
|
||||
return null;
|
||||
if (!show || !inputMode || hideNormalUI || !assistant) return null;
|
||||
return (
|
||||
<SlashCommandUI
|
||||
assistant={assistant}
|
||||
filter={filter}
|
||||
selectedIndex={selectedIndex}
|
||||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
|
@ -181,10 +179,8 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
}>(["fileIndex"]);
|
||||
|
||||
const getSlashCommands = () => {
|
||||
if (assistant || isRemoteMode) {
|
||||
return getAllSlashCommands(assistant || ({} as AssistantConfig), {
|
||||
isRemoteMode,
|
||||
});
|
||||
if (assistant) {
|
||||
return getAllSlashCommands(assistant);
|
||||
}
|
||||
|
||||
// Fallback - basic commands without assistant
|
||||
|
|
|
|||
|
|
@ -1,90 +0,0 @@
|
|||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
|
||||
import { createUITestContext } from "../../test-helpers/ui-test-context.js";
|
||||
import { AppRoot } from "../AppRoot.js";
|
||||
|
||||
describe("TUIChat - Remote Server Tests", () => {
|
||||
let context: any;
|
||||
|
||||
beforeEach(() => {
|
||||
context = createUITestContext({
|
||||
allServicesReady: true,
|
||||
serviceState: "ready",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
context.cleanup();
|
||||
});
|
||||
|
||||
it("renders in remote mode with remote URL", () => {
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toBeDefined();
|
||||
expect(frame).toContain("Remote Mode");
|
||||
expect(frame).toContain("Ask anything");
|
||||
});
|
||||
|
||||
it("shows remote mode indicator", () => {
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should show remote mode in the UI
|
||||
expect(frame).toContain("◉ Remote Mode");
|
||||
});
|
||||
|
||||
it("does not show service loading in remote mode", () => {
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should not show loading services message
|
||||
expect(frame).not.toContain("Loading services");
|
||||
|
||||
// Should go directly to chat UI
|
||||
expect(frame).toContain("Ask anything");
|
||||
});
|
||||
|
||||
it("handles different remote URLs", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="https://api.example.com:8080" />,
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should still work with different URLs
|
||||
expect(frame).toBeDefined();
|
||||
expect(frame).toContain("Remote Mode");
|
||||
});
|
||||
|
||||
it("shows slash commands in remote mode", async () => {
|
||||
const { lastFrame, stdin } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />,
|
||||
);
|
||||
|
||||
// Wait for initial render
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
// Type / to see slash commands
|
||||
stdin.write("/");
|
||||
|
||||
// Wait longer for slash command menu to appear
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should show slash character at minimum
|
||||
expect(frame).toContain("/");
|
||||
|
||||
// The slash command menu might show /exit or navigation instructions
|
||||
// Different timing might show different states
|
||||
const hasSlashCommandUI = frame
|
||||
? frame.includes("/exit") ||
|
||||
frame.includes("↑/↓ to navigate") ||
|
||||
frame.includes("◉ /") ||
|
||||
frame.includes("/ for slash commands") // Placeholder text is also valid
|
||||
: false;
|
||||
|
||||
expect(hasSlashCommandUI).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -418,10 +418,7 @@ export function useChat({
|
|||
return message;
|
||||
}
|
||||
|
||||
const commandResult = await handleSlashCommands(message, assistant, {
|
||||
remoteUrl,
|
||||
isRemoteMode,
|
||||
});
|
||||
const commandResult = await handleSlashCommands(message, assistant);
|
||||
|
||||
if (!commandResult) {
|
||||
return message;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|||
|
||||
import {
|
||||
ApiRequestError,
|
||||
AuthenticationRequiredError,
|
||||
del,
|
||||
get,
|
||||
makeAuthenticatedRequest,
|
||||
|
|
@ -10,12 +9,6 @@ import {
|
|||
put,
|
||||
} from "./apiClient.js";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn(),
|
||||
getAccessToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../env.js", () => ({
|
||||
env: {
|
||||
apiBase: "https://api.continue.dev",
|
||||
|
|
@ -35,21 +28,10 @@ vi.mock("./logger.js", () => ({
|
|||
global.fetch = vi.fn();
|
||||
|
||||
describe("apiClient", () => {
|
||||
let mockLoadAuthConfig: any;
|
||||
let mockGetAccessToken: any;
|
||||
const mockFetch = vi.mocked(global.fetch);
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Get mocked functions
|
||||
const authModule = await import("../auth/workos.js");
|
||||
mockLoadAuthConfig = vi.mocked(authModule.loadAuthConfig);
|
||||
mockGetAccessToken = vi.mocked(authModule.getAccessToken);
|
||||
|
||||
// Setup default successful authentication
|
||||
mockLoadAuthConfig.mockReturnValue({ some: "config" });
|
||||
mockGetAccessToken.mockReturnValue("test-access-token");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
@ -77,7 +59,6 @@ describe("apiClient", () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-access-token",
|
||||
},
|
||||
body: JSON.stringify({ key: "value" }),
|
||||
},
|
||||
|
|
@ -104,22 +85,6 @@ describe("apiClient", () => {
|
|||
expect(result.data).toBe("plain text response");
|
||||
});
|
||||
|
||||
test("should throw AuthenticationRequiredError when no auth config", async () => {
|
||||
mockLoadAuthConfig.mockReturnValue(null);
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
AuthenticationRequiredError,
|
||||
);
|
||||
});
|
||||
|
||||
test("should throw AuthenticationRequiredError when no access token", async () => {
|
||||
mockGetAccessToken.mockReturnValue(null);
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
AuthenticationRequiredError,
|
||||
);
|
||||
});
|
||||
|
||||
test("should throw ApiRequestError on API error", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: false,
|
||||
|
|
@ -182,7 +147,6 @@ describe("apiClient", () => {
|
|||
expect.objectContaining({
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-access-token",
|
||||
"Custom-Header": "custom-value",
|
||||
},
|
||||
}),
|
||||
|
|
@ -245,16 +209,18 @@ describe("apiClient", () => {
|
|||
});
|
||||
|
||||
describe("error classes", () => {
|
||||
test("AuthenticationRequiredError should have correct properties", () => {
|
||||
test("AuthenticationRequiredError should have correct properties", async () => {
|
||||
const { AuthenticationRequiredError } = await import("./apiClient.js");
|
||||
const error = new AuthenticationRequiredError();
|
||||
|
||||
expect(error.name).toBe("AuthenticationRequiredError");
|
||||
expect(error.message).toBe(
|
||||
"Not authenticated. Please run 'cn login' first.",
|
||||
"Not authenticated. Hub integration has been removed.",
|
||||
);
|
||||
});
|
||||
|
||||
test("AuthenticationRequiredError should accept custom message", () => {
|
||||
test("AuthenticationRequiredError should accept custom message", async () => {
|
||||
const { AuthenticationRequiredError } = await import("./apiClient.js");
|
||||
const customMessage = "Custom auth error";
|
||||
const error = new AuthenticationRequiredError(customMessage);
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ describe("updateAnthropicModelInYaml", () => {
|
|||
it("should create new config from empty string", () => {
|
||||
const result = updateAnthropicModelInYaml("", testApiKey);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("name: Main Config");
|
||||
expect(result).toContain("version: 1.0.0");
|
||||
expect(result).toContain("schema: v1");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-6");
|
||||
|
|
@ -20,7 +20,7 @@ describe("updateAnthropicModelInYaml", () => {
|
|||
const invalidYaml = "invalid: [yaml content";
|
||||
const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("name: Main Config");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-6");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
|
@ -29,7 +29,7 @@ describe("updateAnthropicModelInYaml", () => {
|
|||
describe("comment preservation", () => {
|
||||
it("should preserve comments when adding new model", () => {
|
||||
const yamlWithComments = `# My Continue config
|
||||
name: Local Config
|
||||
name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
# List of available models
|
||||
|
|
@ -50,7 +50,7 @@ models:
|
|||
|
||||
it("should preserve comments when updating existing model", () => {
|
||||
const yamlWithComments = `# My Continue config
|
||||
name: Local Config
|
||||
name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
# List of available models
|
||||
|
|
@ -72,7 +72,7 @@ models:
|
|||
|
||||
describe("model management", () => {
|
||||
it("should add new anthropic model when none exists", () => {
|
||||
const existingConfig = `name: Local Config
|
||||
const existingConfig = `name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
models:
|
||||
|
|
@ -90,7 +90,7 @@ models:
|
|||
});
|
||||
|
||||
it("should update existing anthropic model", () => {
|
||||
const existingConfig = `name: Local Config
|
||||
const existingConfig = `name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
models:
|
||||
|
|
@ -118,7 +118,7 @@ models:
|
|||
});
|
||||
|
||||
it("should handle config with no models array", () => {
|
||||
const configWithoutModels = `name: Local Config
|
||||
const configWithoutModels = `name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
`;
|
||||
|
|
@ -128,14 +128,14 @@ schema: v1
|
|||
testApiKey,
|
||||
);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("name: Main Config");
|
||||
expect(result).toContain("models:");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-6");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
||||
it("should handle config with empty models array", () => {
|
||||
const configWithEmptyModels = `name: Local Config
|
||||
const configWithEmptyModels = `name: Main Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
models: []
|
||||
|
|
@ -146,7 +146,7 @@ models: []
|
|||
testApiKey,
|
||||
);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("name: Main Config");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-6");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
|
@ -183,7 +183,7 @@ models:
|
|||
|
||||
describe("edge cases", () => {
|
||||
it("should handle malformed models array gracefully", () => {
|
||||
const malformedConfig = `name: Local Config
|
||||
const malformedConfig = `name: Main Config
|
||||
models: "not an array"
|
||||
`;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue