refactor: remove Hub/Mission Control connection code (CON-5885)
Remove all ControlPlaneClient infrastructure, WorkOS auth, managed proxy, platform profile loading, org policy enforcement, and credits UI. Config is now fully local — only file-based config.yaml and .env secrets. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
62773b8baf
commit
b60273502e
129 changed files with 238 additions and 12260 deletions
|
|
@ -1,6 +1,5 @@
|
|||
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../control-plane/client.js";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
|
|
@ -12,12 +11,6 @@ import {
|
|||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
||||
import EventEmitter from "node:events";
|
||||
import {
|
||||
AuthType,
|
||||
ControlPlaneSessionInfo,
|
||||
} from "../control-plane/AuthTypes.js";
|
||||
import { getControlPlaneEnv } from "../control-plane/env.js";
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
|
||||
import {
|
||||
|
|
@ -25,7 +18,6 @@ import {
|
|||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants.js";
|
||||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
OrganizationDescription,
|
||||
OrgWithProfiles,
|
||||
|
|
@ -39,7 +31,6 @@ export type { ProfileDescription };
|
|||
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
|
||||
|
||||
export class ConfigHandler {
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private globalLocalProfileManager: ProfileLifecycleManager;
|
||||
|
||||
|
|
@ -60,16 +51,10 @@ export class ConfigHandler {
|
|||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private llmLogger: ILLMLogger,
|
||||
initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
) {
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
initialSessionInfoPromise,
|
||||
this.ide,
|
||||
);
|
||||
|
||||
// This profile manager will always be available
|
||||
this.globalLocalProfileManager = new ProfileLifecycleManager(
|
||||
new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger),
|
||||
new LocalProfileLoader(ide, this.llmLogger),
|
||||
this.ide,
|
||||
);
|
||||
|
||||
|
|
@ -100,14 +85,12 @@ export class ConfigHandler {
|
|||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
private async cascadeInit(reason: string, isLogin?: boolean) {
|
||||
private async cascadeInit(reason: string) {
|
||||
const signal = this.cascadeAbortController.signal;
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
// Always update globalLocalProfileManager before recreating all the loaders
|
||||
// during every cascadeInit so it holds the most recent controlPlaneClient.
|
||||
this.globalLocalProfileManager = new ProfileLifecycleManager(
|
||||
new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger),
|
||||
new LocalProfileLoader(this.ide, this.llmLogger),
|
||||
this.ide,
|
||||
);
|
||||
|
||||
|
|
@ -118,12 +101,7 @@ export class ConfigHandler {
|
|||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
let currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
// reset personal org to first available non-personal org on login
|
||||
if (isLogin && currentSelection === "personal") {
|
||||
currentSelection = null;
|
||||
}
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
|
|
@ -144,7 +122,7 @@ export class ConfigHandler {
|
|||
}
|
||||
|
||||
if (signal.aborted) {
|
||||
return; // local only case, no`fetch to throw abort error
|
||||
return;
|
||||
}
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
|
|
@ -172,43 +150,6 @@ export class ConfigHandler {
|
|||
errors?: ConfigValidationError[];
|
||||
}> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const isSignedIn = await this.controlPlaneClient.isSignedIn();
|
||||
if (isSignedIn) {
|
||||
try {
|
||||
// TODO use policy returned with org, not policy endpoint
|
||||
const policyResponse = await this.controlPlaneClient.getPolicy();
|
||||
PolicySingleton.getInstance().policy = policyResponse;
|
||||
const orgDescriptions =
|
||||
await this.controlPlaneClient.listOrganizations();
|
||||
const orgsWithPolicy = orgDescriptions.map((d) => ({
|
||||
...d,
|
||||
policy: policyResponse?.policy,
|
||||
}));
|
||||
|
||||
if (policyResponse?.policy?.allowOtherOrgs === false) {
|
||||
if (orgsWithPolicy.length === 0) {
|
||||
return { orgs: [] };
|
||||
} else {
|
||||
const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
|
||||
return { orgs: [firstOrg] };
|
||||
}
|
||||
}
|
||||
const orgs = await Promise.all([
|
||||
this.getPersonalHubOrg(),
|
||||
...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
]);
|
||||
// TODO make try/catch more granular here, to catch specific org errors
|
||||
return { orgs };
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
PolicySingleton.getInstance().policy = null;
|
||||
}
|
||||
// Load local org if not signed in or hub orgs fail
|
||||
try {
|
||||
const orgs = [await this.getLocalOrg()];
|
||||
return { orgs };
|
||||
|
|
@ -235,58 +176,12 @@ export class ConfigHandler {
|
|||
}));
|
||||
}
|
||||
|
||||
private async getHubProfiles(orgScopeId: string | null) {
|
||||
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
|
||||
|
||||
return await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create({
|
||||
configResult: {
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
ownerSlug: assistant.ownerSlug,
|
||||
packageSlug: assistant.packageSlug,
|
||||
iconUrl: assistant.iconUrl,
|
||||
versionSlug: assistant.configResult.config?.version ?? "latest",
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
ide: this.ide,
|
||||
llmLogger: this.llmLogger,
|
||||
rawYaml: assistant.rawYaml,
|
||||
orgScopeId: orgScopeId,
|
||||
});
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private PERSONAL_ORG_DESC: OrganizationDescription = {
|
||||
iconUrl: "",
|
||||
id: "personal",
|
||||
name: "Personal",
|
||||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: true,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
private async getLocalOrg() {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
|
|
@ -344,13 +239,6 @@ export class ConfigHandler {
|
|||
/**
|
||||
* Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
|
||||
*/
|
||||
|
||||
// Local customization disabled for on-premise deployments
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
if (env.AUTH_TYPE === AuthType.OnPrem) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const localProfiles: ProfileLifecycleManager[] = [];
|
||||
|
||||
if (options.includeGlobal) {
|
||||
|
|
@ -369,12 +257,7 @@ export class ConfigHandler {
|
|||
"agents",
|
||||
);
|
||||
const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
);
|
||||
return new LocalProfileLoader(this.ide, this.llmLogger, assistant);
|
||||
});
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
|
|
@ -399,49 +282,6 @@ export class ConfigHandler {
|
|||
await this.cascadeInit("IDE settings update");
|
||||
}
|
||||
|
||||
// Session change: refresh session and cascade refresh from the top
|
||||
async updateControlPlaneSessionInfo(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
) {
|
||||
const currentSession = await this.controlPlaneClient.sessionInfoPromise;
|
||||
const newSession = sessionInfo;
|
||||
|
||||
let reload = false;
|
||||
let isLogin = false;
|
||||
if (newSession) {
|
||||
if (currentSession) {
|
||||
if (
|
||||
newSession.AUTH_TYPE !== AuthType.OnPrem &&
|
||||
currentSession.AUTH_TYPE !== AuthType.OnPrem
|
||||
) {
|
||||
if (newSession.account.id !== currentSession.account.id) {
|
||||
// session id change (non-on-prem)
|
||||
reload = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// log in
|
||||
reload = true;
|
||||
isLogin = true;
|
||||
}
|
||||
} else {
|
||||
if (currentSession) {
|
||||
// log out
|
||||
reload = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (reload) {
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(sessionInfo),
|
||||
this.ide,
|
||||
);
|
||||
this.abortCascade();
|
||||
await this.cascadeInit("Control plane session info update", isLogin);
|
||||
}
|
||||
return reload;
|
||||
}
|
||||
|
||||
// Org id: check id validity, save selection, switch and reload
|
||||
async setSelectedOrgId(orgId: string, profileId?: string) {
|
||||
if (orgId === this.currentOrg?.id) {
|
||||
|
|
@ -617,13 +457,8 @@ export class ConfigHandler {
|
|||
return;
|
||||
}
|
||||
|
||||
if (profile.profileDescription.profileType === "local") {
|
||||
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
|
||||
await this.ide.openFile(configFile);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
|
||||
await this.ide.openFile(configFile);
|
||||
}
|
||||
|
||||
// Ancient method of adding custom providers through vs code
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/b
|
|||
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
|
||||
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
|
||||
import { useHub } from "../control-plane/env";
|
||||
import { BaseLLM } from "../llm";
|
||||
import { LLMClasses, llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
|
|
@ -60,7 +59,6 @@ import { localPathToUri } from "../util/pathToUri";
|
|||
|
||||
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions, serializeTool } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
|
|
@ -240,7 +238,6 @@ async function intermediateToFinalConfig({
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
loadPromptFiles = true,
|
||||
}: {
|
||||
config: Config;
|
||||
|
|
@ -249,7 +246,6 @@ async function intermediateToFinalConfig({
|
|||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
loadPromptFiles?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
|
@ -550,10 +546,7 @@ async function intermediateToFinalConfig({
|
|||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
{
|
||||
const mcpOptions: InternalMcpOptions[] = (
|
||||
config.experimental?.modelContextProtocolServers ?? []
|
||||
).map((server, index) => ({
|
||||
|
|
@ -677,7 +670,6 @@ async function finalToBrowserConfig(
|
|||
tools: final.tools.map(serializeTool),
|
||||
mcpServerStatuses: final.mcpServerStatuses,
|
||||
tabAutocompleteOptions: final.tabAutocompleteOptions,
|
||||
usePlatform: await useHub(ide.getIdeSettings()),
|
||||
modelsByRole: Object.fromEntries(
|
||||
Object.entries(final.modelsByRole).map(([k, v]) => [
|
||||
k,
|
||||
|
|
@ -828,7 +820,6 @@ async function loadContinueConfigFromJson(
|
|||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const workspaceConfigs = await getWorkspaceRcConfigs(ide);
|
||||
|
|
@ -924,7 +915,6 @@ async function loadContinueConfigFromJson(
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
});
|
||||
return {
|
||||
config: finalConfig,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
|
|
@ -15,7 +14,6 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
|
||||
constructor(
|
||||
private ide: IDE,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
private llmLogger: ILLMLogger,
|
||||
private overrideAssistantFile?:
|
||||
| { path: string; content: string }
|
||||
|
|
@ -56,11 +54,9 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const result = await doLoadConfig({
|
||||
ide: this.ide,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
|
||||
orgScopeId: null,
|
||||
packageIdentifier: {
|
||||
uriType: "file",
|
||||
fileUri: this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { LLMLogger } from "../../llm/logger.js";
|
||||
import { testIde } from "../../test/fixtures.js";
|
||||
import LocalProfileLoader from "./LocalProfileLoader.js";
|
||||
|
|
@ -17,10 +16,6 @@ vi.mock("./doLoadConfig.js", () => ({
|
|||
}));
|
||||
|
||||
describe("LocalProfileLoader", () => {
|
||||
const controlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(undefined),
|
||||
testIde,
|
||||
);
|
||||
const llmLogger = new LLMLogger();
|
||||
|
||||
it("should pass pre-read content in packageIdentifier for override files", async () => {
|
||||
|
|
@ -29,12 +24,7 @@ describe("LocalProfileLoader", () => {
|
|||
content: "name: Test\nversion: 1.0.0\nschema: v1\n",
|
||||
};
|
||||
|
||||
const loader = new LocalProfileLoader(
|
||||
testIde,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideFile,
|
||||
);
|
||||
const loader = new LocalProfileLoader(testIde, llmLogger, overrideFile);
|
||||
|
||||
await loader.doLoadConfig();
|
||||
|
||||
|
|
@ -50,11 +40,7 @@ describe("LocalProfileLoader", () => {
|
|||
});
|
||||
|
||||
it("should not include content in packageIdentifier when no override file", async () => {
|
||||
const loader = new LocalProfileLoader(
|
||||
testIde,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
);
|
||||
const loader = new LocalProfileLoader(testIde, llmLogger);
|
||||
|
||||
await loader.doLoadConfig();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,158 +0,0 @@
|
|||
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
/**
|
||||
* Metadata about the package that is currently being loaded
|
||||
* If this is `undefined`, it's not a config from the platform,
|
||||
* could be local for example.
|
||||
*/
|
||||
export interface PlatformConfigMetadata {
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
}
|
||||
|
||||
export default class PlatformProfileLoader implements IProfileLoader {
|
||||
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
|
||||
|
||||
private configResult: ConfigResult<AssistantUnrolled>;
|
||||
private readonly ownerSlug: string;
|
||||
private readonly packageSlug: string;
|
||||
private readonly iconUrl: string;
|
||||
private readonly versionSlug: string;
|
||||
private readonly controlPlaneClient: ControlPlaneClient;
|
||||
private readonly ide: IDE;
|
||||
private llmLogger: ILLMLogger;
|
||||
readonly description: ProfileDescription;
|
||||
private readonly orgScopeId: string | null;
|
||||
|
||||
private constructor({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
llmLogger,
|
||||
description,
|
||||
orgScopeId,
|
||||
}: {
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
versionSlug: string;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
ide: IDE;
|
||||
llmLogger: ILLMLogger;
|
||||
description: ProfileDescription;
|
||||
orgScopeId: string | null;
|
||||
}) {
|
||||
this.configResult = configResult;
|
||||
this.ownerSlug = ownerSlug;
|
||||
this.packageSlug = packageSlug;
|
||||
this.iconUrl = iconUrl;
|
||||
this.versionSlug = versionSlug;
|
||||
this.controlPlaneClient = controlPlaneClient;
|
||||
this.ide = ide;
|
||||
this.llmLogger = llmLogger;
|
||||
this.description = description;
|
||||
this.orgScopeId = orgScopeId;
|
||||
}
|
||||
|
||||
static async create({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
llmLogger,
|
||||
rawYaml,
|
||||
orgScopeId,
|
||||
}: {
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
versionSlug: string;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
ide: IDE;
|
||||
llmLogger: ILLMLogger;
|
||||
rawYaml: string;
|
||||
orgScopeId: string | null;
|
||||
}): Promise<PlatformProfileLoader> {
|
||||
const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings());
|
||||
|
||||
const description: ProfileDescription = {
|
||||
id: `${ownerSlug}/${packageSlug}`,
|
||||
profileType: "platform",
|
||||
fullSlug: {
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
versionSlug,
|
||||
},
|
||||
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
|
||||
errors: configResult.errors,
|
||||
iconUrl: iconUrl,
|
||||
uri: `${controlPlaneEnv.APP_URL}${ownerSlug}/${packageSlug}`,
|
||||
rawYaml,
|
||||
};
|
||||
|
||||
return new PlatformProfileLoader({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
llmLogger,
|
||||
description,
|
||||
orgScopeId,
|
||||
});
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (this.configResult.errors?.find((e) => e.fatal)) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: this.configResult.errors,
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
}
|
||||
|
||||
const results = await doLoadConfig({
|
||||
ide: this.ide,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigYaml: this.configResult.config,
|
||||
profileId: this.description.id,
|
||||
orgScopeId: this.orgScopeId,
|
||||
packageIdentifier: {
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
versionSlug: this.versionSlug,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
config: results.config,
|
||||
errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])],
|
||||
configLoadInterrupted: results.configLoadInterrupted,
|
||||
};
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
}
|
||||
|
|
@ -4,7 +4,6 @@ import {
|
|||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
ModelRole,
|
||||
PackageIdentifier,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
|
|
@ -20,13 +19,7 @@ import {
|
|||
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
|
||||
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
|
||||
import MCPContextProvider from "../../context/providers/MCPContextProvider";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { initSlashCommand } from "../../promptFiles/initPrompt";
|
||||
import { getConfigDependentToolDefinitions } from "../../tools";
|
||||
import { encodeMCPToolUri } from "../../tools/callTool";
|
||||
|
|
@ -70,32 +63,26 @@ async function loadRules(ide: IDE) {
|
|||
|
||||
export default async function doLoadConfig(options: {
|
||||
ide: IDE;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
llmLogger: ILLMLogger;
|
||||
overrideConfigJson?: SerializedContinueConfig;
|
||||
overrideConfigYaml?: AssistantUnrolled;
|
||||
profileId: string;
|
||||
overrideConfigYamlByPath?: string;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const {
|
||||
ide,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideConfigJson,
|
||||
overrideConfigYaml,
|
||||
profileId,
|
||||
overrideConfigYamlByPath,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
const uniqueId = await ide.getUniqueId();
|
||||
const ideSettings = await ide.getIdeSettings();
|
||||
const workOsAccessToken = await controlPlaneClient.getAccessToken();
|
||||
const isSignedIn = await controlPlaneClient.isSignedIn();
|
||||
|
||||
// Migrations for old config files
|
||||
// Removes
|
||||
|
|
@ -128,10 +115,7 @@ export default async function doLoadConfig(options: {
|
|||
uniqueId,
|
||||
llmLogger,
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
workOsAccessToken,
|
||||
});
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
|
|
@ -143,7 +127,6 @@ export default async function doLoadConfig(options: {
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigJson,
|
||||
);
|
||||
newConfig = result.config;
|
||||
|
|
@ -181,14 +164,6 @@ export default async function doLoadConfig(options: {
|
|||
|
||||
newConfig.slashCommands.push(initSlashCommand);
|
||||
|
||||
const proxyContextProvider = newConfig.contextProviders?.find(
|
||||
(cp) => cp.description.title === "continue-proxy",
|
||||
);
|
||||
if (proxyContextProvider) {
|
||||
(proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
// Show deprecation warnings for providers
|
||||
const globalContext = new GlobalContext();
|
||||
newConfig.contextProviders.forEach((provider) => {
|
||||
|
|
@ -311,7 +286,6 @@ export default async function doLoadConfig(options: {
|
|||
rules: newConfig.rules,
|
||||
enableExperimentalTools:
|
||||
newConfig.experimental?.enableExperimentalTools ?? false,
|
||||
isSignedIn,
|
||||
isRemote: await ide.isWorkspaceRemote(),
|
||||
modelName: newConfig.selectedModelByRole.chat?.model,
|
||||
ide,
|
||||
|
|
@ -368,76 +342,11 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
}
|
||||
|
||||
// Org policies
|
||||
const policy = PolicySingleton.getInstance().policy?.policy;
|
||||
if (policy?.allowAnonymousTelemetry === false) {
|
||||
newConfig.allowAnonymousTelemetry = false;
|
||||
}
|
||||
if (policy?.allowCodebaseIndexing === false) {
|
||||
newConfig.disableIndexing = true;
|
||||
}
|
||||
|
||||
// Setup IdeInfoService
|
||||
IdeInfoService.setup(
|
||||
uniqueId,
|
||||
ideInfo,
|
||||
);
|
||||
IdeInfoService.setup(uniqueId, ideInfo);
|
||||
|
||||
// TODO: pass config to pre-load non-system TTS models
|
||||
await TTS.setup();
|
||||
|
||||
// Set up control plane proxy if configured
|
||||
const controlPlane = (newConfig as any).controlPlane;
|
||||
const useOnPremProxy =
|
||||
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
|
||||
|
||||
const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
|
||||
let controlPlaneProxyUrl: string = useOnPremProxy
|
||||
? controlPlane?.proxyUrl
|
||||
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;
|
||||
|
||||
if (!controlPlaneProxyUrl.endsWith("/")) {
|
||||
controlPlaneProxyUrl += "/";
|
||||
}
|
||||
const controlPlaneProxyInfo = {
|
||||
profileId,
|
||||
controlPlaneProxyUrl,
|
||||
workOsAccessToken,
|
||||
};
|
||||
|
||||
newConfig = await injectControlPlaneProxyInfo(
|
||||
newConfig,
|
||||
controlPlaneProxyInfo,
|
||||
);
|
||||
|
||||
return { config: newConfig, errors, configLoadInterrupted: false };
|
||||
}
|
||||
|
||||
// Pass ControlPlaneProxyInfo to objects that need it
|
||||
async function injectControlPlaneProxyInfo(
|
||||
config: ContinueConfig,
|
||||
info: ControlPlaneProxyInfo,
|
||||
): Promise<ContinueConfig> {
|
||||
Object.keys(config.modelsByRole).forEach((key) => {
|
||||
config.modelsByRole[key as ModelRole].forEach((model) => {
|
||||
if (model.providerName === "continue-proxy") {
|
||||
(model as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Object.keys(config.selectedModelByRole).forEach((key) => {
|
||||
const model = config.selectedModelByRole[key as ModelRole];
|
||||
if (model?.providerName === "continue-proxy") {
|
||||
(model as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
});
|
||||
|
||||
config.modelsByRole.chat.forEach((model) => {
|
||||
if (model.providerName === "continue-proxy") {
|
||||
(model as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
});
|
||||
|
||||
return config;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,17 +72,6 @@ vi.mock("../../util/GlobalContext", () => ({
|
|||
update() {}
|
||||
},
|
||||
}));
|
||||
vi.mock("../../control-plane/env", () => ({
|
||||
getControlPlaneEnv: vi.fn().mockResolvedValue({
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://proxy.example.com/",
|
||||
}),
|
||||
getControlPlaneEnvSync: vi.fn().mockReturnValue({
|
||||
CONTROL_PLANE_URL: "https://api.example.com/",
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../control-plane/PolicySingleton", () => ({
|
||||
PolicySingleton: { getInstance: () => ({ policy: null }) },
|
||||
}));
|
||||
vi.mock("../../promptFiles/initPrompt", () => ({
|
||||
initSlashCommand: { name: "init", description: "init" },
|
||||
}));
|
||||
|
|
@ -116,12 +105,6 @@ const mockIde = {
|
|||
isWorkspaceRemote: vi.fn().mockResolvedValue(true),
|
||||
} as any;
|
||||
|
||||
const mockControlPlaneClient = {
|
||||
getAccessToken: vi.fn().mockResolvedValue("token"),
|
||||
isSignedIn: vi.fn().mockResolvedValue(false),
|
||||
sessionInfoPromise: Promise.resolve(undefined),
|
||||
} as any;
|
||||
|
||||
const mockLlmLogger = {} as any;
|
||||
|
||||
describe("doLoadConfig pre-read content bypass", () => {
|
||||
|
|
@ -138,11 +121,11 @@ describe("doLoadConfig pre-read content bypass", () => {
|
|||
|
||||
await doLoadConfig({
|
||||
ide: mockIde,
|
||||
controlPlaneClient: mockControlPlaneClient,
|
||||
|
||||
llmLogger: mockLlmLogger,
|
||||
profileId: "test-profile",
|
||||
overrideConfigYamlByPath: packageIdentifier.fileUri,
|
||||
orgScopeId: null,
|
||||
|
||||
packageIdentifier,
|
||||
});
|
||||
|
||||
|
|
@ -162,11 +145,11 @@ describe("doLoadConfig pre-read content bypass", () => {
|
|||
|
||||
await doLoadConfig({
|
||||
ide: mockIde,
|
||||
controlPlaneClient: mockControlPlaneClient,
|
||||
|
||||
llmLogger: mockLlmLogger,
|
||||
profileId: "test-profile",
|
||||
overrideConfigYamlByPath: packageIdentifier.fileUri,
|
||||
orgScopeId: null,
|
||||
|
||||
packageIdentifier,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -809,7 +809,6 @@ declare global {
|
|||
| "currentFile"
|
||||
| "greptile"
|
||||
| "outline"
|
||||
| "continue-proxy"
|
||||
| "highlights"
|
||||
| "file"
|
||||
| "issue"
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
@ -124,7 +124,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
@ -186,7 +186,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
@ -249,7 +249,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
@ -305,7 +305,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
@ -349,7 +349,7 @@ describe("usesFreeTrialApiKey", () => {
|
|||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
|
||||
rules: [],
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -6,16 +6,11 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import * as dotenv from "dotenv";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { getContinueDotEnv } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
) {}
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
/**
|
||||
* searches for the first valid secret file in order of ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
|
||||
|
|
@ -97,41 +92,28 @@ export class LocalPlatformClient implements PlatformClient {
|
|||
return [];
|
||||
}
|
||||
|
||||
let results: (SecretResult | undefined)[] = [];
|
||||
try {
|
||||
results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
} catch (e) {
|
||||
console.error("Error getting secrets from control plane", e);
|
||||
}
|
||||
const results: (SecretResult | undefined)[] = [];
|
||||
|
||||
// For any secret that isn't found, look in .env files, then process.env
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
if (!results[i]?.found) {
|
||||
let secretResult = await this.findSecretInEnvFiles(fqsns[i]);
|
||||
for (let i = 0; i < fqsns.length; i++) {
|
||||
let secretResult = await this.findSecretInEnvFiles(fqsns[i]);
|
||||
|
||||
// If not found in .env files, try process.env
|
||||
if (!secretResult?.found) {
|
||||
const secretValueFromProcessEnv = process.env[fqsns[i].secretName];
|
||||
if (secretValueFromProcessEnv !== undefined) {
|
||||
secretResult = {
|
||||
found: true,
|
||||
fqsn: fqsns[i],
|
||||
value: secretValueFromProcessEnv,
|
||||
secretLocation: {
|
||||
secretName: fqsns[i].secretName,
|
||||
// Cast to SecretType.ProcessEnv is necessary because the specific type
|
||||
// ProcessEnvSecretLocation expects secretType to be exactly SecretType.ProcessEnv,
|
||||
// not the general enum SecretType.
|
||||
secretType: SecretType.ProcessEnv as SecretType.ProcessEnv,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (secretResult?.found) {
|
||||
results[i] = secretResult;
|
||||
// If not found in .env files, try process.env
|
||||
if (!secretResult?.found) {
|
||||
const secretValueFromProcessEnv = process.env[fqsns[i].secretName];
|
||||
if (secretValueFromProcessEnv !== undefined) {
|
||||
secretResult = {
|
||||
found: true,
|
||||
fqsn: fqsns[i],
|
||||
value: secretValueFromProcessEnv,
|
||||
secretLocation: {
|
||||
secretName: fqsns[i].secretName,
|
||||
secretType: SecretType.ProcessEnv as SecretType.ProcessEnv,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
results[i] = secretResult;
|
||||
}
|
||||
|
||||
return results;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
vi,
|
||||
} from "vitest";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
||||
vi.mock("../../util/paths", { spy: true });
|
||||
|
|
@ -34,23 +33,11 @@ describe("LocalPlatformClient", () => {
|
|||
secretName: "TEST_WORKSPACE_SECRET_KEY",
|
||||
};
|
||||
|
||||
const testResolvedFQSN: SecretResult = {
|
||||
found: true,
|
||||
fqsn: testFQSN,
|
||||
secretLocation: {
|
||||
secretName: testFQSN.secretName,
|
||||
secretType: SecretType.Organization,
|
||||
orgSlug: "test-org-slug",
|
||||
},
|
||||
};
|
||||
|
||||
let testControlPlaneClient: ControlPlaneClient;
|
||||
let testIde: IDE;
|
||||
beforeEach(
|
||||
/**dynamic import before each test for test isolation */
|
||||
async () => {
|
||||
const testFixtures = await import("../../test/fixtures");
|
||||
testControlPlaneClient = testFixtures.testControlPlaneClient;
|
||||
testIde = testFixtures.testIde;
|
||||
},
|
||||
);
|
||||
|
|
@ -79,28 +66,11 @@ describe("LocalPlatformClient", () => {
|
|||
});
|
||||
|
||||
test("should not be able to resolve FQSNs if they do not exist", async () => {
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBeGreaterThan(0);
|
||||
expect(resolvedFQSNs[0]?.found).toBe(false);
|
||||
});
|
||||
|
||||
test("should be able to resolve FQSNs if they exist", async () => {
|
||||
testControlPlaneClient.resolveFQSNs = vi.fn(async () => [testResolvedFQSN]);
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
expect(testControlPlaneClient.resolveFQSNs).toHaveBeenCalled();
|
||||
expect(resolvedFQSNs).toEqual([testResolvedFQSN]);
|
||||
expect(resolvedFQSNs[0]?.found).toBe(true);
|
||||
expect(resolvedFQSNs[0]?.found).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("searches for secrets in local .env files", () => {
|
||||
|
|
@ -112,11 +82,7 @@ describe("LocalPlatformClient", () => {
|
|||
});
|
||||
|
||||
test("should be able to get secrets from ~/.continue/.env files", async () => {
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
expect(getContinueDotEnv).toHaveBeenCalled();
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
|
|
@ -155,11 +121,7 @@ describe("LocalPlatformClient", () => {
|
|||
return originalIdeReadFile(fileUri);
|
||||
});
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([
|
||||
testFQSN,
|
||||
testFQSN2,
|
||||
|
|
@ -209,11 +171,7 @@ describe("LocalPlatformClient", () => {
|
|||
return originalIdeReadFile(fileUri);
|
||||
});
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
|
|
@ -234,20 +192,6 @@ describe("LocalPlatformClient", () => {
|
|||
const ogProcessEnv = { ...process.env };
|
||||
|
||||
beforeEach(async () => {
|
||||
// Ensure secrets are not found in ControlPlane initially for these tests
|
||||
const mockResolveFQSNsNotFound = async (
|
||||
fqsns: FQSN[],
|
||||
): Promise<(SecretResult | undefined)[]> =>
|
||||
fqsns.map((fqsn) => ({
|
||||
found: false,
|
||||
fqsn,
|
||||
secretLocation: {
|
||||
secretName: fqsn.secretName,
|
||||
secretType: SecretType.NotFound as SecretType.NotFound,
|
||||
},
|
||||
}));
|
||||
testControlPlaneClient.resolveFQSNs = vi.fn(mockResolveFQSNsNotFound);
|
||||
|
||||
// Ensure secrets are not found in local .env files
|
||||
const utilPaths = await import("../../util/paths");
|
||||
utilPaths.getContinueDotEnv = vi.fn(() => ({}));
|
||||
|
|
@ -270,11 +214,7 @@ describe("LocalPlatformClient", () => {
|
|||
const processEnvSecretValue = "secret-from-process-env";
|
||||
process.env[testFQSN.secretName] = processEnvSecretValue;
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
|
|
@ -297,58 +237,11 @@ describe("LocalPlatformClient", () => {
|
|||
// Ensure it's not in process.env
|
||||
expect(process.env[testFQSN.secretName]).toBeUndefined();
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
expect(resolvedFQSNs[0]?.found).toBe(false);
|
||||
expect(resolvedFQSNs[0]?.secretLocation?.secretType).toBe(
|
||||
SecretType.NotFound,
|
||||
);
|
||||
});
|
||||
|
||||
test("should prioritize ControlPlane over process.env", async () => {
|
||||
const controlPlaneValue = "secret-from-control-plane";
|
||||
|
||||
const mockResolveFQSNsControlPlaneFound = async (): Promise<
|
||||
(SecretResult | undefined)[]
|
||||
> => [
|
||||
{
|
||||
found: true,
|
||||
fqsn: testFQSN,
|
||||
value: controlPlaneValue,
|
||||
secretLocation: {
|
||||
secretType: SecretType.Organization as SecretType.Organization,
|
||||
orgSlug: (testResolvedFQSN.secretLocation as any).orgSlug,
|
||||
secretName: testFQSN.secretName,
|
||||
},
|
||||
},
|
||||
];
|
||||
testControlPlaneClient.resolveFQSNs = vi.fn(
|
||||
mockResolveFQSNsControlPlaneFound,
|
||||
);
|
||||
|
||||
process.env[testFQSN.secretName] =
|
||||
"secret-from-process-env-should-be-ignored";
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
const result = resolvedFQSNs[0];
|
||||
expect(result?.found).toBe(true);
|
||||
expect((result as SecretResult & { value: unknown })?.value).toBe(
|
||||
controlPlaneValue,
|
||||
);
|
||||
expect(result?.secretLocation?.secretType).toBe(SecretType.Organization);
|
||||
expect(resolvedFQSNs[0]).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should prioritize local ~/.continue/.env file over process.env", async () => {
|
||||
|
|
@ -361,11 +254,7 @@ describe("LocalPlatformClient", () => {
|
|||
process.env[testFQSN.secretName] =
|
||||
"secret-from-process-env-should-be-ignored";
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
|
|
@ -393,11 +282,7 @@ describe("LocalPlatformClient", () => {
|
|||
process.env[testFQSN.secretName] =
|
||||
"secret-from-process-env-should-be-ignored";
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const localPlatformClient = new LocalPlatformClient(testIde);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import {
|
|||
unrollAssistantFromContent,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
||||
// This is a certain approach to unrolling local YAML where it
|
||||
|
|
@ -16,8 +15,6 @@ export async function unrollLocalYamlBlocks(
|
|||
packageIdentifiers: PackageIdentifier[],
|
||||
ide: IDE,
|
||||
registryClient: RegistryClient,
|
||||
orgScopeId: string | null,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
try {
|
||||
const unrollResult = await unrollAssistantFromContent(
|
||||
|
|
@ -29,13 +26,7 @@ export async function unrollLocalYamlBlocks(
|
|||
registryClient,
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
platformClient: new LocalPlatformClient(ide),
|
||||
renderSecrets: true,
|
||||
injectBlocks: packageIdentifiers,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import {
|
|||
InternalMcpOptions,
|
||||
} from "../..";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
|
|
@ -32,8 +31,6 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { loadConfigContextProviders } from "../loadContextProviders";
|
||||
|
|
@ -48,20 +45,11 @@ import {
|
|||
|
||||
async function loadConfigYaml(options: {
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
orgScopeId: string | null;
|
||||
ideSettings: IdeSettings;
|
||||
ide: IDE;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
const {
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
ide,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
const { overrideConfigYaml, ideSettings, ide, packageIdentifier } = options;
|
||||
|
||||
// Add local .continue blocks
|
||||
// Use "content" field to pass pre-read content directly, avoiding
|
||||
|
|
@ -82,10 +70,6 @@ async function loadConfigYaml(options: {
|
|||
await Promise.all(localBlockPromises)
|
||||
).flat();
|
||||
|
||||
// logger.info(
|
||||
// `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
|
||||
// );
|
||||
|
||||
// Registry client is only used if local blocks are present, but logic same for hub/local assistants
|
||||
const getRegistryClient = async () => {
|
||||
const rootPath =
|
||||
|
|
@ -93,9 +77,6 @@ async function loadConfigYaml(options: {
|
|||
? dirname(getCleanUriPath(packageIdentifier.fileUri))
|
||||
: undefined;
|
||||
return new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
|
||||
.CONTROL_PLANE_URL,
|
||||
rootPath,
|
||||
});
|
||||
};
|
||||
|
|
@ -111,8 +92,6 @@ async function loadConfigYaml(options: {
|
|||
localPackageIdentifiers,
|
||||
ide,
|
||||
await getRegistryClient(),
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
);
|
||||
if (unrolledLocal.errors) {
|
||||
errors.push(...unrolledLocal.errors);
|
||||
|
|
@ -129,13 +108,7 @@ async function loadConfigYaml(options: {
|
|||
{
|
||||
renderSecrets: true,
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
platformClient: new LocalPlatformClient(ide),
|
||||
injectBlocks: localPackageIdentifiers,
|
||||
},
|
||||
);
|
||||
|
|
@ -186,7 +159,6 @@ export async function configYamlToContinueConfig(options: {
|
|||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
let { unrolledAssistant, ide, ideInfo, uniqueId, llmLogger } = options;
|
||||
|
||||
|
|
@ -406,23 +378,18 @@ export async function configYamlToContinueConfig(options: {
|
|||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
|
||||
(server) =>
|
||||
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
|
||||
);
|
||||
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
|
||||
ide,
|
||||
true,
|
||||
config.requestOptions,
|
||||
);
|
||||
localErrors.push(...jsonMcpErrors);
|
||||
mcpOptions.push(...mcpServers);
|
||||
mcpManager.setConnections(mcpOptions, false, { ide });
|
||||
}
|
||||
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
|
||||
(server) =>
|
||||
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
|
||||
);
|
||||
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
|
||||
ide,
|
||||
true,
|
||||
config.requestOptions,
|
||||
);
|
||||
localErrors.push(...jsonMcpErrors);
|
||||
mcpOptions.push(...mcpServers);
|
||||
mcpManager.setConnections(mcpOptions, false, { ide });
|
||||
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
|
@ -433,10 +400,7 @@ export async function loadContinueConfigFromYaml(options: {
|
|||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const {
|
||||
|
|
@ -445,17 +409,12 @@ export async function loadContinueConfigFromYaml(options: {
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const configYamlResult = await loadConfigYaml({
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
ide,
|
||||
packageIdentifier,
|
||||
|
|
@ -476,7 +435,6 @@ export async function loadContinueConfigFromYaml(options: {
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
});
|
||||
|
||||
// Apply shared config
|
||||
|
|
|
|||
|
|
@ -1,82 +0,0 @@
|
|||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class ContinueProxyContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "continue-proxy",
|
||||
displayTitle: "Continue Proxy",
|
||||
description: "Retrieve a context item from a Continue for Teams add-on",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
workOsAccessToken: string | undefined = undefined;
|
||||
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title:
|
||||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
ContinueProxyContextProvider.description.description,
|
||||
type: this.options.type || ContinueProxyContextProvider.description.type,
|
||||
};
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const env = await getControlPlaneEnv(args.ide.getIdeSettings());
|
||||
const response = await args.fetch(
|
||||
new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.workOsAccessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
return data.items;
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
|
||||
const response = await extras.fetch(
|
||||
new URL(
|
||||
`/proxy/context/${this.options.id}/retrieve`,
|
||||
env.CONTROL_PLANE_URL,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.workOsAccessToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: query || "",
|
||||
fullInput: extras.fullInput,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const items: any = await response.json();
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
export default ContinueProxyContextProvider;
|
||||
|
|
@ -8,8 +8,6 @@ import {
|
|||
LoadSubmenuItemsArgs,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env";
|
||||
|
||||
class RulesContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "rules",
|
||||
|
|
@ -33,10 +31,7 @@ class RulesContextProvider extends BaseContextProvider {
|
|||
return rule.description ?? rule.name ?? "";
|
||||
}
|
||||
|
||||
private getUriFromRule(
|
||||
rule: RuleWithSource,
|
||||
appUrl: string,
|
||||
): ContextItemUri | undefined {
|
||||
private getUriFromRule(rule: RuleWithSource): ContextItemUri | undefined {
|
||||
if (rule.sourceFile) {
|
||||
return {
|
||||
type: "file",
|
||||
|
|
@ -44,14 +39,6 @@ class RulesContextProvider extends BaseContextProvider {
|
|||
};
|
||||
}
|
||||
|
||||
if (rule.slug) {
|
||||
let url = `${appUrl}${rule.slug}`;
|
||||
return {
|
||||
type: "url",
|
||||
value: url,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
@ -66,13 +53,12 @@ class RulesContextProvider extends BaseContextProvider {
|
|||
return [];
|
||||
}
|
||||
|
||||
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
|
||||
return [
|
||||
{
|
||||
name: this.getNameFromRule(rule),
|
||||
content: rule.rule,
|
||||
description: this.getDescriptionFromRule(rule),
|
||||
uri: this.getUriFromRule(rule, env.APP_URL),
|
||||
uri: this.getUriFromRule(rule),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
FetchFunction,
|
||||
} from "../..";
|
||||
import { getHeaders } from "../../continueServer/stubs/headers";
|
||||
import { TRIAL_PROXY_URL } from "../../control-plane/client";
|
||||
const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
export const fetchSearchResults = async (
|
||||
query: string,
|
||||
|
|
|
|||
|
|
@ -29,11 +29,7 @@ async function getContextProviderExtras(
|
|||
setUpTestDir();
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
const llmLogger = new LLMLogger();
|
||||
const configHandler = new ConfigHandler(
|
||||
ide,
|
||||
llmLogger,
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
const configHandler = new ConfigHandler(ide, llmLogger);
|
||||
await configHandler.isInitialized;
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { ContextProviderName } from "../../";
|
|||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import CodeContextProvider from "./CodeContextProvider";
|
||||
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
|
||||
|
||||
import CurrentFileContextProvider from "./CurrentFileContextProvider";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider";
|
||||
import DebugLocalsProvider from "./DebugLocalsProvider";
|
||||
|
|
@ -63,7 +63,6 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
CodeContextProvider,
|
||||
CurrentFileContextProvider,
|
||||
URLContextProvider,
|
||||
ContinueProxyContextProvider,
|
||||
RepoMapContextProvider,
|
||||
DiscordContextProvider,
|
||||
GreptileContextProvider,
|
||||
|
|
|
|||
|
|
@ -1,51 +0,0 @@
|
|||
export interface HubSessionInfo {
|
||||
AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
|
||||
accessToken: string;
|
||||
account: {
|
||||
label: string;
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OnPremSessionInfo {
|
||||
AUTH_TYPE: AuthType.OnPrem;
|
||||
}
|
||||
|
||||
export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
|
||||
|
||||
export function isOnPremSession(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
): sessionInfo is OnPremSessionInfo {
|
||||
return sessionInfo !== undefined && sessionInfo.AUTH_TYPE === AuthType.OnPrem;
|
||||
}
|
||||
|
||||
export enum AuthType {
|
||||
WorkOsProd = "continue",
|
||||
WorkOsStaging = "continue-staging",
|
||||
OnPrem = "on-prem",
|
||||
}
|
||||
|
||||
export interface HubEnv {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
|
||||
CONTROL_PLANE_URL: string;
|
||||
AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
|
||||
WORKOS_CLIENT_ID: string;
|
||||
APP_URL: string;
|
||||
}
|
||||
|
||||
export interface OnPremEnv {
|
||||
AUTH_TYPE: AuthType.OnPrem;
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
|
||||
CONTROL_PLANE_URL: string;
|
||||
APP_URL: string;
|
||||
}
|
||||
|
||||
export type ControlPlaneEnv = HubEnv | OnPremEnv;
|
||||
|
||||
export function isHubEnv(env: ControlPlaneEnv): env is HubEnv {
|
||||
return (
|
||||
"AUTH_TYPE" in env &&
|
||||
env.AUTH_TYPE !== "on-prem" &&
|
||||
"WORKOS_CLIENT_ID" in env
|
||||
);
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import { PolicyResponse } from "./client.js";
|
||||
|
||||
export class PolicySingleton {
|
||||
private static instance: PolicySingleton;
|
||||
public policy: PolicyResponse | null = null;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): PolicySingleton {
|
||||
if (!PolicySingleton.instance) {
|
||||
PolicySingleton.instance = new PolicySingleton();
|
||||
}
|
||||
return PolicySingleton.instance;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { AnalyticsConfig } from "../..";
|
||||
|
||||
export interface AnalyticsMetadata {
|
||||
extensionVersion: string;
|
||||
}
|
||||
|
||||
export interface ControlPlaneProxyInfo {
|
||||
workspaceId?: string;
|
||||
controlPlaneProxyUrl: string;
|
||||
workOsAccessToken?: string;
|
||||
}
|
||||
|
||||
export interface IAnalyticsProvider {
|
||||
capture(event: string, properties: { [key: string]: any }): Promise<void>;
|
||||
setup(
|
||||
config: AnalyticsConfig,
|
||||
uniqueId: string,
|
||||
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
|
||||
): Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import { IdeSettings } from "../..";
|
||||
import { isHubEnv } from "../AuthTypes";
|
||||
import { getControlPlaneEnv } from "../env";
|
||||
|
||||
export async function getAuthUrlForTokenPage(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
useOnboarding: boolean,
|
||||
): Promise<string> {
|
||||
const env = await getControlPlaneEnv(ideSettingsPromise);
|
||||
|
||||
if (!isHubEnv(env)) {
|
||||
throw new Error("Sign in disabled");
|
||||
}
|
||||
|
||||
const url = new URL("https://api.workos.com/user_management/authorize");
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id: env.WORKOS_CLIENT_ID,
|
||||
redirect_uri: `${env.APP_URL}tokens/${useOnboarding ? "onboarding-" : ""}callback`,
|
||||
// redirect_uri: "http://localhost:3000/tokens/callback",
|
||||
state: uuidv4(),
|
||||
provider: "authkit",
|
||||
};
|
||||
Object.keys(params).forEach((key) =>
|
||||
url.searchParams.append(key, params[key as keyof typeof params]),
|
||||
);
|
||||
return url.toString();
|
||||
}
|
||||
|
|
@ -1,662 +0,0 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
FQSN,
|
||||
FullSlug,
|
||||
Policy,
|
||||
SecretResult,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
|
||||
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
|
||||
import {
|
||||
BaseSessionMetadata,
|
||||
IDE,
|
||||
ModelDescription,
|
||||
Session,
|
||||
} from "../index.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
|
||||
import {
|
||||
ControlPlaneSessionInfo,
|
||||
HubSessionInfo,
|
||||
isOnPremSession,
|
||||
} from "./AuthTypes.js";
|
||||
import { getControlPlaneEnv } from "./env.js";
|
||||
|
||||
export interface PolicyResponse {
|
||||
orgSlug?: string;
|
||||
policy?: Policy;
|
||||
}
|
||||
|
||||
export interface ControlPlaneWorkspace {
|
||||
id: string;
|
||||
name: string;
|
||||
settings: ConfigJson;
|
||||
}
|
||||
|
||||
export interface ControlPlaneModelDescription extends ModelDescription {}
|
||||
|
||||
export interface CreditStatus {
|
||||
optedInToFreeTrial: boolean;
|
||||
hasCredits: boolean;
|
||||
creditBalance: number;
|
||||
hasPurchasedCredits: boolean;
|
||||
}
|
||||
|
||||
export const TRIAL_PROXY_URL =
|
||||
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
export interface RemoteSessionMetadata extends BaseSessionMetadata {
|
||||
isRemote: true;
|
||||
remoteId: string;
|
||||
}
|
||||
|
||||
export interface AgentSessionMetadata {
|
||||
createdBy: string;
|
||||
github_repo: string;
|
||||
organizationId?: string;
|
||||
idempotencyKey?: string;
|
||||
source?: string;
|
||||
continueApiKeyId?: string;
|
||||
s3Url?: string;
|
||||
prompt?: string | null;
|
||||
createdBySlug?: string;
|
||||
}
|
||||
|
||||
export interface AgentSessionView {
|
||||
id: string;
|
||||
devboxId: string | null;
|
||||
name: string | null;
|
||||
icon: string | null;
|
||||
status: string;
|
||||
agentStatus: string | null;
|
||||
unread: boolean;
|
||||
state: string;
|
||||
metadata: AgentSessionMetadata;
|
||||
repoUrl: string;
|
||||
branch: string | null;
|
||||
pullRequestUrl: string | null;
|
||||
pullRequestStatus: string | null;
|
||||
tunnelUrl: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
create_time_ms: string;
|
||||
end_time_ms: string;
|
||||
}
|
||||
|
||||
export class ControlPlaneClient {
|
||||
constructor(
|
||||
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
private readonly ide: IDE,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(
|
||||
fqsns: FQSN[],
|
||||
orgScopeId: string | null,
|
||||
): Promise<(SecretResult | undefined)[]> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return fqsns.map((fqsn) => ({
|
||||
found: false,
|
||||
fqsn,
|
||||
secretLocation: {
|
||||
secretName: fqsn.secretName,
|
||||
secretType: SecretType.NotFound,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
const resp = await this.requestAndHandleError("ide/sync-secrets", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ fqsns, orgScopeId }),
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
}
|
||||
|
||||
async isSignedIn(): Promise<boolean> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
return !!sessionInfo;
|
||||
}
|
||||
|
||||
async getAccessToken(): Promise<string | undefined> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
|
||||
}
|
||||
|
||||
private async request(path: string, init: RequestInit): Promise<Response> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
const onPremSession = isOnPremSession(sessionInfo);
|
||||
const accessToken = await this.getAccessToken();
|
||||
|
||||
// Bearer token not necessary for on-prem auth type
|
||||
if (!accessToken && !onPremSession) {
|
||||
throw new Error("No access token");
|
||||
}
|
||||
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
|
||||
const resp = await fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
...init.headers,
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
...{
|
||||
"x-extension-version": ideInfo.extensionVersion,
|
||||
"x-is-prerelease": String(ideInfo.isPrerelease),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
private async requestAndHandleError(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
): Promise<Response> {
|
||||
const resp = await this.request(path, init);
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(
|
||||
`Control plane request failed: ${resp.status} ${await resp.text()}`,
|
||||
);
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
public async listAssistants(organizationId: string | null): Promise<
|
||||
{
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
rawYaml: string;
|
||||
}[]
|
||||
> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const url = organizationId
|
||||
? `ide/list-assistants?organizationId=${organizationId}`
|
||||
: "ide/list-assistants";
|
||||
|
||||
const resp = await this.requestAndHandleError(url, {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_list_assistants",
|
||||
organizationId,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// We try again here because when users sign up with an email domain that is
|
||||
// captured by an org, we need to wait for the user account creation webhook to
|
||||
// take effect. Otherwise the organization(s) won't show up.
|
||||
// This error manifests as a 404 (user not found)
|
||||
let retries = 0;
|
||||
const maxRetries = 10;
|
||||
const maxWaitTime = 20000; // 20 seconds in milliseconds
|
||||
|
||||
while (retries < maxRetries) {
|
||||
const resp = await this.request("ide/list-organizations", {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
if (resp.status === 404) {
|
||||
retries++;
|
||||
if (retries >= maxRetries) {
|
||||
console.warn(
|
||||
`Failed to list organizations after ${maxRetries} retries: user not found`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
const waitTime = Math.min(
|
||||
Math.pow(2, retries) * 100,
|
||||
maxWaitTime / maxRetries,
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, waitTime));
|
||||
continue;
|
||||
} else if (!resp.ok) {
|
||||
console.warn(
|
||||
`Failed to list organizations (${resp.status}): ${await resp.text()}`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
const { organizations } = (await resp.json()) as any;
|
||||
return organizations;
|
||||
}
|
||||
|
||||
// This should never be reached due to the while condition, but adding for safety
|
||||
console.warn(
|
||||
`Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
public async listAssistantFullSlugs(
|
||||
organizationId: string | null,
|
||||
): Promise<FullSlug[] | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = organizationId
|
||||
? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
|
||||
: "ide/list-assistant-full-slugs";
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError(url, {
|
||||
method: "GET",
|
||||
});
|
||||
const { fullSlugs } = (await resp.json()) as any;
|
||||
return fullSlugs;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_list_assistant_slugs",
|
||||
organizationId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getPolicy(): Promise<PolicyResponse | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request(`ide/policy`, {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as PolicyResponse;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getCreditStatus(): Promise<CreditStatus | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError("ide/credits", {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as CreditStatus;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_credit_status",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
|
||||
* @param vsCodeUriScheme
|
||||
* @returns
|
||||
*/
|
||||
public async getModelsAddOnCheckoutUrl(
|
||||
vsCodeUriScheme?: string,
|
||||
): Promise<{ url: string } | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
// LocalProfileLoader ID
|
||||
profile_id: "local",
|
||||
});
|
||||
|
||||
if (vsCodeUriScheme) {
|
||||
params.set("vscode_uri_scheme", vsCodeUriScheme);
|
||||
}
|
||||
|
||||
const resp = await this.requestAndHandleError(
|
||||
`ide/get-models-add-on-checkout-url?${params.toString()}`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
return (await resp.json()) as { url: string };
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_models_checkout_url",
|
||||
vsCodeUriScheme,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if remote sessions should be enabled based on feature flags
|
||||
*/
|
||||
public async shouldEnableRemoteSessions(): Promise<boolean> {
|
||||
// Check if user is signed in
|
||||
if (!(await this.isSignedIn())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
if (isOnPremSession(sessionInfo) || !sessionInfo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_check_remote_sessions_enabled",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user's session info
|
||||
*/
|
||||
public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> {
|
||||
return await this.sessionInfoPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch remote agents/sessions from the control plane
|
||||
*/
|
||||
public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError("agents/devboxes", {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
const agents = (await resp.json()) as any[];
|
||||
|
||||
return agents.map(
|
||||
(agent: any): RemoteSessionMetadata => ({
|
||||
sessionId: `remote-${agent.id}`,
|
||||
title: agent.name || "Remote Agent",
|
||||
dateCreated: new Date(agent.create_time_ms).toISOString(),
|
||||
workspaceDirectory: "",
|
||||
isRemote: true,
|
||||
remoteId: agent.id,
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
// Log error but don't throw - remote sessions are optional
|
||||
Logger.error(e, {
|
||||
context: "control_plane_list_remote_sessions",
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async loadRemoteSession(remoteId: string): Promise<Session> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
throw new Error("Not signed in to load remote session");
|
||||
}
|
||||
|
||||
try {
|
||||
// First get the tunnel URL for the remote agent
|
||||
const tunnelResp = await this.requestAndHandleError(
|
||||
`agents/devboxes/${remoteId}/tunnel`,
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
const tunnelData = (await tunnelResp.json()) as { url?: string };
|
||||
const tunnelUrl = tunnelData.url;
|
||||
|
||||
if (!tunnelUrl) {
|
||||
throw new Error(`Failed to get tunnel URL for agent ${remoteId}`);
|
||||
}
|
||||
|
||||
// Now fetch the session state from the remote agent's /state endpoint
|
||||
const stateResponse = await fetch(`${tunnelUrl}/state`);
|
||||
if (!stateResponse.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch state from remote agent: ${stateResponse.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const remoteState = (await stateResponse.json()) as { session?: Session };
|
||||
|
||||
// The remote state contains a session property with the full session data
|
||||
if (!remoteState.session) {
|
||||
throw new Error(
|
||||
"Remote agent returned invalid state - no session found",
|
||||
);
|
||||
}
|
||||
|
||||
return remoteState.session;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_load_remote_session",
|
||||
remoteId,
|
||||
});
|
||||
throw new Error(
|
||||
`Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new background agent
|
||||
*/
|
||||
public async createBackgroundAgent(
|
||||
prompt: string,
|
||||
repoUrl: string,
|
||||
name: string,
|
||||
branch?: string,
|
||||
organizationId?: string,
|
||||
contextItems?: any[],
|
||||
selectedCode?: any[],
|
||||
agent?: string,
|
||||
): Promise<{ id: string }> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
throw new Error("Not signed in to Continue");
|
||||
}
|
||||
|
||||
const requestBody: any = {
|
||||
prompt,
|
||||
repoUrl,
|
||||
name,
|
||||
branchName: branch,
|
||||
};
|
||||
|
||||
if (organizationId) {
|
||||
requestBody.organizationId = organizationId;
|
||||
}
|
||||
|
||||
// Include context items if provided
|
||||
if (contextItems && contextItems.length > 0) {
|
||||
requestBody.contextItems = contextItems.map((item) => ({
|
||||
content: item.content,
|
||||
description: item.description,
|
||||
name: item.name,
|
||||
uri: item.uri,
|
||||
}));
|
||||
}
|
||||
|
||||
// Include selected code if provided
|
||||
if (selectedCode && selectedCode.length > 0) {
|
||||
requestBody.selectedCode = selectedCode.map((code) => ({
|
||||
filepath: code.filepath,
|
||||
range: code.range,
|
||||
contents: code.contents,
|
||||
}));
|
||||
}
|
||||
|
||||
// Include agent configuration if provided
|
||||
if (agent) {
|
||||
requestBody.agent = agent;
|
||||
}
|
||||
|
||||
const resp = await this.requestAndHandleError("agents", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
return (await resp.json()) as { id: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* List all background agents for the current user or organization
|
||||
* @param organizationId - Optional organization ID to filter agents by organization scope
|
||||
* @param limit - Optional limit for number of agents to return (default: 5)
|
||||
*/
|
||||
public async listBackgroundAgents(
|
||||
organizationId?: string,
|
||||
limit?: number,
|
||||
): Promise<{
|
||||
agents: Array<{
|
||||
id: string;
|
||||
name: string | null;
|
||||
status: string;
|
||||
repoUrl: string;
|
||||
createdAt: string;
|
||||
metadata?: {
|
||||
github_repo?: string;
|
||||
};
|
||||
}>;
|
||||
totalCount: number;
|
||||
}> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return { agents: [], totalCount: 0 };
|
||||
}
|
||||
|
||||
try {
|
||||
// Build URL with query parameters
|
||||
const params = new URLSearchParams();
|
||||
if (organizationId) {
|
||||
params.set("organizationId", organizationId);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
params.set("limit", limit.toString());
|
||||
}
|
||||
|
||||
const url = `agents${params.toString() ? `?${params.toString()}` : ""}`;
|
||||
|
||||
const resp = await this.requestAndHandleError(url, {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
const result = (await resp.json()) as {
|
||||
agents: AgentSessionView[];
|
||||
totalCount: number;
|
||||
};
|
||||
|
||||
return {
|
||||
agents: result.agents.map((agent) => ({
|
||||
id: agent.id,
|
||||
name: agent.name,
|
||||
status: agent.status,
|
||||
repoUrl: agent.repoUrl,
|
||||
createdAt: agent.createdAt,
|
||||
metadata: {
|
||||
github_repo: agent.metadata.github_repo,
|
||||
},
|
||||
})),
|
||||
totalCount: result.totalCount,
|
||||
};
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_list_background_agents",
|
||||
});
|
||||
return { agents: [], totalCount: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full agent session information
|
||||
* @param agentSessionId - The ID of the agent session
|
||||
* @returns The agent session view including metadata and status
|
||||
*/
|
||||
public async getAgentSession(
|
||||
agentSessionId: string,
|
||||
): Promise<AgentSessionView | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError(
|
||||
`agents/${agentSessionId}`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
|
||||
return (await resp.json()) as AgentSessionView;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_get_agent_session",
|
||||
agentSessionId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the state of a specific background agent
|
||||
* @param agentSessionId - The ID of the agent session
|
||||
* @returns The agent's session state including history, workspace, and branch
|
||||
*/
|
||||
public async getAgentState(agentSessionId: string): Promise<{
|
||||
session: Session;
|
||||
isProcessing: boolean;
|
||||
messageQueueLength: number;
|
||||
pendingPermission: any;
|
||||
} | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError(
|
||||
`agents/${agentSessionId}/state`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
|
||||
const result = (await resp.json()) as {
|
||||
session: Session;
|
||||
isProcessing: boolean;
|
||||
messageQueueLength: number;
|
||||
pendingPermission: any;
|
||||
};
|
||||
return result;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_get_agent_state",
|
||||
agentSessionId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
import * as fs from "node:fs";
|
||||
import { IdeSettings } from "..";
|
||||
import {
|
||||
getLocalEnvironmentDotFilePath,
|
||||
getStagingEnvironmentDotFilePath,
|
||||
} from "../util/paths";
|
||||
import { AuthType, ControlPlaneEnv } from "./AuthTypes";
|
||||
import { getLicenseKeyData } from "./mdm/mdm";
|
||||
|
||||
export const EXTENSION_NAME = "continue";
|
||||
|
||||
const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
|
||||
const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
|
||||
|
||||
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api.continue.dev/",
|
||||
AUTH_TYPE: AuthType.WorkOsProd,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
|
||||
APP_URL: "https://continue.dev/",
|
||||
};
|
||||
|
||||
const STAGING_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
|
||||
CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
|
||||
AUTH_TYPE: AuthType.WorkOsStaging,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "https://hub.continue-stage.tools/",
|
||||
};
|
||||
|
||||
const TEST_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api-test.continue.dev/",
|
||||
AUTH_TYPE: AuthType.WorkOsStaging,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "https://app-test.continue.dev/",
|
||||
};
|
||||
|
||||
const LOCAL_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/",
|
||||
CONTROL_PLANE_URL: "http://localhost:3001/",
|
||||
AUTH_TYPE: AuthType.WorkOsStaging,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "http://localhost:3000/",
|
||||
};
|
||||
|
||||
export async function enableHubContinueDev() {
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function getControlPlaneEnv(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<ControlPlaneEnv> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
|
||||
}
|
||||
|
||||
export function getControlPlaneEnvSync(
|
||||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
): ControlPlaneEnv {
|
||||
// MDM override
|
||||
const licenseKeyData = getLicenseKeyData();
|
||||
if (licenseKeyData?.unsignedData?.apiUrl) {
|
||||
const { apiUrl } = licenseKeyData.unsignedData;
|
||||
return {
|
||||
AUTH_TYPE: AuthType.OnPrem,
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
|
||||
CONTROL_PLANE_URL: apiUrl,
|
||||
APP_URL: "https://continue.dev/",
|
||||
};
|
||||
}
|
||||
|
||||
// Note .local overrides .staging
|
||||
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
|
||||
return LOCAL_ENV;
|
||||
}
|
||||
|
||||
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
|
||||
return STAGING_ENV;
|
||||
}
|
||||
|
||||
const env =
|
||||
ideTestEnvironment === "production"
|
||||
? "hub"
|
||||
: ideTestEnvironment === "staging"
|
||||
? "staging"
|
||||
: ideTestEnvironment === "local"
|
||||
? "local"
|
||||
: process.env.CONTROL_PLANE_ENV;
|
||||
|
||||
return env === "local"
|
||||
? LOCAL_ENV
|
||||
: env === "staging"
|
||||
? STAGING_ENV
|
||||
: env === "test"
|
||||
? TEST_ENV
|
||||
: PRODUCTION_HUB_ENV;
|
||||
}
|
||||
|
||||
export async function useHub(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<boolean> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return ideSettings.continueTestEnvironment !== "none";
|
||||
}
|
||||
|
|
@ -1,370 +0,0 @@
|
|||
import * as crypto from "crypto";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import * as plist from "plist";
|
||||
|
||||
export interface MdmKeys {
|
||||
licenseKey: string;
|
||||
}
|
||||
|
||||
const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
|
||||
93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
|
||||
HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
|
||||
zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
|
||||
U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
|
||||
LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
|
||||
FQIDAQAB
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
interface LicenseKeyUnsignedData {
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
export interface LicenseKey {
|
||||
signature: string;
|
||||
data: string;
|
||||
unsignedData: LicenseKeyUnsignedData;
|
||||
}
|
||||
|
||||
export interface LicenseKeyData {
|
||||
customerId: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export function validateLicenseKey(licenseKey: string): {
|
||||
isValid: boolean;
|
||||
licenseKeyData?: LicenseKey;
|
||||
} {
|
||||
try {
|
||||
// Decode the base64 license key
|
||||
const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
|
||||
const { data, signature, unsignedData } = JSON.parse(decodedString);
|
||||
|
||||
// Verify the signature
|
||||
const verify = crypto.createVerify("SHA256");
|
||||
verify.update(data);
|
||||
verify.end();
|
||||
|
||||
const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
|
||||
|
||||
if (!isValid) return { isValid: false };
|
||||
|
||||
// Check license expiration
|
||||
const licenseData: LicenseKeyData = JSON.parse(data);
|
||||
const expirationDate = new Date(licenseData.expiresAt);
|
||||
const now = new Date();
|
||||
|
||||
const isNotExpired = expirationDate > now;
|
||||
|
||||
if (!isNotExpired) return { isValid: false };
|
||||
|
||||
// Return both validation result and license key data
|
||||
const licenseKeyData: LicenseKey = {
|
||||
signature,
|
||||
data,
|
||||
unsignedData,
|
||||
};
|
||||
|
||||
return { isValid: true, licenseKeyData };
|
||||
} catch (error) {
|
||||
console.error("License validation error:", error);
|
||||
return { isValid: false };
|
||||
}
|
||||
}
|
||||
|
||||
const MACOS_MDM_PATHS = [
|
||||
// Organization-specific MDM plist
|
||||
"/Library/Managed Preferences/dev.continue.app.plist",
|
||||
// User-specific MDM plist
|
||||
path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
|
||||
];
|
||||
|
||||
function readMdmKeysMacOS(): MdmKeys | undefined {
|
||||
try {
|
||||
// MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
|
||||
// The filename is often the bundle identifier of the application
|
||||
|
||||
// Try to find a valid MDM configuration file
|
||||
for (const mdmPath of MACOS_MDM_PATHS) {
|
||||
if (fs.existsSync(mdmPath)) {
|
||||
// Read the file content
|
||||
const fileContent = fs.readFileSync(mdmPath, "utf8");
|
||||
|
||||
try {
|
||||
// Parse the plist file using the plist package
|
||||
const config = plist.parse(fileContent) as
|
||||
| { licenseKey: string | undefined }
|
||||
| undefined;
|
||||
|
||||
if (config && config?.licenseKey) {
|
||||
// Extract the license key from the configuration
|
||||
return { licenseKey: config?.licenseKey };
|
||||
} else {
|
||||
console.error("Invalid MDM configuration format");
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error(`Error parsing MDM configuration: ${parseError}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.error("Error reading macOS MDM keys:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function readMdmKeysWindows(): MdmKeys | undefined {
|
||||
try {
|
||||
// For Windows, we need to read from the registry
|
||||
// Using regedit or another synchronous registry access module
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
// Path to the registry where MDM configuration is stored
|
||||
const regPath = "HKLM\\Software\\Continue\\MDM";
|
||||
const userRegPath = "HKCU\\Software\\Continue\\MDM";
|
||||
|
||||
// Try to read from HKEY_LOCAL_MACHINE first
|
||||
try {
|
||||
// Use REG QUERY command to read registry values
|
||||
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist, fallback to HKEY_CURRENT_USER
|
||||
}
|
||||
|
||||
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
|
||||
try {
|
||||
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist in HKCU either
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.error("Error reading Windows MDM keys:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to extract registry values from reg query output
|
||||
function extractRegValue(output: string): string | undefined {
|
||||
const match = output.match(/REG_SZ\s+(.+)$/m);
|
||||
return match ? match[1].trim() : undefined;
|
||||
}
|
||||
|
||||
// Common locations for MDM configurations in Linux systems
|
||||
const LINUX_MDM_PATHS = [
|
||||
// System-wide configuration
|
||||
"/etc/continue/mdm.json",
|
||||
"/var/lib/continue/mdm.json",
|
||||
// User-specific configuration
|
||||
path.join(os.homedir(), ".config/continue/mdm.json"),
|
||||
];
|
||||
|
||||
function readMdmKeysLinux(): MdmKeys | undefined {
|
||||
try {
|
||||
// Try to find a valid MDM configuration file
|
||||
for (const mdmPath of LINUX_MDM_PATHS) {
|
||||
if (fs.existsSync(mdmPath)) {
|
||||
// Read the file content
|
||||
const fileContent = fs.readFileSync(mdmPath, "utf8");
|
||||
|
||||
try {
|
||||
// Parse the JSON configuration file
|
||||
const config = JSON.parse(fileContent);
|
||||
|
||||
// Check if required key is present
|
||||
if (config.licenseKey) {
|
||||
return {
|
||||
licenseKey: config.licenseKey,
|
||||
};
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error(`Error parsing Linux MDM configuration: ${parseError}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.error("Error reading Linux MDM keys:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function readMdmKeys(): MdmKeys | undefined {
|
||||
const platform = os.platform();
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return readMdmKeysMacOS();
|
||||
|
||||
case "win32":
|
||||
return readMdmKeysWindows();
|
||||
|
||||
case "linux":
|
||||
return readMdmKeysLinux();
|
||||
|
||||
default:
|
||||
console.error(`MDM keys not supported on platform: ${platform}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and validate MDM keys from the operating system's configuration files or registry.
|
||||
*/
|
||||
export function getLicenseKeyData(): LicenseKey | undefined {
|
||||
try {
|
||||
const mdmKeys = readMdmKeys();
|
||||
|
||||
if (mdmKeys) {
|
||||
const { isValid, licenseKeyData } = validateLicenseKey(
|
||||
mdmKeys.licenseKey,
|
||||
);
|
||||
if (!isValid) {
|
||||
console.error("Invalid license key found: ", mdmKeys.licenseKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return licenseKeyData;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (e) {
|
||||
console.warn("Error reading MDM keys: ", e);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysMacOS(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific MDM plist
|
||||
const userMdmPath = path.join(
|
||||
os.homedir(),
|
||||
"Library/Managed Preferences/dev.continue.app.plist",
|
||||
);
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the plist file
|
||||
const plistContent = plist.build(config);
|
||||
fs.writeFileSync(userMdmPath, plistContent, "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing macOS MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysWindows(licenseKey: string): boolean {
|
||||
try {
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
// Use HKEY_CURRENT_USER to avoid needing admin privileges
|
||||
const userRegPath = "HKCU\\Software\\Continue\\MDM";
|
||||
|
||||
// Create the registry key if it doesn't exist
|
||||
try {
|
||||
execSync(`reg add "${userRegPath}" /f`);
|
||||
} catch (error) {
|
||||
// Key might already exist
|
||||
}
|
||||
|
||||
// Set the license key and API URL
|
||||
execSync(
|
||||
`reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Windows MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysLinux(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific configuration
|
||||
const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the JSON configuration file
|
||||
fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Linux MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the license key in the appropriate OS-specific location.
|
||||
* For now, we'll use a default API URL since it's not provided in the command.
|
||||
*/
|
||||
export function setMdmLicenseKey(licenseKey: string): boolean {
|
||||
try {
|
||||
// Validate the license key first
|
||||
const { isValid } = validateLicenseKey(licenseKey);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const platform = os.platform();
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return writeMdmKeysMacOS(licenseKey);
|
||||
|
||||
case "win32":
|
||||
return writeMdmKeysWindows(licenseKey);
|
||||
|
||||
case "linux":
|
||||
return writeMdmKeysLinux(licenseKey);
|
||||
|
||||
default:
|
||||
console.error(
|
||||
`Setting MDM keys not supported on platform: ${platform}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error setting MDM license key:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,211 +0,0 @@
|
|||
import * as crypto from "crypto";
|
||||
import { expect, test } from "vitest";
|
||||
import { LicenseKeyData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
const testKeyPair = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
},
|
||||
});
|
||||
|
||||
// Custom function to create test licenses with the new structure including unsignedData
|
||||
function createTestLicense(
|
||||
licenseData: LicenseKeyData,
|
||||
apiUrl: string = "https://api.continue.dev",
|
||||
useValidSignature: boolean = true,
|
||||
): string {
|
||||
// Convert license data to a string
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
|
||||
// Create a signature with our generated private key
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
|
||||
let signature: string;
|
||||
if (useValidSignature) {
|
||||
signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
} else {
|
||||
// For invalid tests, create an intentionally wrong signature by signing different data
|
||||
const wrongSign = crypto.createSign("SHA256");
|
||||
wrongSign.update(licenseDataStr + "tampered");
|
||||
wrongSign.end();
|
||||
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
|
||||
}
|
||||
|
||||
// Combine data, signature, and unsigned data into a license key
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: {
|
||||
apiUrl: apiUrl,
|
||||
},
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
|
||||
}
|
||||
|
||||
// We need to test the actual implementation - which we can't mock with ESM
|
||||
// Instead, we'll have tests that bypass validation or are expected to fail
|
||||
// depending on what we're testing
|
||||
|
||||
test("validateLicenseKey returns false for malformed license key", () => {
|
||||
// Test with a completely invalid license key
|
||||
const invalidLicenseKey = "not-a-valid-license-key";
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid JSON in license key", () => {
|
||||
// Create a malformed but base64-encoded string
|
||||
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(malformedLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for expired license", () => {
|
||||
// Without mocking, we expect this to fail signature verification
|
||||
// We're testing the date logic by itself
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
|
||||
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
|
||||
};
|
||||
|
||||
// Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
|
||||
const expiredLicenseKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
);
|
||||
|
||||
// Test - expect false, either due to signature or expiration - both are valid test cases
|
||||
const result = validateLicenseKey(expiredLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid signature", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
|
||||
};
|
||||
|
||||
// Create a license with an invalid signature but valid unsignedData structure
|
||||
const invalidSignatureKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
false,
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidSignatureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
|
||||
// Create a base64 string that decodes to valid JSON but lacks required fields
|
||||
const invalidStructureKey = Buffer.from(
|
||||
JSON.stringify({
|
||||
notTheRightField: "wrong structure",
|
||||
}),
|
||||
).toString("base64");
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidStructureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles missing unsignedData gracefully", () => {
|
||||
// Create a license key structure without unsignedData field
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key without unsignedData
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
// Missing unsignedData field
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles invalid unsignedData structure", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key with invalid unsignedData structure
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: "not an object", // Should be an object with apiUrl
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
import { z } from "zod";
|
||||
|
||||
const modelDescriptionSchema = z.object({
|
||||
title: z.string(),
|
||||
provider: z.enum([
|
||||
"openai",
|
||||
"anthropic",
|
||||
"cohere",
|
||||
"ollama",
|
||||
"huggingface-tgi",
|
||||
"huggingface-inference-api",
|
||||
"replicate",
|
||||
"gemini",
|
||||
"mistral",
|
||||
"bedrock",
|
||||
"sagemaker",
|
||||
"cloudflare",
|
||||
"azure",
|
||||
"ovhcloud",
|
||||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx",
|
||||
]),
|
||||
model: z.string(),
|
||||
apiKey: z.string().optional(),
|
||||
apiBase: z.string().optional(),
|
||||
contextLength: z.number().optional(),
|
||||
maxStopWords: z.number().optional(),
|
||||
template: z
|
||||
.enum([
|
||||
"llama2",
|
||||
"alpaca",
|
||||
"zephyr",
|
||||
"phi2",
|
||||
"phind",
|
||||
"anthropic",
|
||||
"chatml",
|
||||
"none",
|
||||
"openchat",
|
||||
"deepseek",
|
||||
"xwin-coder",
|
||||
"neural-chat",
|
||||
"codellama-70b",
|
||||
"llava",
|
||||
"gemma",
|
||||
"llama3",
|
||||
"codestral",
|
||||
])
|
||||
.optional(),
|
||||
completionOptions: z
|
||||
.object({
|
||||
temperature: z.number().optional(),
|
||||
topP: z.number().optional(),
|
||||
topK: z.number().optional(),
|
||||
minP: z.number().optional(),
|
||||
presencePenalty: z.number().optional(),
|
||||
frequencyPenalty: z.number().optional(),
|
||||
mirostat: z.number().optional(),
|
||||
stop: z.array(z.string()).optional(),
|
||||
maxTokens: z.number().optional(),
|
||||
numThreads: z.number().optional(),
|
||||
useMmap: z.boolean().optional(),
|
||||
keepAlive: z.number().optional(),
|
||||
numGpu: z.number().optional(),
|
||||
raw: z.boolean().optional(),
|
||||
stream: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
systemMessage: z.string().optional(),
|
||||
requestOptions: z
|
||||
.object({
|
||||
timeout: z.number().optional(),
|
||||
verifySsl: z.boolean().optional(),
|
||||
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
proxy: z.string().optional(),
|
||||
headers: z.record(z.string()).optional(),
|
||||
extraBodyProperties: z.record(z.any()).optional(),
|
||||
noProxy: z.array(z.string()).optional(),
|
||||
})
|
||||
.optional(),
|
||||
promptTemplates: z.record(z.string()).optional(),
|
||||
});
|
||||
|
||||
const embeddingsProviderSchema = z.object({
|
||||
provider: z.enum([
|
||||
"transformers.js",
|
||||
"ollama",
|
||||
"openai",
|
||||
"cohere",
|
||||
"gemini",
|
||||
"ovhcloud",
|
||||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx",
|
||||
]),
|
||||
apiBase: z.string().optional(),
|
||||
apiKey: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
deployment: z.string().optional(),
|
||||
apiType: z.string().optional(),
|
||||
apiVersion: z.string().optional(),
|
||||
requestOptions: z
|
||||
.object({
|
||||
timeout: z.number().optional(),
|
||||
verifySsl: z.boolean().optional(),
|
||||
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
proxy: z.string().optional(),
|
||||
headers: z.record(z.string()).optional(),
|
||||
extraBodyProperties: z.record(z.any()).optional(),
|
||||
noProxy: z.array(z.string()).optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const rerankerSchema = z.object({
|
||||
name: z.enum(["cohere", "voyage", "llm", "watsonx"]),
|
||||
params: z.record(z.any()).optional(),
|
||||
});
|
||||
|
||||
const analyticsSchema = z.object({
|
||||
url: z.string().optional(),
|
||||
clientKey: z.string().optional(),
|
||||
});
|
||||
|
||||
export type ControlPlaneAnalytics = z.infer<typeof analyticsSchema>;
|
||||
|
||||
const devDataSchema = z.object({
|
||||
url: z.string().optional(),
|
||||
});
|
||||
|
||||
export const controlPlaneSettingsSchema = z.object({
|
||||
models: z.array(modelDescriptionSchema),
|
||||
tabAutocompleteModel: modelDescriptionSchema,
|
||||
embeddingsModel: embeddingsProviderSchema,
|
||||
reranker: rerankerSchema,
|
||||
analytics: analyticsSchema,
|
||||
devData: devDataSchema,
|
||||
});
|
||||
|
||||
export type ControlPlaneSettings = z.infer<typeof controlPlaneSettingsSchema>;
|
||||
88
core/core.ts
88
core/core.ts
|
|
@ -9,8 +9,6 @@ import {
|
|||
} from "./autocomplete/util/openedFilesLruCache";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import { DevDataSqliteDb } from "./data/devdataSqlite";
|
||||
import { DataLogger } from "./data/log";
|
||||
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
||||
|
|
@ -69,7 +67,6 @@ import {
|
|||
} from "./config/workspace/workspaceBlocks";
|
||||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
import { myersDiff } from "./diff/myers";
|
||||
import { ApplyAbortManager } from "./edit/applyAbortManager";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
|
|
@ -137,19 +134,7 @@ export class Core {
|
|||
|
||||
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
|
||||
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
|
||||
const initialSessionInfoPromise = messenger.request(
|
||||
"getControlPlaneSessionInfo",
|
||||
{
|
||||
silent: true,
|
||||
useOnboarding: false,
|
||||
},
|
||||
);
|
||||
|
||||
this.configHandler = new ConfigHandler(
|
||||
this.ide,
|
||||
this.llmLogger,
|
||||
initialSessionInfoPromise,
|
||||
);
|
||||
this.configHandler = new ConfigHandler(this.ide, this.llmLogger);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
this.configHandler,
|
||||
|
|
@ -318,26 +303,9 @@ export class Core {
|
|||
|
||||
// History
|
||||
on("history/list", async (msg) => {
|
||||
const localSessions = historyManager.list(msg.data);
|
||||
|
||||
// Check if remote sessions should be enabled based on feature flags
|
||||
const shouldFetchRemote =
|
||||
await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
|
||||
|
||||
// Get remote sessions from control plane if feature is enabled
|
||||
const remoteSessions = shouldFetchRemote
|
||||
? await this.configHandler.controlPlaneClient.listRemoteSessions()
|
||||
: [];
|
||||
|
||||
// Combine and sort by date (most recent first)
|
||||
const allSessions = [...localSessions, ...remoteSessions].sort(
|
||||
(a, b) =>
|
||||
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
|
||||
);
|
||||
|
||||
// Apply limit if specified
|
||||
const sessions = historyManager.list(msg.data);
|
||||
const limit = msg.data?.limit ?? 100;
|
||||
return allSessions.slice(0, limit);
|
||||
return sessions.slice(0, limit);
|
||||
});
|
||||
|
||||
on("history/delete", (msg) => {
|
||||
|
|
@ -348,12 +316,6 @@ export class Core {
|
|||
return historyManager.load(msg.data.id);
|
||||
});
|
||||
|
||||
on("history/loadRemote", async (msg) => {
|
||||
return this.configHandler.controlPlaneClient.loadRemoteSession(
|
||||
msg.data.remoteId,
|
||||
);
|
||||
});
|
||||
|
||||
on("history/save", (msg) => {
|
||||
historyManager.save(msg.data);
|
||||
});
|
||||
|
|
@ -492,28 +454,6 @@ export class Core {
|
|||
return newSelectedModels;
|
||||
});
|
||||
|
||||
on("controlPlane/openUrl", async (msg) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
const urlPath = msg.data.path.startsWith("/")
|
||||
? msg.data.path.slice(1)
|
||||
: msg.data.path;
|
||||
let url;
|
||||
if (msg.data.orgSlug) {
|
||||
url = `${env.APP_URL}organizations/${msg.data.orgSlug}/${urlPath}`;
|
||||
} else {
|
||||
url = `${env.APP_URL}${urlPath}`;
|
||||
}
|
||||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/getEnvironment", async (msg) => {
|
||||
return await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
});
|
||||
|
||||
on("controlPlane/getCreditStatus", async (msg) => {
|
||||
return this.configHandler.controlPlaneClient.getCreditStatus();
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
|
|
@ -1099,21 +1039,8 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
this.messenger.send("sessionUpdate", {
|
||||
sessionInfo: msg.data.sessionInfo,
|
||||
});
|
||||
await this.configHandler.updateControlPlaneSessionInfo(
|
||||
msg.data.sessionInfo,
|
||||
);
|
||||
});
|
||||
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage(
|
||||
ideSettingsPromise,
|
||||
msg.data.useOnboarding,
|
||||
);
|
||||
return { url };
|
||||
on("auth/getAuthUrl", async (_msg) => {
|
||||
return { url: "" };
|
||||
});
|
||||
|
||||
on("tools/call", async ({ data: { toolCall } }) =>
|
||||
|
|
@ -1204,11 +1131,6 @@ export class Core {
|
|||
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
|
||||
await killTerminalProcess(toolCallId);
|
||||
});
|
||||
|
||||
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
|
||||
const isValid = setMdmLicenseKey(licenseKey);
|
||||
return isValid;
|
||||
});
|
||||
}
|
||||
|
||||
private async handleToolCall(toolCall: ToolCall) {
|
||||
|
|
|
|||
|
|
@ -189,13 +189,8 @@ export class DataLogger {
|
|||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
// If an API key is provided, use it, otherwise use the Continue access token
|
||||
if (dataConfig.apiKey) {
|
||||
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
|
||||
} else {
|
||||
const accessToken =
|
||||
await this.core?.configHandler.controlPlaneClient.getAccessToken();
|
||||
headers["Authorization"] = `Bearer ${accessToken}`;
|
||||
}
|
||||
|
||||
const profileId =
|
||||
|
|
|
|||
|
|
@ -87,9 +87,6 @@ describe("DataLogger", () => {
|
|||
id: "test-profile-id",
|
||||
},
|
||||
},
|
||||
controlPlaneClient: {
|
||||
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
|
||||
},
|
||||
},
|
||||
} as unknown as Core;
|
||||
|
||||
|
|
|
|||
5
core/index.d.ts
vendored
5
core/index.d.ts
vendored
|
|
@ -667,7 +667,6 @@ export interface LLMOptions {
|
|||
apiKeyLocation?: string;
|
||||
envSecretLocations?: Record<string, string>;
|
||||
apiBase?: string;
|
||||
orgScopeId?: string | null;
|
||||
|
||||
onPremProxyUrl?: string | null;
|
||||
|
||||
|
|
@ -1028,7 +1027,6 @@ export type ContextProviderName =
|
|||
| "currentFile"
|
||||
| "greptile"
|
||||
| "outline"
|
||||
| "continue-proxy"
|
||||
| "highlights"
|
||||
| "file"
|
||||
| "issue"
|
||||
|
|
@ -1187,7 +1185,6 @@ interface ToolChoice {
|
|||
export interface ConfigDependentToolParams {
|
||||
rules: RuleWithSource[];
|
||||
enableExperimentalTools: boolean;
|
||||
isSignedIn: boolean;
|
||||
isRemote: boolean;
|
||||
modelName: string | undefined;
|
||||
ide: IDE;
|
||||
|
|
@ -1235,7 +1232,6 @@ export interface ModelDescription {
|
|||
apiBase?: string;
|
||||
apiKeyLocation?: string;
|
||||
envSecretLocations?: Record<string, string>;
|
||||
orgScopeId?: string | null;
|
||||
|
||||
onPremProxyUrl?: string | null;
|
||||
|
||||
|
|
@ -1861,7 +1857,6 @@ export interface BrowserSerializedContinueConfig {
|
|||
tools: Omit<Tool, "preprocessArgs", "evaluateToolCallPolicy">[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules: RuleWithSource[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
selectedModelByRole: Record<ModelRole, ModelDescription | null>;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { URL } from "node:url";
|
||||
|
||||
import { getHeaders } from "../../../continueServer/stubs/headers";
|
||||
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
|
||||
const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export class DefaultCrawler {
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
|||
"bedrock",
|
||||
"cohere",
|
||||
"sagemaker",
|
||||
"continue-proxy",
|
||||
"mistral",
|
||||
"mimo",
|
||||
"sambanova",
|
||||
|
|
@ -119,7 +118,6 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
|
|||
"anthropic",
|
||||
"bedrock",
|
||||
"sagemaker",
|
||||
"continue-proxy",
|
||||
"openrouter",
|
||||
"venice",
|
||||
"sambanova",
|
||||
|
|
|
|||
|
|
@ -99,10 +99,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
return (this.constructor as typeof BaseLLM).providerName;
|
||||
}
|
||||
|
||||
/**
|
||||
* This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server
|
||||
* For example, the underlying provider should always be sent with dev data
|
||||
*/
|
||||
get underlyingProviderName(): string {
|
||||
return this.providerName;
|
||||
}
|
||||
|
|
@ -168,8 +164,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
apiKeyLocation?: string;
|
||||
envSecretLocations?: Record<string, string>;
|
||||
apiBase?: string;
|
||||
orgScopeId?: string | null;
|
||||
|
||||
onPremProxyUrl?: string | null;
|
||||
|
||||
cacheBehavior?: CacheBehavior;
|
||||
|
|
@ -222,11 +216,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
this.model = options.model;
|
||||
// Use @continuedev/llm-info package to autodetect certain parameters
|
||||
const modelSearchString =
|
||||
this.providerName === "continue-proxy"
|
||||
? this.model?.split("/").pop() || this.model
|
||||
: this.model;
|
||||
const llmInfo = findLlmInfo(modelSearchString, this.underlyingProviderName);
|
||||
const llmInfo = findLlmInfo(this.model, this.underlyingProviderName);
|
||||
|
||||
const templateType =
|
||||
options.template ?? autodetectTemplateType(options.model);
|
||||
|
|
@ -272,7 +262,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
// continueProperties
|
||||
this.apiKeyLocation = options.apiKeyLocation;
|
||||
this.envSecretLocations = options.envSecretLocations;
|
||||
this.orgScopeId = options.orgScopeId;
|
||||
this.apiBase = options.apiBase;
|
||||
|
||||
this.onPremProxyUrl = options.onPremProxyUrl;
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ import SageMaker from "./SageMaker";
|
|||
import SambaNova from "./SambaNova";
|
||||
import Scaleway from "./Scaleway";
|
||||
import SiliconFlow from "./SiliconFlow";
|
||||
import ContinueProxy from "./stubs/ContinueProxy";
|
||||
|
||||
import TARS from "./TARS";
|
||||
import TestLLM from "./Test";
|
||||
import TextGenWebUI from "./TextGenWebUI";
|
||||
|
|
@ -100,7 +100,6 @@ export const LLMClasses = [
|
|||
Groq,
|
||||
Fireworks,
|
||||
NCompass,
|
||||
ContinueProxy,
|
||||
Cloudflare,
|
||||
Deepseek,
|
||||
Docker,
|
||||
|
|
@ -180,16 +179,6 @@ export async function llmFromDescription(
|
|||
uniqueId,
|
||||
};
|
||||
|
||||
if (desc.provider === "continue-proxy") {
|
||||
options.apiKey = ideSettings.userToken;
|
||||
if (ideSettings.remoteConfigServerUrl) {
|
||||
options.apiBase = new URL(
|
||||
"/proxy/v1",
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
).toString();
|
||||
}
|
||||
}
|
||||
|
||||
return new cls(options);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
import {
|
||||
ContinueProperties,
|
||||
decodeSecretLocation,
|
||||
parseProxyModelName,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { IdeInfoService } from "../../../util/IdeInfoService.js";
|
||||
import OpenAI from "../OpenAI.js";
|
||||
|
||||
import type { Chunk, LLMOptions } from "../../../index.js";
|
||||
import { LLMConfigurationStatuses } from "../../constants.js";
|
||||
import { LlmApiRequestType } from "../../openaiTypeConverters.js";
|
||||
|
||||
class ContinueProxy extends OpenAI {
|
||||
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
|
||||
this.apiKey = value.workOsAccessToken;
|
||||
if (!this.onPremProxyUrl) {
|
||||
this.apiBase = new URL(
|
||||
"model-proxy/v1/",
|
||||
value.controlPlaneProxyUrl,
|
||||
).toString();
|
||||
}
|
||||
}
|
||||
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
|
||||
|
||||
// The apiKey and apiBase are set to the values for the proxy,
|
||||
// but we need to keep track of the actual values that the proxy will use
|
||||
// to call whatever LLM API is chosen
|
||||
private actualApiBase?: string;
|
||||
|
||||
// Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
|
||||
private configEnv?: Record<string, any>;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this.configEnv = options.env;
|
||||
// This it set to `undefined` to handle the case where we are proxying requests to Azure. We pass the correct env vars
|
||||
// needed to do this in `extraBodyProperties` below, but if we don't set `apiType` to `undefined`, we end up proxying to
|
||||
// `/openai/deployments/` which is invalid since that URL construction happens on the proxy.
|
||||
this.apiType = undefined;
|
||||
this.actualApiBase = options.apiBase;
|
||||
this.apiKeyLocation = options.apiKeyLocation;
|
||||
this.envSecretLocations = options.envSecretLocations;
|
||||
this.orgScopeId = options.orgScopeId;
|
||||
this.onPremProxyUrl = options.onPremProxyUrl;
|
||||
if (this.onPremProxyUrl) {
|
||||
this.apiBase = new URL("model-proxy/v1/", this.onPremProxyUrl).toString();
|
||||
}
|
||||
}
|
||||
|
||||
static providerName = "continue-proxy";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
|
||||
get underlyingProviderName(): string {
|
||||
const { provider } = parseProxyModelName(this.model);
|
||||
return provider;
|
||||
}
|
||||
|
||||
protected extraBodyProperties(): Record<string, any> {
|
||||
const continueProperties: ContinueProperties = {
|
||||
apiKeyLocation: this.apiKeyLocation,
|
||||
envSecretLocations: this.envSecretLocations,
|
||||
apiBase: this.actualApiBase,
|
||||
orgScopeId: this.orgScopeId ?? null,
|
||||
env: this.configEnv,
|
||||
};
|
||||
return {
|
||||
continueProperties,
|
||||
};
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
if (!this.apiKeyLocation && !this.envSecretLocations) {
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
||||
if (this.apiKeyLocation) {
|
||||
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
|
||||
if (secretLocation.secretType === SecretType.NotFound) {
|
||||
return LLMConfigurationStatuses.MISSING_API_KEY;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.envSecretLocations) {
|
||||
for (const secretLocation of Object.values(this.envSecretLocations)) {
|
||||
const decoded = decodeSecretLocation(secretLocation);
|
||||
if (decoded.secretType === SecretType.NotFound) {
|
||||
return LLMConfigurationStatuses.MISSING_ENV_SECRET;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
||||
protected _getHeaders() {
|
||||
const headers: any = super._getHeaders();
|
||||
headers["x-continue-unique-id"] = IdeInfoService.uniqueId;
|
||||
headers["user-agent"] = this._getUserAgent();
|
||||
return headers;
|
||||
}
|
||||
|
||||
private _getUserAgent(): string {
|
||||
const ideInfo = IdeInfoService.ideInfo;
|
||||
const extensionVersion = ideInfo?.extensionVersion ?? "unknown";
|
||||
const ideName = ideInfo?.name ?? "unknown";
|
||||
const ideType = ideInfo?.ideType ?? "unknown";
|
||||
return `Continue/${extensionVersion} (${ideName}; ${ideType})`;
|
||||
}
|
||||
|
||||
supportsCompletions(): boolean {
|
||||
// This was a hotfix and contains duplicate logic from class-specific completion support methods
|
||||
if (this.underlyingProviderName === "vllm") {
|
||||
return true;
|
||||
}
|
||||
// other providers that don't support completions include groq, mistral, nvidia, deepseek, etc.
|
||||
// For now disabling all except vllm
|
||||
return false;
|
||||
}
|
||||
|
||||
supportsFim(): boolean {
|
||||
const { provider } = parseProxyModelName(this.model);
|
||||
if (provider === "vllm") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const url = new URL("rerank", this.apiBase);
|
||||
const resp = await this.fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"user-agent": this._getUserAgent(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
model: this.model,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
});
|
||||
const data: any = await resp.json();
|
||||
const results = data.data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default ContinueProxy;
|
||||
|
|
@ -1,758 +0,0 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../../index.js";
|
||||
import ContinueProxy from "./ContinueProxy.js";
|
||||
|
||||
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
|
||||
const mod = (await importOriginal()) as any;
|
||||
return {
|
||||
...mod,
|
||||
parseProxyModelName: vi.fn(() => ({
|
||||
provider: "test-provider",
|
||||
model: "test-model",
|
||||
ownerSlug: "test-owner",
|
||||
packageSlug: "test-package",
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("ContinueProxy", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("rerank should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamFim should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["function test() {\n ", "\n}"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "function test() {\n ",
|
||||
suffix: "\n}",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["text to embed", "another text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["text to embed", "another text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("listModels should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different provider configurations", () => {
|
||||
test("should handle on-prem proxy URL", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
onPremProxyUrl: "https://my-proxy.company.com/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: undefined,
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle environment variables", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle API key location", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["test text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["test text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle env secret locations", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["const x = ", ";"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "const x = ",
|
||||
suffix: ";",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle organization scope ID", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: "org_12345",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
test("should handle empty chunks array for rerank", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: ["test query", []],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: [],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle complex chat messages", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
const complexMessages = [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
{ role: "assistant", content: "Hi there! How can I help you today?" },
|
||||
{ role: "user", content: "What's the weather like?" },
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [complexMessages],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: complexMessages,
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle single embedding chunk", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["single text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["single text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -4,35 +4,10 @@ import Deepseek from "../Deepseek.js";
|
|||
import FunctionNetwork from "../FunctionNetwork.js";
|
||||
import Mistral from "../Mistral.js";
|
||||
import OpenAI from "../OpenAI.js";
|
||||
import ContinueProxy from "../stubs/ContinueProxy.js";
|
||||
import Vllm from "../Vllm.js";
|
||||
|
||||
// Mock the parseProxyModelName function
|
||||
const mockParseProxyModelName = jest.fn();
|
||||
jest.mock("@continuedev/config-yaml", () => ({
|
||||
parseProxyModelName: mockParseProxyModelName,
|
||||
decodeSecretLocation: jest.fn(),
|
||||
SecretType: { NotFound: "not-found" },
|
||||
}));
|
||||
|
||||
// Test cases: [LLM class, model, expected supportsFim result, description]
|
||||
const testCases: [any, string, boolean, string][] = [
|
||||
[ContinueProxy, "owner/package/vllm/some-model", false, "vllm provider"],
|
||||
[ContinueProxy, "owner/package/openai/gpt-4", true, "openai provider"],
|
||||
[
|
||||
ContinueProxy,
|
||||
"owner/package/anthropic/claude-3",
|
||||
true,
|
||||
"anthropic provider",
|
||||
],
|
||||
[ContinueProxy, "owner/package/cohere/command-r", true, "cohere provider"],
|
||||
[
|
||||
ContinueProxy,
|
||||
"owner/package/unknown-provider/some-model",
|
||||
true,
|
||||
"unknown provider",
|
||||
],
|
||||
[ContinueProxy, "owner/package/groq/llama-model", true, "groq provider"],
|
||||
[Vllm, "any-model", false, "Vllm"],
|
||||
[Anthropic, "claude-3-5-sonnet-latest", false, "Anthropic"],
|
||||
[FunctionNetwork, "any-model", false, "FunctionNetwork"],
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { ChatMessage, IDE, PromptLog } from "..";
|
||||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { usesCreditsBasedApiKey } from "../config/usesFreeTrialApiKey";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import { IMessenger, Message } from "../protocol/messenger";
|
||||
|
||||
import { TTS } from "../util/tts";
|
||||
import { isOutOfStarterCredits } from "./utils/starterCredits";
|
||||
|
||||
export async function* llmStreamChat(
|
||||
configHandler: ConfigHandler,
|
||||
|
|
@ -136,8 +134,6 @@ export async function* llmStreamChat(
|
|||
void TTS.read(next.value?.completion);
|
||||
}
|
||||
|
||||
void checkForOutOfStarterCredits(configHandler, messenger);
|
||||
|
||||
if (!next.done) {
|
||||
throw new Error("Will never happen");
|
||||
}
|
||||
|
|
@ -149,24 +145,3 @@ export async function* llmStreamChat(
|
|||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkForOutOfStarterCredits(
|
||||
configHandler: ConfigHandler,
|
||||
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
) {
|
||||
try {
|
||||
const { config } = await configHandler.getSerializedConfig();
|
||||
const creditStatus =
|
||||
await configHandler.controlPlaneClient.getCreditStatus();
|
||||
|
||||
if (
|
||||
config &&
|
||||
creditStatus &&
|
||||
isOutOfStarterCredits(usesCreditsBasedApiKey(config), creditStatus)
|
||||
) {
|
||||
void messenger.request("freeTrialExceeded", undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error checking free trial status:", error);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,70 +2,6 @@
|
|||
import { PROVIDER_TOOL_SUPPORT, isRecommendedAgentModel } from "./toolSupport";
|
||||
|
||||
describe("PROVIDER_TOOL_SUPPORT", () => {
|
||||
describe("continue-proxy", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"];
|
||||
|
||||
it("should return true for Claude 3.5 models", () => {
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/anthropic/claude-3-5-sonnet"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/anthropic/claude-3.5-sonnet"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for Claude 3.7 models", () => {
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/anthropic/claude-3-7-haiku"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/anthropic/claude-3.7-sonnet"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for GPT-4 models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gpt-4-turbo")).toBe(true);
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/openai/gpt-4-1106-preview"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for Gemma models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gemma")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gemma3")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for O3 models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for Gemini models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return false for unsupported models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gpt-3.5-turbo")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(supportsFn("ownerSlug/packageSlug/anthropic/claude-2")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(supportsFn("ownerSlug/packageSlug/together/llama-3")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle case insensitivity", () => {
|
||||
expect(
|
||||
supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
|
||||
).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma3")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("anthropic", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["anthropic"];
|
||||
|
||||
|
|
@ -395,7 +331,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
|
||||
describe("edge cases", () => {
|
||||
it("should handle empty model names", () => {
|
||||
expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
|
||||
|
|
|
|||
|
|
@ -1,23 +1,7 @@
|
|||
import { parseProxyModelName } from "@continuedev/config-yaml";
|
||||
import { ModelDescription } from "..";
|
||||
|
||||
export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
||||
{
|
||||
"continue-proxy": (model) => {
|
||||
try {
|
||||
const { provider, model: _model } = parseProxyModelName(model);
|
||||
if (provider && _model && provider !== "continue-proxy") {
|
||||
const fn = PROVIDER_TOOL_SUPPORT[provider];
|
||||
if (fn) {
|
||||
return fn(_model);
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
return ["claude", "gpt-4", "o3", "gemini", "gemma"].some((part) =>
|
||||
model.toLowerCase().startsWith(part),
|
||||
);
|
||||
},
|
||||
anthropic: (model) => {
|
||||
if (model.includes("claude-2") || model.includes("claude-instant")) {
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import { CreditStatus } from "../../control-plane/client";
|
||||
|
||||
export function isOutOfStarterCredits(
|
||||
usingModelsAddOnApiKey: boolean,
|
||||
creditStatus: CreditStatus,
|
||||
): boolean {
|
||||
return (
|
||||
usingModelsAddOnApiKey &&
|
||||
!creditStatus.hasCredits &&
|
||||
!creditStatus.hasPurchasedCredits
|
||||
);
|
||||
}
|
||||
|
|
@ -45,11 +45,6 @@ import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
|
|||
import { GetLspDefinitionsFunction } from "../autocomplete/types";
|
||||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
import {
|
||||
ControlPlaneEnv,
|
||||
ControlPlaneSessionInfo,
|
||||
} from "../control-plane/AuthTypes";
|
||||
import { CreditStatus, RemoteSessionMetadata } from "../control-plane/client";
|
||||
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
|
||||
import { NextEditOutcome } from "../nextEdit/types";
|
||||
import { ContinueErrorReason } from "../util/errors";
|
||||
|
|
@ -72,13 +67,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
cancelApply: [undefined, void];
|
||||
|
||||
// History
|
||||
"history/list": [
|
||||
ListHistoryOptions,
|
||||
(BaseSessionMetadata | RemoteSessionMetadata)[],
|
||||
];
|
||||
"history/list": [ListHistoryOptions, BaseSessionMetadata[]];
|
||||
"history/delete": [{ id: string }, void];
|
||||
"history/load": [{ id: string }, Session];
|
||||
"history/loadRemote": [{ remoteId: string }, Session];
|
||||
"history/save": [Session, void];
|
||||
"history/share": [{ id: string; outputDir?: string }, void];
|
||||
"history/clear": [undefined, void];
|
||||
|
|
@ -338,14 +329,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
|
||||
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
|
||||
"controlPlane/getCreditStatus": [undefined, CreditStatus | null];
|
||||
isItemTooBig: [{ item: ContextItemWithId }, boolean];
|
||||
didChangeControlPlaneSessionInfo: [
|
||||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
"process/markAsBackgrounded": [{ toolCallId: string }, void];
|
||||
"process/isBackgrounded": [{ toolCallId: string }, boolean];
|
||||
"process/killTerminalProcess": [{ toolCallId: string }, void];
|
||||
|
|
|
|||
|
|
@ -14,8 +14,6 @@ import type {
|
|||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
|
||||
|
||||
export interface GetGhTokenArgs {
|
||||
force?: boolean;
|
||||
}
|
||||
|
|
@ -88,11 +86,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
getReferences: [{ location: Location }, RangeInFile[]];
|
||||
getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]];
|
||||
|
||||
getControlPlaneSessionInfo: [
|
||||
{ silent: boolean; useOnboarding: boolean },
|
||||
ControlPlaneSessionInfo | undefined,
|
||||
];
|
||||
logoutOfControlPlane: [undefined, void];
|
||||
reportError: [any, void];
|
||||
closeSidebar: [undefined, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,10 +6,8 @@ import {
|
|||
AddToChatPayload,
|
||||
ApplyState,
|
||||
ApplyToFilePayload,
|
||||
ContextItemWithId,
|
||||
HighlightedCodePayload,
|
||||
MessageContent,
|
||||
RangeInFile,
|
||||
RangeInFileWithContents,
|
||||
SetCodeToEditPayload,
|
||||
ShowFilePayload,
|
||||
|
|
@ -52,38 +50,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
"edit/addCurrentSelection": [undefined, void];
|
||||
"edit/clearDecorations": [undefined, void];
|
||||
"session/share": [{ sessionId: string }, void];
|
||||
createBackgroundAgent: [
|
||||
{
|
||||
content: MessageContent;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
organizationId?: string;
|
||||
agent?: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
listBackgroundAgents: [
|
||||
{ organizationId?: string; limit?: number },
|
||||
{
|
||||
agents: Array<{
|
||||
id: string;
|
||||
name: string | null;
|
||||
status: string;
|
||||
repoUrl: string;
|
||||
createdAt: string;
|
||||
metadata?: {
|
||||
github_repo?: string;
|
||||
};
|
||||
}>;
|
||||
totalCount: number;
|
||||
},
|
||||
];
|
||||
openAgentLocally: [
|
||||
{
|
||||
agentSessionId: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
};
|
||||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
|
|
@ -100,7 +66,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
|
||||
focusContinueSessionId: [{ sessionId: string | undefined }, void];
|
||||
newSession: [undefined, void];
|
||||
loadAgentSession: [{ session: any }, void];
|
||||
setTheme: [{ theme: any }, void];
|
||||
setColors: [{ [key: string]: string }, void];
|
||||
"jetbrains/editorInsetRefresh": [undefined, void];
|
||||
|
|
|
|||
|
|
@ -109,11 +109,6 @@ export class ReverseMessageIde {
|
|||
return this.ide.showLines(data.filepath, data.startLine, data.endLine);
|
||||
});
|
||||
|
||||
this.on("getControlPlaneSessionInfo", async (msg) => {
|
||||
// Not supported in testing
|
||||
return undefined;
|
||||
});
|
||||
|
||||
this.on("writeFile", (data) => {
|
||||
return this.ide.writeFile(data.path, data.contents);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"history/list",
|
||||
"history/delete",
|
||||
"history/load",
|
||||
"history/loadRemote",
|
||||
"history/save",
|
||||
"history/clear",
|
||||
"devdata/log",
|
||||
|
|
@ -84,9 +83,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"tools/preprocessArgs",
|
||||
"controlPlane/getEnvironment",
|
||||
"controlPlane/getCreditStatus",
|
||||
"controlPlane/openUrl",
|
||||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
|
|
@ -41,7 +40,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
getWebviewHistoryLength: [undefined, number];
|
||||
getCurrentSessionId: [undefined, string];
|
||||
"jetbrains/setColors": [Record<string, string | null | undefined>, void];
|
||||
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
|
||||
sessionUpdate: [{ sessionInfo: any | undefined }, void];
|
||||
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
|
||||
freeTrialExceeded: [undefined, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { ControlPlaneClient } from "../control-plane/client";
|
||||
import Mock from "../llm/llms/Mock";
|
||||
import { LLMLogger } from "../llm/logger";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
|
|
@ -10,16 +9,7 @@ export const testIde = new FileSystemIde(TEST_DIR);
|
|||
|
||||
export const ideSettingsPromise = testIde.getIdeSettings();
|
||||
|
||||
export const testControlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(undefined),
|
||||
testIde,
|
||||
);
|
||||
|
||||
export const testConfigHandler = new ConfigHandler(
|
||||
testIde,
|
||||
new LLMLogger(),
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
export const testConfigHandler = new ConfigHandler(testIde, new LLMLogger());
|
||||
|
||||
export const testLLM = new Mock({
|
||||
model: "mock-model",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ describe("Tool Definitions", () => {
|
|||
const mockParams: ConfigDependentToolParams = {
|
||||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: false,
|
||||
isRemote: false,
|
||||
modelName: "a model",
|
||||
ide: {} as any,
|
||||
|
|
|
|||
|
|
@ -18,16 +18,13 @@ export const getBaseToolDefinitions = () => [
|
|||
export const getConfigDependentToolDefinitions = async (
|
||||
params: ConfigDependentToolParams,
|
||||
): Promise<Tool[]> => {
|
||||
const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params;
|
||||
const { modelName, enableExperimentalTools, isRemote } = params;
|
||||
const tools: Tool[] = [];
|
||||
|
||||
tools.push(await toolDefinitions.requestRuleTool(params));
|
||||
tools.push(await toolDefinitions.readSkillTool(params));
|
||||
|
||||
if (isSignedIn) {
|
||||
// Web search is only available for signed-in users
|
||||
tools.push(toolDefinitions.searchWebTool);
|
||||
}
|
||||
tools.push(toolDefinitions.searchWebTool);
|
||||
|
||||
if (enableExperimentalTools) {
|
||||
tools.push(
|
||||
|
|
|
|||
|
|
@ -2,35 +2,18 @@ import { expect, test } from "vitest";
|
|||
import { BuiltInToolNames } from "./builtIn";
|
||||
import { getConfigDependentToolDefinitions } from "./index";
|
||||
|
||||
test("searchWeb tool is only available when user is signed in", async () => {
|
||||
// Test with signed-in user
|
||||
const signedInTools = await getConfigDependentToolDefinitions({
|
||||
test("searchWeb tool is always available", async () => {
|
||||
const tools = await getConfigDependentToolDefinitions({
|
||||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: true,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
ide: {} as any,
|
||||
});
|
||||
|
||||
const searchWebToolSignedIn = signedInTools.find(
|
||||
const searchWebTool = tools.find(
|
||||
(tool) => tool.function.name === BuiltInToolNames.SearchWeb,
|
||||
);
|
||||
expect(searchWebToolSignedIn).toBeDefined();
|
||||
expect(searchWebToolSignedIn?.displayTitle).toBe("Search Web");
|
||||
|
||||
// Test with non-signed-in user
|
||||
const notSignedInTools = await getConfigDependentToolDefinitions({
|
||||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: false,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
ide: {} as any,
|
||||
});
|
||||
|
||||
const searchWebToolNotSignedIn = notSignedInTools.find(
|
||||
(tool) => tool.function.name === BuiltInToolNames.SearchWeb,
|
||||
);
|
||||
expect(searchWebToolNotSignedIn).toBeUndefined();
|
||||
expect(searchWebTool).toBeDefined();
|
||||
expect(searchWebTool?.displayTitle).toBe("Search Web");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
export const EXTENSION_NAME = "continue";
|
||||
|
||||
export const NEW_SESSION_TITLE = "New Session";
|
||||
|
||||
export const GITHUB_LINK =
|
||||
|
|
|
|||
|
|
@ -408,8 +408,6 @@ export async function unrollPackageIdentifiersAsConfigYaml(
|
|||
},
|
||||
"name: Agent\nschema: v1\nversion: 0.0.1",
|
||||
new RegistryClient({
|
||||
accessToken: accessToken ?? undefined,
|
||||
apiBase: env.apiBase,
|
||||
rootPath: undefined, // TODO verify this doesn't cause issues with file blocks
|
||||
}),
|
||||
{
|
||||
|
|
@ -444,8 +442,6 @@ async function unrollAssistantWithConfig(
|
|||
const unrollResult = await unrollAssistant(
|
||||
packageIdentifier,
|
||||
new RegistryClient({
|
||||
accessToken: accessToken ?? undefined,
|
||||
apiBase: env.apiBase,
|
||||
rootPath:
|
||||
packageIdentifier.uriType === "file"
|
||||
? dirname(packageIdentifier.fileUri)
|
||||
|
|
|
|||
|
|
@ -34,8 +34,6 @@ class MessageTypes {
|
|||
"getFileStats",
|
||||
"insertAtCursor",
|
||||
"applyToFile",
|
||||
"getControlPlaneSessionInfo",
|
||||
"logoutOfControlPlane",
|
||||
"showToast",
|
||||
"openUrl",
|
||||
"isWorkspaceRemote",
|
||||
|
|
@ -148,7 +146,6 @@ class MessageTypes {
|
|||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"tools/preprocessArgs",
|
||||
"controlPlane/openUrl",
|
||||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
|
|
|
|||
|
|
@ -14,9 +14,6 @@
|
|||
"model": "this field is not used"
|
||||
}
|
||||
],
|
||||
"analytics": {
|
||||
"provider": "continue-proxy"
|
||||
},
|
||||
"tabAutocompleteModel": {
|
||||
"title": "TEST LLM",
|
||||
"provider": "test",
|
||||
|
|
|
|||
|
|
@ -2854,7 +2854,6 @@
|
|||
"ollama",
|
||||
"openai",
|
||||
"cohere",
|
||||
"continue-proxy",
|
||||
"gemini",
|
||||
"voyage",
|
||||
"nvidia",
|
||||
|
|
|
|||
|
|
@ -69,9 +69,6 @@
|
|||
}
|
||||
],
|
||||
"systemMessage": "TEST_SYS_MSG",
|
||||
"analytics": {
|
||||
"provider": "continue-proxy"
|
||||
},
|
||||
"tabAutocompleteModel": {
|
||||
"title": "TEST LLM",
|
||||
"provider": "test",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { LLMInteractionItem } from "core";
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import { LLMLogger } from "core/llm/logger";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import * as child_process from "node:child_process";
|
|||
import { exec } from "node:child_process";
|
||||
|
||||
import { Range } from "core";
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import { DEFAULT_IGNORES, defaultIgnoresGlob } from "core/indexing/ignore";
|
||||
import * as URI from "uri-js";
|
||||
import * as vscode from "vscode";
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
// @ts-ignore
|
||||
import svgBuilder from "svg-builder";
|
||||
import * as vscode from "vscode";
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
// @ts-ignore
|
||||
import * as vscode from "vscode";
|
||||
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ vi.mock("vscode", () => ({
|
|||
},
|
||||
}));
|
||||
|
||||
vi.mock("core/control-plane/env", () => ({
|
||||
vi.mock("core/util/constants", () => ({
|
||||
EXTENSION_NAME: "continue",
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ILLM } from "core";
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { Battery } from "../util/battery";
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import * as fs from "node:fs";
|
|||
import { ContextMenuConfig, ILLM, ModelInstaller } from "core";
|
||||
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import { Core } from "core/core";
|
||||
import { walkDirAsync } from "core/indexing/walkDir";
|
||||
import { isModelInstaller } from "core/llm";
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import path from "path";
|
|||
|
||||
import { IContextProvider } from "core";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import { Core } from "core/core";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
|
||||
import { InProcessMessenger } from "core/protocol/messenger";
|
||||
|
|
@ -30,12 +30,7 @@ import { registerAllCodeLensProviders } from "../lang-server/codeLens";
|
|||
import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions";
|
||||
import EditDecorationManager from "../quickEdit/EditDecorationManager";
|
||||
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
|
||||
import { setupRemoteConfigSync } from "../stubs/activation";
|
||||
import { UriEventHandler } from "../stubs/uriHandler";
|
||||
import {
|
||||
getControlPlaneSessionInfo,
|
||||
WorkOsAuthProvider,
|
||||
} from "../stubs/WorkOsAuthProvider";
|
||||
import { Battery } from "../util/battery";
|
||||
import { FileSearch } from "../util/FileSearch";
|
||||
import { VsCodeIdeUtils } from "../util/ideUtils";
|
||||
|
|
@ -80,7 +75,6 @@ export class VsCodeExtension {
|
|||
webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
|
||||
private core: Core;
|
||||
private battery: Battery;
|
||||
private workOsAuthProvider: WorkOsAuthProvider;
|
||||
private fileSearch: FileSearch;
|
||||
private uriHandler = new UriEventHandler();
|
||||
private completionProvider: ContinueCompletionProvider;
|
||||
|
|
@ -176,12 +170,6 @@ export class VsCodeExtension {
|
|||
}
|
||||
|
||||
constructor(context: vscode.ExtensionContext) {
|
||||
// Register auth provider
|
||||
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
|
||||
|
||||
void this.workOsAuthProvider.refreshSessions();
|
||||
context.subscriptions.push(this.workOsAuthProvider);
|
||||
|
||||
this.editDecorationManager = new EditDecorationManager(context);
|
||||
|
||||
let resolveWebviewProtocol: any = undefined;
|
||||
|
|
@ -285,7 +273,6 @@ export class VsCodeExtension {
|
|||
this.ide,
|
||||
verticalDiffManagerPromise,
|
||||
configHandlerPromise,
|
||||
this.workOsAuthProvider,
|
||||
this.editDecorationManager,
|
||||
context,
|
||||
this,
|
||||
|
|
@ -304,12 +291,6 @@ export class VsCodeExtension {
|
|||
);
|
||||
resolveVerticalDiffManager?.(this.verticalDiffManager);
|
||||
|
||||
void setupRemoteConfigSync(() =>
|
||||
this.configHandler.reloadConfig.bind(this.configHandler)(
|
||||
"Remote config sync",
|
||||
),
|
||||
);
|
||||
|
||||
void this.configHandler.loadConfig().then(async ({ config }) => {
|
||||
const shouldUseFullFileDiff = await getUsingFullFileDiff();
|
||||
this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff);
|
||||
|
|
@ -560,28 +541,8 @@ export class VsCodeExtension {
|
|||
|
||||
// When GitHub sign-in status changes, reload config
|
||||
vscode.authentication.onDidChangeSessions(async (e) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
if (e.provider.id === env.AUTH_TYPE) {
|
||||
void vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.isSignedInToControlPlane",
|
||||
true,
|
||||
);
|
||||
|
||||
const sessionInfo = await getControlPlaneSessionInfo(true, false);
|
||||
void this.core.invoke("didChangeControlPlaneSessionInfo", {
|
||||
sessionInfo,
|
||||
});
|
||||
} else {
|
||||
void vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.isSignedInToControlPlane",
|
||||
false,
|
||||
);
|
||||
|
||||
if (e.provider.id === "github") {
|
||||
this.configHandler.reloadConfig("Github sign-in status changed");
|
||||
}
|
||||
if (e.provider.id === "github") {
|
||||
this.configHandler.reloadConfig("Github sign-in status changed");
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -15,28 +15,18 @@ import {
|
|||
WEBVIEW_TO_CORE_PASS_THROUGH,
|
||||
} from "core/protocol/passThrough";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { normalizeRepoUrl } from "core/util/repoUrl";
|
||||
import {
|
||||
sanitizeShellArgument,
|
||||
validateGitHubRepoUrl,
|
||||
} from "core/util/sanitization";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { ApplyManager } from "../apply";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
|
||||
import EditDecorationManager from "../quickEdit/EditDecorationManager";
|
||||
import {
|
||||
getControlPlaneSessionInfo,
|
||||
WorkOsAuthProvider,
|
||||
} from "../stubs/WorkOsAuthProvider";
|
||||
import { handleLLMError } from "../util/errorHandling";
|
||||
import { showTutorial } from "../util/tutorial";
|
||||
import { getExtensionUri } from "../util/vscode";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
import { encodeFullSlug } from "../../../../packages/config-yaml/dist";
|
||||
import { VsCodeExtension } from "./VsCodeExtension";
|
||||
|
||||
type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
|
||||
|
|
@ -88,7 +78,6 @@ export class VsCodeMessenger {
|
|||
private readonly ide: VsCodeIde,
|
||||
private readonly verticalDiffManagerPromise: Promise<VerticalDiffManager>,
|
||||
private readonly configHandlerPromise: Promise<ConfigHandler>,
|
||||
private readonly workOsAuthProvider: WorkOsAuthProvider,
|
||||
private readonly editDecorationManager: EditDecorationManager,
|
||||
private readonly context: vscode.ExtensionContext,
|
||||
private readonly vsCodeExtension: VsCodeExtension,
|
||||
|
|
@ -269,388 +258,6 @@ export class VsCodeMessenger {
|
|||
);
|
||||
});
|
||||
|
||||
this.onWebview("createBackgroundAgent", async (msg) => {
|
||||
const configHandler = await configHandlerPromise;
|
||||
const { content, contextItems, selectedCode, organizationId } = msg.data;
|
||||
|
||||
// Convert resolved content to plain text prompt
|
||||
const prompt = stripImages(content);
|
||||
|
||||
if (!prompt || prompt.trim().length === 0) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Please enter a prompt to create a background agent",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get workspace information
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
vscode.window.showErrorMessage(
|
||||
"No workspace folder found. Please open a workspace to create a background agent.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const workspaceDir = workspaceDirs[0];
|
||||
let repoUrl = "";
|
||||
let branch = "";
|
||||
|
||||
try {
|
||||
// Get repo name/URL
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
if (repoName) {
|
||||
// Normalize the URL first to get canonical form
|
||||
const normalized = normalizeRepoUrl(repoName);
|
||||
|
||||
// Validate the normalized URL to prevent injection attacks
|
||||
// This ensures we validate what we'll actually use, not just the input
|
||||
if (!validateGitHubRepoUrl(normalized)) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Invalid repository format. Please ensure you're using a valid GitHub repository.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
repoUrl = normalized;
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
const branchInfo = await this.ide.getBranch(workspaceDir);
|
||||
if (branchInfo) {
|
||||
branch = branchInfo;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error getting repo info:", e);
|
||||
}
|
||||
|
||||
if (!repoUrl) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Unable to determine repository URL. Make sure you're in a git repository.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a name from the prompt (first 50 chars, cleaned up)
|
||||
let name = prompt.substring(0, 50).replace(/\n/g, " ").trim();
|
||||
if (prompt.length > 50) {
|
||||
name += "...";
|
||||
}
|
||||
// Fallback to a generic name if prompt is too short
|
||||
if (name.length < 3) {
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
name = `Agent for ${repoName || "repository"}`;
|
||||
}
|
||||
|
||||
// Get the current agent configuration from the selected profile
|
||||
let agent: string | undefined;
|
||||
try {
|
||||
const currentProfile = configHandler.currentProfile;
|
||||
if (
|
||||
currentProfile &&
|
||||
currentProfile.profileDescription.profileType !== "local"
|
||||
) {
|
||||
// Encode the full slug to pass as the agent parameter
|
||||
agent = encodeFullSlug(currentProfile.profileDescription.fullSlug);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error getting agent configuration from profile:", e);
|
||||
// Continue without agent config - will use default
|
||||
}
|
||||
|
||||
// Create the background agent
|
||||
try {
|
||||
console.log("Creating background agent with:", {
|
||||
name,
|
||||
prompt: prompt.substring(0, 50) + "...",
|
||||
repoUrl,
|
||||
branch,
|
||||
contextItemsCount: contextItems?.length || 0,
|
||||
selectedCodeCount: selectedCode?.length || 0,
|
||||
agent: agent || "default",
|
||||
});
|
||||
|
||||
const result =
|
||||
await configHandler.controlPlaneClient.createBackgroundAgent(
|
||||
prompt,
|
||||
repoUrl,
|
||||
name,
|
||||
branch,
|
||||
organizationId,
|
||||
contextItems,
|
||||
selectedCode,
|
||||
agent,
|
||||
);
|
||||
|
||||
vscode.window.showInformationMessage(
|
||||
`Background agent created successfully! Agent ID: ${result.id}`,
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Failed to create background agent:", e);
|
||||
const errorMessage =
|
||||
e instanceof Error ? e.message : "Unknown error occurred";
|
||||
|
||||
// Check if this is a GitHub authorization error
|
||||
if (
|
||||
errorMessage.includes("GitHub token") ||
|
||||
errorMessage.includes("GitHub App")
|
||||
) {
|
||||
const selection = await vscode.window.showErrorMessage(
|
||||
"Background agents need GitHub access. Please connect your GitHub account to Continue.",
|
||||
"Connect GitHub",
|
||||
"Cancel",
|
||||
);
|
||||
|
||||
if (selection === "Connect GitHub") {
|
||||
await this.inProcessMessenger.externalRequest(
|
||||
"controlPlane/openUrl",
|
||||
{
|
||||
path: "settings/integrations",
|
||||
orgSlug: configHandler.currentOrg?.slug,
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
vscode.window.showErrorMessage(
|
||||
`Failed to create background agent: ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.onWebview("listBackgroundAgents", async (msg) => {
|
||||
const configHandler = await configHandlerPromise;
|
||||
const { organizationId, limit } = msg.data;
|
||||
|
||||
try {
|
||||
const result =
|
||||
await configHandler.controlPlaneClient.listBackgroundAgents(
|
||||
organizationId,
|
||||
limit,
|
||||
);
|
||||
return result;
|
||||
} catch (e) {
|
||||
console.error("Error listing background agents:", e);
|
||||
return { agents: [], totalCount: 0 };
|
||||
}
|
||||
});
|
||||
|
||||
this.onWebview("openAgentLocally", async (msg) => {
|
||||
const configHandler = await configHandlerPromise;
|
||||
const { agentSessionId } = msg.data;
|
||||
|
||||
try {
|
||||
// First, fetch the agent session to get repo URL and branch
|
||||
const agentSession =
|
||||
await configHandler.controlPlaneClient.getAgentSession(
|
||||
agentSessionId,
|
||||
);
|
||||
if (!agentSession) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Failed to load agent session details.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const repoUrl = agentSession.repoUrl;
|
||||
const branch = agentSession.branch;
|
||||
|
||||
if (!repoUrl || !branch) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Agent session is missing repository or branch information.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate the repo URL from API response to prevent injection attacks
|
||||
if (!validateGitHubRepoUrl(repoUrl)) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Invalid repository URL from agent session. Please contact support.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get workspace directories
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
vscode.window.showErrorMessage("No workspace folder is open.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize and validate again to ensure the normalized form is safe
|
||||
const normalizedAgentRepo = normalizeRepoUrl(repoUrl);
|
||||
if (!validateGitHubRepoUrl(normalizedAgentRepo)) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Invalid repository URL after normalization. Please contact support.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the workspace that matches the agent's repo URL
|
||||
let matchingWorkspace: string | null = null;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
if (repoName) {
|
||||
const normalizedRepoName = normalizeRepoUrl(repoName);
|
||||
|
||||
if (normalizedRepoName === normalizedAgentRepo) {
|
||||
matchingWorkspace = workspaceDir;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchingWorkspace) {
|
||||
vscode.window.showErrorMessage(
|
||||
`This agent is for repository ${repoUrl}. Please open that workspace to take over the workflow.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the git repository
|
||||
const repo = await this.ide.getRepo(matchingWorkspace);
|
||||
if (!repo) {
|
||||
vscode.window.showErrorMessage("Could not access git repository.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Ask user what to do with uncommitted changes
|
||||
if (
|
||||
repo.state.workingTreeChanges.length > 0 ||
|
||||
repo.state.indexChanges.length > 0
|
||||
) {
|
||||
const changeCount =
|
||||
repo.state.workingTreeChanges.length +
|
||||
repo.state.indexChanges.length;
|
||||
|
||||
const choice = await vscode.window.showWarningMessage(
|
||||
`You have ${changeCount} uncommitted change(s). What would you like to do?`,
|
||||
"Stash & Continue",
|
||||
"Continue Without Stashing",
|
||||
"Cancel",
|
||||
);
|
||||
|
||||
if (choice === "Cancel" || !choice) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (choice === "Stash & Continue") {
|
||||
try {
|
||||
await vscode.window.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Notification,
|
||||
title: "Stashing local changes...",
|
||||
cancellable: false,
|
||||
},
|
||||
async () => {
|
||||
const workspacePath =
|
||||
vscode.Uri.parse(matchingWorkspace).fsPath;
|
||||
// Sanitize agentSessionId to prevent command injection
|
||||
const stashMessage = `Continue: Stashed before opening agent ${agentSessionId}`;
|
||||
await this.ide.subprocess(
|
||||
`git stash push -m ${sanitizeShellArgument(stashMessage)}`,
|
||||
workspacePath,
|
||||
);
|
||||
},
|
||||
);
|
||||
vscode.window.showInformationMessage(
|
||||
"Local changes have been stashed.",
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Failed to stash changes:", e);
|
||||
const errorMsg = e instanceof Error ? e.message : String(e);
|
||||
vscode.window.showErrorMessage(
|
||||
`Failed to stash changes: ${errorMsg}`,
|
||||
);
|
||||
return; // Stop on stash failure
|
||||
}
|
||||
}
|
||||
// If "Continue Without Stashing" was chosen, just proceed
|
||||
}
|
||||
|
||||
// Check if we're already on the target branch
|
||||
try {
|
||||
const currentBranch = await this.ide.getBranch(matchingWorkspace);
|
||||
console.log(
|
||||
`Current branch: ${currentBranch}, Target branch: ${branch}`,
|
||||
);
|
||||
|
||||
if (currentBranch !== branch) {
|
||||
// Try to switch to the branch using VS Code Git API
|
||||
await vscode.window.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Notification,
|
||||
title: `Switching to branch ${branch}...`,
|
||||
cancellable: false,
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
// Use VS Code Git API for checkout
|
||||
await repo.checkout(branch);
|
||||
} catch (checkoutError: any) {
|
||||
console.log(
|
||||
"Checkout failed, trying to fetch first...",
|
||||
checkoutError,
|
||||
);
|
||||
// If checkout fails, fetch and try again
|
||||
await repo.fetch();
|
||||
await repo.checkout(branch);
|
||||
}
|
||||
},
|
||||
);
|
||||
vscode.window.showInformationMessage(
|
||||
`Switched to branch ${branch}`,
|
||||
);
|
||||
} else {
|
||||
console.log("Already on target branch, skipping checkout");
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error("Failed to switch branch:", e);
|
||||
vscode.window.showErrorMessage(
|
||||
`Failed to switch to branch ${branch}: ${e.message || String(e)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the agent state
|
||||
const agentState =
|
||||
await configHandler.controlPlaneClient.getAgentState(agentSessionId);
|
||||
|
||||
if (!agentState) {
|
||||
vscode.window.showErrorMessage(
|
||||
"Failed to fetch agent state from API. The agent may not exist or you may not have permission.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!agentState.session) {
|
||||
console.error(
|
||||
"Agent state is missing session field. Full response:",
|
||||
agentState,
|
||||
);
|
||||
vscode.window.showErrorMessage(
|
||||
"Agent state returned but missing session data. This may be a backend issue.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// For MVP: Simply load the session by sending to webview
|
||||
// The webview will dispatch the newSession action with the session data
|
||||
this.webviewProtocol.send("loadAgentSession", {
|
||||
session: agentState.session,
|
||||
});
|
||||
|
||||
vscode.window.showInformationMessage(
|
||||
`Successfully loaded agent workflow: ${agentState.session.title || "Untitled"}`,
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Failed to open agent locally:", e);
|
||||
vscode.window.showErrorMessage(
|
||||
`Failed to open agent locally: ${e instanceof Error ? e.message : "Unknown error"}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
|
||||
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
|
||||
this.onWebview(messageType, async (msg) => {
|
||||
|
|
@ -754,23 +361,6 @@ export class VsCodeMessenger {
|
|||
this.onWebviewOrCore("showToast", (msg) => {
|
||||
this.ide.showToast(...msg.data);
|
||||
});
|
||||
this.onWebviewOrCore("getControlPlaneSessionInfo", async (msg) => {
|
||||
return getControlPlaneSessionInfo(
|
||||
msg.data.silent,
|
||||
msg.data.useOnboarding,
|
||||
);
|
||||
});
|
||||
this.onWebviewOrCore("logoutOfControlPlane", async (msg) => {
|
||||
const sessions = await this.workOsAuthProvider.getSessions();
|
||||
await Promise.all(
|
||||
sessions.map((session) => workOsAuthProvider.removeSession(session.id)),
|
||||
);
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.isSignedInToControlPlane",
|
||||
false,
|
||||
);
|
||||
});
|
||||
this.onWebviewOrCore("saveFile", async (msg) => {
|
||||
return await ide.saveFile(msg.data.filepath);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,634 +0,0 @@
|
|||
import crypto from "crypto";
|
||||
import { EventEmitter as NodeEventEmitter } from "node:events";
|
||||
|
||||
import {
|
||||
AuthType,
|
||||
ControlPlaneSessionInfo,
|
||||
HubEnv,
|
||||
isHubEnv,
|
||||
} from "core/control-plane/AuthTypes";
|
||||
import { getControlPlaneEnvSync } from "core/control-plane/env";
|
||||
import { Logger } from "core/util/Logger";
|
||||
import fetch from "node-fetch";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
authentication,
|
||||
AuthenticationProvider,
|
||||
AuthenticationProviderAuthenticationSessionsChangeEvent,
|
||||
AuthenticationSession,
|
||||
Disposable,
|
||||
env,
|
||||
EventEmitter,
|
||||
ExtensionContext,
|
||||
ProgressLocation,
|
||||
Uri,
|
||||
window,
|
||||
} from "vscode";
|
||||
|
||||
import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
|
||||
import { SecretStorage } from "./SecretStorage";
|
||||
import { UriEventHandler } from "./uriHandler";
|
||||
|
||||
const AUTH_NAME = "Continue";
|
||||
|
||||
const controlPlaneEnv = getControlPlaneEnvSync(true ? "production" : "none");
|
||||
|
||||
const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`;
|
||||
|
||||
// Function to generate a random string of specified length
|
||||
function generateRandomString(length: number): string {
|
||||
const possibleCharacters =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
|
||||
let randomString = "";
|
||||
for (let i = 0; i < length; i++) {
|
||||
const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
|
||||
randomString += possibleCharacters[randomIndex];
|
||||
}
|
||||
return randomString;
|
||||
}
|
||||
|
||||
// Function to generate a code challenge from the code verifier
|
||||
|
||||
async function generateCodeChallenge(verifier: string) {
|
||||
// Create a SHA-256 hash of the verifier
|
||||
const hash = crypto.createHash("sha256").update(verifier).digest();
|
||||
|
||||
// Convert the hash to a base64 URL-encoded string
|
||||
const base64String = hash
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
|
||||
return base64String;
|
||||
}
|
||||
|
||||
interface ContinueAuthenticationSession extends AuthenticationSession {
|
||||
refreshToken: string;
|
||||
expiresInMs: number;
|
||||
loginNeeded: boolean;
|
||||
}
|
||||
|
||||
export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
||||
private _sessionChangeEmitter =
|
||||
new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>();
|
||||
private _disposable: Disposable;
|
||||
private _pendingStates: string[] = [];
|
||||
private _codeExchangePromises = new Map<
|
||||
string,
|
||||
{ promise: Promise<string>; cancel: EventEmitter<void> }
|
||||
>();
|
||||
private _refreshInterval: NodeJS.Timeout | null = null;
|
||||
private _isRefreshing = false;
|
||||
|
||||
private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes
|
||||
private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes
|
||||
|
||||
private secretStorage: SecretStorage;
|
||||
|
||||
constructor(
|
||||
private readonly context: ExtensionContext,
|
||||
private readonly _uriHandler: UriEventHandler,
|
||||
) {
|
||||
this._disposable = Disposable.from(
|
||||
authentication.registerAuthenticationProvider(
|
||||
controlPlaneEnv.AUTH_TYPE,
|
||||
AUTH_NAME,
|
||||
this,
|
||||
{ supportsMultipleAccounts: false },
|
||||
),
|
||||
window.registerUriHandler(this._uriHandler),
|
||||
);
|
||||
|
||||
this.secretStorage = new SecretStorage(context);
|
||||
|
||||
// Immediately refresh any existing sessions
|
||||
this.attemptEmitter = new NodeEventEmitter();
|
||||
WorkOsAuthProvider.hasAttemptedRefresh = new Promise((resolve) => {
|
||||
this.attemptEmitter.on("attempted", resolve);
|
||||
});
|
||||
void this.refreshSessions();
|
||||
|
||||
// Set up a regular interval to refresh tokens
|
||||
this._refreshInterval = setInterval(() => {
|
||||
void this.refreshSessions();
|
||||
}, WorkOsAuthProvider.REFRESH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private decodeJwt(jwt: string): Record<string, any> | null {
|
||||
try {
|
||||
const decodedToken = JSON.parse(
|
||||
Buffer.from(jwt.split(".")[1], "base64").toString(),
|
||||
);
|
||||
return decodedToken;
|
||||
} catch (e: any) {
|
||||
Logger.error(e, {
|
||||
context: "workOS_auth_jwt_decode",
|
||||
jwtLength: jwt.length,
|
||||
jwtPrefix: jwt.substring(0, 20) + "...", // Safe prefix for debugging
|
||||
});
|
||||
|
||||
console.warn(`Error decoding JWT: ${e}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private jwtIsExpiredOrInvalid(jwt: string): boolean {
|
||||
const decodedToken = this.decodeJwt(jwt);
|
||||
if (!decodedToken) {
|
||||
return true;
|
||||
}
|
||||
return decodedToken.exp * 1000 < Date.now();
|
||||
}
|
||||
|
||||
private getExpirationTimeMs(jwt: string): number {
|
||||
const decodedToken = this.decodeJwt(jwt);
|
||||
if (!decodedToken) {
|
||||
return WorkOsAuthProvider.EXPIRATION_TIME_MS;
|
||||
}
|
||||
return decodedToken.exp && decodedToken.iat
|
||||
? (decodedToken.exp - decodedToken.iat) * 1000
|
||||
: WorkOsAuthProvider.EXPIRATION_TIME_MS;
|
||||
}
|
||||
|
||||
private async storeSessions(value: ContinueAuthenticationSession[]) {
|
||||
const data = JSON.stringify(value, null, 2);
|
||||
await this.secretStorage.store(SESSIONS_SECRET_KEY, data);
|
||||
}
|
||||
|
||||
public async getSessions(
|
||||
scopes?: string[],
|
||||
): Promise<ContinueAuthenticationSession[]> {
|
||||
// await this.hasAttemptedRefresh;
|
||||
try {
|
||||
const data = await this.secretStorage.get(SESSIONS_SECRET_KEY);
|
||||
if (!data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const value = JSON.parse(data) as ContinueAuthenticationSession[];
|
||||
return value;
|
||||
} catch (e: any) {
|
||||
Logger.error(e, {
|
||||
context: "workOS_sessions_retrieval",
|
||||
errorMessage: e.message,
|
||||
});
|
||||
|
||||
console.warn(`Error retrieving or parsing sessions: ${e.message}`);
|
||||
|
||||
// Delete the corrupted cache file to allow fresh start on next attempt
|
||||
// This handles cases where decryption succeeded but JSON parsing failed
|
||||
try {
|
||||
await this.secretStorage.delete(SESSIONS_SECRET_KEY);
|
||||
} catch (deleteError: any) {
|
||||
console.error(
|
||||
`Failed to delete corrupted sessions cache:`,
|
||||
deleteError.message,
|
||||
);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
get onDidChangeSessions() {
|
||||
return this._sessionChangeEmitter.event;
|
||||
}
|
||||
|
||||
get ideRedirectUri() {
|
||||
// We redirect to a page that says "you can close this page", and that page finishes the redirect
|
||||
const url = new URL(controlPlaneEnv.APP_URL);
|
||||
url.pathname = `/auth/${env.uriScheme}-redirect`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
public static useOnboardingUri: boolean = false;
|
||||
get redirectUri() {
|
||||
return this.ideRedirectUri;
|
||||
}
|
||||
|
||||
public static hasAttemptedRefresh: Promise<void>;
|
||||
private attemptEmitter: NodeEventEmitter;
|
||||
async refreshSessions() {
|
||||
// Prevent concurrent refresh operations
|
||||
if (this._isRefreshing) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this._isRefreshing = true;
|
||||
await this._refreshSessions();
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "workOS_auth_session_refresh",
|
||||
authType: controlPlaneEnv.AUTH_TYPE,
|
||||
});
|
||||
|
||||
console.error(`Error refreshing sessions: ${e}`);
|
||||
} finally {
|
||||
this._isRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
// It is important that every path in this function emits the attempted event
|
||||
// As config loading in core will be locked until refresh is attempted
|
||||
private async _refreshSessions(): Promise<void> {
|
||||
const sessions = await this.getSessions();
|
||||
if (!sessions.length) {
|
||||
this.attemptEmitter.emit("attempted");
|
||||
return;
|
||||
}
|
||||
|
||||
const finalSessions = [];
|
||||
for (const session of sessions) {
|
||||
try {
|
||||
const newSession = await this._refreshSessionWithRetry(
|
||||
session.refreshToken,
|
||||
);
|
||||
finalSessions.push({
|
||||
...session,
|
||||
accessToken: newSession.accessToken,
|
||||
refreshToken: newSession.refreshToken,
|
||||
expiresInMs: newSession.expiresInMs,
|
||||
});
|
||||
} catch (e: any) {
|
||||
Logger.error(e, {
|
||||
context: "workOS_individual_session_refresh",
|
||||
sessionId: session.id,
|
||||
});
|
||||
|
||||
// If refresh fails (after retries for valid tokens), drop the session
|
||||
console.debug(`Error refreshing session token: ${e.message}`);
|
||||
this._sessionChangeEmitter.fire({
|
||||
added: [],
|
||||
removed: [session],
|
||||
changed: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await this.storeSessions(finalSessions);
|
||||
this._sessionChangeEmitter.fire({
|
||||
added: [],
|
||||
removed: [],
|
||||
changed: finalSessions,
|
||||
});
|
||||
}
|
||||
|
||||
private async _refreshSessionWithRetry(
|
||||
refreshToken: string,
|
||||
attempt = 1,
|
||||
baseDelay = 1000,
|
||||
): Promise<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresInMs: number;
|
||||
}> {
|
||||
try {
|
||||
return await this._refreshSession(refreshToken);
|
||||
} catch (error: any) {
|
||||
Logger.error(error, {
|
||||
attempt,
|
||||
errorMessage: error.message,
|
||||
isAuthError:
|
||||
error.message?.includes("401") ||
|
||||
error.message?.includes("Invalid refresh token") ||
|
||||
error.message?.includes("Unauthorized"),
|
||||
});
|
||||
|
||||
this.attemptEmitter.emit("attempted");
|
||||
// Don't retry for auth errors
|
||||
if (
|
||||
error.message?.includes("401") ||
|
||||
error.message?.includes("Invalid refresh token") ||
|
||||
error.message?.includes("Unauthorized")
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// For network errors or transient server issues, retry with backoff
|
||||
// Calculate exponential backoff delay with jitter
|
||||
const delay = Math.min(
|
||||
baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5),
|
||||
2 * 60 * 1000, // 2 minutes
|
||||
);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
this._refreshSessionWithRetry(refreshToken, attempt + 1, baseDelay)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
}, delay);
|
||||
});
|
||||
} finally {
|
||||
this.attemptEmitter.emit("attempted");
|
||||
}
|
||||
}
|
||||
|
||||
private async _refreshSession(refreshToken: string): Promise<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresInMs: number;
|
||||
}> {
|
||||
const response = await fetch(
|
||||
new URL("/auth/refresh", controlPlaneEnv.CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refreshToken,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error("Error refreshing token: " + text);
|
||||
}
|
||||
const data = (await response.json()) as any;
|
||||
return {
|
||||
accessToken: data.accessToken,
|
||||
refreshToken: data.refreshToken,
|
||||
expiresInMs: this.getExpirationTimeMs(data.accessToken),
|
||||
};
|
||||
}
|
||||
|
||||
private _formatProfileLabel(
|
||||
firstName: string | null,
|
||||
lastName: string | null,
|
||||
) {
|
||||
return ((firstName ?? "") + " " + (lastName ?? "")).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new auth session
|
||||
* @param scopes
|
||||
* @returns
|
||||
*/
|
||||
public async createSession(
|
||||
scopes: string[],
|
||||
): Promise<ContinueAuthenticationSession> {
|
||||
try {
|
||||
const codeVerifier = generateRandomString(64);
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
if (!isHubEnv(controlPlaneEnv)) {
|
||||
throw new Error("Login is disabled");
|
||||
}
|
||||
|
||||
const token = await this.login(codeChallenge, controlPlaneEnv, scopes);
|
||||
if (!token) {
|
||||
throw new Error(`Continue login failure`);
|
||||
}
|
||||
|
||||
const userInfo = (await this.getUserInfo(
|
||||
token,
|
||||
codeVerifier,
|
||||
controlPlaneEnv,
|
||||
)) as any;
|
||||
const { user, access_token, refresh_token } = userInfo;
|
||||
|
||||
const session: ContinueAuthenticationSession = {
|
||||
id: uuidv4(),
|
||||
accessToken: access_token,
|
||||
refreshToken: refresh_token,
|
||||
expiresInMs: this.getExpirationTimeMs(access_token),
|
||||
loginNeeded: false,
|
||||
account: {
|
||||
label: this._formatProfileLabel(user.first_name, user.last_name),
|
||||
id: user.email,
|
||||
},
|
||||
scopes: [],
|
||||
};
|
||||
|
||||
await this.storeSessions([session]);
|
||||
|
||||
this._sessionChangeEmitter.fire({
|
||||
added: [session],
|
||||
removed: [],
|
||||
changed: [],
|
||||
});
|
||||
|
||||
return session;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "workOS_auth_session_creation",
|
||||
scopes: scopes.join(","),
|
||||
authType: controlPlaneEnv.AUTH_TYPE,
|
||||
});
|
||||
|
||||
void window.showErrorMessage(`Sign in failed: ${e}`);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an existing session
|
||||
* @param sessionId
|
||||
*/
|
||||
public async removeSession(sessionId: string): Promise<void> {
|
||||
const sessions = await this.getSessions();
|
||||
const sessionIdx = sessions.findIndex((s) => s.id === sessionId);
|
||||
const session = sessions[sessionIdx];
|
||||
sessions.splice(sessionIdx, 1);
|
||||
|
||||
await this.storeSessions(sessions);
|
||||
|
||||
if (session) {
|
||||
this._sessionChangeEmitter.fire({
|
||||
added: [],
|
||||
removed: [session],
|
||||
changed: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose the registered services
|
||||
*/
|
||||
public async dispose() {
|
||||
if (this._refreshInterval) {
|
||||
clearInterval(this._refreshInterval);
|
||||
this._refreshInterval = null;
|
||||
}
|
||||
this._disposable.dispose();
|
||||
}
|
||||
|
||||
/**
|
||||
* Log in to Continue
|
||||
*/
|
||||
private async login(
|
||||
codeChallenge: string,
|
||||
hubEnv: HubEnv,
|
||||
scopes: string[] = [],
|
||||
) {
|
||||
return await window.withProgress<string>(
|
||||
{
|
||||
location: ProgressLocation.Notification,
|
||||
title: "Signing in to Continue...",
|
||||
cancellable: true,
|
||||
},
|
||||
async (_, token) => {
|
||||
const stateId = uuidv4();
|
||||
|
||||
this._pendingStates.push(stateId);
|
||||
|
||||
const scopeString = scopes.join(" ");
|
||||
|
||||
const url = new URL("https://api.workos.com/user_management/authorize");
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id: hubEnv.WORKOS_CLIENT_ID,
|
||||
redirect_uri: this.redirectUri,
|
||||
state: stateId,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: "S256",
|
||||
provider: "authkit",
|
||||
screen_hint: WorkOsAuthProvider.useOnboardingUri
|
||||
? "sign-up"
|
||||
: "sign-in",
|
||||
};
|
||||
|
||||
Object.keys(params).forEach((key) =>
|
||||
url.searchParams.append(key, params[key as keyof typeof params]),
|
||||
);
|
||||
|
||||
const oauthUrl = url;
|
||||
if (oauthUrl) {
|
||||
await env.openExternal(Uri.parse(oauthUrl.toString()));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
let codeExchangePromise = this._codeExchangePromises.get(scopeString);
|
||||
if (!codeExchangePromise) {
|
||||
codeExchangePromise = promiseFromEvent(
|
||||
this._uriHandler.event,
|
||||
this.handleUri(scopes),
|
||||
);
|
||||
this._codeExchangePromises.set(scopeString, codeExchangePromise);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
codeExchangePromise.promise,
|
||||
new Promise<string>(
|
||||
(_, reject) =>
|
||||
setTimeout(() => reject("Cancelled"), 60 * 60 * 1_000), // 60min timeout
|
||||
),
|
||||
promiseFromEvent<any, any>(
|
||||
token.onCancellationRequested,
|
||||
(_, __, reject) => {
|
||||
reject("User Cancelled");
|
||||
},
|
||||
).promise,
|
||||
]);
|
||||
} finally {
|
||||
this._pendingStates = this._pendingStates.filter(
|
||||
(n) => n !== stateId,
|
||||
);
|
||||
codeExchangePromise?.cancel.fire();
|
||||
this._codeExchangePromises.delete(scopeString);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the redirect to VS Code (after sign in from Continue)
|
||||
* @param scopes
|
||||
* @returns
|
||||
*/
|
||||
private handleUri: (
|
||||
scopes: readonly string[],
|
||||
) => PromiseAdapter<Uri, string> =
|
||||
(scopes) => async (uri, resolve, reject) => {
|
||||
const query = new URLSearchParams(uri.query);
|
||||
const access_token = query.get("code");
|
||||
const state = query.get("state");
|
||||
|
||||
if (!access_token) {
|
||||
reject(new Error("No token"));
|
||||
return;
|
||||
}
|
||||
if (!state) {
|
||||
reject(new Error("No state"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it is a valid auth request started by the extension
|
||||
if (!this._pendingStates.some((n) => n === state)) {
|
||||
reject(new Error("State not found"));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(access_token);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the user info from WorkOS
|
||||
* @param token
|
||||
* @returns
|
||||
*/
|
||||
private async getUserInfo(
|
||||
token: string,
|
||||
codeVerifier: string,
|
||||
hubEnv: HubEnv,
|
||||
) {
|
||||
const resp = await fetch(
|
||||
"https://api.workos.com/user_management/authenticate",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: hubEnv.WORKOS_CLIENT_ID,
|
||||
code_verifier: codeVerifier,
|
||||
grant_type: "authorization_code",
|
||||
code: token,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const text = await resp.text();
|
||||
const data = JSON.parse(text);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getControlPlaneSessionInfo(
|
||||
silent: boolean,
|
||||
useOnboarding: boolean,
|
||||
): Promise<ControlPlaneSessionInfo | undefined> {
|
||||
if (!isHubEnv(controlPlaneEnv)) {
|
||||
return {
|
||||
AUTH_TYPE: AuthType.OnPrem,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
if (useOnboarding) {
|
||||
WorkOsAuthProvider.useOnboardingUri = true;
|
||||
}
|
||||
await WorkOsAuthProvider.hasAttemptedRefresh;
|
||||
const session = await authentication.getSession(
|
||||
controlPlaneEnv.AUTH_TYPE,
|
||||
[],
|
||||
silent ? { silent: true } : { createIfNone: true },
|
||||
);
|
||||
if (!session) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
AUTH_TYPE: controlPlaneEnv.AUTH_TYPE,
|
||||
accessToken: session.accessToken,
|
||||
account: {
|
||||
id: session.account.id,
|
||||
label: session.account.label,
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
WorkOsAuthProvider.useOnboardingUri = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,805 +0,0 @@
|
|||
// @ts-nocheck
|
||||
import fetch from "node-fetch";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "vscode";
|
||||
|
||||
// Don't import WorkOsAuthProvider directly here
|
||||
|
||||
// Mock the modules we need
|
||||
vi.mock("vscode", () => ({
|
||||
authentication: {
|
||||
registerAuthenticationProvider: vi.fn(),
|
||||
},
|
||||
window: {
|
||||
registerUriHandler: vi.fn(),
|
||||
},
|
||||
EventEmitter: vi.fn(() => ({
|
||||
event: { dispose: vi.fn() },
|
||||
fire: vi.fn(),
|
||||
})),
|
||||
Disposable: {
|
||||
from: vi.fn(() => ({ dispose: vi.fn() })),
|
||||
},
|
||||
env: {
|
||||
uriScheme: "vscode",
|
||||
},
|
||||
}));
|
||||
|
||||
// Properly mock node-fetch
|
||||
vi.mock("node-fetch", () => {
|
||||
return {
|
||||
__esModule: true,
|
||||
default: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("core/control-plane/env", () => ({
|
||||
getControlPlaneEnvSync: vi.fn(() => ({
|
||||
AUTH_TYPE: "workos",
|
||||
APP_URL: "https://continue.dev",
|
||||
CONTROL_PLANE_URL: "https://api.continue.dev",
|
||||
WORKOS_CLIENT_ID: "client_123",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("crypto", () => ({
|
||||
createHash: vi.fn(() => ({
|
||||
update: vi.fn(() => ({
|
||||
digest: vi.fn(() => Buffer.from("test-hash")),
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
|
||||
// Create a simple SecretStorage mock that we can control
|
||||
const mockSecretStorageGet = vi.fn();
|
||||
const mockSecretStorageStore = vi.fn();
|
||||
|
||||
// Mock SecretStorage class
|
||||
vi.mock("./SecretStorage", () => {
|
||||
return {
|
||||
SecretStorage: vi.fn().mockImplementation(() => ({
|
||||
store: mockSecretStorageStore,
|
||||
get: mockSecretStorageGet,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
// Helper to create valid and expired JWTs
|
||||
function createJwt({ expired }: { expired: boolean }): string {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const header = { alg: "HS256", typ: "JWT" };
|
||||
const payload = {
|
||||
sub: "user123",
|
||||
iat: now,
|
||||
exp: expired ? now - 3600 : now + 3600, // Expired 1 hour ago or valid for 1 hour
|
||||
};
|
||||
|
||||
const base64Header = Buffer.from(JSON.stringify(header))
|
||||
.toString("base64")
|
||||
.replace(/=/g, "");
|
||||
const base64Payload = Buffer.from(JSON.stringify(payload))
|
||||
.toString("base64")
|
||||
.replace(/=/g, "");
|
||||
const signature = "dummysignature";
|
||||
|
||||
return `${base64Header}.${base64Payload}.${signature}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
// Set up fake timers before each test
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers(); // Restore real timers after each test
|
||||
});
|
||||
|
||||
it("should refresh tokens on initialization when sessions exist", async () => {
|
||||
// Mock setInterval to prevent the refresh interval
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "refresh-token",
|
||||
expiresInMs: 3600000, // 1 hour
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Setup successful token refresh
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
accessToken: createJwt({ expired: false }),
|
||||
refreshToken: "new-refresh-token",
|
||||
}),
|
||||
text: async () => "",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for all promises to resolve, including any nested promise chains
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify that the token refresh endpoint was called
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: expect.stringContaining("refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Restore setInterval
|
||||
global.setInterval = originalSetInterval;
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should not remove sessions during transient network errors", async () => {
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "refresh-token",
|
||||
expiresInMs: 300000, // 5 minutes
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// First refresh attempt fails with network error
|
||||
fetchMock.mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
// Second refresh attempt should succeed
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
accessToken: createJwt({ expired: false }),
|
||||
refreshToken: "new-refresh-token",
|
||||
}),
|
||||
text: async () => "",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Allow setInterval to work normally with fake timers
|
||||
// We're not mocking it anymore, instead we'll control when it fires
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions with the network error
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Run microtasks to process promises from the initial refresh call
|
||||
await Promise.resolve();
|
||||
|
||||
// Check that sessions were not cleared after network error
|
||||
expect(mockSecretStorageStore).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.stringMatching(/\[\]/),
|
||||
);
|
||||
|
||||
// Reset the fetch mock call count to verify the next call
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Advance timers to the next refresh interval to simulate the timer firing
|
||||
vi.advanceTimersByTime(WorkOsAuthProvider.REFRESH_INTERVAL_MS);
|
||||
|
||||
// Run microtasks to process promises from the interval-triggered refresh
|
||||
await Promise.resolve();
|
||||
|
||||
// Verify the second attempt was made via the interval
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
body: expect.stringContaining("refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should refresh tokens at regular intervals rather than based on expiration", async () => {
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "refresh-token",
|
||||
expiresInMs: 3600000, // 1 hour
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Setup successful token refresh responses for multiple calls
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
accessToken: createJwt({ expired: false }),
|
||||
refreshToken: "new-refresh-token",
|
||||
}),
|
||||
text: async () => "",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Capture the original setInterval to restore it later
|
||||
const originalSetInterval = global.setInterval;
|
||||
|
||||
// Create our own implementation of setInterval that we can control better
|
||||
let intervalCallback: Function;
|
||||
global.setInterval = vi.fn((callback, ms) => {
|
||||
intervalCallback = callback;
|
||||
return 123 as any; // Return a dummy interval ID
|
||||
});
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for all promises to resolve, including any nested promise chains
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// First refresh should happen immediately on initialization
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Verify that setInterval was called to set up regular refreshes
|
||||
expect(global.setInterval).toHaveBeenCalled();
|
||||
|
||||
// Get the interval time from the call to setInterval
|
||||
const intervalTime = (global.setInterval as any).mock.calls[0][1];
|
||||
|
||||
// Should be a reasonable interval (less than the expiration time)
|
||||
expect(intervalTime).toBeLessThan(mockSession.expiresInMs);
|
||||
|
||||
// Now manually trigger the interval callback - First interval
|
||||
intervalCallback();
|
||||
|
||||
// Wait for all promises to resolve
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify that refresh was called again when the interval callback fired
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Check that we're making refresh calls to the right endpoint with the right data
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pathname: "/auth/refresh" }),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
body: expect.stringContaining("refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Clear mock calls for the second interval test
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Trigger the callback again - Second interval
|
||||
intervalCallback();
|
||||
|
||||
// Wait for all promises to resolve
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify the refresh was called a second time
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Verify the second call has the same correct parameters
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pathname: "/auth/refresh" }),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
body: expect.stringContaining("refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Restore the original setInterval
|
||||
global.setInterval = originalSetInterval;
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should remove session if token refresh fails with authentication error", async () => {
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "invalid-refresh-token",
|
||||
expiresInMs: 300000, // 5 minutes
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Setup refresh to fail with 401 unauthorized
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 401,
|
||||
text: async () => "Invalid refresh token",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Mock setInterval to prevent continuous refreshes
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
mockSecretStorageStore.mockClear();
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for all promises to resolve, including any nested promise chains
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify that the token refresh endpoint was called
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: expect.stringContaining("invalid-refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify sessions were removed due to auth error
|
||||
expect(mockSecretStorageStore).toHaveBeenCalledWith(
|
||||
"workos.sessions", // Use the hard-coded key that matches our mock
|
||||
expect.stringMatching(/\[\]/),
|
||||
);
|
||||
|
||||
// Restore setInterval
|
||||
global.setInterval = originalSetInterval;
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should remove session if token refresh returns Unauthorized error message", async () => {
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "invalid-refresh-token",
|
||||
expiresInMs: 300000, // 5 minutes
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Setup refresh to return an error containing "Unauthorized" in the message
|
||||
// Status code doesn't matter here, what matters is the error message text
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 403, // Could be any error code
|
||||
text: async () => "Unauthorized",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Mock setInterval to prevent continuous refreshes
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
mockSecretStorageStore.mockClear();
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for all promises to resolve, including any nested promise chains
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify that the token refresh endpoint was called
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: expect.stringContaining("invalid-refresh-token"),
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify sessions were removed due to Unauthorized error message
|
||||
expect(mockSecretStorageStore).toHaveBeenCalledWith(
|
||||
"workos.sessions", // Use the hard-coded key that matches our mock
|
||||
expect.stringMatching(/\[\]/),
|
||||
);
|
||||
|
||||
// Restore setInterval
|
||||
global.setInterval = originalSetInterval;
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should preserve valid tokens during network errors by retrying", async () => {
|
||||
// Mock Date.now to return a fixed timestamp for token validation
|
||||
const originalDateNow = Date.now;
|
||||
const currentTimestamp = Date.now();
|
||||
Date.now = vi.fn(() => currentTimestamp);
|
||||
|
||||
// Setup with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const validSession = {
|
||||
id: "valid-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "valid-refresh-token",
|
||||
expiresInMs: 3600000,
|
||||
account: { label: "Valid User", id: "valid@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Create mock objects
|
||||
const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() };
|
||||
const mockContext = {
|
||||
secrets: { store: vi.fn(), get: vi.fn() },
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Mock setInterval and setTimeout
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
const originalSetTimeout = global.setTimeout;
|
||||
global.setTimeout = vi.fn((callback) => {
|
||||
callback();
|
||||
return 123 as any;
|
||||
});
|
||||
|
||||
// Network error followed by success
|
||||
fetchMock.mockRejectedValueOnce(new Error("Network error"));
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
accessToken: createJwt({ expired: false }),
|
||||
refreshToken: "new-refresh-token",
|
||||
}),
|
||||
text: async () => "",
|
||||
});
|
||||
|
||||
// Setup storage
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([validSession]));
|
||||
mockSecretStorageStore.mockClear();
|
||||
|
||||
// Import and create provider
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for promises to resolve
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Check that a non-empty session array was stored (session was preserved)
|
||||
const storeCall = mockSecretStorageStore.mock.calls[0];
|
||||
expect(storeCall[0]).toBe("workos.sessions");
|
||||
expect(JSON.parse(storeCall[1])).toHaveLength(1); // Should contain one session
|
||||
|
||||
// Restore originals
|
||||
global.setTimeout = originalSetTimeout;
|
||||
global.setInterval = originalSetInterval;
|
||||
Date.now = originalDateNow;
|
||||
|
||||
// Clean up provider
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should remove expired tokens when refresh fails with a 401 error", async () => {
|
||||
// Mock Date.now to return a time that makes tokens appear expired
|
||||
const originalDateNow = Date.now;
|
||||
const futureTime = Date.now() + 7200000; // 2 hours in the future
|
||||
Date.now = vi.fn(() => futureTime);
|
||||
|
||||
// Setup with an expired token
|
||||
const expiredToken = createJwt({ expired: true });
|
||||
const expiredSession = {
|
||||
id: "expired-id",
|
||||
accessToken: expiredToken,
|
||||
refreshToken: "expired-refresh-token",
|
||||
expiresInMs: 3600000,
|
||||
account: { label: "Expired User", id: "expired@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Create mock objects
|
||||
const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() };
|
||||
const mockContext = {
|
||||
secrets: { store: vi.fn(), get: vi.fn() },
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Mock setInterval
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Refresh will fail with network error
|
||||
fetchMock.mockRejectedValueOnce(new Error("401"));
|
||||
|
||||
// Setup storage
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession]));
|
||||
mockSecretStorageStore.mockClear();
|
||||
|
||||
// Import and create provider
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for promises to resolve
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Check that an empty session array was stored (session was removed)
|
||||
const storeCall = mockSecretStorageStore.mock.calls[0];
|
||||
expect(storeCall[0]).toBe("workos.sessions");
|
||||
expect(JSON.parse(storeCall[1])).toHaveLength(0); // Should be empty
|
||||
|
||||
// Restore originals
|
||||
global.setInterval = originalSetInterval;
|
||||
Date.now = originalDateNow;
|
||||
|
||||
// Clean up provider
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("should implement exponential backoff for failed refresh attempts", async () => {
|
||||
// Setup existing sessions with a valid token
|
||||
const validToken = createJwt({ expired: false });
|
||||
const mockSession = {
|
||||
id: "test-id",
|
||||
accessToken: validToken,
|
||||
refreshToken: "refresh-token",
|
||||
expiresInMs: 300000, // 5 minutes
|
||||
account: { label: "Test User", id: "user@example.com" },
|
||||
scopes: [],
|
||||
loginNeeded: false,
|
||||
};
|
||||
|
||||
// Setup fetch mock
|
||||
const fetchMock = fetch as any;
|
||||
fetchMock.mockClear();
|
||||
|
||||
// Setup repeated network errors followed by success
|
||||
fetchMock.mockRejectedValueOnce(new Error("Network error 1"));
|
||||
fetchMock.mockRejectedValueOnce(new Error("Network error 2"));
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
accessToken: createJwt({ expired: false }),
|
||||
refreshToken: "new-refresh-token",
|
||||
}),
|
||||
text: async () => "",
|
||||
});
|
||||
|
||||
// Create a mock UriHandler
|
||||
const mockUriHandler = {
|
||||
event: new EventEmitter(),
|
||||
handleCallback: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a mock ExtensionContext
|
||||
const mockContext = {
|
||||
secrets: {
|
||||
store: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
subscriptions: [],
|
||||
};
|
||||
|
||||
// Mock setInterval to prevent continuous refreshes
|
||||
const originalSetInterval = global.setInterval;
|
||||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Track setTimeout calls
|
||||
const setTimeoutSpy = vi.spyOn(global, "setTimeout");
|
||||
|
||||
// Set up our SecretStorage mock to return the session
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession]));
|
||||
|
||||
// Import WorkOsAuthProvider after setting up all mocks
|
||||
const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider");
|
||||
|
||||
// Create provider instance - this will automatically call refreshSessions
|
||||
const provider = new WorkOsAuthProvider(mockContext, mockUriHandler);
|
||||
|
||||
// Wait for all promises to resolve for the initial refresh attempt
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify the first fetch attempt was made
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Trigger first retry
|
||||
vi.advanceTimersByTime(1000); // Initial backoff
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify the second fetch attempt was made
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Trigger second retry
|
||||
vi.advanceTimersByTime(2000); // Double the backoff
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
// Verify the third fetch attempt was made
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Verify setTimeout was called with increasing delays
|
||||
expect(setTimeoutSpy).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Check that the backoff periods increased
|
||||
const firstDelay = setTimeoutSpy.mock.calls[0][1];
|
||||
const secondDelay = setTimeoutSpy.mock.calls[1][1];
|
||||
|
||||
// Check that backoff increased
|
||||
expect(secondDelay).toBeGreaterThan(firstDelay);
|
||||
|
||||
// Restore setInterval
|
||||
global.setInterval = originalSetInterval;
|
||||
|
||||
// Clean up
|
||||
if (provider._refreshInterval) {
|
||||
clearInterval(provider._refreshInterval);
|
||||
provider._refreshInterval = null;
|
||||
}
|
||||
});
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { getUserToken } from "./auth";
|
||||
import { RemoteConfigSync } from "./remoteConfig";
|
||||
|
||||
export async function setupRemoteConfigSync(reloadConfig: () => void) {
|
||||
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
|
||||
const remoteConfigServerUrl = settings.get<string | null>(
|
||||
"remoteConfigServerUrl",
|
||||
null,
|
||||
);
|
||||
if (
|
||||
remoteConfigServerUrl === null ||
|
||||
remoteConfigServerUrl === undefined ||
|
||||
remoteConfigServerUrl.trim() === ""
|
||||
) {
|
||||
return;
|
||||
}
|
||||
getUserToken().then(async (token) => {
|
||||
await vscode.workspace
|
||||
.getConfiguration(EXTENSION_NAME)
|
||||
.update("userToken", token, vscode.ConfigurationTarget.Global);
|
||||
try {
|
||||
const configSync = new RemoteConfigSync(reloadConfig, token);
|
||||
configSync.setup();
|
||||
} catch (e) {
|
||||
console.warn(`Failed to sync remote config: ${e}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
export async function getUserToken(): Promise<string> {
|
||||
// Prefer manual user token first
|
||||
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
|
||||
const userToken = settings.get<string | null>("userToken", null);
|
||||
if (userToken) {
|
||||
return userToken;
|
||||
}
|
||||
|
||||
const session = await vscode.authentication.getSession("github", [], {
|
||||
createIfNone: true,
|
||||
});
|
||||
return session.accessToken;
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { ContinueServerClient } from "core/continueServer/stubs/client";
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { getConfigJsonPathForRemote } from "core/util/paths";
|
||||
import { canParseUrl } from "core/util/url";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig";
|
||||
|
||||
export class RemoteConfigSync {
|
||||
private userToken: string | null;
|
||||
private remoteConfigServerUrl: string | null;
|
||||
private remoteConfigSyncPeriod: number;
|
||||
|
||||
private syncInterval: NodeJS.Timer | undefined = undefined;
|
||||
|
||||
constructor(
|
||||
private triggerReloadConfig: () => void,
|
||||
userToken: string | null,
|
||||
) {
|
||||
let {
|
||||
userToken: settingsUserToken,
|
||||
remoteConfigServerUrl,
|
||||
remoteConfigSyncPeriod,
|
||||
} = this.loadVsCodeSettings();
|
||||
this.userToken = settingsUserToken || userToken;
|
||||
this.remoteConfigServerUrl = remoteConfigServerUrl;
|
||||
this.remoteConfigSyncPeriod = remoteConfigSyncPeriod;
|
||||
|
||||
// Listen for changes to VS Code settings, then trigger a refresh
|
||||
vscode.workspace.onDidChangeConfiguration(async (event) => {
|
||||
if (event.affectsConfiguration(CONTINUE_WORKSPACE_KEY)) {
|
||||
const { userToken, remoteConfigServerUrl, remoteConfigSyncPeriod } =
|
||||
await this.loadVsCodeSettings();
|
||||
if (
|
||||
userToken !== this.userToken ||
|
||||
remoteConfigServerUrl !== this.remoteConfigServerUrl ||
|
||||
remoteConfigSyncPeriod !== this.remoteConfigSyncPeriod
|
||||
) {
|
||||
this.userToken = userToken;
|
||||
this.remoteConfigServerUrl = remoteConfigServerUrl;
|
||||
this.remoteConfigSyncPeriod = remoteConfigSyncPeriod;
|
||||
|
||||
this.setInterval();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadVsCodeSettings() {
|
||||
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
|
||||
const userToken = settings.get<string | null>("userToken", null);
|
||||
const remoteConfigServerUrl = settings.get<string | null>(
|
||||
"remoteConfigServerUrl",
|
||||
null,
|
||||
);
|
||||
const remoteConfigSyncPeriod = settings.get<number>(
|
||||
"remoteConfigSyncPeriod",
|
||||
60,
|
||||
);
|
||||
|
||||
return {
|
||||
userToken,
|
||||
remoteConfigServerUrl,
|
||||
remoteConfigSyncPeriod,
|
||||
};
|
||||
}
|
||||
|
||||
async setup() {
|
||||
if (
|
||||
this.userToken === null ||
|
||||
this.remoteConfigServerUrl === null ||
|
||||
this.remoteConfigServerUrl.trim() === ""
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!canParseUrl(this.remoteConfigServerUrl)) {
|
||||
vscode.window.showErrorMessage(
|
||||
"The value set for 'remoteConfigServerUrl' is not valid: ",
|
||||
this.remoteConfigServerUrl,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Sync once
|
||||
await this.sync(this.userToken, this.remoteConfigServerUrl);
|
||||
|
||||
// Set timer to sync at user-defined interval
|
||||
this.setInterval();
|
||||
}
|
||||
|
||||
private setInterval() {
|
||||
if (this.syncInterval !== undefined) {
|
||||
// @ts-ignore
|
||||
clearInterval(this.syncInterval);
|
||||
}
|
||||
this.syncInterval = setInterval(
|
||||
() => {
|
||||
if (!this.userToken || !this.remoteConfigServerUrl) {
|
||||
return;
|
||||
}
|
||||
this.sync(this.userToken, this.remoteConfigServerUrl);
|
||||
},
|
||||
this.remoteConfigSyncPeriod * 1000 * 60,
|
||||
);
|
||||
}
|
||||
|
||||
async sync(userToken: string, remoteConfigServerUrl: string) {
|
||||
try {
|
||||
const client = new ContinueServerClient(
|
||||
remoteConfigServerUrl.toString(),
|
||||
userToken,
|
||||
);
|
||||
const { configJson } = await client.getConfig();
|
||||
|
||||
fs.writeFileSync(
|
||||
getConfigJsonPathForRemote(remoteConfigServerUrl),
|
||||
configJson,
|
||||
);
|
||||
this.triggerReloadConfig();
|
||||
} catch (e) {
|
||||
vscode.window.showWarningMessage(`Failed to sync remote config: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { EXTENSION_NAME } from "core/util/constants";
|
||||
import { findUriInDirs } from "core/util/uri";
|
||||
import _ from "lodash";
|
||||
import * as URI from "uri-js";
|
||||
|
|
|
|||
|
|
@ -1,100 +0,0 @@
|
|||
import { Cog6ToothIcon } from "@heroicons/react/24/outline";
|
||||
import {
|
||||
BuildingOfficeIcon,
|
||||
UserCircleIcon,
|
||||
UserIcon,
|
||||
} from "@heroicons/react/24/solid";
|
||||
import { useContext } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { setSelectedOrgId } from "../../redux/slices/profilesSlice";
|
||||
import { CONFIG_ROUTES } from "../../util/navigation";
|
||||
import { Button, ListboxOption } from "../ui";
|
||||
|
||||
interface OrganizationOptionProps {
|
||||
organization: { id: string; name: string; iconUrl?: string | null };
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function getOrgIcon(
|
||||
org: { name: string; iconUrl?: string | null },
|
||||
size: "sm" | "md" = "sm",
|
||||
) {
|
||||
const sizeClasses = size === "sm" ? "h-3.5 w-3.5" : "xs:h-4 xs:w-4 h-3 w-3";
|
||||
|
||||
if (org.iconUrl) {
|
||||
return (
|
||||
<img
|
||||
src={org.iconUrl}
|
||||
alt=""
|
||||
className={`${sizeClasses} flex-shrink-0 rounded-full`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const IconComponent =
|
||||
org.name === "Personal"
|
||||
? size === "md"
|
||||
? UserIcon
|
||||
: UserCircleIcon
|
||||
: BuildingOfficeIcon;
|
||||
return <IconComponent className={`${sizeClasses} flex-shrink-0`} />;
|
||||
}
|
||||
|
||||
export function OrganizationOption({
|
||||
organization,
|
||||
onClose,
|
||||
}: OrganizationOptionProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const selectedOrgId = useAppSelector(
|
||||
(state) => state.profiles.selectedOrganizationId,
|
||||
);
|
||||
const isSelected = selectedOrgId === organization.id;
|
||||
|
||||
function handleOptionClick() {
|
||||
dispatch(setSelectedOrgId(organization.id));
|
||||
ideMessenger.post("didChangeSelectedOrg", {
|
||||
id: organization.id,
|
||||
});
|
||||
onClose();
|
||||
}
|
||||
|
||||
return (
|
||||
<ListboxOption
|
||||
value={organization.id}
|
||||
onClick={handleOptionClick}
|
||||
fontSizeModifier={-2}
|
||||
className={`group ${isSelected ? "bg-list-active text-list-active-foreground" : ""}`}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-10 py-0.5">
|
||||
<div className="flex w-full items-center gap-3">
|
||||
<div className="flex h-4 w-4 flex-shrink-0 items-center justify-center">
|
||||
{getOrgIcon(organization, "sm")}
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 flex-1 ${isSelected ? "font-semibold" : ""}`}
|
||||
>
|
||||
{organization.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-description-muted hover:enabled:text-foreground my-0 h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate(CONFIG_ROUTES.ORGANIZATIONS);
|
||||
onClose(); // Close the listbox
|
||||
}}
|
||||
>
|
||||
<Cog6ToothIcon className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ListboxOption>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { useAuth } from "../../context/Auth";
|
||||
import { OrganizationOption } from "./OrganizationOption";
|
||||
|
||||
interface OrganizationOptionsProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function OrganizationOptions({ onClose }: OrganizationOptionsProps) {
|
||||
const { organizations } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="thin-scrollbar flex max-h-24 flex-col overflow-y-auto">
|
||||
{organizations.map((org) => (
|
||||
<OrganizationOption key={org.id} organization={org} onClose={onClose} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,19 +1,14 @@
|
|||
import {
|
||||
ArrowPathIcon,
|
||||
ArrowRightStartOnRectangleIcon,
|
||||
Cog6ToothIcon,
|
||||
PlusIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useContext, useEffect, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
setSelectedProfile,
|
||||
} from "../../redux/slices/profilesSlice";
|
||||
import { setSelectedProfile } from "../../redux/slices/profilesSlice";
|
||||
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
|
||||
import { cn } from "../../util/cn";
|
||||
import { CONFIG_ROUTES } from "../../util/navigation";
|
||||
|
|
@ -24,9 +19,7 @@ import {
|
|||
Transition,
|
||||
useFontSize,
|
||||
} from "../ui";
|
||||
import { Divider } from "../ui/Divider";
|
||||
import { AssistantOptions } from "./AssistantOptions";
|
||||
import { OrganizationOptions } from "./OrganizationOptions";
|
||||
import { SelectedAssistantButton } from "./SelectedAssistantButton";
|
||||
|
||||
export interface AssistantAndOrgListboxProps {
|
||||
|
|
@ -39,21 +32,10 @@ export function AssistantAndOrgListbox({
|
|||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const listboxRef = useRef<HTMLDivElement>(null);
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const {
|
||||
profiles,
|
||||
selectedProfile,
|
||||
session,
|
||||
logout,
|
||||
login,
|
||||
organizations,
|
||||
refreshProfiles,
|
||||
} = useAuth();
|
||||
const { profiles, selectedProfile, refreshProfiles } = useAuth();
|
||||
const configLoading = useAppSelector((store) => store.config.loading);
|
||||
const tinyFont = useFontSize(-4);
|
||||
const shouldRenderOrgInfo =
|
||||
session && organizations.length > 1 && !isOnPremSession(session);
|
||||
|
||||
function close() {
|
||||
// Close the listbox by clicking outside or programmatically
|
||||
|
|
@ -62,21 +44,7 @@ export function AssistantAndOrgListbox({
|
|||
}
|
||||
|
||||
function onNewAssistant() {
|
||||
if (session) {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/new",
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
} else {
|
||||
void ideMessenger.request("config/newAssistantFile", undefined);
|
||||
}
|
||||
close();
|
||||
}
|
||||
|
||||
function onNewOrganization() {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/organizations/new",
|
||||
});
|
||||
void ideMessenger.request("config/newAssistantFile", undefined);
|
||||
close();
|
||||
}
|
||||
|
||||
|
|
@ -85,21 +53,6 @@ export function AssistantAndOrgListbox({
|
|||
close();
|
||||
}
|
||||
|
||||
function onOrganizationsConfig() {
|
||||
navigate(CONFIG_ROUTES.ORGANIZATIONS);
|
||||
close();
|
||||
}
|
||||
|
||||
function onRulesConfig() {
|
||||
navigate(CONFIG_ROUTES.RULES);
|
||||
close();
|
||||
}
|
||||
|
||||
function onToolsConfig() {
|
||||
navigate(CONFIG_ROUTES.TOOLS);
|
||||
close();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let lastToggleTime = 0;
|
||||
const DEBOUNCE_MS = 800;
|
||||
|
|
@ -139,7 +92,7 @@ export function AssistantAndOrgListbox({
|
|||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [currentOrg, selectedProfile]);
|
||||
}, [selectedProfile]);
|
||||
|
||||
return (
|
||||
<Listbox>
|
||||
|
|
@ -188,45 +141,6 @@ export function AssistantAndOrgListbox({
|
|||
onClose={close}
|
||||
/>
|
||||
|
||||
{shouldRenderOrgInfo && (
|
||||
<>
|
||||
<Divider className="!mb-0.5 !mt-0" />
|
||||
<div className="flex items-center justify-between px-1.5 py-1">
|
||||
<span className="text-description text-xs font-medium">
|
||||
Organizations
|
||||
</span>
|
||||
<div className="flex items-center gap-0.5">
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onNewOrganization();
|
||||
}}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="my-0 h-5 w-5 p-0"
|
||||
>
|
||||
<PlusIcon className="text-description h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOrganizationsConfig();
|
||||
}}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="my-0 h-5 w-5 p-0"
|
||||
>
|
||||
<Cog6ToothIcon className="text-description h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OrganizationOptions onClose={close} />
|
||||
|
||||
<Divider className="!mb-0 mt-0.5" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Settings Section */}
|
||||
{variant !== "sidebar" && (
|
||||
<div>
|
||||
|
|
@ -249,41 +163,6 @@ export function AssistantAndOrgListbox({
|
|||
<span className="text-2xs">Reload</span>
|
||||
</div>
|
||||
</Button>
|
||||
{session ? (
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
logout();
|
||||
close();
|
||||
}}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
|
||||
>
|
||||
<div className="flex w-full items-center">
|
||||
<ArrowRightStartOnRectangleIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
|
||||
<span className="text-2xs">Log out</span>
|
||||
</div>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
login(false);
|
||||
close();
|
||||
}}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
|
||||
>
|
||||
<div className="flex w-full items-center">
|
||||
<ArrowRightStartOnRectangleIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0 rotate-180" />
|
||||
<span className="text-2xs">Log in</span>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Divider className="!mt-0" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,314 +1,11 @@
|
|||
import { ArrowPathIcon, PlayIcon } from "@heroicons/react/24/outline";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { normalizeRepoUrl } from "core/util/repoUrl";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectCurrentOrg } from "../../redux/slices/profilesSlice";
|
||||
import { Button } from "../ui";
|
||||
|
||||
interface Agent {
|
||||
id: string;
|
||||
name: string | null;
|
||||
status: string;
|
||||
repoUrl: string;
|
||||
createdAt: string;
|
||||
metadata?: {
|
||||
github_repo?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AgentsListProps {
|
||||
isCreatingAgent?: boolean;
|
||||
}
|
||||
|
||||
interface WorkspaceInfo {
|
||||
repoUrl: string;
|
||||
workspaceDir: string;
|
||||
workspaceName: string;
|
||||
}
|
||||
|
||||
export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
|
||||
const { session } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const [agents, setAgents] = useState<Agent[] | null>(null);
|
||||
const [totalCount, setTotalCount] = useState<number>(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [workspaces, setWorkspaces] = useState<WorkspaceInfo[]>([]);
|
||||
|
||||
// Fetch workspace repo URLs once on mount
|
||||
useEffect(() => {
|
||||
async function fetchWorkspaceRepos() {
|
||||
try {
|
||||
const workspaceDirs = await ideMessenger.request(
|
||||
"getWorkspaceDirs",
|
||||
undefined,
|
||||
);
|
||||
if (workspaceDirs.status === "success" && workspaceDirs.content) {
|
||||
const workspaceInfos: WorkspaceInfo[] = [];
|
||||
for (const dir of workspaceDirs.content) {
|
||||
const repoNameResult = await ideMessenger.request("getRepoName", {
|
||||
dir,
|
||||
});
|
||||
if (repoNameResult.status === "success" && repoNameResult.content) {
|
||||
const normalizedUrl = normalizeRepoUrl(repoNameResult.content);
|
||||
if (normalizedUrl) {
|
||||
// Extract workspace name from directory path (last segment)
|
||||
const workspaceName = dir.split("/").pop() || dir;
|
||||
workspaceInfos.push({
|
||||
repoUrl: normalizedUrl,
|
||||
workspaceDir: dir,
|
||||
workspaceName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
setWorkspaces(workspaceInfos);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch workspace repos:", err);
|
||||
}
|
||||
}
|
||||
void fetchWorkspaceRepos();
|
||||
}, [ideMessenger]);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchAgents() {
|
||||
if (!session) {
|
||||
setAgents([]);
|
||||
setTotalCount(0);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const organizationId =
|
||||
currentOrg?.id !== "personal" ? currentOrg?.id : undefined;
|
||||
const result = await ideMessenger.request("listBackgroundAgents", {
|
||||
organizationId,
|
||||
limit: 5,
|
||||
});
|
||||
|
||||
if ("status" in result && result.status === "success") {
|
||||
const content = result.content as {
|
||||
agents: Agent[];
|
||||
totalCount: number;
|
||||
};
|
||||
setAgents(content.agents || []);
|
||||
setTotalCount(content.totalCount || 0);
|
||||
setError(null);
|
||||
} else if ("error" in result) {
|
||||
setError(result.error);
|
||||
setAgents([]);
|
||||
setTotalCount(0);
|
||||
} else {
|
||||
setAgents([]);
|
||||
setTotalCount(0);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error("Failed to fetch agents:", err);
|
||||
setError(err.message || "Failed to load agents");
|
||||
setAgents([]);
|
||||
setTotalCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
void fetchAgents();
|
||||
|
||||
// Poll for updates every 10 seconds
|
||||
const interval = setInterval(() => {
|
||||
void fetchAgents();
|
||||
}, 10000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [session, ideMessenger, currentOrg]);
|
||||
|
||||
// Helper function to check if an agent's repo matches any workspace repo
|
||||
const isAgentInCurrentWorkspace = (agent: Agent): boolean => {
|
||||
// Get all possible agent repo URLs (both repoUrl and metadata.github_repo)
|
||||
const agentUrls = [agent.repoUrl, agent.metadata?.github_repo]
|
||||
.filter((url): url is string => Boolean(url))
|
||||
.map(normalizeRepoUrl)
|
||||
.filter((url) => url !== "");
|
||||
|
||||
// Check if any of the agent URLs match any workspace URL
|
||||
return workspaces.some((workspace) =>
|
||||
agentUrls.some((agentUrl) => agentUrl === workspace.repoUrl),
|
||||
);
|
||||
};
|
||||
|
||||
// Helper function to get the agent's repository name (for display in tooltips)
|
||||
const getAgentRepoName = (agent: Agent): string | null => {
|
||||
// Try to extract repo name from the agent's repository URL
|
||||
// Handles URLs like: https://github.com/org/repo or git@github.com:org/repo.git
|
||||
const repoUrl = agent.metadata?.github_repo || agent.repoUrl;
|
||||
if (!repoUrl) return null;
|
||||
|
||||
try {
|
||||
// Remove .git suffix if present
|
||||
const cleanUrl = repoUrl.replace(/\.git$/, "");
|
||||
// Extract the last path segment (repo name)
|
||||
const parts = cleanUrl.split("/");
|
||||
const repoName = parts[parts.length - 1];
|
||||
return repoName || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenLocally = (agent: Agent, e: React.MouseEvent) => {
|
||||
e.stopPropagation(); // Prevent opening the agent detail page
|
||||
ideMessenger.post("openAgentLocally", { agentSessionId: agent.id });
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-error px-2 py-4 text-sm">
|
||||
Error loading agents: {error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (agents === null) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<ArrowPathIcon className="text-description-muted h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (agents.length === 0) {
|
||||
return (
|
||||
<div className="text-description-muted px-2 py-4 text-center text-sm">
|
||||
No background tasks yet. Submit a message above to create one.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="text-description-muted px-2 text-xs font-semibold">
|
||||
Background Tasks
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 px-2">
|
||||
{agents.map((agent) => {
|
||||
const isInWorkspace = isAgentInCurrentWorkspace(agent);
|
||||
const canOpenLocally = isInWorkspace;
|
||||
const agentRepoName = getAgentRepoName(agent);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={agent.id}
|
||||
className="border-command-border bg-input cursor-pointer rounded-md border p-3 shadow-md transition-colors hover:brightness-110"
|
||||
onClick={() => {
|
||||
// Open agent detail in browser
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `agents/${agent.id}`,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">
|
||||
{agent.name || "Unnamed Agent"}
|
||||
</div>
|
||||
<div className="text-description mt-0.5 truncate text-xs">
|
||||
{agent.metadata?.github_repo || agent.repoUrl}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-2 flex items-center gap-2">
|
||||
<AgentStatusBadge status={agent.status} />
|
||||
<Button
|
||||
onClick={(e) =>
|
||||
canOpenLocally && handleOpenLocally(agent, e)
|
||||
}
|
||||
disabled={!canOpenLocally}
|
||||
variant="icon"
|
||||
size="lg"
|
||||
title={
|
||||
canOpenLocally
|
||||
? "Open this agent workflow locally"
|
||||
: agentRepoName
|
||||
? `This agent is for a different repository (${agentRepoName}). Open that workspace to take over this workflow.`
|
||||
: "This agent is for a different repository. Open the correct workspace to take over this workflow."
|
||||
}
|
||||
>
|
||||
<PlayIcon className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-description-muted mt-1 text-xs">
|
||||
{formatRelativeTime(agent.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{totalCount > agents.length && (
|
||||
<div className="mt-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "agents",
|
||||
});
|
||||
}}
|
||||
variant="ghost"
|
||||
className="text-link my-0 w-full py-0 text-center text-sm font-medium hover:underline"
|
||||
>
|
||||
See all {totalCount} tasks →
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-description-muted px-2 py-4 text-center text-sm">
|
||||
Background agents are not available.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentStatusBadge({ status }: { status: string }) {
|
||||
const statusColors: Record<string, string> = {
|
||||
running: "border-success text-success",
|
||||
pending: "border-warning text-warning",
|
||||
creating: "border-info text-info",
|
||||
failure: "border-error text-error",
|
||||
suspended: "border-description text-description",
|
||||
};
|
||||
|
||||
const color = statusColors[status] || "border-description text-description";
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`bg-badge inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium ${color}`}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateString: string): string {
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
const timestamp = date.getTime();
|
||||
|
||||
// Guard against invalid dates (NaN)
|
||||
if (isNaN(timestamp)) {
|
||||
return dateString;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - timestamp;
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMs / 3600000);
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
|
||||
if (diffMins < 1) {
|
||||
return "just now";
|
||||
} else if (diffMins < 60) {
|
||||
return `${diffMins}m ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours}h ago`;
|
||||
} else {
|
||||
return `${diffDays}d ago`;
|
||||
}
|
||||
} catch {
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,4 @@
|
|||
import {
|
||||
ArrowPathIcon,
|
||||
ExclamationTriangleIcon,
|
||||
RocketLaunchIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { useCallback, useContext, useEffect, useState } from "react";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectCurrentOrg } from "../../redux/slices/profilesSlice";
|
||||
import { ArrowPathIcon } from "@heroicons/react/24/outline";
|
||||
import { AgentsList } from "./AgentsList";
|
||||
|
||||
interface BackgroundModeViewProps {
|
||||
|
|
@ -17,125 +8,8 @@ interface BackgroundModeViewProps {
|
|||
export function BackgroundModeView({
|
||||
isCreatingAgent = false,
|
||||
}: BackgroundModeViewProps) {
|
||||
const { session, login } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const [isLoggingIn, setIsLoggingIn] = useState(false);
|
||||
const [showGitHubSetup, setShowGitHubSetup] = useState(false);
|
||||
const [checkingGitHub, setCheckingGitHub] = useState(true);
|
||||
|
||||
const handleSignIn = useCallback(async () => {
|
||||
setIsLoggingIn(true);
|
||||
try {
|
||||
await login(false);
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
} finally {
|
||||
setIsLoggingIn(false);
|
||||
}
|
||||
}, [login]);
|
||||
|
||||
const handleOpenGitHubSettings = useCallback(() => {
|
||||
// Open the hub settings page for GitHub integration
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "settings/integrations/github",
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
}, [ideMessenger, currentOrg]);
|
||||
|
||||
// Check if user has GitHub installations when signed in
|
||||
useEffect(() => {
|
||||
async function checkGitHubAuth() {
|
||||
if (!session) {
|
||||
setCheckingGitHub(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setCheckingGitHub(true);
|
||||
// Try to list agents - if this fails with GitHub token error,
|
||||
// we know GitHub isn't connected
|
||||
const organizationId =
|
||||
currentOrg?.id !== "personal" ? currentOrg?.id : undefined;
|
||||
const result = await ideMessenger.request("listBackgroundAgents", {
|
||||
organizationId,
|
||||
});
|
||||
|
||||
// Check for error response
|
||||
if ("error" in result) {
|
||||
// Check if error is related to GitHub token
|
||||
if (
|
||||
result.error?.includes("GitHub token") ||
|
||||
result.error?.includes("GitHub App")
|
||||
) {
|
||||
setShowGitHubSetup(true);
|
||||
}
|
||||
} else {
|
||||
// If we got here without error, GitHub is connected
|
||||
setShowGitHubSetup(false);
|
||||
}
|
||||
} catch (error: any) {
|
||||
// Check if error is related to GitHub token
|
||||
if (
|
||||
error?.message?.includes("GitHub token") ||
|
||||
error?.message?.includes("GitHub App")
|
||||
) {
|
||||
setShowGitHubSetup(true);
|
||||
}
|
||||
} finally {
|
||||
setCheckingGitHub(false);
|
||||
}
|
||||
}
|
||||
|
||||
void checkGitHubAuth();
|
||||
}, [session, ideMessenger, currentOrg]);
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 px-4 py-8">
|
||||
<RocketLaunchIcon className="text-description-muted h-16 w-16" />
|
||||
<div className="max-w-md text-center">
|
||||
<h3 className="mb-2 text-lg font-semibold">Background Agents</h3>
|
||||
<p className="text-description mb-4 text-sm">
|
||||
Trigger long-running background agents that work on your codebase
|
||||
autonomously. Sign in to Continue to get started.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleSignIn}
|
||||
disabled={isLoggingIn}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary-hover rounded-lg px-6 py-2 disabled:opacity-50"
|
||||
>
|
||||
{isLoggingIn ? "Signing in..." : "Sign In to Continue"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4">
|
||||
{!checkingGitHub && showGitHubSetup && (
|
||||
<div className="mx-2 rounded-lg border border-yellow-200 bg-yellow-50 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<ExclamationTriangleIcon className="h-5 w-5 flex-shrink-0 text-yellow-600" />
|
||||
<div className="flex-1">
|
||||
<h4 className="text-sm font-semibold text-yellow-900">
|
||||
Connect GitHub
|
||||
</h4>
|
||||
<p className="mt-1 text-sm text-yellow-800">
|
||||
Background agents need access to your GitHub repositories.
|
||||
Connect your GitHub account to get started.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleOpenGitHubSettings}
|
||||
className="mt-3 rounded-md bg-yellow-600 px-4 py-2 text-sm font-medium text-white hover:bg-yellow-700"
|
||||
>
|
||||
Connect GitHub Account
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="px-2">
|
||||
<div className="text-description text-sm">
|
||||
Submit a task above to run a background agent. Your task will appear
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
import {
|
||||
ArrowDownOnSquareIcon,
|
||||
CloudIcon,
|
||||
PencilSquareIcon,
|
||||
TrashIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { BaseSessionMetadata } from "core";
|
||||
import type { RemoteSessionMetadata } from "core/control-plane/client";
|
||||
import { getUriPathBasename } from "core/util/uri";
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
|
@ -16,7 +14,6 @@ import { exitEdit } from "../../redux/thunks/edit";
|
|||
import {
|
||||
deleteSession,
|
||||
getSession,
|
||||
loadRemoteSession,
|
||||
loadSession,
|
||||
updateSession,
|
||||
} from "../../redux/thunks/session";
|
||||
|
|
@ -30,7 +27,7 @@ export function HistoryTableRow({
|
|||
sessionMetadata,
|
||||
index,
|
||||
}: {
|
||||
sessionMetadata: BaseSessionMetadata | RemoteSessionMetadata;
|
||||
sessionMetadata: BaseSessionMetadata;
|
||||
index: number;
|
||||
}) {
|
||||
const dispatch = useAppDispatch();
|
||||
|
|
@ -56,18 +53,10 @@ export function HistoryTableRow({
|
|||
});
|
||||
}
|
||||
};
|
||||
const isRemote = "isRemote" in sessionMetadata && sessionMetadata.isRemote;
|
||||
|
||||
const handleKeyUp = async (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
if (sessionTitleEditValue !== sessionMetadata.title) {
|
||||
// Don't allow editing remote sessions
|
||||
if (isRemote) {
|
||||
setSessionTitleEditValue(sessionMetadata.title);
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// imperfect solution of loading session just to update it
|
||||
// but fine for now, pretty low latency
|
||||
const currentSession = await getSession(
|
||||
|
|
@ -95,21 +84,6 @@ export function HistoryTableRow({
|
|||
data-testid={`history-row-${index}`}
|
||||
className="hover:bg-input relative mb-2 box-border flex w-full cursor-pointer overflow-hidden rounded-lg p-3"
|
||||
onClick={async () => {
|
||||
// Handle remote sessions - load remote session data
|
||||
if (isRemote) {
|
||||
const remoteSession = sessionMetadata as RemoteSessionMetadata;
|
||||
await dispatch(exitEdit({}));
|
||||
await dispatch(
|
||||
loadRemoteSession({
|
||||
remoteId: remoteSession.remoteId,
|
||||
saveCurrentSession: true,
|
||||
}),
|
||||
);
|
||||
navigate("/");
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle local sessions - load and navigate as before
|
||||
await dispatch(exitEdit({}));
|
||||
if (sessionMetadata.sessionId !== currentSessionId) {
|
||||
await dispatch(
|
||||
|
|
@ -140,11 +114,6 @@ export function HistoryTableRow({
|
|||
<span className="line-clamp-1 break-all text-sm font-semibold">
|
||||
{sessionMetadata.title}
|
||||
</span>
|
||||
{isRemote && (
|
||||
<span className="inline-flex items-center rounded-full bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800 dark:bg-blue-900/20 dark:text-blue-300">
|
||||
Remote
|
||||
</span>
|
||||
)}
|
||||
|
||||
{sessionMetadata.messageCount !== undefined && (
|
||||
<ToolTip
|
||||
|
|
@ -180,19 +149,7 @@ export function HistoryTableRow({
|
|||
|
||||
{hovered && !editing && (
|
||||
<td className="bg-input absolute right-2 top-12 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
|
||||
{isRemote ? (
|
||||
<HeaderButtonWithToolTip
|
||||
text="Open in browser"
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: `/agents/${sessionMetadata.remoteId}`,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<CloudIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
) : (
|
||||
{
|
||||
<>
|
||||
<HeaderButtonWithToolTip
|
||||
text="Edit"
|
||||
|
|
@ -224,7 +181,7 @@ export function HistoryTableRow({
|
|||
<TrashIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { BaseSessionMetadata } from "core";
|
||||
import type { RemoteSessionMetadata } from "core/control-plane/client";
|
||||
import MiniSearch from "minisearch";
|
||||
import React, {
|
||||
Fragment,
|
||||
|
|
@ -67,10 +66,7 @@ export function History() {
|
|||
|
||||
const platform = useMemo(() => getPlatform(), []);
|
||||
|
||||
const filteredAndSortedSessions: (
|
||||
| BaseSessionMetadata
|
||||
| RemoteSessionMetadata
|
||||
)[] = useMemo(() => {
|
||||
const filteredAndSortedSessions: BaseSessionMetadata[] = useMemo(() => {
|
||||
// 1. Exact phrase matching
|
||||
const exactResults = minisearch.search(searchTerm, {
|
||||
fuzzy: false,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { BaseSessionMetadata } from "core";
|
||||
import type { RemoteSessionMetadata } from "core/control-plane/client";
|
||||
|
||||
export const parseDate = (date: string): Date => {
|
||||
let dateObj = new Date(date);
|
||||
|
|
@ -11,11 +10,11 @@ export const parseDate = (date: string): Date => {
|
|||
|
||||
export interface SessionGroup {
|
||||
label: string;
|
||||
sessions: (BaseSessionMetadata | RemoteSessionMetadata)[];
|
||||
sessions: BaseSessionMetadata[];
|
||||
}
|
||||
|
||||
export const groupSessionsByDate = (
|
||||
sessions: (BaseSessionMetadata | RemoteSessionMetadata)[],
|
||||
sessions: BaseSessionMetadata[],
|
||||
): SessionGroup[] => {
|
||||
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
|
||||
const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { OnboardingModes } from "core/protocol/core";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { useContext, useEffect } from "react";
|
||||
import { Outlet, useLocation, useNavigate } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import { CustomScrollbarDiv } from ".";
|
||||
|
|
@ -25,7 +25,6 @@ import {
|
|||
} from "./OnboardingCard";
|
||||
import OSRContextMenu from "./OSRContextMenu";
|
||||
|
||||
|
||||
const LayoutTopDiv = styled(CustomScrollbarDiv)`
|
||||
height: 100%;
|
||||
position: relative;
|
||||
|
|
@ -40,7 +39,6 @@ const GridDiv = styled.div`
|
|||
`;
|
||||
|
||||
const Layout = () => {
|
||||
const [showStagingIndicator, setShowStagingIndicator] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const dispatch = useAppDispatch();
|
||||
|
|
@ -56,17 +54,6 @@ const Layout = () => {
|
|||
location.pathname === ROUTES.HOME ||
|
||||
location.pathname === ROUTES.HOME_INDEX;
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const response = await ideMessenger.request(
|
||||
"controlPlane/getEnvironment",
|
||||
undefined,
|
||||
);
|
||||
response.status === "success" &&
|
||||
setShowStagingIndicator(response.content.AUTH_TYPE.includes("staging"));
|
||||
})();
|
||||
}, []);
|
||||
|
||||
useWebviewListener(
|
||||
"newSession",
|
||||
async () => {
|
||||
|
|
@ -236,44 +223,35 @@ const Layout = () => {
|
|||
return (
|
||||
<LocalStorageProvider>
|
||||
<AuthProvider>
|
||||
<LayoutTopDiv>
|
||||
{showStagingIndicator && (
|
||||
<span
|
||||
title="Staging environment"
|
||||
className="absolute right-0 mx-1.5 h-1.5 w-1.5 rounded-full"
|
||||
style={{
|
||||
backgroundColor: "var(--vscode-list-warningForeground)",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<OSRContextMenu />
|
||||
<div
|
||||
style={{
|
||||
scrollbarGutter: "stable both-edges",
|
||||
minHeight: "100%",
|
||||
display: "grid",
|
||||
gridTemplateRows: "1fr auto",
|
||||
<LayoutTopDiv>
|
||||
<OSRContextMenu />
|
||||
<div
|
||||
style={{
|
||||
scrollbarGutter: "stable both-edges",
|
||||
minHeight: "100%",
|
||||
display: "grid",
|
||||
gridTemplateRows: "1fr auto",
|
||||
}}
|
||||
>
|
||||
<TextDialog
|
||||
showDialog={showDialog}
|
||||
onEnter={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
>
|
||||
<TextDialog
|
||||
showDialog={showDialog}
|
||||
onEnter={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
onClose={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
message={dialogMessage}
|
||||
/>
|
||||
onClose={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
message={dialogMessage}
|
||||
/>
|
||||
|
||||
<GridDiv>
|
||||
<Outlet />
|
||||
{/* The fatal error for chat is shown below input */}
|
||||
{!isHome && <FatalErrorIndicator />}
|
||||
</GridDiv>
|
||||
</div>
|
||||
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
|
||||
</LayoutTopDiv>
|
||||
<GridDiv>
|
||||
<Outlet />
|
||||
{/* The fatal error for chat is shown below input */}
|
||||
{!isHome && <FatalErrorIndicator />}
|
||||
</GridDiv>
|
||||
</div>
|
||||
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
|
||||
</LayoutTopDiv>
|
||||
</AuthProvider>
|
||||
</LocalStorageProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,5 @@
|
|||
import { useContext } from "react";
|
||||
import { Button, SecondaryButton } from "../..";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { selectCurrentOrg } from "../../../redux/slices/profilesSlice";
|
||||
import { selectFirstHubProfile } from "../../../redux/thunks/selectFirstHubProfile";
|
||||
import { SecondaryButton } from "../..";
|
||||
import ContinueLogo from "../../svg/ContinueLogo";
|
||||
import { useOnboardingCard } from "../hooks/useOnboardingCard";
|
||||
|
||||
export function OnboardingCardLanding({
|
||||
onSelectConfigure,
|
||||
|
|
@ -15,54 +8,18 @@ export function OnboardingCardLanding({
|
|||
onSelectConfigure: () => void;
|
||||
isDialog?: boolean;
|
||||
}) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const onboardingCard = useOnboardingCard();
|
||||
const auth = useAuth();
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
function onGetStarted() {
|
||||
void auth.login(true).then((success) => {
|
||||
if (success) {
|
||||
onboardingCard.close(isDialog);
|
||||
|
||||
// A new assistant is created when the account is created
|
||||
// We want to switch to this immediately
|
||||
void dispatch(selectFirstHubProfile());
|
||||
|
||||
ideMessenger.post("showTutorial", undefined);
|
||||
ideMessenger.post("showToast", ["info", "🎉 Welcome to Continue!"]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openBillingPage() {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "settings/billing",
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
onboardingCard.close(isDialog);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="xs:px-0 flex w-full max-w-full flex-col items-center justify-center px-4 text-center">
|
||||
<div className="xs:px-0 max-full flex w-full flex-col items-center justify-center px-4 text-center">
|
||||
<div className="xs:flex hidden">
|
||||
<ContinueLogo height={75} />
|
||||
</div>
|
||||
|
||||
<p className="mb-5 mt-0 w-full text-sm">
|
||||
Log in to Continue Hub to get started with AI-powered coding
|
||||
Get started with AI-powered coding by configuring your models
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={onGetStarted}
|
||||
className="mt-4 grid w-full grid-flow-col items-center gap-2"
|
||||
>
|
||||
Log in to Continue Hub
|
||||
</Button>
|
||||
|
||||
<SecondaryButton onClick={onSelectConfigure} className="w-full">
|
||||
Or, configure your own models
|
||||
Configure your models
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,49 +1,22 @@
|
|||
import { CheckIcon } from "@heroicons/react/24/outline";
|
||||
import { useContext } from "react";
|
||||
import { Button } from "../..";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import { selectFirstHubProfile } from "../../../redux/thunks/selectFirstHubProfile";
|
||||
import { useOnboardingCard } from "../hooks/useOnboardingCard";
|
||||
|
||||
/**
|
||||
* Models Add-On tab component with two-step onboarding:
|
||||
* 1. Create Account - Uses auth.login(true) to sign up and redirect back to IDE
|
||||
* 2. Purchase Credits - Opens /settings/billing to purchase credits
|
||||
* Models Add-On tab - directs users to configure their own models.
|
||||
*/
|
||||
export function OnboardingModelsAddOnTab() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { close } = useOnboardingCard();
|
||||
const auth = useAuth();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const isLoggedIn = !!auth.session;
|
||||
|
||||
function handleCreateAccount() {
|
||||
void auth.login(true).then((success) => {
|
||||
if (success) {
|
||||
// A new assistant is created when the account is created
|
||||
// Switch to it immediately
|
||||
void dispatch(selectFirstHubProfile());
|
||||
ideMessenger.post("showToast", ["info", "Account created!"]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handlePurchaseCredits() {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "settings/billing",
|
||||
function handleConfigureModels() {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
});
|
||||
close();
|
||||
}
|
||||
|
||||
function openPricingPage() {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "pricing",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center text-center">
|
||||
<div className="mb-4 flex flex-col items-center text-center">
|
||||
|
|
@ -52,77 +25,15 @@ export function OnboardingModelsAddOnTab() {
|
|||
</h2>
|
||||
|
||||
<span className="text-description text-xs">
|
||||
Use a{" "}
|
||||
<span
|
||||
className="cursor-pointer underline hover:brightness-125"
|
||||
onClick={openPricingPage}
|
||||
>
|
||||
variety of frontier models
|
||||
</span>{" "}
|
||||
at cost.
|
||||
Configure your own model providers to get started.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Vertical step indicators */}
|
||||
<div className="flex w-full flex-col gap-4">
|
||||
{/* Step 1: Create Account */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full text-xs font-medium ring-1 ring-inset ${
|
||||
isLoggedIn
|
||||
? "bg-green-500 text-white ring-green-500"
|
||||
: "text-foreground ring-foreground bg-transparent"
|
||||
}`}
|
||||
>
|
||||
{isLoggedIn ? <CheckIcon className="h-3 w-3" /> : "1"}
|
||||
</div>
|
||||
<span
|
||||
className={`text-sm ${isLoggedIn ? "text-description" : "text-foreground font-medium"}`}
|
||||
>
|
||||
Create Account
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="w-5 flex-shrink-0" />
|
||||
<Button
|
||||
onClick={handleCreateAccount}
|
||||
className="flex-1"
|
||||
disabled={isLoggedIn}
|
||||
>
|
||||
Create Account
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 2: Purchase Credits */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full text-xs font-medium ring-1 ring-inset ${
|
||||
isLoggedIn
|
||||
? "text-foreground ring-foreground bg-transparent"
|
||||
: "text-description ring-description bg-transparent"
|
||||
}`}
|
||||
>
|
||||
2
|
||||
</div>
|
||||
<span
|
||||
className={`text-sm ${isLoggedIn ? "text-foreground font-medium" : "text-description"}`}
|
||||
>
|
||||
Purchase Credits
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="w-5 flex-shrink-0" />
|
||||
<Button
|
||||
onClick={handlePurchaseCredits}
|
||||
className="flex-1"
|
||||
disabled={!isLoggedIn}
|
||||
>
|
||||
Purchase Credits
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleConfigureModels} className="flex-1">
|
||||
Configure Models
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,38 +0,0 @@
|
|||
import { GiftIcon } from "@heroicons/react/24/outline";
|
||||
import { CreditStatus } from "core/control-plane/client";
|
||||
import StarterCreditsPopover from "./StarterCreditsPopover";
|
||||
|
||||
interface FreeTrialButtonProps {
|
||||
creditStatus?: CreditStatus | null;
|
||||
refreshCreditStatus?: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use StarterCreditsPopover with a custom button/icon instead.
|
||||
* This component is kept for backward compatibility.
|
||||
*/
|
||||
export default function StarterCreditsButton({
|
||||
creditStatus,
|
||||
refreshCreditStatus,
|
||||
}: FreeTrialButtonProps) {
|
||||
return (
|
||||
<StarterCreditsPopover
|
||||
creditStatus={creditStatus}
|
||||
refreshCreditStatus={refreshCreditStatus}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
paddingLeft: "8px",
|
||||
paddingRight: "8px",
|
||||
paddingTop: "2px",
|
||||
paddingBottom: "2px",
|
||||
cursor: "pointer",
|
||||
transition: "color 200ms, background-color 200ms, box-shadow 200ms",
|
||||
display: "inline-flex",
|
||||
}}
|
||||
>
|
||||
<GiftIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
|
||||
</span>
|
||||
</StarterCreditsPopover>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,196 +0,0 @@
|
|||
import {
|
||||
ArrowPathIcon,
|
||||
GiftIcon,
|
||||
XMarkIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { CreditStatus } from "core/control-plane/client";
|
||||
import { useContext, useState } from "react";
|
||||
import { Button, SecondaryButton, vscButtonBackground } from ".";
|
||||
import { useAuth } from "../context/Auth";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
import { cn } from "../util/cn";
|
||||
import { setLocalStorage } from "../util/localStorage";
|
||||
import { ToolbarButtonWithTooltip } from "./StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip";
|
||||
import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui";
|
||||
|
||||
interface ProgressBarProps {
|
||||
label: string;
|
||||
current: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
function ProgressBar({ label, current, total }: ProgressBarProps) {
|
||||
const percentage = Math.min((current / total) * 100, 100);
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<div className="mb-1 flex justify-between text-xs">
|
||||
<span>{label}</span>
|
||||
<span>
|
||||
${(current / 100).toFixed(2)} / ${(total / 100).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 w-full rounded-full bg-gray-700">
|
||||
<div
|
||||
className="h-2 rounded-full transition-all duration-300"
|
||||
style={{
|
||||
width: `${percentage}%`,
|
||||
backgroundColor: vscButtonBackground,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface CreditStatusProgressBarsProps {
|
||||
creditStatus: CreditStatus;
|
||||
}
|
||||
|
||||
function CreditStatusProgressBar({
|
||||
creditStatus,
|
||||
}: CreditStatusProgressBarsProps) {
|
||||
const total = 50;
|
||||
const usage = total - (creditStatus.creditBalance ?? 0);
|
||||
|
||||
return (
|
||||
<ProgressBar label="Starter credits usage" current={usage} total={total} />
|
||||
);
|
||||
}
|
||||
|
||||
interface StarterCreditsPopoverProps {
|
||||
creditStatus?: CreditStatus | null;
|
||||
refreshCreditStatus?: () => Promise<void>;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function StarterCreditsPopover({
|
||||
creditStatus,
|
||||
refreshCreditStatus,
|
||||
children,
|
||||
}: StarterCreditsPopoverProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { refreshProfiles } = useAuth();
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
const onSetupApiKeys = async () => {
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "setup-models/api-keys",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const onPurchaseCredits = async () => {
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "settings/billing",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const onHideStarterCreditsUsage = async () => {
|
||||
// At this point the user doesn't want to see the credit usage UI, so we make sure this is gone right away
|
||||
setLocalStorage("hasExitedFreeTrial", true);
|
||||
};
|
||||
|
||||
const onRefresh = async () => {
|
||||
if (isRefreshing) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRefreshing(true);
|
||||
|
||||
const refreshCalls: Promise<unknown>[] = [
|
||||
refreshProfiles("Manual refresh from starter credits button"),
|
||||
];
|
||||
|
||||
if (refreshCreditStatus) {
|
||||
refreshCalls.push(refreshCreditStatus());
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all(refreshCalls);
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Listbox>
|
||||
<ListboxButton
|
||||
as="span"
|
||||
className="!m-0 !flex-none !gap-0 !border-none !bg-transparent !p-0"
|
||||
>
|
||||
{children}
|
||||
</ListboxButton>
|
||||
|
||||
<Transition>
|
||||
<ListboxOptions className="pb-0">
|
||||
<div className="relative max-w-96 px-4 pb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<GiftIcon className="h-4 w-4" />
|
||||
<h3 className="text-sm font-semibold">Starter credits</h3>
|
||||
</div>
|
||||
<div className="absolute right-3 top-3 flex items-center gap-1">
|
||||
<ToolbarButtonWithTooltip
|
||||
onClick={() => {
|
||||
void onRefresh();
|
||||
}}
|
||||
tooltipContent="Refresh credit usage"
|
||||
>
|
||||
<ArrowPathIcon
|
||||
className={cn("h-3 w-3", isRefreshing && "animate-spin-slow")}
|
||||
/>
|
||||
</ToolbarButtonWithTooltip>
|
||||
<ToolbarButtonWithTooltip
|
||||
onClick={onHideStarterCreditsUsage}
|
||||
tooltipContent="Hide starter credits usage"
|
||||
>
|
||||
<XMarkIcon className="h-3 w-3" />
|
||||
</ToolbarButtonWithTooltip>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<span className="text-description">
|
||||
You are currently using starter credits for Continue, which
|
||||
allows you to use a variety of frontier models at cost. Read
|
||||
more{" "}
|
||||
<span
|
||||
onClick={async () => {
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "pricing",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
``;
|
||||
}}
|
||||
className="cursor-pointer text-blue-400 underline hover:text-blue-300"
|
||||
>
|
||||
here
|
||||
</span>
|
||||
.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{!creditStatus ? (
|
||||
<div className="mb-4 flex items-center justify-center py-8">
|
||||
<span className="text-description">
|
||||
Loading credit usage...
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<CreditStatusProgressBar creditStatus={creditStatus} />
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex gap-2">
|
||||
<SecondaryButton className="flex-1" onClick={onSetupApiKeys}>
|
||||
Setup API Keys
|
||||
</SecondaryButton>
|
||||
<Button className="flex-1" onClick={onPurchaseCredits}>
|
||||
Purchase Credits
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ListboxOptions>
|
||||
</Transition>
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import {
|
||||
CubeIcon,
|
||||
ExclamationTriangleIcon,
|
||||
GiftIcon,
|
||||
PencilIcon,
|
||||
WrenchScrewdriverIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
|
|
@ -14,12 +13,10 @@ import {
|
|||
selectToolCallsByStatus,
|
||||
} from "../../../../redux/selectors/selectToolCalls";
|
||||
import { setSelectedProfile } from "../../../../redux/slices/profilesSlice";
|
||||
import StarterCreditsPopover from "../../../StarterCreditsPopover";
|
||||
import { ToolTip } from "../../../gui/Tooltip";
|
||||
import HoverItem from "../../InputToolbar/HoverItem";
|
||||
|
||||
import { useAuth } from "../../../../context/Auth";
|
||||
import { useCreditStatus } from "../../../../hooks/useCredits";
|
||||
import { CONFIG_ROUTES } from "../../../../util/navigation";
|
||||
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
|
||||
|
||||
|
|
@ -40,9 +37,6 @@ export function BlockSettingsTopToolbar() {
|
|||
|
||||
const shouldShowError = configError && configError?.length > 0;
|
||||
|
||||
const { creditStatus, isUsingFreeTrial, refreshCreditStatus } =
|
||||
useCreditStatus();
|
||||
|
||||
const handleRulesClick = () => {
|
||||
if (selectedProfile) {
|
||||
dispatch(setSelectedProfile(selectedProfile.id));
|
||||
|
|
@ -101,19 +95,6 @@ export function BlockSettingsTopToolbar() {
|
|||
|
||||
{!hasActiveContent && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{isUsingFreeTrial && (
|
||||
<ToolTip content="View remaining starter credits">
|
||||
<StarterCreditsPopover
|
||||
creditStatus={creditStatus}
|
||||
refreshCreditStatus={refreshCreditStatus}
|
||||
>
|
||||
<HoverItem px={2}>
|
||||
<GiftIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
|
||||
</HoverItem>
|
||||
</StarterCreditsPopover>
|
||||
</ToolTip>
|
||||
)}
|
||||
|
||||
<ToolTip content="Configure rules">
|
||||
<HoverItem onClick={handleRulesClick} px={2}>
|
||||
<PencilIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
|
||||
|
|
|
|||
|
|
@ -9,12 +9,7 @@ export function useEditBlock() {
|
|||
const { selectedProfile } = useAuth();
|
||||
|
||||
return (slug?: string, sourceFile?: string) => {
|
||||
if (slug) {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `${slug}/new-version`,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
} else if (sourceFile) {
|
||||
if (sourceFile) {
|
||||
ideMessenger.post("openFile", {
|
||||
path: sourceFile,
|
||||
});
|
||||
|
|
@ -25,16 +20,7 @@ export function useEditBlock() {
|
|||
ideMessenger.post("openFile", {
|
||||
path: selectedProfile.uri,
|
||||
});
|
||||
} else if (
|
||||
selectedProfile?.fullSlug?.ownerSlug &&
|
||||
selectedProfile?.fullSlug.packageSlug
|
||||
) {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}/new-version`,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
} else {
|
||||
// Local etc
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,34 +1,17 @@
|
|||
import {
|
||||
ProfileDescription,
|
||||
SerializedOrgWithProfiles,
|
||||
} from "core/config/ProfileLifecycleManager";
|
||||
import { ControlPlaneSessionInfo } from "core/control-plane/AuthTypes";
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useWebviewListener } from "../hooks/useWebviewListener";
|
||||
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
|
||||
import React, { createContext, useCallback, useContext } from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import { setConfigLoading } from "../redux/slices/configSlice";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
selectSelectedProfile,
|
||||
setOrganizations,
|
||||
setSelectedOrgId,
|
||||
} from "../redux/slices/profilesSlice";
|
||||
import { IdeMessengerContext } from "./IdeMessenger";
|
||||
|
||||
interface AuthContextType {
|
||||
session: ControlPlaneSessionInfo | undefined;
|
||||
logout: () => void;
|
||||
login: (useOnboarding: boolean) => Promise<boolean>;
|
||||
selectedProfile: ProfileDescription | null;
|
||||
profiles: ProfileDescription[] | null;
|
||||
refreshProfiles: (reason?: string) => Promise<void>;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
|
@ -38,69 +21,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
}) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
// Session
|
||||
const [session, setSession] = useState<ControlPlaneSessionInfo | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Orgs
|
||||
const orgs = useAppSelector((store) => store.profiles.organizations);
|
||||
|
||||
// Profiles
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const selectedProfile = useAppSelector(selectSelectedProfile);
|
||||
|
||||
const login: AuthContextType["login"] = async (useOnboarding: boolean) => {
|
||||
try {
|
||||
const result = await ideMessenger.request("getControlPlaneSessionInfo", {
|
||||
silent: false,
|
||||
useOnboarding,
|
||||
});
|
||||
|
||||
if (result.status === "error") {
|
||||
console.error("Login failed:", result.error);
|
||||
return false;
|
||||
}
|
||||
|
||||
const session = result.content;
|
||||
setSession(session);
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error("Login request failed:", error);
|
||||
// Let the error propagate so the caller can handle it
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
ideMessenger.post("logoutOfControlPlane", undefined);
|
||||
dispatch(setOrganizations(orgs.filter((org) => org.id === "personal")));
|
||||
dispatch(setSelectedOrgId("personal"));
|
||||
setSession(undefined);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
async function init() {
|
||||
const result = await ideMessenger.request("getControlPlaneSessionInfo", {
|
||||
silent: true,
|
||||
useOnboarding: false,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
setSession(result.content);
|
||||
}
|
||||
}
|
||||
void init();
|
||||
}, []);
|
||||
|
||||
useWebviewListener(
|
||||
"sessionUpdate",
|
||||
async (data) => {
|
||||
setSession(data.sessionInfo);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const refreshProfiles = useCallback(
|
||||
async (reason?: string) => {
|
||||
try {
|
||||
|
|
@ -122,13 +47,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
session,
|
||||
logout,
|
||||
login,
|
||||
selectedProfile,
|
||||
profiles: currentOrg?.profiles ?? [],
|
||||
refreshProfiles,
|
||||
organizations: orgs,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { ChatMessage, IDE, PromptLog } from "core";
|
||||
import { AuthType } from "core/control-plane/AuthTypes";
|
||||
import {
|
||||
FromWebviewProtocol,
|
||||
ToCoreProtocol,
|
||||
|
|
@ -33,12 +32,6 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
|||
contents: "Current file contents",
|
||||
path: "file:///Users/user/workspace1/current_file.py",
|
||||
},
|
||||
"controlPlane/getCreditStatus": {
|
||||
optedInToFreeTrial: false,
|
||||
creditBalance: 0,
|
||||
hasCredits: false,
|
||||
hasPurchasedCredits: false,
|
||||
},
|
||||
getWorkspaceDirs: [
|
||||
"file:///Users/user/workspace1",
|
||||
"file:///Users/user/workspace2",
|
||||
|
|
@ -46,14 +39,6 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
|||
"history/list": [],
|
||||
"docs/getIndexedPages": [],
|
||||
"history/save": undefined,
|
||||
getControlPlaneSessionInfo: {
|
||||
AUTH_TYPE: AuthType.WorkOsStaging,
|
||||
accessToken: "",
|
||||
account: {
|
||||
label: "",
|
||||
id: "",
|
||||
},
|
||||
},
|
||||
"config/getSerializedProfileInfo": {
|
||||
organizations: [
|
||||
{
|
||||
|
|
@ -124,7 +109,6 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
|||
},
|
||||
},
|
||||
],
|
||||
listBackgroundAgents: { agents: [], totalCount: 0 },
|
||||
};
|
||||
|
||||
const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = {
|
||||
|
|
|
|||
|
|
@ -227,11 +227,6 @@ function ParallelListeners() {
|
|||
void dispatch(cancelStream());
|
||||
});
|
||||
|
||||
useWebviewListener("loadAgentSession", async (data) => {
|
||||
dispatch(newSession(data.session));
|
||||
dispatch(setMode("agent"));
|
||||
});
|
||||
|
||||
useWebviewListener("setTTSActive", async (status) => {
|
||||
dispatch(setTTSActive(status));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
import { usesCreditsBasedApiKey } from "core/config/usesFreeTrialApiKey";
|
||||
import { CreditStatus } from "core/control-plane/client";
|
||||
import { isOutOfStarterCredits } from "core/llm/utils/starterCredits";
|
||||
import { useCallback, useContext, useEffect, useState } from "react";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
import { useAppSelector } from "../redux/hooks";
|
||||
import { getLocalStorage } from "../util/localStorage";
|
||||
|
||||
export function useCreditStatus() {
|
||||
const config = useAppSelector((state) => state.config.config);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const [creditStatus, setCreditStatus] = useState<CreditStatus | null>(null);
|
||||
|
||||
const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial");
|
||||
const usingCreditsBasedApiKey = usesCreditsBasedApiKey(config);
|
||||
const isUsingFreeTrial = usingCreditsBasedApiKey && !hasExitedFreeTrial;
|
||||
const outOfStarterCredits = creditStatus
|
||||
? isOutOfStarterCredits(usingCreditsBasedApiKey, creditStatus)
|
||||
: false;
|
||||
|
||||
const refreshCreditStatus = useCallback(async () => {
|
||||
try {
|
||||
const resp = await ideMessenger.request(
|
||||
"controlPlane/getCreditStatus",
|
||||
undefined,
|
||||
);
|
||||
if (resp.status === "success") {
|
||||
setCreditStatus(resp.content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh credit status", error);
|
||||
}
|
||||
}, [ideMessenger]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshCreditStatus();
|
||||
|
||||
let intervalId: NodeJS.Timeout | null = null;
|
||||
|
||||
if (isUsingFreeTrial) {
|
||||
intervalId = setInterval(() => {
|
||||
void refreshCreditStatus();
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
}
|
||||
};
|
||||
}, [isUsingFreeTrial, refreshCreditStatus]);
|
||||
|
||||
return {
|
||||
creditStatus,
|
||||
outOfStarterCredits,
|
||||
isUsingFreeTrial,
|
||||
refreshCreditStatus,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import ToggleSwitch from "../../../components/gui/Switch";
|
||||
interface ContinueFeaturesMenuProps {
|
||||
enableStaticContextualization: boolean;
|
||||
handleEnableStaticContextualizationToggle: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export function ContinueFeaturesMenu({
|
||||
enableStaticContextualization,
|
||||
handleEnableStaticContextualizationToggle,
|
||||
}: ContinueFeaturesMenuProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-y-4">
|
||||
<div className="my-2 text-center text-xs font-medium text-slate-400">
|
||||
🚧 INTERNAL SETTINGS 🚧
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-y-4">
|
||||
<ToggleSwitch
|
||||
isToggled={enableStaticContextualization}
|
||||
onToggle={() =>
|
||||
handleEnableStaticContextualizationToggle(
|
||||
!enableStaticContextualization,
|
||||
)
|
||||
}
|
||||
text="Use Static Contextualization"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,107 +1,4 @@
|
|||
import {
|
||||
ArrowRightStartOnRectangleIcon,
|
||||
Cog6ToothIcon,
|
||||
UserCircleIcon as UserCircleIconOutline,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { UserCircleIcon as UserCircleIconSolid } from "@heroicons/react/24/solid";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useContext } from "react";
|
||||
import { ToolTip } from "../../../../components/gui/Tooltip";
|
||||
import {
|
||||
Button,
|
||||
Listbox,
|
||||
ListboxButton,
|
||||
ListboxOption,
|
||||
ListboxOptions,
|
||||
} from "../../../../components/ui";
|
||||
import { Divider } from "../../../../components/ui/Divider";
|
||||
import { useAuth } from "../../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
|
||||
|
||||
// Account dropdown removed - no longer needed without Hub auth
|
||||
export function AccountDropdown() {
|
||||
const { session, logout, login } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
if (isOnPremSession(session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<ToolTip content="Log in" className="text-xs md:!hidden">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="text-description flex w-full flex-row items-center gap-2 px-2 py-1.5"
|
||||
onClick={() => login(false)}
|
||||
>
|
||||
<UserCircleIconOutline className="xs:h-4 xs:w-4 h-3 w-3 flex-shrink-0" />
|
||||
<span className="text-description hidden text-xs md:block">
|
||||
Log in
|
||||
</span>
|
||||
</Button>
|
||||
</ToolTip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Listbox>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<ListboxButton
|
||||
className={`text-description w-full justify-start gap-1 border-none px-2 py-1.5 ${
|
||||
open ? "bg-input" : "hover:bg-input bg-inherit"
|
||||
}`}
|
||||
>
|
||||
<UserCircleIconSolid className="xs:h-4 xs:w-4 h-3 w-3 flex-shrink-0" />
|
||||
<div className="ml-1 flex min-w-0 flex-1 flex-col items-start overflow-hidden">
|
||||
<span className="w-full truncate text-xs font-medium hover:brightness-110">
|
||||
{session.account.label}
|
||||
</span>
|
||||
<span className="text-description-muted w-full truncate text-xs">
|
||||
{session.account.id}
|
||||
</span>
|
||||
</div>
|
||||
</ListboxButton>
|
||||
<ListboxOptions anchor="right end">
|
||||
{/* Account info section for small screens */}
|
||||
<div className="md:hidden">
|
||||
<div className="flex items-center gap-2 px-2 py-1">
|
||||
<UserCircleIconSolid className="h-5 w-5 flex-shrink-0" />
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-xs font-medium">
|
||||
{session.account.label}
|
||||
</span>
|
||||
<span className="text-description-muted truncate text-xs">
|
||||
{session.account.id}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
</div>
|
||||
|
||||
<ListboxOption
|
||||
onClick={() =>
|
||||
ideMessenger.post("openUrl", "https://continue.dev/settings")
|
||||
}
|
||||
value="manage-account"
|
||||
>
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<Cog6ToothIcon className="h-3.5 w-3.5" />
|
||||
<span>Manage Account</span>
|
||||
</div>
|
||||
</ListboxOption>
|
||||
|
||||
<ListboxOption onClick={logout} value="logout">
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<ArrowRightStartOnRectangleIcon className="h-3.5 w-3.5" />
|
||||
<span>Log out</span>
|
||||
</div>
|
||||
</ListboxOption>
|
||||
</ListboxOptions>
|
||||
</>
|
||||
)}
|
||||
</Listbox>
|
||||
</div>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import React from "react";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { AssistantAndOrgListbox } from "../../components/AssistantAndOrgListbox";
|
||||
import Alert from "../../components/gui/Alert";
|
||||
import { Divider } from "../../components/ui/Divider";
|
||||
import { TabGroup } from "../../components/ui/TabGroup";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { useNavigationListener } from "../../hooks/useNavigationListener";
|
||||
import { bottomTabSections, getAllTabs, topTabSections } from "./configTabs";
|
||||
import { CliInstallBanner } from "../../components/CliInstallBanner";
|
||||
|
|
@ -16,11 +13,8 @@ function ConfigPage() {
|
|||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const activeTab = searchParams.get("tab") || "settings";
|
||||
const { session, organizations } = useAuth();
|
||||
|
||||
const allTabs = getAllTabs();
|
||||
const shouldRenderOrgInfo =
|
||||
session && organizations.length > 1 && !isOnPremSession(session);
|
||||
|
||||
const handleTabClick = (tabId: string) => {
|
||||
if (tabId === "back") {
|
||||
|
|
@ -35,7 +29,7 @@ function ConfigPage() {
|
|||
{/* Vertical Sidebar - full height */}
|
||||
<div className="bg-vsc-background flex w-12 flex-shrink-0 flex-col border-0 md:w-40">
|
||||
<div className="border-r-border flex flex-1 flex-col overflow-y-auto border-b-0 border-l-0 border-r-2 border-t-0 border-solid p-2 text-xs">
|
||||
{topTabSections.map((section, index) => (
|
||||
{topTabSections.map((section) => (
|
||||
<React.Fragment key={section.id}>
|
||||
<TabGroup
|
||||
tabs={section.tabs}
|
||||
|
|
@ -45,12 +39,6 @@ function ConfigPage() {
|
|||
showBottomDivider={section.showBottomDivider}
|
||||
className={section.className}
|
||||
/>
|
||||
{index === 0 && shouldRenderOrgInfo && (
|
||||
<>
|
||||
<Divider />
|
||||
<AssistantAndOrgListbox variant="sidebar" />
|
||||
</>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,25 +41,16 @@ export function ModelsSection() {
|
|||
const handleConfigureModel = useEditModel();
|
||||
|
||||
function handleAddModel() {
|
||||
const isLocal = selectedProfile?.profileType === "local";
|
||||
|
||||
if (isLocal) {
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(
|
||||
setDialogMessage(
|
||||
<AddModelForm
|
||||
onDone={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "?type=models",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
}
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(
|
||||
setDialogMessage(
|
||||
<AddModelForm
|
||||
onDone={() => {
|
||||
dispatch(setShowDialog(false));
|
||||
}}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,105 +1,17 @@
|
|||
import { Cog6ToothIcon } from "@heroicons/react/24/outline";
|
||||
import { BuildingOfficeIcon, UserIcon } from "@heroicons/react/24/solid";
|
||||
import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useContext } from "react";
|
||||
import { Button, Card, Divider } from "../../../components/ui";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { ConfigHeader } from "../components/ConfigHeader";
|
||||
|
||||
function getOrgIcon(org: { name: string; iconUrl?: string | null }) {
|
||||
if (org.iconUrl) {
|
||||
return (
|
||||
<img
|
||||
src={org.iconUrl}
|
||||
alt=""
|
||||
className="h-5 w-5 flex-shrink-0 rounded-full"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const IconComponent = org.name === "Personal" ? UserIcon : BuildingOfficeIcon;
|
||||
return <IconComponent className="h-5 w-5 flex-shrink-0" />;
|
||||
}
|
||||
import { Card } from "../../../components/ui";
|
||||
|
||||
export function OrganizationsSection() {
|
||||
const { organizations, session } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const shouldRenderOrgInfo =
|
||||
session && organizations.length > 1 && !isOnPremSession(session);
|
||||
|
||||
function handleAddOrganization() {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/organizations/new",
|
||||
});
|
||||
}
|
||||
|
||||
function handleConfigureOrganization(org: SerializedOrgWithProfiles) {
|
||||
let path: string;
|
||||
if (org.id === "personal" || org.slug === undefined) {
|
||||
path = "/settings";
|
||||
} else {
|
||||
path = `/organizations/${org.slug}/settings`;
|
||||
}
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path,
|
||||
});
|
||||
}
|
||||
|
||||
if (!shouldRenderOrgInfo) {
|
||||
return (
|
||||
<>
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
<h2 className="mb-0 text-xl font-semibold">Organizations</h2>
|
||||
</div>
|
||||
</div>
|
||||
<Card>
|
||||
<div className="text-description py-8 text-center text-sm">
|
||||
Organizations are only available with cloud accounts. Sign in to
|
||||
manage organizations.
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConfigHeader
|
||||
title="Organizations"
|
||||
onAddClick={handleAddOrganization}
|
||||
addButtonTooltip="Add organization"
|
||||
/>
|
||||
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
<h2 className="mb-0 text-xl font-semibold">Organizations</h2>
|
||||
</div>
|
||||
</div>
|
||||
<Card>
|
||||
{organizations.map((organization, index) => (
|
||||
<div key={organization.id}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-5 w-5 flex-shrink-0 items-center justify-center">
|
||||
{getOrgIcon(organization)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="my-2 text-sm font-medium">
|
||||
{organization.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleConfigureOrganization(organization)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-description-muted hover:enabled:text-foreground my-0 h-6 w-6 p-0"
|
||||
>
|
||||
<Cog6ToothIcon className="h-4 w-4 flex-shrink-0" />
|
||||
</Button>
|
||||
</div>
|
||||
{index < organizations.length - 1 && <Divider />}
|
||||
</div>
|
||||
))}
|
||||
<div className="text-description py-8 text-center text-sm">
|
||||
Organizations are not available in this version.
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -299,16 +299,9 @@ function PromptsSubSection() {
|
|||
};
|
||||
|
||||
const handleAddPrompt = () => {
|
||||
if (isLocal) {
|
||||
void ideMessenger.request("config/addLocalWorkspaceBlock", {
|
||||
blockType: "prompts",
|
||||
});
|
||||
} else {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "?type=prompts",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
}
|
||||
void ideMessenger.request("config/addLocalWorkspaceBlock", {
|
||||
blockType: "prompts",
|
||||
});
|
||||
};
|
||||
|
||||
const sortedCommands = useMemo(() => {
|
||||
|
|
@ -437,21 +430,14 @@ function RulesSubSection() {
|
|||
|
||||
const handleAddRule = (mode?: string) => {
|
||||
const currentMode = mode || globalRulesMode;
|
||||
if (isLocal) {
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(
|
||||
setDialogMessage(
|
||||
<AddRuleDialog
|
||||
mode={currentMode === "global" ? "global" : "workspace"}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/hub?type=rules",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
}
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(
|
||||
setDialogMessage(
|
||||
<AddRuleDialog
|
||||
mode={currentMode === "global" ? "global" : "workspace"}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleOptionClick = (value: string) => {
|
||||
|
|
|
|||
|
|
@ -454,16 +454,9 @@ export function ToolsSection() {
|
|||
}, [servers, selectedProfile]);
|
||||
|
||||
const handleAddMcpServer = () => {
|
||||
if (isLocal) {
|
||||
void ideMessenger.request("config/addLocalWorkspaceBlock", {
|
||||
blockType: "mcpServers",
|
||||
});
|
||||
} else {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "?type=mcpServers",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
}
|
||||
void ideMessenger.request("config/addLocalWorkspaceBlock", {
|
||||
blockType: "mcpServers",
|
||||
});
|
||||
};
|
||||
|
||||
const allToolsOff = useMemo(() => {
|
||||
|
|
|
|||
|
|
@ -2,18 +2,14 @@ import {
|
|||
SharedConfigSchema,
|
||||
modifyAnyConfigWithSharedConfig,
|
||||
} from "core/config/sharedConfig";
|
||||
import { HubSessionInfo } from "core/control-plane/AuthTypes";
|
||||
import { isContinueTeamMember } from "core/util/isContinueTeamMember";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { Card, Toggle, useFontSize } from "../../../components/ui";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { updateConfig } from "../../../redux/slices/configSlice";
|
||||
import { selectCurrentOrg } from "../../../redux/slices/profilesSlice";
|
||||
import { setLocalStorage } from "../../../util/localStorage";
|
||||
import { ConfigHeader } from "../components/ConfigHeader";
|
||||
import { ContinueFeaturesMenu } from "../components/ContinueFeaturesMenu";
|
||||
import { UserSetting } from "../components/UserSetting";
|
||||
|
||||
export function UserSettingsSection() {
|
||||
|
|
@ -24,7 +20,6 @@ export function UserSettingsSection() {
|
|||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
|
||||
const [showExperimental, setShowExperimental] = useState(false);
|
||||
const { session } = useAuth();
|
||||
|
||||
function handleUpdate(sharedConfig: SharedConfigSchema) {
|
||||
// Optimistic update
|
||||
|
|
@ -53,10 +48,6 @@ export function UserSettingsSection() {
|
|||
// Workspace prompts
|
||||
const promptPath = config.experimental?.promptPath || "";
|
||||
|
||||
const handleEnableStaticContextualizationToggle = (value: boolean) => {
|
||||
handleUpdate({ enableStaticContextualization: value });
|
||||
};
|
||||
|
||||
// TODO defaults are in multiple places, should be consolidated and probably not explicit here
|
||||
const showSessionTabs = config.ui?.showSessionTabs ?? false;
|
||||
const continueAfterToolRejection =
|
||||
|
|
@ -74,9 +65,6 @@ export function UserSettingsSection() {
|
|||
config.experimental?.onlyUseSystemMessageTools ?? false;
|
||||
const codebaseToolCallingOnly =
|
||||
config.experimental?.codebaseToolCallingOnly ?? false;
|
||||
const enableStaticContextualization =
|
||||
config.experimental?.enableStaticContextualization ?? false;
|
||||
|
||||
const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
|
||||
|
||||
const useAutocompleteMultilineCompletions =
|
||||
|
|
@ -97,10 +85,6 @@ export function UserSettingsSection() {
|
|||
});
|
||||
};
|
||||
|
||||
const hasContinueEmail = isContinueTeamMember(
|
||||
(session as HubSessionInfo)?.account?.id,
|
||||
);
|
||||
|
||||
const disableTelemetryToggle =
|
||||
currentOrg?.policy?.allowAnonymousTelemetry === false;
|
||||
|
||||
|
|
@ -321,17 +305,6 @@ export function UserSettingsSection() {
|
|||
handleUpdate({ continueAfterToolRejection: value })
|
||||
}
|
||||
/>
|
||||
|
||||
{hasContinueEmail && (
|
||||
<ContinueFeaturesMenu
|
||||
enableStaticContextualization={
|
||||
enableStaticContextualization
|
||||
}
|
||||
handleEnableStaticContextualizationToggle={
|
||||
handleEnableStaticContextualizationToggle
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Toggle>
|
||||
</Card>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue