feat: strip more hub config

This commit is contained in:
Patrick Erichsen 2026-03-23 17:32:28 -07:00
parent 2485dc0128
commit 92b99cad90
130 changed files with 443 additions and 6029 deletions

View file

@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient`
- uses configuration via a `ConfigHandler`, which is stored in the global directory
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
@ -25,7 +25,6 @@ Jest testing setup includes
@core/test/fixtures.ts provides fixtures that should be used in tests to emulate extension behavior
- import `testIde` for IDE/workspace operations
- import `testConfigHandler` for any ConfigHandler needs
- import `testControlPlaneClient` for control plane operations
- import `ideSettingsPromise` for any IdeSettings needs
- import `testLLM` for any ILLM/BaseLLM needs. Set the `completion` property to the desired completion, e.g. `testLLM.completion = "Desired completion";`

2
.idea/gradle.xml generated
View file

@ -5,7 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="gradleHome" value="/usr/local/Cellar/gradle/8.13/libexec" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

6
.vscode/launch.json vendored
View file

@ -142,9 +142,6 @@
"env": {
"NODE_ENV": "development",
"USE_VERCEL_AI_SDK_ANTHROPIC": "true"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
@ -172,9 +169,6 @@
"env": {
"NODE_ENV": "development",
"CONTINUE_USE_BEDROCK": "1"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",

30
TESTING.md Normal file
View file

@ -0,0 +1,30 @@
# PR #2 Testing Checklist — Strip Hub/Mission Control Code
## Critical
- [x] **Extension cold start** — Launch VS Code with the extension. No errors in Output panel ("Continue" channel) or Dev Tools console. _(Found and fixed `message.includes` crash in `webviewProtocol.ts` + removed dead proxy-server error handling block.)_
- [x] **Fresh install onboarding** — Delete/rename `~/.continue/config.yaml`, restart. Onboarding card shows "Configure your models" (no Hub sign-in). _(Removed "Credits" tab, fixed Ollama link padding, title font sizes, and "Google Gemini API API key" duplicate.)_
- [x] **Existing config loads** — With existing `config.yaml`, models/context providers/MCP servers all load.
- [x] **API key resolution from `.env`** — Models using secrets from `~/.continue/.env` or workspace `.env` authenticate and respond.
- [x] **Config reload** — Edit `config.yaml` while running, changes picked up without restart.
## High Priority
- [x] **Profile/assistant switching** — Assistant dropdown shows only local profiles. Switching works. _(Fixed missing profiles list in GUI by adding `profiles` to configUpdate message. Also fixed initial Redux state label and adjusted dropdown styling.)_
- [x] **Compilation** — `tsc --noEmit` passes for core, GUI, and VS Code extension.
- [x] **Test suite** — Vitest tests pass: `LocalPlatformClient` (8), `LocalProfileLoader` (2), `doLoadConfig` (2) — all 12 pass.
- [x] **No telemetry network calls** — Dev Tools Network tab shows no requests to `posthog.com` or `sentry.io`.
- [x] **Agent mode tools** — Start an agent conversation, all tools load correctly.
## Medium Priority
- [x] **MCP servers connect** — Configured MCP servers connect and tools appear.
- [x] **Local blocks in YAML** — Local model block files in `.continue/models/` auto-merge into config correctly.
- [x] **Background mode view** — N/A, component removed from UI routing. No way to navigate to it.
- [x] **Keyboard shortcut `Cmd+Shift+'`** — Toggles between configs without errors.
- [x] **Config settings page** — Settings page renders cleanly, no Account dropdown or Organizations tab. _(Removed GitHub issue/community links.)_
## Low Priority
- [x] **"Main Config" naming** — Fresh installs show "Main Config" as default profile name.
- [ ] **IntelliJ startup** — IntelliJ plugin has pre-existing issues: `Unknown message type: configUpdate/subprocess`. Not a regression from this PR, needs separate fix.

View file

@ -282,8 +282,6 @@ export class CompletionProvider {
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: new Date().toISOString(),
profileType:
this.configHandler.currentProfile?.profileDescription.profileType,
...helper.options,
};

View file

@ -119,8 +119,6 @@ export class AutocompleteLoggingService {
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
profileType: restOfOutcome.profileType,
};
}
}

View file

@ -43,5 +43,4 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
uniqueId: string;
timestamp: string;
enabledStaticContextualization?: boolean;
profileType?: "local" | "platform" | "control-plane";
}

View file

@ -19,11 +19,8 @@ import {
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import {
OrganizationDescription,
OrgWithProfiles,
ProfileDescription,
ProfileLifecycleManager,
SerializedOrgWithProfiles,
} from "./ProfileLifecycleManager.js";
export type { ProfileDescription };
@ -34,9 +31,12 @@ export class ConfigHandler {
private readonly globalContext = new GlobalContext();
private globalLocalProfileManager: ProfileLifecycleManager;
private organizations: OrgWithProfiles[] = [];
private profiles: ProfileLifecycleManager[] = [];
get profileDescriptions(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
}
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles | null;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
@ -58,9 +58,8 @@ export class ConfigHandler {
this.ide,
);
this.currentOrg = null;
this.currentProfile = null;
this.organizations = [];
this.profiles = [];
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
@ -80,11 +79,6 @@ export class ConfigHandler {
return this.workspaceDirs.join("&");
}
async getProfileKey(orgId: string) {
const workspaceId = await this.getWorkspaceId();
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit(reason: string) {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
@ -95,44 +89,39 @@ export class ConfigHandler {
);
try {
const { orgs, errors } = await this.getOrgs();
const { profiles, errors } = await this.loadProfiles();
// Figure out selected org
// Figure out selected profile
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const currentSelection = selectedProfiles[workspaceId];
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback: OrgWithProfiles | null =
firstNonPersonal ?? orgs[0] ?? null;
const fallback = profiles.length > 0 ? profiles[0] : null;
let selectedOrg: OrgWithProfiles | null;
let selectedProfile: ProfileLifecycleManager | null;
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
selectedProfile = match ?? fallback;
} else {
selectedOrg = fallback;
selectedProfile = fallback;
}
if (signal.aborted) {
return;
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg?.id,
});
if (selectedProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[workspaceId]: selectedProfile.profileDescription.id,
});
}
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg?.currentProfile;
this.profiles = profiles;
this.currentProfile = selectedProfile;
await this.reloadConfig(reason, errors);
} catch (e) {
@ -145,96 +134,29 @@ export class ConfigHandler {
}
}
private async getOrgs(): Promise<{
orgs: OrgWithProfiles[];
private async loadProfiles(): Promise<{
profiles: ProfileLifecycleManager[];
errors?: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
try {
const orgs = [await this.getLocalOrg()];
return { orgs };
const profiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return { profiles };
} catch (e) {
errors.push({
fatal: true,
message: `Error loading local assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
return {
orgs: [],
profiles: [],
errors,
};
}
}
getSerializedOrgs(): SerializedOrgWithProfiles[] {
return this.organizations.map((org) => ({
iconUrl: org.iconUrl,
id: org.id,
name: org.name,
slug: org.slug,
profiles: org.profiles.map((profile) => profile.profileDescription),
selectedProfileId: org.currentProfile?.profileDescription.id || null,
}));
}
private PERSONAL_ORG_DESC: OrganizationDescription = {
iconUrl: "",
id: "personal",
name: "Personal",
slug: undefined,
};
private async getLocalOrg() {
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
}
private async rectifyProfilesForOrg(
org: OrganizationDescription,
profiles: ProfileLifecycleManager[],
): Promise<OrgWithProfiles> {
const profileKey = await this.getProfileKey(org.id);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const currentSelection = selectedProfiles[profileKey];
const firstNonLocal = profiles.find(
(profile) => profile.profileDescription.profileType !== "local",
);
const fallback =
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
let currentProfile: ProfileLifecycleManager | null;
if (currentSelection) {
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
if (match) {
currentProfile = match;
} else {
currentProfile = fallback;
}
} else {
currentProfile = fallback;
}
if (currentProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: currentProfile.profileDescription.id,
});
}
return {
...org,
profiles,
currentProfile,
};
}
async getLocalProfiles(options: LoadAssistantFilesOptions) {
/**
* Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
@ -282,58 +204,27 @@ export class ConfigHandler {
await this.cascadeInit("IDE settings update");
}
// Org id: check id validity, save selection, switch and reload
async setSelectedOrgId(orgId: string, profileId?: string) {
if (orgId === this.currentOrg?.id) {
return;
}
const org = this.organizations.find((org) => org.id === orgId);
if (!org) {
throw new Error(`Org ${orgId} not found`);
}
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: org.id,
});
this.currentOrg = org;
if (profileId) {
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig("Selected org changed");
}
}
// Profile id: check id validity, save selection, switch and reload
async setSelectedProfileId(profileId: string) {
if (!this.currentOrg) {
throw new Error(`No org selected`);
}
if (
this.currentProfile &&
profileId === this.currentProfile.profileDescription.id
) {
return;
}
const profile = this.currentOrg.profiles.find(
const profile = this.profiles.find(
(profile) => profile.profileDescription.id === profileId,
);
if (!profile) {
throw new Error(`Profile ${profileId} not found in current org`);
throw new Error(`Profile ${profileId} not found`);
}
const profileKey = await this.getProfileKey(this.currentOrg.id);
const workspaceId = await this.getWorkspaceId();
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: profileId,
[workspaceId]: profileId,
});
this.currentProfile = profile;
@ -358,14 +249,12 @@ export class ConfigHandler {
return out;
}
for (const org of this.organizations) {
for (const profile of org.profiles) {
if (
profile.profileDescription.id !==
this.currentProfile.profileDescription.id
) {
profile.clearConfig();
}
for (const profile of this.profiles) {
if (
profile.profileDescription.id !==
this.currentProfile.profileDescription.id
) {
profile.clearConfig();
}
}
@ -449,7 +338,7 @@ export class ConfigHandler {
if (!openProfileId) {
return;
}
const profile = this.currentOrg?.profiles.find(
const profile = this.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (!profile) {

View file

@ -10,10 +10,6 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.currentOrg?.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].profileDescription.id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile?.profileDescription.id).toBe("local");
});

View file

@ -2,7 +2,6 @@ import {
ConfigResult,
ConfigValidationError,
FullSlug,
Policy,
} from "@continuedev/config-yaml";
import {
@ -18,7 +17,6 @@ import { IProfileLoader } from "./profile/IProfileLoader.js";
export interface ProfileDescription {
fullSlug: FullSlug;
profileType: "control-plane" | "local" | "platform";
title: string;
id: string;
iconUrl: string;
@ -27,24 +25,6 @@ export interface ProfileDescription {
rawYaml?: string;
}
export interface OrganizationDescription {
id: string;
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
policy?: Policy;
}
export type OrgWithProfiles = OrganizationDescription & {
profiles: ProfileLifecycleManager[];
currentProfile: ProfileLifecycleManager | null;
};
export type SerializedOrgWithProfiles = OrganizationDescription & {
profiles: ProfileDescription[];
selectedProfileId: string | null;
};
export class ProfileLifecycleManager {
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;

View file

@ -342,13 +342,6 @@ async function intermediateToFinalConfig({
"summarize",
]); // Default to chat role if not specified
// Free trial provider will be completely ignored
let warnAboutFreeTrial = false;
models = models.filter((model) => model.providerName !== "free-trial");
if (models.filter((m) => m.providerName === "free-trial").length) {
warnAboutFreeTrial = true;
}
// Tab autocomplete model
const tabAutocompleteModels: BaseLLM[] = [];
if (config.tabAutocompleteModel) {
@ -369,11 +362,7 @@ async function intermediateToFinalConfig({
config.completionOptions,
);
if (llm) {
if (llm.providerName === "free-trial") {
warnAboutFreeTrial = true;
} else {
tabAutocompleteModels.push(llm);
}
tabAutocompleteModels.push(llm);
}
} else {
tabAutocompleteModels.push(new CustomLLMClass(desc));
@ -414,10 +403,7 @@ async function intermediateToFinalConfig({
return embedConfig;
}
const { provider, ...options } = embedConfig;
if (provider === "transformers.js" || provider === "free-trial") {
if (provider === "free-trial") {
warnAboutFreeTrial = true;
}
if (provider === "transformers.js") {
return new TransformersJsEmbeddingsProvider();
} else {
const cls = LLMClasses.find((c) => c.providerName === provider);
@ -454,10 +440,6 @@ async function intermediateToFinalConfig({
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
if (name === "free-trial") {
warnAboutFreeTrial = true;
return null;
}
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
@ -488,14 +470,6 @@ async function intermediateToFinalConfig({
}
const newReranker = getRerankingILLM(config.reranker);
if (warnAboutFreeTrial) {
errors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored",
});
}
const continueConfig: ContinueConfig = {
...config,
contextProviders,

View file

@ -21,7 +21,6 @@ export default class LocalProfileLoader implements IProfileLoader {
) {
const description: ProfileDescription = {
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",

View file

@ -1,40 +0,0 @@
import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml";
import { BrowserSerializedContinueConfig, ModelDescription } from "..";
/**
* Helper function to determine if the config uses an API key that relies on Continue credits (free trial or models add-on)
* @param config The serialized config object
* @returns true if the config is using any free trial models
*/
export function usesCreditsBasedApiKey(
config: BrowserSerializedContinueConfig | null,
): boolean {
if (!config) {
return false;
}
// Check if the currently selected chat model uses free-trial provider
const modelsByRole = config.modelsByRole;
const allModels = [...Object.values(modelsByRole)].flat();
// Check if any of the chat models use free-trial provider
try {
const hasFreeTrial = allModels?.some(modelUsesCreditsBasedApiKey);
return hasFreeTrial;
} catch (e) {
console.error("Error checking for free trial API key:", e);
}
return false;
}
const modelUsesCreditsBasedApiKey = (model: ModelDescription) => {
if (!model.apiKeyLocation) {
return false;
}
const secretType = decodeSecretLocation(model.apiKeyLocation).secretType;
return secretType === SecretType.FreeTrial;
};

View file

@ -1,360 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = vi.fn();
// Mock the module
vi.mock("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesCreditsBasedApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesCreditsBasedApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});
});

View file

@ -277,14 +277,10 @@ export async function configYamlToContinueConfig(options: {
});
// Models
let warnAboutFreeTrial = false;
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
if (model.provider === "free-trial") {
warnAboutFreeTrial = true;
}
try {
const llms = await llmsFromModelConfig({
model,
@ -358,14 +354,6 @@ export async function configYamlToContinueConfig(options: {
);
}
if (warnAboutFreeTrial) {
localErrors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored.",
});
}
const { providers, errors: contextErrors } = loadConfigContextProviders(
config.context,
!!config.docs?.length,

View file

@ -15,14 +15,6 @@ function getModelClass(
return LLMClasses.find((llm) => llm.providerName === model.provider);
}
// function getContinueProxyModelName(
// ownerSlug: string,
// packageSlug: string,
// model: ModelConfig,
// ): string {
// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
// }
async function modelConfigToBaseLLM({
model,
uniqueId,

View file

@ -173,8 +173,7 @@ export class Core {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
profiles: this.configHandler.profileDescriptions,
});
if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
@ -425,11 +424,9 @@ export class Core {
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
const { selectOrgId, selectProfileId, reason } = msg.data ?? {};
const { selectProfileId, reason } = msg.data ?? {};
await this.configHandler.refreshAll(reason);
if (selectOrgId) {
await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
} else if (selectProfileId) {
if (selectProfileId) {
await this.configHandler.setSelectedProfileId(selectProfileId);
}
});
@ -545,8 +542,7 @@ export class Core {
result: await this.configHandler.getSerializedConfig(),
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
profiles: this.configHandler.profileDescriptions,
};
});
@ -1030,15 +1026,6 @@ export class Core {
}
});
on("didChangeSelectedOrg", async (msg) => {
if (msg.data.id) {
await this.configHandler.setSelectedOrgId(
msg.data.id,
msg.data.profileId || undefined,
);
}
});
on("auth/getAuthUrl", async (_msg) => {
return { url: "" };
});

3
core/index.d.ts vendored
View file

@ -1366,9 +1366,6 @@ export interface MCPPrompt {
arguments?: MCPPromptArgs;
}
// Leaving here to ideate on
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
// https://modelcontextprotocol.io/docs/concepts/resources#direct-resources
export interface MCPResource {
name: string;

View file

@ -156,13 +156,6 @@ export class NextEditProvider {
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
// TODO: Resolve import error with TRIAL_FIM_MODEL
// else if (
// llm.providerName === "free-trial" &&
// llm.model !== TRIAL_FIM_MODEL
// ) {
// llm.model = TRIAL_FIM_MODEL;
// }
return llm;
}
@ -510,9 +503,6 @@ export class NextEditProvider {
let outcome: NextEditOutcome | undefined;
// Handle based on diff type.
const profileType =
this.configHandler.currentProfile?.profileDescription.profileType;
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
outcome = await this.modelProvider.handlePartialFileDiff({
helper,
@ -523,7 +513,6 @@ export class NextEditProvider {
nextCompletion,
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
} else {
outcome = await this.modelProvider.handleFullFileDiff({
@ -535,7 +524,6 @@ export class NextEditProvider {
nextCompletion,
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
}

View file

@ -56,7 +56,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
helper,
@ -67,7 +66,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const oldEditRangeSlice = helper.fileContents
.split("\n")
@ -95,7 +93,6 @@ export abstract class BaseNextEditModelProvider {
originalEditableRange: oldEditRangeSlice,
diffLines: [],
ide,
profileType,
});
return outcome;
@ -110,7 +107,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome | undefined> {
const {
helper,
@ -121,7 +117,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
@ -145,7 +140,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
});
if (cursorLocalDiffGroup) {
@ -158,7 +152,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup: true,
promptMetadata,
ide,
profileType,
});
}
@ -177,7 +170,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<DiffGroup | undefined> {
const {
diffGroups,
@ -188,7 +180,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
let cursorGroup: DiffGroup | undefined;
@ -204,7 +195,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
});
}
}
@ -220,7 +210,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<void> {
const {
group,
@ -230,7 +219,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
// Extract lines that are not old.
const groupContent = group.lines
@ -274,7 +262,6 @@ export abstract class BaseNextEditModelProvider {
completionId: uuidv4(), // Generate a new ID for this prefetched item.
diffLines: group.lines,
ide,
profileType,
});
prefetchQueue.enqueueProcessed({
@ -292,7 +279,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup: boolean;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
diffGroup,
@ -303,7 +289,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup,
promptMetadata,
ide,
profileType,
} = params;
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
@ -342,7 +327,6 @@ export abstract class BaseNextEditModelProvider {
completionId,
diffLines: diffGroup.lines,
ide,
profileType,
});
return outcomeNext;
@ -364,7 +348,6 @@ export abstract class BaseNextEditModelProvider {
completionId?: string;
diffLines: DiffLine[];
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
@ -391,7 +374,6 @@ export abstract class BaseNextEditModelProvider {
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
profileType: outcomeCtx.profileType,
...outcomeCtx.helper.options,
};
}

View file

@ -68,7 +68,6 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
editableRegionStartLine: number;
editableRegionEndLine: number;
diffLines: DiffLine[];
profileType?: "local" | "platform" | "control-plane";
}
export interface PromptMetadata {

View file

@ -10,6 +10,7 @@ import {
AutocompleteInput,
RecentlyEditedRange,
} from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ProfileLifecycleManager";
import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
@ -44,7 +45,6 @@ import {
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
import { GetLspDefinitionsFunction } from "../autocomplete/types";
import { ConfigHandler } from "../config/ConfigHandler";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
import { ContinueErrorReason } from "../util/errors";
@ -52,7 +52,6 @@ import { ContinueErrorReason } from "../util/errors";
export enum OnboardingModes {
API_KEY = "API Key",
LOCAL = "Local",
MODELS_ADD_ON = "Models Add-On",
}
export interface ListHistoryOptions {
@ -96,8 +95,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string | null;
profiles: ProfileDescription[];
},
];
"config/deleteModel": [{ title: string }, void];
@ -106,7 +104,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
| undefined
| {
reason?: string;
selectOrgId?: string;
selectProfileId?: string;
}
),

View file

@ -3,6 +3,5 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
didChangeSelectedProfile: [{ id: string }, void];
didChangeSelectedOrg: [{ id: string; profileId?: string }, void];
};
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol;

View file

@ -79,7 +79,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"onboarding/complete",
"addAutocompleteModel",
"didChangeSelectedProfile",
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
@ -106,5 +105,4 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"sessionUpdate",
"didCloseFiles",
"toolCallPartialOutput",
"freeTrialExceeded",
];

View file

@ -1,5 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
@ -7,14 +6,14 @@ import type {
IndexingProgressUpdate,
IndexingStatus,
} from "../index.js";
import type { ProfileDescription } from "../config/ProfileLifecycleManager.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string | null;
profiles: ProfileDescription[];
},
void,
];
@ -42,5 +41,4 @@ export type ToWebviewFromIdeOrCoreProtocol = {
"jetbrains/setColors": [Record<string, string | null | undefined>, void];
sessionUpdate: [{ sessionInfo: any | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
freeTrialExceeded: [undefined, void];
};

View file

@ -121,8 +121,6 @@ export class CLIPlatformClient implements PlatformClient {
});
// Merge API results - keep all found results (with or without value)
// Results with value = user secrets (rendered directly)
// Results with secretLocation but no value = org/package/models_add_on/free_trial (will be proxied)
for (let j = 0; j < apiResults.length; j++) {
if (apiResults[j]?.found) {
results[unresolvedIndices[j]] = apiResults[j];

View file

@ -11,7 +11,6 @@ export const getOrganizationId = vi.fn(() => null);
export const saveAuthConfig = vi.fn();
export const listUserOrganizations = vi.fn();
export const hasMultipleOrganizations = vi.fn();
export const initWorkOS = vi.fn();
export const getModelName = vi.fn(() => null);
export const getAccessToken = vi.fn(() => null);
export const getConfigUri = vi.fn(() => null);
@ -21,3 +20,10 @@ export const updateConfigUri = vi.fn();
export const updateModelName = vi.fn();
export const updateAssistantSlug = vi.fn();
export const updateLocalConfigPath = vi.fn();
// Type re-exports for test compatibility
export type AuthConfig = null;
export type {
AuthenticatedConfig,
EnvironmentAuthConfig,
} from "../../auth/workos.js";

View file

@ -1,29 +0,0 @@
import chalk from "chalk";
import { isAuthenticated, login } from "./workos.js";
/**
* Ensures the user is authenticated before proceeding
* Returns true if authentication is successful, false otherwise
*/
export async function ensureAuthenticated(
requireAuth: boolean = true,
): Promise<boolean> {
if (await isAuthenticated()) {
return true;
}
if (!requireAuth) {
return false;
}
console.info(chalk.yellow("Authentication required."));
try {
await login();
return true;
} catch (error) {
console.error(chalk.red("Failed to authenticate."), error);
return false;
}
}

View file

@ -1,233 +0,0 @@
import * as fs from "fs";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
autoSelectOrganizationAndConfig,
createUpdatedAuthConfig,
} from "./orgSelection.js";
import { AuthenticatedConfig } from "./workos-types.js";
// Mock dependencies
vi.mock("fs");
vi.mock("../config.js");
vi.mock("../env.js");
vi.mock("./workos.js");
const mockApiClient = {
listOrganizations: vi.fn(),
listAssistants: vi.fn(),
} as any; // Mock API client for testing
describe("orgSelection", () => {
const mockConfig: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: undefined,
configUri: undefined,
modelName: undefined,
};
beforeEach(async () => {
vi.clearAllMocks();
// Mock modules using vi.mocked
const configMod = await import("../config.js");
const envMod = await import("../env.js");
const workosMod = await import("./workos.js");
vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient);
vi.mocked(envMod.env).continueHome = "/mock/home";
vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {});
// Default: no local config
vi.mocked(fs.existsSync).mockReturnValue(false);
});
describe("createUpdatedAuthConfig", () => {
it("should update organization ID", () => {
const result = createUpdatedAuthConfig(mockConfig, "org123");
expect(result.organizationId).toBe("org123");
});
it("should update organization ID and config URI", () => {
const result = createUpdatedAuthConfig(
mockConfig,
"org123",
"slug://owner/assistant",
);
expect(result.organizationId).toBe("org123");
expect(result!.configUri).toBe("slug://owner/assistant");
});
it("should set personal organization", () => {
const result = createUpdatedAuthConfig(mockConfig, null);
expect(result.organizationId).toBe(null);
});
});
describe("autoSelectOrganizationAndConfig scenarios", () => {
it("Priority 1: Org with assistants → select first assistant", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [
{ id: "org1", name: "Org 1" },
{ id: "org2", name: "Org 2" },
],
});
// Mock API calls in order: org1 assistants, org2 assistants
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1") return Promise.resolve([]);
if (organizationId === "org2")
return Promise.resolve([
{ ownerSlug: "owner", packageSlug: "assistant1" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe("org2");
expect(result!.configUri).toBe("slug://owner/assistant1");
});
it("Priority 2: No org assistants → personal assistants exist", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1") return Promise.resolve([]);
if (organizationId === undefined)
return Promise.resolve([
{ ownerSlug: "personal", packageSlug: "my-assistant" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null); // personal org
expect(result!.configUri).toBe("slug://personal/my-assistant");
expect(mockApiClient.listAssistants).toHaveBeenCalledWith({
organizationId: undefined,
});
});
it("Priority 3: No assistants anywhere → local config.yaml exists", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toContain("config.yaml");
});
it("Priority 4: No assistants, no config.yaml → fallback", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBeUndefined();
});
it("Multiple orgs with assistants → pick first one", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [
{ id: "org1", name: "Org 1" },
{ id: "org2", name: "Org 2" },
],
});
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1")
return Promise.resolve([
{ ownerSlug: "owner1", packageSlug: "assistant1" },
]);
if (organizationId === "org2")
return Promise.resolve([
{ ownerSlug: "owner2", packageSlug: "assistant2" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe("org1"); // First org wins
expect(result!.configUri).toBe("slug://owner1/assistant1");
});
it("Personal assistants API fails → fallback to config.yaml", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants
.mockResolvedValueOnce([]) // org1: no assistants
.mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toContain("config.yaml");
});
it("Empty organizations list → check personal assistants", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [], // No orgs
});
mockApiClient.listAssistants.mockResolvedValue([
{ ownerSlug: "personal", packageSlug: "my-assistant" },
]);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBe("slug://personal/my-assistant");
});
it("API error → fallback with error message", async () => {
mockApiClient.listOrganizations.mockRejectedValue(
new Error("Network error"),
);
const consoleSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBeUndefined();
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining("Error fetching organizations:"),
"Network error",
);
consoleSpy.mockRestore();
});
});
});

View file

@ -1,157 +0,0 @@
import * as fs from "fs";
import * as path from "path";
import chalk from "chalk";
import type { AuthConfig } from "../auth/workos.js";
import { saveAuthConfig } from "../auth/workos.js";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
import { AuthenticatedConfig } from "./workos-types.js";
/**
* Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
organizationId: string | null | undefined,
configUri?: string | null,
): AuthenticatedConfig {
return {
userId: config.userId,
userEmail: config.userEmail,
accessToken: config.accessToken,
refreshToken: config.refreshToken,
expiresAt: config.expiresAt,
organizationId,
configUri: configUri ?? config.configUri,
modelName: config.modelName,
};
}
/**
* Check if an organization has available assistants
*/
async function hasOrgAssistants(
apiClient: ReturnType<typeof getApiClient>,
organizationId: string,
): Promise<boolean> {
try {
const assistants = await apiClient.listAssistants({ organizationId });
return assistants.length > 0;
} catch {
// If we can't check, assume no assistants
return false;
}
}
/**
* Get the first available assistant from an organization
*/
async function getFirstAssistant(
apiClient: ReturnType<typeof getApiClient>,
organizationId: string,
): Promise<string | null> {
try {
const assistants = await apiClient.listAssistants({ organizationId });
if (assistants.length > 0) {
const first = assistants[0];
return `${first.ownerSlug}/${first.packageSlug}`;
}
return null;
} catch {
return null;
}
}
/**
* Check if personal local config.yaml exists
*/
function hasPersonalLocalConfig(): boolean {
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
return fs.existsSync(defaultConfigPath);
}
/**
* Automatically select organization and configuration for authenticated config
* Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback
*/
export async function autoSelectOrganizationAndConfig(
authenticatedConfig: AuthenticatedConfig,
): Promise<AuthConfig> {
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
// Priority 1: Find any organization that has assistants - use first assistant
for (const org of organizations) {
const hasAssistants = await hasOrgAssistants(apiClient, org.id);
if (hasAssistants) {
// Get the first assistant from this org
const firstAssistantSlug = await getFirstAssistant(apiClient, org.id);
const configUri = firstAssistantSlug
? `slug://${firstAssistantSlug}`
: undefined;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
org.id,
configUri,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}
// Priority 2: Check if personal organization has assistants
try {
const personalAssistants = await apiClient.listAssistants({
organizationId: undefined,
});
if (personalAssistants.length > 0) {
const firstAssistant = personalAssistants[0];
const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`;
const configUri = `slug://${firstAssistantSlug}`;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
null,
configUri,
);
saveAuthConfig(updatedConfig);
console.log(chalk.green("✓ Automatically selected personal assistant"));
return updatedConfig;
}
} catch {
// If personal assistants can't be fetched, continue to next priority
}
// Priority 3: If no assistants anywhere, use local config.yaml
if (hasPersonalLocalConfig()) {
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
null,
`file://${path.join(env.continueHome, "config.yaml")}`,
);
saveAuthConfig(updatedConfig);
console.log(chalk.green("✓ Using local config.yaml"));
return updatedConfig;
}
// no org assistants or config.yaml
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
} catch (error: any) {
console.error(
chalk.red("Error fetching organizations:"),
error.response?.data?.message || error.message || error,
);
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}

View file

@ -1,204 +0,0 @@
import chalk from "chalk";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { getApiClient } from "../config.js";
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
import { ensureOrganization } from "./workos.js";
// Mock dependencies
vi.mock("../config.js", () => ({
getApiClient: vi.fn(() => ({
listOrganizations: vi.fn(),
})),
}));
vi.mock("../init.js", () => ({
safeStderr: vi.fn(),
}));
vi.mock("fs", () => ({
default: {
existsSync: vi.fn(() => false),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
},
}));
describe("ensureOrganization with CLI organization slug", () => {
const mockAuthConfig: AuthenticatedConfig = {
userId: "user-123",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "refresh-token",
expiresAt: Date.now() + 3600000,
organizationId: null,
};
const mockEnvAuthConfig: EnvironmentAuthConfig = {
accessToken: "env-token",
organizationId: null,
};
const mockOrganizations = [
{ id: "org-1", name: "Organization One", slug: "org-one" },
{ id: "org-2", name: "Organization Two", slug: "org-two" },
{ id: "org-3", name: "Test Org", slug: "test-org" },
];
beforeEach(() => {
vi.clearAllMocks();
// Suppress console output during tests
vi.spyOn(console, "error").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
});
describe("Organization resolution by slug", () => {
test("should resolve organization by exact slug match", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
expect(apiClient.listOrganizations).toHaveBeenCalled();
});
test("should show available organizations when slug not found", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const consoleInfoSpy = vi.spyOn(console, "info");
await expect(
ensureOrganization(mockAuthConfig, true, "invalid-org"),
).rejects.toThrow('Organization "invalid-org" not found');
expect(consoleInfoSpy).toHaveBeenCalledWith(
chalk.yellow("Available organizations:"),
expect.stringContaining("personal"),
);
});
});
describe("Mode restriction", () => {
test("should reject --org flag in interactive mode", async () => {
const { safeStderr } = await import("../init.js");
const safeStderrSpy = vi.mocked(safeStderr);
const processExitSpy = vi
.spyOn(process, "exit")
.mockImplementation(() => {
throw new Error("Process exit");
});
await expect(
ensureOrganization(mockAuthConfig, false, "org-one"),
).rejects.toThrow("Process exit");
expect(safeStderrSpy).toHaveBeenCalledWith(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
expect(processExitSpy).toHaveBeenCalledWith(1);
processExitSpy.mockRestore();
});
});
describe("Auth type handling", () => {
test("should work with authenticated config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "test-org");
expect(result).toMatchObject({
userId: "user-123",
organizationId: "org-3",
});
});
test("should work with environment auth config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(
mockEnvAuthConfig,
true,
"org-two",
);
expect(result).toMatchObject({
accessToken: "env-token",
organizationId: "org-2",
});
});
test("should override existing organization with CLI slug", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(authWithOrg, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
});
test("should keep existing organization when no slug provided", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const result = await ensureOrganization(authWithOrg, true);
expect(result).toMatchObject({
organizationId: "existing-org",
});
});
});
describe("Error handling", () => {
test("should handle API errors during organization fetch", async () => {
const apiClient = {
listOrganizations: vi.fn().mockRejectedValue(new Error("API Error")),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
await expect(
ensureOrganization(mockAuthConfig, true, "org-one"),
).rejects.toThrow("API Error");
});
});
});

View file

@ -1,38 +0,0 @@
/**
* Device authorization response from WorkOS
*/
export interface DeviceAuthorizationResponse {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete: string;
expires_in: number;
interval: number;
}
// Represents an authenticated user's configuration
export interface AuthenticatedConfig {
userId: string;
userEmail: string;
accessToken: string;
refreshToken: string;
expiresAt: number;
organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
// Represents configuration when using environment variable auth
export interface EnvironmentAuthConfig {
/**
* This userId?: undefined; field a trick to help TypeScript differentiate between
* AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
* a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
* type guards are involved.
*/
userId?: undefined;
accessToken: string;
organizationId: string | null; // Can be set via --org flag in headless mode
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}

View file

@ -1,123 +0,0 @@
import chalk from "chalk";
import { getApiClient } from "../config.js";
import { safeStderr } from "../init.js";
import { gracefulExit } from "../util/exit.js";
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
import type { AuthConfig } from "./workos.js";
import { saveAuthConfig } from "./workos.js";
/**
* Creates an updated AuthenticatedConfig with a new organization ID
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
organizationId: string | null | undefined,
): AuthenticatedConfig {
return {
userId: config.userId,
userEmail: config.userEmail,
accessToken: config.accessToken,
refreshToken: config.refreshToken,
expiresAt: config.expiresAt,
organizationId,
configUri: config.configUri,
modelName: config.modelName,
};
}
/**
* Helper function to resolve organization by slug
*/
export async function resolveOrganizationBySlug(
apiClient: ReturnType<typeof getApiClient>,
organizationSlug: string,
): Promise<{ id: string; slug: string }> {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
// Find organization by slug (case-insensitive)
const matchedOrg = organizations.find(
(org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase(),
);
if (matchedOrg) {
return { id: matchedOrg.id, slug: matchedOrg.slug };
} else {
// Organization not found - show available options
const availableSlugs = organizations
.map((org) => org?.slug)
.filter(Boolean);
const availableOptions = ["personal", ...availableSlugs];
console.info(
chalk.yellow("Available organizations:"),
availableOptions.join(", "),
);
throw new Error(`Organization "${organizationSlug}" not found`);
}
}
/**
* Handle CLI organization flag for environment auth configs
*/
export async function handleCliOrgForEnvironmentAuth(
authConfig: EnvironmentAuthConfig,
cliOrganizationSlug: string,
isHeadless: boolean,
): Promise<AuthConfig> {
// Only allow --org flag in headless mode
if (!isHeadless) {
safeStderr(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
await gracefulExit(1);
}
const apiClient = getApiClient(authConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
// Return modified environment auth config with organization ID
return {
...authConfig,
organizationId: resolvedOrg.id,
};
}
/**
* Handle CLI organization flag for authenticated configs
*/
export async function handleCliOrgForAuthenticatedConfig(
authenticatedConfig: AuthenticatedConfig,
cliOrganizationSlug: string,
isHeadless: boolean,
): Promise<AuthConfig> {
// Only allow --org flag in headless mode
if (!isHeadless) {
safeStderr(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
await gracefulExit(1);
}
const apiClient = getApiClient(authenticatedConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
resolvedOrg.id,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
}

View file

@ -1,58 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js";
describe("ensureOrganization with API key org scope", () => {
const originalEnv = { ...process.env };
const originalFetch = global.fetch;
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
process.env = { ...originalEnv };
global.fetch = originalFetch as any;
});
it("resolves organizationId via auth/scope for API key auth", async () => {
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ organizationId: "org_123" }),
});
(global as any).fetch = mockFetch;
const envAuthConfig = {
accessToken: "sk_test_api_key",
organizationId: null as string | null,
} as const;
const result = await ensureOrganization(envAuthConfig, true);
expect(result).not.toBeNull();
if (result && isEnvironmentAuthConfig(result)) {
expect(result.organizationId).toBe("org_123");
} else {
throw new Error("Expected environment auth config result");
}
expect(mockFetch).toHaveBeenCalledOnce();
});
it("keeps organizationId null if endpoint not available", async () => {
const mockFetch = vi.fn().mockResolvedValue({ ok: false });
(global as any).fetch = mockFetch;
const envAuthConfig = {
accessToken: "sk_test_api_key",
organizationId: null as string | null,
} as const;
const result = await ensureOrganization(envAuthConfig, true);
expect(result).not.toBeNull();
if (result && isEnvironmentAuthConfig(result)) {
expect(result.organizationId).toBeNull();
} else {
throw new Error("Expected environment auth config result");
}
expect(mockFetch).toHaveBeenCalledOnce();
});
});

View file

@ -1,186 +0,0 @@
import { slugToUri } from "./uriUtils.js";
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
import {
getAccessToken,
getAssistantSlug,
getOrganizationId,
isAuthenticatedConfig,
isEnvironmentAuthConfig,
} from "./workos.js";
describe("workos utility functions", () => {
describe("isAuthenticatedConfig", () => {
it("should return true for authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(isAuthenticatedConfig(config)).toBe(true);
});
it("should return false for environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(isAuthenticatedConfig(config)).toBe(false);
});
it("should return false for null config", () => {
expect(isAuthenticatedConfig(null)).toBe(false);
});
});
describe("isEnvironmentAuthConfig", () => {
it("should return true for environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(isEnvironmentAuthConfig(config)).toBe(true);
});
it("should return false for authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(isEnvironmentAuthConfig(config)).toBe(false);
});
it("should return false for null config", () => {
expect(isEnvironmentAuthConfig(null)).toBe(false);
});
});
describe("getAccessToken", () => {
it("should return access token from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getAccessToken(config)).toBe("token123");
});
it("should return access token from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getAccessToken(config)).toBe("env-token123");
});
it("should return null for null config", () => {
expect(getAccessToken(null)).toBe(null);
});
});
describe("getOrganizationId", () => {
it("should return organization ID from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe("org123");
});
it("should return null organization ID from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe(null);
});
it("should return null from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe(null);
});
it("should return null for null config", () => {
expect(getOrganizationId(null)).toBe(null);
});
});
describe("getAssistantSlug", () => {
it("should return assistant slug from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getAssistantSlug(config)).toBe("assistant123");
});
it("should return null when assistant slug is undefined in authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: undefined,
};
expect(getAssistantSlug(config)).toBe(null);
});
it("should return assistant slug from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("env-assistant123"),
};
expect(getAssistantSlug(config)).toBe("env-assistant123");
});
it("should return null when assistant slug is undefined in environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: undefined,
};
expect(getAssistantSlug(config)).toBe(null);
});
it("should return null for null config", () => {
expect(getAssistantSlug(null)).toBe(null);
});
});
});

View file

@ -1,698 +1,153 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import chalk from "chalk";
import nodeFetch from "node-fetch";
import open from "open";
import { logger } from "src/util/logger.js";
import { getApiClient } from "../config.js";
// eslint-disable-next-line import/order
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
// Config file path - define as a function to avoid initialization order issues
function getAuthConfigPath() {
const continueHome =
process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
return path.join(continueHome, "auth.json");
}
// Union type representing the possible authentication states
export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null;
/**
* Type guard to check if config is authenticated via file-based auth
* Auth configuration stubs.
*
* Hub/WorkOS authentication has been removed. These exports are kept as
* no-op stubs so that the rest of the codebase compiles without changing
* every import site.
*/
export function isAuthenticatedConfig(
config: AuthConfig,
): config is AuthenticatedConfig {
return config !== null && "userId" in config;
}
/**
* Type guard to check if config is authenticated via environment variable
*/
export function isEnvironmentAuthConfig(
config: AuthConfig,
): config is EnvironmentAuthConfig {
return config !== null && !("userId" in config);
}
/**
* Gets the access token from any auth config type
*/
export function getAccessToken(config: AuthConfig): string | null {
if (config === null) return null;
return config.accessToken;
}
/**
* Gets the organization ID from any auth config type
*/
export function getOrganizationId(
config: AuthConfig,
): string | null | undefined {
if (config === null) return null;
return config.organizationId;
}
/**
* Gets the config URI from any auth config type
*/
export function getConfigUri(config: AuthConfig): string | null {
if (config === null) return null;
return config.configUri || null;
}
/**
* Gets the model name from any auth config type
* For unauthenticated users or when auth config has no modelName, checks GlobalContext
*/
export function getModelName(config: AuthConfig): string | null {
// Priority 1: Logged-in users with modelName in auth config
if (config !== null && config.modelName) {
return config.modelName;
}
// Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName)
return getPersistedModelName();
}
// URI utility functions have been moved to ./uriUtils.ts
import {
getPersistedModelName,
persistModelName,
} from "../util/modelPersistence.js";
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
AuthenticatedConfig,
DeviceAuthorizationResponse,
EnvironmentAuthConfig,
} from "./workos-types.js";
import {
handleCliOrgForAuthenticatedConfig,
handleCliOrgForEnvironmentAuth,
} from "./workos.helpers.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/**
* Legacy functions for backward compatibility
* AuthConfig is always null now that Hub auth has been removed.
*/
export function getAssistantSlug(config: AuthConfig): string | null {
const uri = getConfigUri(config);
return uri ? uriToSlug(uri) : null;
}
export function getLocalConfigPath(config: AuthConfig): string | null {
const uri = getConfigUri(config);
return uri ? uriToPath(uri) : null;
}
export type AuthConfig = null;
/**
* Loads the authentication configuration from disk
* Kept for type compatibility - code that references AuthenticatedConfig will
* still compile but the type is never instantiated at runtime.
*/
export function loadAuthConfig(): AuthConfig {
// If CONTINUE_API_KEY environment variable exists, use that instead
if (process.env.CONTINUE_API_KEY) {
return {
accessToken: process.env.CONTINUE_API_KEY,
organizationId: null,
};
}
export interface AuthenticatedConfig {
userId: string;
userEmail: string;
accessToken: string;
refreshToken: string;
expiresAt: number;
organizationId: string | null | undefined;
configUri?: string;
modelName?: string;
}
try {
const authConfigPath = getAuthConfigPath();
if (fs.existsSync(authConfigPath)) {
const data = JSON.parse(fs.readFileSync(authConfigPath, "utf8"));
export interface EnvironmentAuthConfig {
userId?: undefined;
accessToken: string;
organizationId: string | null;
configUri?: string;
modelName?: string;
}
// Validate that we have all required fields for authenticated config
if (
data.userId &&
data.userEmail &&
data.accessToken &&
data.refreshToken &&
data.expiresAt
) {
return {
userId: data.userId,
userEmail: data.userEmail,
accessToken: data.accessToken,
refreshToken: data.refreshToken,
expiresAt: data.expiresAt,
organizationId: data.organizationId || null,
configUri: data.configUri,
modelName: data.modelName,
};
} else {
console.warn("Invalid auth config found, ignoring.");
return null;
}
}
} catch (error) {
console.error(`Error loading auth config: ${error}`);
}
// ---------------------------------------------------------------------------
// Type guards
// ---------------------------------------------------------------------------
export function isAuthenticatedConfig(_config: AuthConfig): _config is never {
return false;
}
export function isEnvironmentAuthConfig(_config: AuthConfig): _config is never {
return false;
}
// ---------------------------------------------------------------------------
// Accessors
// ---------------------------------------------------------------------------
export function getAccessToken(_config: AuthConfig): null {
return null;
}
/**
* Saves the authentication configuration to disk
*/
export function saveAuthConfig(config: AuthenticatedConfig): void {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
}
try {
const authConfigPath = getAuthConfigPath();
// Make sure the directory exists
const dir = path.dirname(authConfigPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(authConfigPath, JSON.stringify(config, null, 2));
} catch (error) {
console.error(`Error saving auth config: ${error}`);
}
export function getOrganizationId(_config: AuthConfig): null {
return null;
}
/**
* Updates the config URI in the authentication configuration
*/
export function updateConfigUri(configUri: string | null): void {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
}
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
configUri: configUri || undefined,
};
saveAuthConfig(updatedConfig);
}
export function getConfigUri(_config: AuthConfig): null {
return null;
}
export function getModelName(_config: AuthConfig): string | null {
return getPersistedModelName();
}
// ---------------------------------------------------------------------------
// Config loading / saving (no-ops)
// ---------------------------------------------------------------------------
export function loadAuthConfig(): AuthConfig {
return null;
}
export function saveAuthConfig(_config: AuthenticatedConfig): void {
// no-op
}
export function updateConfigUri(_configUri: string | null): void {
// no-op
}
/**
* Updates the model name in the authentication configuration
* Returns the updated config so the caller can update in-memory state
* For unauthenticated users, saves to GlobalContext
*/
export function updateModelName(modelName: string | null): AuthConfig {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return loadAuthConfig();
}
const config = loadAuthConfig();
// If logged in, save to auth.json
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
modelName: modelName || undefined,
};
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// If logged out, save to GlobalContext
persistModelName(modelName);
return config;
return null;
}
/**
* Legacy functions for backward compatibility
*/
export function updateAssistantSlug(assistantSlug: string | null): void {
updateConfigUri(assistantSlug ? slugToUri(assistantSlug) : null);
// ---------------------------------------------------------------------------
// Legacy convenience helpers
// ---------------------------------------------------------------------------
export function getAssistantSlug(_config: AuthConfig): null {
return null;
}
export function updateLocalConfigPath(localConfigPath: string | null): void {
updateConfigUri(localConfigPath ? pathToUri(localConfigPath) : null);
export function getLocalConfigPath(_config: AuthConfig): null {
return null;
}
/**
* Checks if the user is authenticated and the token is valid
*/
export function updateAssistantSlug(_assistantSlug: string | null): void {
// no-op
}
export function updateLocalConfigPath(_localConfigPath: string | null): void {
// no-op
}
// ---------------------------------------------------------------------------
// Auth operations (stubs)
// ---------------------------------------------------------------------------
export async function isAuthenticated(): Promise<boolean> {
const config = loadAuthConfig();
if (config === null) {
return false;
}
if (isEnvironmentAuthConfig(config)) {
return true;
}
if (Date.now() > config.expiresAt) {
try {
const refreshed = await refreshToken(config.refreshToken);
return isAuthenticatedConfig(refreshed);
} catch (e) {
logger.error("Failed to refresh auto token", e);
return false;
}
}
return true;
return false;
}
/**
* Request device authorization from WorkOS
*/
async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse> {
try {
const params = new URLSearchParams({
client_id: env.workOsClientId,
screen_hint: "sign-up",
});
// Use WorkOS User Management device authorization endpoint
const response = await fetch(
"https://api.workos.com/user_management/authorize/device",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params,
},
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error: any) {
console.error(
chalk.red("Device authorization error:"),
error.message || error,
);
throw error;
}
}
/**
* Poll for device authorization completion
*/
async function pollForDeviceToken(
deviceCode: string,
interval: number,
expiresIn: number,
): Promise<AuthenticatedConfig> {
const startTime = Date.now();
const expirationTime = startTime + expiresIn * 1000;
let currentInterval = interval;
while (Date.now() < expirationTime) {
try {
const params = new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
device_code: deviceCode,
client_id: env.workOsClientId,
});
const headers: Record<string, string> = {
"Content-Type": "application/x-www-form-urlencoded",
};
// Poll WorkOS User Management token endpoint
const response = await fetch(
"https://api.workos.com/user_management/authenticate",
{
method: "POST",
headers,
body: params,
},
);
if (response.ok) {
const data = await response.json();
const { access_token, refresh_token, user } = data;
// Calculate token expiration (assuming 1 hour validity)
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
const authConfig: AuthenticatedConfig = {
userId: user.id,
userEmail: user.email,
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: tokenExpiresAt,
organizationId: undefined, // undefined triggers auto-selection, null means personal org selected
};
// Save the config
saveAuthConfig(authConfig);
return authConfig;
} else {
// Handle HTTP error responses
const errorData = await response.json().catch(() => ({}));
const errorCode = errorData.error;
// Log response details for debugging
if (response.status === 401) {
throw new Error(
"Oops! We had trouble authenticating. Please try again and reach out if the error persists.",
);
}
if (errorCode === "authorization_pending") {
// Continue polling
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "slow_down") {
// Increase polling interval
currentInterval += 5;
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "access_denied") {
throw new Error("User denied access");
} else if (errorCode === "expired_token") {
throw new Error("Device code has expired");
} else {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
}
} catch (error: any) {
console.error(chalk.red("Token polling error:"), error.message || error);
throw error;
}
}
throw new Error("Device authorization timeout");
}
/**
* Refreshes the access token using a refresh token
*/
async function refreshToken(
refreshToken: string,
): Promise<AuthenticatedConfig> {
try {
// Load existing config to preserve organizationId and other fields
const existingConfig = loadAuthConfig();
const response = await fetch(new URL("auth/refresh", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
refreshToken,
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
const { accessToken, refreshToken: newRefreshToken, user } = data;
// Calculate token expiration (assuming 1 hour validity)
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
const authConfig: AuthenticatedConfig = {
userId: user.id,
userEmail: user.email,
accessToken,
refreshToken: newRefreshToken,
expiresAt: tokenExpiresAt,
// Preserve existing organizationId if it exists, otherwise set to null
organizationId: isAuthenticatedConfig(existingConfig)
? existingConfig.organizationId
: null,
// Preserve existing configUri if it exists
configUri: isAuthenticatedConfig(existingConfig)
? existingConfig.configUri
: undefined,
// Preserve existing modelName if it exists
modelName: isAuthenticatedConfig(existingConfig)
? existingConfig.modelName
: undefined,
};
// Save the config
saveAuthConfig(authConfig);
return authConfig;
} catch (error: any) {
console.error(chalk.red("Token refresh error:"), error.message || error);
throw error;
}
}
/**
* Authenticates using the WorkOS device flow
*/
export async function login(): Promise<AuthConfig> {
// If CONTINUE_API_KEY environment variable exists, use that instead
if (process.env.CONTINUE_API_KEY) {
console.info(
chalk.green("Using CONTINUE_API_KEY from environment variables"),
);
return {
accessToken: process.env.CONTINUE_API_KEY,
organizationId: null,
};
}
console.info(chalk.white("\nSigning in with Continue..."));
// Request device authorization
const deviceAuth = await requestDeviceAuthorization();
console.info(
chalk.white(
`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`,
),
);
console.info(
chalk.dim(
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`,
),
throw new Error(
"Login is not available. Hub authentication has been removed.",
);
}
// Try to open the complete verification URL in browser
try {
await open(deviceAuth.verification_uri_complete);
} catch {
console.info(chalk.yellow("Unable to open browser automatically"));
}
console.info(chalk.dim("\nWaiting for confirmation..."));
// Poll for token
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in,
);
console.info(chalk.white("✅ Success!"));
export function logout(): void {
// no-op
}
export async function ensureOrganization(
authConfig: AuthConfig,
_isHeadless?: boolean,
_cliOrganizationSlug?: string,
): Promise<AuthConfig> {
return authConfig;
}
/**
* Ensures the user has selected an organization, automatically selecting the first one if available
*/
export async function ensureOrganization(
authConfig: AuthConfig,
isHeadless: boolean = false,
cliOrganizationSlug?: string,
): Promise<AuthConfig> {
// Handle CLI organization slug if provided (undefined means no --org flag or --org personal)
if (cliOrganizationSlug) {
// For environment auth configs
if (isEnvironmentAuthConfig(authConfig)) {
return handleCliOrgForEnvironmentAuth(
authConfig,
cliOrganizationSlug,
isHeadless,
);
}
} else if (isEnvironmentAuthConfig(authConfig)) {
// No CLI organization slug (or "personal" was specified)
// If using API key auth, attempt to resolve its organization scope once
const resolved = await resolveOrgScopeForApiKey(authConfig);
return resolved;
}
// If not authenticated, return as-is
if (!isAuthenticatedConfig(authConfig)) {
return authConfig;
}
// TypeScript now knows authConfig is AuthenticatedConfig
const authenticatedConfig: AuthenticatedConfig = authConfig;
// If a CLI organization slug is provided, try to use it (for authenticated configs)
if (cliOrganizationSlug) {
return handleCliOrgForAuthenticatedConfig(
authenticatedConfig,
cliOrganizationSlug,
isHeadless,
);
}
// Only auto-select if user hasn't made any previous selections
// - organizationId === undefined means first-time setup
// - configUri being set means they've chosen a specific assistant/config
if (
authenticatedConfig.organizationId === undefined &&
!authenticatedConfig.configUri
) {
return autoSelectOrganizationAndConfig(authenticatedConfig);
}
// User already has made a selection (org or config) - respect their choice
return authenticatedConfig;
export async function listUserOrganizations(): Promise<null> {
return null;
}
/**
* Attempts to resolve the organization scope for API key auth (environment-based auth).
* Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
* If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
*/
async function resolveOrgScopeForApiKey(
envConfig: EnvironmentAuthConfig,
): Promise<EnvironmentAuthConfig> {
// If already set (including explicit null), return as-is
if (envConfig.organizationId !== null) {
return envConfig;
}
const accessToken = envConfig.accessToken;
if (!accessToken) return envConfig;
try {
// Prefer a dedicated endpoint for scope discovery. This should return JSON like:
// { organizationId: string | null } (aka orgScopeId)
const url = new URL("auth/scope", env.apiBase);
const resp = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
if (!resp.ok) {
// Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
return envConfig;
}
const data: any = await resp.json().catch(() => ({}));
const orgId =
data?.organizationId ??
data?.orgScopeId ??
data?.organization?.id ??
null;
if (orgId && typeof orgId === "string") {
return {
...envConfig,
organizationId: orgId,
};
}
} catch {
// Network or parsing issues: leave config unchanged
}
return envConfig;
}
/**
* Gets the list of available organizations for the user
*/
export async function listUserOrganizations(): Promise<
{ id: string; name: string; slug: string }[] | null
> {
const authConfig = loadAuthConfig();
// If using CONTINUE_API_KEY environment variable, organization switching is not supported
if (isEnvironmentAuthConfig(authConfig)) {
return null;
}
if (!isAuthenticatedConfig(authConfig)) {
return null;
}
const apiClient = getApiClient(authConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
// Map the organizations to include slug field
return (
resp.organizations?.map((org) => ({
id: org.id,
name: org.name,
slug: org.slug,
})) || []
);
} catch {
return null;
}
}
/**
* Checks if the user has multiple organizations available
*/
export async function hasMultipleOrganizations(): Promise<boolean> {
const organizations = await listUserOrganizations();
// Has multiple organizations if there's at least one organization (plus personal)
return organizations !== null && organizations.length > 0;
}
/**
* Logs the user out by clearing saved credentials
*/
export function logout(): void {
const continueHome =
process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
const onboardingFlagPath = path.join(continueHome, ".onboarding_complete");
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
fs.unlinkSync(onboardingFlagPath);
}
if (process.env.CONTINUE_API_KEY) {
console.info(
chalk.yellow(
"Using CONTINUE_API_KEY from environment variables, nothing to log out",
),
);
return;
}
const authConfigPath = getAuthConfigPath();
if (fs.existsSync(authConfigPath)) {
fs.unlinkSync(authConfigPath);
console.info(chalk.green("Successfully logged out"));
} else {
console.info(chalk.yellow("No active session found"));
}
return false;
}

View file

@ -1,22 +1,10 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
import { gracefulExit } from "../util/exit.js";
import { chat } from "./chat.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
try {
await workosLogin();
console.info(chalk.green("Successfully logged in!"));
// Start the CLI session after successful login
console.info(chalk.blue("Starting Continue CLI..."));
await chat();
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
await gracefulExit(1);
}
console.error(
chalk.red("Login is not available. Hub authentication has been removed."),
);
await gracefulExit(1);
}

View file

@ -1,5 +1,3 @@
import { logout as workosLogout } from "../auth/workos.js";
export async function logout() {
workosLogout();
// no-op: Hub authentication has been removed
}

View file

@ -55,8 +55,6 @@ describe("remote command", () => {
mockEnv.env = {
apiBase: "https://api.example.com",
workOsClientId: "test-client-id",
appUrl: "https://test.example.com",
continueHome: "/tmp/test-continue-home",
};

View file

@ -139,7 +139,7 @@ async function createAndConnectRemoteEnvironment(
printStartJson({
status: "success",
message: "Remote development environment created successfully",
url: `${env.appUrl}/agents/${result.id}`,
url: `https://continue.dev/agents/${result.id}`,
containerUrl: result.url,
containerPort: result.port,
name: requestBody.name,

View file

@ -1,9 +1,6 @@
import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import { loadAuthConfig, getAccessToken } from "../../auth/workos.js";
import { env } from "../../env.js";
import { logger } from "../../util/logger.js";
export interface ResolvedReview {
@ -49,61 +46,10 @@ export async function resolveReviews(
}
/**
* Try to resolve reviews from the hub API based on the current repo.
* Hub review resolution has been removed.
*/
async function resolveFromHub(): Promise<ResolvedReview[]> {
try {
const authConfig = loadAuthConfig();
if (!authConfig) {
return [];
}
const accessToken = getAccessToken(authConfig);
if (!accessToken) {
return [];
}
// Get the repo URL from git
let repoUrl: string;
try {
repoUrl = execSync("git config --get remote.origin.url", {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim();
} catch {
return [];
}
if (!repoUrl) {
return [];
}
const url = new URL("api/checks/resolve", env.apiBase);
url.searchParams.set("repoUrl", repoUrl);
const response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
logger.debug(`Hub review resolution returned ${response.status}`);
return [];
}
const data = (await response.json()) as {
checks: Array<{ slug: string; name: string }>;
};
return (data.checks || []).map((c) => ({
name: c.name,
source: c.slug,
sourceType: "hub" as const,
}));
} catch (e) {
logger.debug("Hub review resolution failed", { error: e });
return [];
}
return [];
}
/**

View file

@ -5,7 +5,6 @@ import express, { Request, Response } from "express";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { prependPrompt } from "src/util/promptProcessor.js";
import { getAccessToken, getAssistantSlug } from "../auth/workos.js";
import { runEnvironmentInstallSafe } from "../environment/environmentHandler.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { setAgentId } from "../index.js";
@ -121,29 +120,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
model: modelState.model,
};
// Organization selection is already handled in initializeServices
const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH);
if (authState.organizationId) {
telemetryService.updateOrganization(authState.organizationId);
}
const accessToken = getAccessToken(authState.authConfig);
// Log configuration information
const organizationId = authState.organizationId || "personal";
const assistantName = config.name;
const assistantSlug = getAssistantSlug(authState.authConfig);
const modelProvider = model.provider;
const modelName = model.model;
console.log(chalk.blue(`\nConfiguration:`));
console.log(chalk.dim(` Organization: ${organizationId}`));
console.log(
chalk.dim(
` Assistant: ${assistantName}${
assistantSlug ? ` (${assistantSlug})` : ""
}`,
),
);
console.log(chalk.dim(` Assistant: ${assistantName}`));
console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
if (options.config) {
console.log(chalk.dim(` Config file: ${options.config}`));
@ -203,7 +186,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const storageSyncService = services.storageSync;
let storageSyncActive = await storageSyncService.startFromOptions({
storageOption: options.id,
accessToken,
accessToken: null,
syncSessionHistory,
getCompleteStateSnapshot: () =>
getCompleteStateSnapshot(

View file

@ -9,11 +9,7 @@ import {
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import {
AuthConfig,
getAccessToken,
getOrganizationId,
} from "./auth/workos.js";
import { AuthConfig } from "./auth/workos.js";
import { env } from "./env.js";
import { getUniqueId } from "./util/uniqueId.js";
import { getVersion } from "./version.js";
@ -44,40 +40,19 @@ function mergeUserAgentIntoRequestOptions(
/**
* Creates an LLM API instance from a ModelConfig and auth configuration
* Handles special logic for continue-proxy provider and constructs the API
*/
export function createLlmApi(
model: ModelConfig,
authConfig: AuthConfig | null,
_authConfig: AuthConfig,
): BaseLlmApi | null {
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
model.provider === "continue-proxy"
? {
provider: model.provider,
requestOptions: mergeUserAgentIntoRequestOptions(
model.requestOptions,
),
apiBase: model.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (model as any).apiKeyLocation,
orgScopeId: organizationId ?? null,
proxyUrl:
(model as { onPremProxyUrl: string | undefined })
.onPremProxyUrl ?? (env.apiBase ? env.apiBase : undefined),
},
}
: {
provider: model.provider as any,
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
requestOptions: model.requestOptions,
env: model.env,
};
const config: LLMConfig = {
provider: model.provider as any,
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
requestOptions: model.requestOptions,
env: model.env,
};
return constructLlmApi(config) ?? null;
}

View file

@ -15,12 +15,11 @@ import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { uriToPath, uriToSlug } from "./auth/uriUtils.js";
import type { AuthConfig } from "./auth/workos.js";
import {
AuthConfig,
getAccessToken,
getConfigUri,
getOrganizationId,
isEnvironmentAuthConfig,
updateConfigUri,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
@ -70,12 +69,10 @@ export async function loadConfiguration(
injectBlocks,
);
// Step 3: Save config URI for session continuity (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const uri = getUriFromSource(configSource);
if (uri) {
updateConfigUri(uri);
}
// Step 3: Save config URI for session continuity
const uri = getUriFromSource(configSource);
if (uri) {
updateConfigUri(uri);
}
return { config, source: configSource };
@ -97,47 +94,12 @@ function determineConfigSource(
return { type: "cli-flag", path: cliConfigPath };
}
// Priority 2: Saved config URI (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const savedUri = getConfigUri(authConfig);
if (savedUri) {
if (savedUri.startsWith("file:")) {
let exists = false; // wrote like this for nested depth linting rule lol
try {
const filepath = fileURLToPath(savedUri);
exists = fs.existsSync(filepath);
} catch (e) {
logger.warn("Invalid saved file URI " + savedUri, e);
}
if (exists) {
return { type: "saved-uri", uri: savedUri };
} else {
logger.warn("Saved config URI does not exist: " + savedUri);
}
} else {
// slug
return { type: "saved-uri", uri: savedUri };
}
}
}
// Priority 3: Default resolution based on auth state
if (authConfig === null) {
// Unauthenticated: check for default config.yaml, then fallback to default config
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
if (fs.existsSync(defaultConfigPath)) {
return { type: "local-config-yaml" };
}
return { type: "remote-default-config" };
} else {
// In headless, user assistant fallback behavior isn't supported
if (isHeadless) {
return { type: "remote-default-config" };
}
// Authenticated: try user assistants first
return { type: "user-assistant", slug: "" }; // Empty slug means "first available"
// Priority 2: Check for default config.yaml, then fallback to default config
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
if (fs.existsSync(defaultConfigPath)) {
return { type: "local-config-yaml" };
}
return { type: "remote-default-config" };
}
/**
@ -412,8 +374,6 @@ export async function unrollPackageIdentifiersAsConfigYaml(
}),
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId: organizationId,
platformClient: new CLIPlatformClient(organizationId, apiClient),
renderSecrets: true,
injectBlocks: packageIdentifiers,
@ -450,10 +410,8 @@ async function unrollAssistantWithConfig(
{
currentUserSlug: "",
alwaysUseProxy: false,
orgScopeId: organizationId,
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
injectBlocks,
},
);

View file

@ -7,9 +7,6 @@ dotenv.config();
export const env = {
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev/",
workOsClientId:
process.env.WORKOS_CLIENT_ID ?? "client_01J0FW6XN8N2XJAECF7NE0Y65J",
appUrl: process.env.HUB_URL || "https://continue.dev",
continueHome:
process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"),
};

View file

@ -1,38 +0,0 @@
import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
describe("Free Trial Transition API Key Validation", () => {
it("should validate API keys properly for free trial transition", () => {
// Valid API keys
expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true);
expect(
isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"),
).toBe(true);
// Invalid API keys
expect(isValidAnthropicApiKey("TEST-")).toBe(false);
expect(isValidAnthropicApiKey("sk-ant-")).toBe(false);
expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false);
expect(isValidAnthropicApiKey("")).toBe(false);
expect(isValidAnthropicApiKey(null)).toBe(false);
expect(isValidAnthropicApiKey(undefined)).toBe(false);
});
it("should provide helpful error messages for invalid API keys", () => {
expect(getApiKeyValidationError("")).toBe("API key is required");
expect(getApiKeyValidationError(null)).toBe("API key is required");
expect(getApiKeyValidationError(undefined)).toBe("API key is required");
expect(getApiKeyValidationError("TEST-")).toBe(
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short");
expect(getApiKeyValidationError("invalid")).toBe(
'API key must start with "sk-ant-"',
);
});
});

View file

@ -1,143 +0,0 @@
import { spawn } from "child_process";
import * as fs from "fs";
import * as path from "path";
import chalk from "chalk";
import { setConfigFilePermissions } from "core/util/paths.js";
import open from "open";
import { env } from "./env.js";
import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
import { gracefulExit } from "./util/exit.js";
import { question, questionWithChoices } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
setConfigFilePermissions(CONFIG_PATH);
}
/**
* Handles the free trial transition flow for users who have maxed out their free trial
* This function provides a specialized flow that:
* 1. Assumes the user is already authenticated
* 2. Provides two specific options for continuing
* 3. Returns to the chat without restarting the entire CLI
*/
export async function handleMaxedOutFreeTrial(
onReload?: () => Promise<void>,
): Promise<void> {
// Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
console.clear();
console.log(chalk.yellow("🚀 Free trial limit reached!\n"));
console.log("Choose how you'd like to Continue:");
console.log(chalk.white("1. 💳 Sign up for models add-on"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
const choice = await questionWithChoices(
chalk.yellow("\nEnter choice (1): "),
["1", "2", ""],
"1",
chalk.dim("Please enter 1 or 2"),
);
if (choice === "1" || choice === "") {
// Option 1: Open models setup page
const modelsUrl = new URL("setup-models", env.appUrl).toString();
console.log(chalk.blue(`Opening ${modelsUrl}...`));
try {
await open(modelsUrl);
console.log(chalk.green("\n✓ Browser opened successfully!"));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue.",
),
);
} catch {
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
console.log(chalk.white(`Please visit: ${modelsUrl}`));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue.",
),
);
}
// Wait for user to acknowledge
await question(chalk.dim("\nPress Enter to exit..."));
await gracefulExit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
);
if (!isValidAnthropicApiKey(apiKey)) {
console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`));
await gracefulExit(1);
}
try {
await createOrUpdateConfig(apiKey);
console.log(chalk.green(`✓ API key saved successfully!`));
console.log(chalk.green("✓ Switching to local configuration..."));
// If a reload callback is provided, use it instead of restarting
if (onReload) {
await onReload();
return;
}
} catch (error) {
console.log(chalk.red(`❌ Error saving API key: ${error}`));
await gracefulExit(1);
}
}
// Fallback: restart the CLI if no reload callback was provided
console.log(
chalk.green(
"\n🔄 Restarting Continue CLI to resume your conversation...\n",
),
);
// Get the path to the current script
const scriptPath = path.resolve(process.argv[1]);
// Restart the CLI with the same arguments, except for the first two (node and script path)
// Use spawn instead of spawnSync, since we want to exit this process
const child = spawn(
process.execPath,
[scriptPath, ...process.argv.slice(2)],
{
stdio: "inherit",
detached: true,
},
);
// Unref the child to allow the parent process to exit
child.unref();
// Exit the current process
await gracefulExit(0);
}

View file

@ -1,426 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAccessToken, loadAuthConfig } from "./auth/workos.js";
import * as hubLoader from "./hubLoader.js";
// Mock auth functions
vi.mock("./auth/workos.js", () => ({
loadAuthConfig: vi.fn(),
getAccessToken: vi.fn(),
}));
const {
loadPackageFromHub,
mcpProcessor,
modelProcessor,
promptProcessor,
ruleProcessor,
processRule,
} = hubLoader;
// Store the original fetch before any mocking
const originalFetch = global.fetch;
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
// Mock JSZip
vi.mock("jszip", () => ({
default: vi.fn(),
}));
const mockedJSZip = vi.fn();
describe("hubLoader", () => {
beforeEach(async () => {
vi.clearAllMocks();
// Reset auth mocks to default state
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
});
describe("loadPackageFromHub", () => {
it("should validate slug format", async () => {
await expect(
loadPackageFromHub("invalid-slug", ruleProcessor),
).rejects.toThrow(
'Invalid hub slug format. Expected "owner/package", got: invalid-slug',
);
});
it("should handle HTTP errors", async () => {
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
statusText: "Not Found",
});
await expect(
loadPackageFromHub("owner/package", ruleProcessor),
).rejects.toThrow(
'Failed to load rule from hub "owner/package": HTTP 404: Not Found',
);
});
it("should make request without auth headers when not authenticated", async () => {
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
const JSZipModule = await import("jszip");
const JSZip = JSZipModule.default;
if (typeof (JSZip as any).mockImplementation === "function") {
(JSZip as any).mockImplementation(() => ({
loadAsync: vi.fn().mockResolvedValueOnce({
files: {
"README.md": {
dir: false,
async: vi.fn().mockResolvedValue("rule content"),
},
},
}),
}));
} else {
return;
}
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
});
await loadPackageFromHub("owner/rule", ruleProcessor);
expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), { headers: {} });
});
it("should include Authorization header when authenticated", async () => {
const mockAuthConfig = {
accessToken: "test-token-123",
userId: "user123",
};
(loadAuthConfig as any).mockReturnValue(mockAuthConfig);
(getAccessToken as any).mockReturnValue("test-token-123");
const JSZipModule = await import("jszip");
const JSZip = JSZipModule.default;
if (typeof (JSZip as any).mockImplementation === "function") {
(JSZip as any).mockImplementation(() => ({
loadAsync: vi.fn().mockResolvedValueOnce({
files: {
"README.md": {
dir: false,
async: vi.fn().mockResolvedValue("rule content"),
},
},
}),
}));
} else {
return;
}
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
});
await loadPackageFromHub("owner/rule", ruleProcessor);
expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), {
headers: {
Authorization: "Bearer test-token-123",
},
});
});
it("should include Authorization header for MCP requests when authenticated", async () => {
const mockAuthConfig = {
accessToken: "test-token-456",
userId: "user456",
};
(loadAuthConfig as any).mockReturnValue(mockAuthConfig);
(getAccessToken as any).mockReturnValue("test-token-456");
const mcpConfig = {
content: "name: test-mcp\nversion: 1.0.0",
};
mockFetch.mockResolvedValueOnce({
ok: true,
json: vi.fn().mockResolvedValue(mcpConfig),
});
await loadPackageFromHub("owner/mcp", mcpProcessor);
expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), {
headers: {
Authorization: "Bearer test-token-456",
},
});
});
it("should load rule content", async () => {
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
const ruleContent = "# Test Rule\n\nThis is a test rule.";
// Check if JSZip is mocked
const JSZipModule = await import("jszip");
const JSZip = JSZipModule.default;
// Since JSZip is mocked, it should be a mock function
if (typeof (JSZip as any).mockImplementation === "function") {
(JSZip as any).mockImplementation(() => ({
loadAsync: vi.fn().mockResolvedValueOnce({
files: {
"README.md": {
dir: false,
async: vi.fn().mockResolvedValue(ruleContent),
},
},
}),
}));
} else {
// If mock doesn't work, skip this test
return;
}
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
});
const result = await loadPackageFromHub("owner/rule", ruleProcessor);
expect(result).toBe(ruleContent);
});
it("should load MCP configuration", async () => {
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
const mcpConfig = {
content: "name: test-mcp\nversion: 1.0.0",
};
mockFetch.mockResolvedValueOnce({
ok: true,
json: vi.fn().mockResolvedValue(mcpConfig),
});
const result = await loadPackageFromHub("owner/mcp", mcpProcessor);
// Should parse the YAML content, not return the wrapper
expect(result).toEqual({
name: "test-mcp",
version: "1.0.0",
});
});
it("should handle missing files", async () => {
(loadAuthConfig as any).mockReturnValue(null);
(getAccessToken as any).mockReturnValue(null);
// Check if JSZip is mocked
const JSZipModule = await import("jszip");
const JSZip = JSZipModule.default;
// Since JSZip is mocked, it should be a mock function
if (typeof (JSZip as any).mockImplementation === "function") {
(JSZip as any).mockImplementation(() => ({
loadAsync: vi.fn().mockResolvedValueOnce({
files: {
"other.txt": {
dir: false,
async: vi.fn().mockResolvedValue("not a rule"),
},
},
}),
}));
} else {
// If mock doesn't work, skip this test
return;
}
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
});
await expect(
loadPackageFromHub("owner/empty", ruleProcessor),
).rejects.toThrow(
'Failed to load rule from hub "owner/empty": No rule content found in downloaded zip file. Expected files with extensions: .md',
);
});
});
describe("processRule", () => {
beforeEach(() => {
// Ensure mocks are set up properly for processRule tests
global.fetch = mockFetch;
});
it("should treat multi-line strings as inline rules", async () => {
const loadRuleSpy = vi
.spyOn(hubLoader, "loadRuleFromHub")
.mockResolvedValue("hub-content");
const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line";
const result = await processRule(multilineRule);
expect(result).toBe(multilineRule);
expect(loadRuleSpy).not.toHaveBeenCalled();
loadRuleSpy.mockRestore();
});
it("should still treat owner/package strings as hub slugs", async () => {
// Mock fetch to return a proper response for this test
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.file("rule.md", "hub-content");
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const slug = "owner/package";
const result = await processRule(slug);
expect(result).toBe("hub-content");
expect(mockFetch).toHaveBeenCalled();
});
});
describe("processors", () => {
it("should define rule processor correctly", () => {
expect(ruleProcessor.type).toBe("rule");
expect(ruleProcessor.expectedFileExtensions).toEqual([".md"]);
expect(ruleProcessor.parseContent("test content", "test.md")).toBe(
"test content",
);
});
it("should define MCP processor correctly", () => {
expect(mcpProcessor.type).toBe("mcp");
expect(mcpProcessor.expectedFileExtensions).toEqual([
".json",
".yaml",
".yml",
]);
});
it("should define model processor correctly", () => {
expect(modelProcessor.type).toBe("model");
expect(modelProcessor.expectedFileExtensions).toEqual([
".json",
".yaml",
".yml",
]);
});
it("should define prompt processor correctly", () => {
expect(promptProcessor.type).toBe("prompt");
expect(promptProcessor.expectedFileExtensions).toEqual([".md", ".txt"]);
expect(promptProcessor.parseContent("test content", "test.md")).toBe(
"test content",
);
});
});
describe("Real Hub Integration Tests", () => {
// Restore real fetch and JSZip for these tests
beforeEach(async () => {
vi.clearAllMocks();
// Restore the original fetch
global.fetch = originalFetch;
// Unmock JSZip to use the real implementation
vi.unmock("jszip");
});
it(
"should load rule from real hub: sanity/sanity-opinionated",
{ retry: 3, timeout: 30000 },
async () => {
const result = await loadPackageFromHub(
"sanity/sanity-opinionated",
ruleProcessor,
);
expect(result).toBeDefined();
expect(typeof result).toBe("string");
expect(result.length).toBeGreaterThan(0);
// Rules are markdown, should contain some markdown elements
expect(result).toMatch(/[#\-\*]/);
},
);
it(
"should load MCP from real hub: upstash/context7-mcp",
{ retry: 3, timeout: 30000 },
async () => {
// Restore real fetch and JSZip for this test
global.fetch = originalFetch;
vi.unmock("jszip");
const testSlug = "upstash/context7-mcp";
const result = await loadPackageFromHub(testSlug, mcpProcessor);
expect(result).toBeDefined();
expect(typeof result).toBe("object");
// Should now return the parsed MCP configuration
expect(result).toHaveProperty("name");
expect(typeof result.name).toBe("string");
// The MCP should have type and url properties
expect(result).toHaveProperty("type");
expect(result).toHaveProperty("url");
},
);
it(
"should load model from real hub: openai/gpt-5",
{ retry: 3, timeout: 30000 },
async () => {
// Restore real fetch and JSZip for this test
global.fetch = originalFetch;
vi.unmock("jszip");
const testSlug = "openai/gpt-5";
const result = await loadPackageFromHub(testSlug, modelProcessor);
expect(result).toBeDefined();
expect(typeof result).toBe("object");
// Should now return the extracted model from the models array
expect(result).toHaveProperty("name");
expect(result).toHaveProperty("provider");
expect(result).toHaveProperty("model");
// Check that the model properties are correct
expect(result.provider).toBe("openai");
expect(result.model).toBe("gpt-5");
expect(result.name).toBe("GPT-5");
},
);
it(
"should load prompt from real hub: launchdarkly/using-flags",
{ retry: 3, timeout: 30000 },
async () => {
const result = await loadPackageFromHub(
"launchdarkly/using-flags",
promptProcessor,
);
expect(result).toBeDefined();
expect(typeof result).toBe("string");
expect(result.length).toBeGreaterThan(0);
},
);
});
});

View file

@ -1,26 +1,31 @@
/**
* Rule/package processing utilities.
*
* Hub package loading has been removed. Only local file-based rule
* processing and string detection remain.
*/
import {
AgentFile,
ModelConfig,
parseAgentFile,
} from "@continuedev/config-yaml";
import JSZip from "jszip";
import { getAccessToken, loadAuthConfig } from "./auth/workos.js";
import { env } from "./env.js";
import { logger } from "./util/logger.js";
/**
* Pattern to match valid hub slugs (owner/package format)
* Pattern to match valid hub slugs (owner/package format).
* Kept so that isStringRule can still detect them (and reject them).
*/
export const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
/**
* Hub package type definitions
* Hub package type definitions (kept for type compatibility)
*/
export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "agentFile";
/**
* Hub package processor interface
* Hub package processor interface (kept for type compatibility)
*/
export interface HubPackageProcessor<T> {
type: HubPackageType;
@ -29,224 +34,47 @@ export interface HubPackageProcessor<T> {
validateContent?(content: T): boolean;
}
/**
* Rule processor - handles text content from .md files
*/
export const ruleProcessor: HubPackageProcessor<string> = {
type: "rule",
expectedFileExtensions: [".md"],
parseContent: (content: string) => content,
};
/**
* MCP processor - handles JSON/YAML configuration files
*/
export const mcpProcessor: HubPackageProcessor<any> = {
type: "mcp",
expectedFileExtensions: [".json", ".yaml", ".yml"],
parseContent: async (content: string, filename: string) => {
let parsed;
if (filename.endsWith(".json")) {
parsed = JSON.parse(content);
} else {
const yaml = await import("yaml");
parsed = yaml.parse(content);
}
// If the parsed content has an 'mcpServers' array, extract the first MCP server
// This handles hub packages that return a full config block
if (
parsed.mcpServers &&
Array.isArray(parsed.mcpServers) &&
parsed.mcpServers.length > 0
) {
return parsed.mcpServers[0];
}
return parsed;
},
};
/**
* Model processor - handles JSON/YAML configuration files
*/
export const modelProcessor: HubPackageProcessor<ModelConfig> = {
type: "model",
expectedFileExtensions: [".json", ".yaml", ".yml"],
parseContent: async (content: string, filename: string) => {
let parsed;
if (filename.endsWith(".json")) {
parsed = JSON.parse(content);
} else {
const yaml = await import("yaml");
parsed = yaml.parse(content);
}
// If the parsed content has a 'models' array, extract the first model
// This handles hub packages that return a full config block
if (
parsed.models &&
Array.isArray(parsed.models) &&
parsed.models.length > 0
) {
return parsed.models[0];
}
return parsed;
},
};
/**
* Prompt processor - handles text content from .md files
*/
export const promptProcessor: HubPackageProcessor<string> = {
type: "prompt",
expectedFileExtensions: [".md", ".txt"],
parseContent: (content: string) => content,
};
export const agentFileProcessor: HubPackageProcessor<AgentFile> = {
type: "agentFile",
expectedFileExtensions: [".md"],
parseContent: (content: string) => parseAgentFile(content),
validateContent: (agentFile: AgentFile) => {
return !!agentFile.name;
},
validateContent: (agentFile: AgentFile) => !!agentFile.name,
};
/**
* Generic hub package loader
* Automatically includes authentication headers when user is logged in,
* enabling access to private packages.
* Hub package loading has been removed.
* This function always throws.
*/
export async function loadPackageFromHub<T>(
slug: string,
processor: HubPackageProcessor<T>,
_processor: HubPackageProcessor<T>,
): Promise<T> {
const parts = slug.split("/");
if (parts.length !== 2) {
throw new Error(
`Invalid hub slug format. Expected "owner/package", got: ${slug}`,
);
}
const [ownerSlug, packageSlug] = parts;
// Use different endpoints based on package type
let downloadUrl: URL;
if (processor.type === "mcp" || processor.type === "model") {
// MCP and models use the registry endpoint
downloadUrl = new URL(
`registry/v1/${ownerSlug}/${packageSlug}/latest`,
env.apiBase,
);
} else {
// Rules and prompts use the v0 endpoint
downloadUrl = new URL(
`v0/${ownerSlug}/${packageSlug}/latest/download`,
env.apiBase,
);
}
try {
// Load auth config and get access token for private package access
const authConfig = loadAuthConfig();
const accessToken = getAccessToken(authConfig);
// Prepare headers with optional authorization
const headers: Record<string, string> = {};
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
const response = await fetch(downloadUrl, { headers });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Check if this is a registry endpoint (returns JSON directly) or a zip file
if (processor.type === "mcp" || processor.type === "model") {
// Registry endpoints return JSON with a 'content' field containing YAML/JSON
const jsonResponse = await response.json();
// Extract and parse the content field
if (jsonResponse.content) {
// Parse the YAML/JSON content
const parsedContent = await processor.parseContent(
jsonResponse.content,
`${slug}.yaml`,
);
return parsedContent;
} else {
// If there's no content field, return the response as-is (backward compatibility)
return jsonResponse;
}
} else {
// v0 endpoints return zip files
const arrayBuffer = await response.arrayBuffer();
const zip = new JSZip();
const zipContents = await zip.loadAsync(arrayBuffer);
// Find files matching expected extensions
const matchingFiles = Object.keys(zipContents.files).filter(
(filename) => {
if (zipContents.files[filename].dir) return false;
return processor.expectedFileExtensions.some((ext) =>
filename.endsWith(ext),
);
},
);
if (matchingFiles.length === 0) {
throw new Error(
`No ${processor.type} content found in downloaded zip file. Expected files with extensions: ${processor.expectedFileExtensions.join(", ")}`,
);
}
// Use the first matching file
const contentFile = zipContents.files[matchingFiles[0]];
const rawContent = await contentFile.async("text");
// Parse content using the processor
const parsedContent = await processor.parseContent(
rawContent,
matchingFiles[0],
);
// Validate if processor has validation
if (
processor.validateContent &&
!processor.validateContent(parsedContent)
) {
throw new Error(
`Invalid ${processor.type} content in ${matchingFiles[0]}`,
);
}
return parsedContent;
}
} catch (error: any) {
throw new Error(
`Failed to load ${processor.type} from hub "${slug}": ${error.message}`,
);
}
throw new Error(
`Hub package loading has been removed. Cannot load "${slug}" from hub.`,
);
}
/**
* Convenience functions for specific package types
* Convenience functions (stubs that throw)
*/
export const loadRuleFromHub = (slug: string) =>
loadPackageFromHub(slug, ruleProcessor);
export const loadMcpFromHub = (slug: string) =>
loadPackageFromHub(slug, mcpProcessor);
export const loadMcpFromHub = (_slug: string): Promise<any> =>
Promise.reject(new Error("Hub package loading has been removed."));
export const loadModelFromHub = (slug: string) =>
loadPackageFromHub(slug, modelProcessor);
export const loadModelFromHub = (_slug: string): Promise<ModelConfig> =>
Promise.reject(new Error("Hub package loading has been removed."));
/**
* Process a rule specification - supports file paths, hub slugs, or direct content
* Process a rule specification - supports file paths or direct content.
* Hub slug resolution has been removed.
*/
export async function processRule(ruleSpec: string): Promise<string> {
const trimmedRuleSpec = ruleSpec.trim();
@ -277,23 +105,6 @@ export async function processRule(ruleSpec: string): Promise<string> {
}
}
// Check if it might be a hub slug (contains "/" and is a single line)
if (!hasNewline && trimmedRuleSpec.includes("/")) {
const parts = trimmedRuleSpec.split("/");
// If it's exactly 2 parts and matches hub slug pattern, treat as hub slug
if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) {
return await loadRuleFromHub(trimmedRuleSpec);
}
// If it has more than 2 parts, it's an invalid hub slug
if (parts.length > 2) {
throw new Error(
`Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`,
);
}
}
// Otherwise, treat it as direct string content
return ruleSpec;
}
@ -315,14 +126,13 @@ export function isStringRule(rule: string) {
}
/**
* Batch load multiple packages with error handling
* Batch load (stub - always returns empty)
*/
export async function loadPackagesFromHub<T>(
slugs: string[],
processor: HubPackageProcessor<T>,
): Promise<T[]> {
const results: T[] = [];
for (const slug of slugs) {
try {
const content = await loadPackageFromHub(slug, processor);
@ -333,6 +143,5 @@ export async function loadPackagesFromHub<T>(
);
}
}
return results;
}

View file

@ -2,11 +2,6 @@ import { execSync } from "child_process";
import chalk from "chalk";
import {
isAuthenticated,
isAuthenticatedConfig,
loadAuthConfig,
} from "./auth/workos.js";
import { services } from "./services/index.js";
import {
getCurrentSession,
@ -27,28 +22,6 @@ function getVersionInfo(): string[] {
];
}
async function getAuthInfo(): Promise<string[]> {
const lines: string[] = ["", chalk.white("Authentication:")];
if (await isAuthenticated()) {
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
const email = config.userEmail || config.userId;
const orgId = config.organizationId;
lines.push(
` Email: ${chalk.green(email)}`,
` Org ID: ${chalk.cyan(orgId)}`,
);
} else {
lines.push(` ${chalk.yellow("Authenticated via environment variable")}`);
}
} else {
lines.push(` ${chalk.red("Not logged in")}`);
}
return lines;
}
function getConfigInfo(): string[] {
const lines: string[] = ["", chalk.white("Configuration:")];
@ -168,7 +141,6 @@ function getDiagnosticInfo(): string[] {
export async function handleInfoSlashCommand() {
const infoLines = [
...getVersionInfo(),
...(await getAuthInfo()),
...getConfigInfo(),
...getSessionInfo(),
...getUsageInfo(),

View file

@ -5,7 +5,7 @@ import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { AuthenticatedConfig } from "src/auth/workos-types.js";
import { AuthenticatedConfig } from "src/auth/workos.js";
import {
getModelName,

View file

@ -5,7 +5,7 @@ import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { AuthenticatedConfig } from "src/auth/workos-types.js";
import { AuthenticatedConfig } from "src/auth/workos.js";
import { AuthService } from "src/services/AuthService.js";
import {

View file

@ -4,7 +4,7 @@ import * as path from "path";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { AuthenticatedConfig } from "src/auth/workos-types.js";
import { AuthenticatedConfig } from "src/auth/workos.js";
import {
getModelName,

View file

@ -1,106 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadMcpFromHub } from "./hubLoader.js";
// Store original fetch to restore later
const originalFetch = global.fetch;
const mockFetch = vi.fn();
// Mock JSZip
vi.mock("jszip", () => {
const MockJSZip = vi.fn();
MockJSZip.prototype.loadAsync = vi.fn();
return { default: MockJSZip };
});
describe("loadMcpFromHub", () => {
let mockJSZip: any;
beforeEach(async () => {
vi.clearAllMocks();
// Set mock fetch for each test
global.fetch = mockFetch;
// Get the mocked JSZip constructor
const JSZip = (await import("jszip")).default;
mockJSZip = new JSZip();
});
afterEach(() => {
// Restore original fetch after each test
global.fetch = originalFetch;
});
it("should validate slug format", async () => {
await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
'Invalid hub slug format. Expected "owner/package", got: invalid-slug',
);
});
it("should handle HTTP errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
statusText: "Not Found",
});
await expect(loadMcpFromHub("continuedev/nonexistent-mcp")).rejects.toThrow(
'Failed to load mcp from hub "continuedev/nonexistent-mcp": HTTP 404: Not Found',
);
});
it("should handle network errors", async () => {
mockFetch.mockRejectedValueOnce(new Error("Network error"));
await expect(loadMcpFromHub("continuedev/test-mcp")).rejects.toThrow(
'Failed to load mcp from hub "continuedev/test-mcp": Network error',
);
});
it("should parse JSON configuration files", async () => {
const mockConfig = {
content:
"name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000",
};
// MCP packages now use the registry endpoint and return JSON directly
mockFetch.mockResolvedValueOnce({
ok: true,
json: vi.fn().mockResolvedValue(mockConfig),
});
const result = await loadMcpFromHub("continuedev/test-mcp");
// Should now parse the YAML content and return the parsed object
expect(result).toEqual({
name: "test-mcp",
command: "npx test-mcp",
args: ["--port", 3000],
});
});
it("should handle missing configuration files", async () => {
// MCP packages now use the registry endpoint
// If the content field is missing or empty, it should fail
mockFetch.mockResolvedValueOnce({
ok: true,
json: vi.fn().mockResolvedValue({}),
});
const result = await loadMcpFromHub("continuedev/no-config");
// The registry endpoint might return an empty object if no config exists
expect(result).toEqual({});
});
it("should handle invalid JSON configuration", async () => {
// MCP packages now use the registry endpoint
// If the registry returns invalid JSON, it should fail at the fetch level
mockFetch.mockResolvedValueOnce({
ok: true,
json: vi.fn().mockRejectedValue(new Error("Invalid JSON")),
});
await expect(loadMcpFromHub("continuedev/invalid-json")).rejects.toThrow(
'Failed to load mcp from hub "continuedev/invalid-json": Invalid JSON',
);
});
});

View file

@ -4,7 +4,7 @@ import * as path from "path";
import chalk from "chalk";
import { setConfigFilePermissions } from "core/util/paths.js";
import { AuthConfig, login } from "./auth/workos.js";
import type { AuthConfig } from "./auth/workos.js";
import { getApiClient } from "./config.js";
import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
@ -12,7 +12,7 @@ import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
import { question, questionWithChoices } from "./util/prompt.js";
import { question } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@ -85,39 +85,23 @@ export async function runOnboardingFlow(
return false;
}
// Step 4: Present user with two options
console.log(chalk.yellow("How do you want to get started?"));
console.log(chalk.white("1. ⏩ Log in with Continue"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
// Step 4: Prompt for API key
console.log(chalk.yellow("To get started, enter your Anthropic API key."));
const choice = await questionWithChoices(
chalk.yellow("\nEnter choice (1): "),
["1", "2", ""],
"1",
chalk.dim("Please enter 1 or 2"),
const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
);
if (choice === "1" || choice === "") {
await login();
return true;
} else if (choice === "2") {
const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
);
if (!isValidAnthropicApiKey(apiKey)) {
throw new Error(getApiKeyValidationError(apiKey));
}
await createOrUpdateConfig(apiKey);
console.log(
chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`),
);
return true;
} else {
throw new Error(`Invalid choice. Please select "1" or "2"`);
if (!isValidAnthropicApiKey(apiKey)) {
throw new Error(getApiKeyValidationError(apiKey));
}
await createOrUpdateConfig(apiKey);
console.log(
chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`),
);
return true;
}
export async function isFirstTime(): Promise<boolean> {
@ -147,7 +131,7 @@ export async function initializeWithOnboarding(
await loadConfiguration(
authConfig,
configPath,
getApiClient(authConfig?.accessToken),
getApiClient(undefined),
[],
false,
);

View file

@ -29,8 +29,8 @@ export class ApiClientService
/**
* Initialize the API client service
*/
async doInitialize(authConfig: AuthConfig): Promise<ApiClientServiceState> {
const apiClient = getApiClient(authConfig?.accessToken);
async doInitialize(_authConfig: AuthConfig): Promise<ApiClientServiceState> {
const apiClient = getApiClient(undefined);
return {
apiClient,
@ -40,11 +40,11 @@ export class ApiClientService
/**
* Update the API client with new auth config
*/
async update(authConfig: AuthConfig): Promise<ApiClientServiceState> {
async update(_authConfig: AuthConfig): Promise<ApiClientServiceState> {
logger.debug("Updating ApiClientService");
try {
const apiClient = getApiClient(authConfig?.accessToken);
const apiClient = getApiClient(undefined);
this.setState({
apiClient,

View file

@ -1,382 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
// Mock the workos module
vi.mock("../auth/workos.js");
// Import the workos functions we need to mock
import {
ensureOrganization,
isAuthenticated,
listUserOrganizations,
loadAuthConfig,
login,
logout,
saveAuthConfig,
} from "../auth/workos.js";
import { AuthService } from "./AuthService.js";
describe("AuthService", () => {
let service: AuthService;
const mockAuthConfig = {
accessToken: "test-token",
organizationId: "org-123",
userId: "user-123",
userEmail: "test@example.com",
refreshToken: "refresh-token",
expiresAt: Date.now() + 3600000,
};
beforeEach(() => {
vi.clearAllMocks();
service = new AuthService();
});
describe("State Management", () => {
test("should initialize with unauthenticated state", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
const state = await service.initialize();
expect(state).toEqual({
authConfig: null,
isAuthenticated: false,
organizationId: undefined,
});
});
test("should initialize with authenticated state", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
const state = await service.initialize();
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: "org-123",
});
});
});
describe("login()", () => {
test("should update state after successful login", async () => {
// Initialize first
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
await service.initialize();
// Mock successful login
vi.mocked(login).mockResolvedValue(mockAuthConfig);
const state = await service.login();
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: "org-123",
});
expect(service.getState()).toEqual(state);
});
test("should handle login failure", async () => {
await service.initialize();
const loginError = new Error("Login failed");
vi.mocked(login).mockRejectedValue(loginError);
await expect(service.login()).rejects.toThrow("Login failed");
});
});
describe("logout()", () => {
test("should clear state after logout", async () => {
// Initialize with authenticated state
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const state = await service.logout();
expect(state).toEqual({
authConfig: null,
isAuthenticated: false,
organizationId: undefined,
});
expect(logout).toHaveBeenCalled();
});
});
describe("ensureOrganization()", () => {
test("should update organization after ensuring", async () => {
// Initialize with auth but no org
const authWithoutOrg = { ...mockAuthConfig, organizationId: null };
vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
// Mock ensure organization
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
const state = await service.ensureOrganization();
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: "org-123",
});
});
test("should throw error if not authenticated", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
await service.initialize();
await expect(service.ensureOrganization()).rejects.toThrow(
"Not authenticated - cannot ensure organization",
);
});
test("should pass organization slug to ensureOrganization in headless mode", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const updatedConfig = { ...mockAuthConfig, organizationId: "org-456" };
vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig);
const state = await service.ensureOrganization(true, "org-slug");
expect(ensureOrganization).toHaveBeenCalledWith(
mockAuthConfig,
true,
"org-slug",
);
expect(state).toEqual({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: "org-456",
});
});
test("should handle personal organization slug", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const personalConfig = { ...mockAuthConfig, organizationId: null };
vi.mocked(ensureOrganization).mockResolvedValue(personalConfig);
const state = await service.ensureOrganization(true, "personal");
expect(ensureOrganization).toHaveBeenCalledWith(
mockAuthConfig,
true,
"personal",
);
expect(state).toEqual({
authConfig: personalConfig,
isAuthenticated: true,
organizationId: undefined,
});
});
test("should work without organization slug parameter", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
const state = await service.ensureOrganization(false);
expect(ensureOrganization).toHaveBeenCalledWith(
mockAuthConfig,
false,
undefined,
);
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: "org-123",
});
});
});
describe("switchOrganization()", () => {
test("should update state with new organization", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const state = await service.switchOrganization("org-456");
expect(state).toEqual({
authConfig: {
...mockAuthConfig,
organizationId: "org-456",
},
isAuthenticated: true,
organizationId: "org-456",
});
expect(saveAuthConfig).toHaveBeenCalledWith({
...mockAuthConfig,
organizationId: "org-456",
});
});
test("should handle null organization", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const state = await service.switchOrganization(null);
expect(state.organizationId).toBeUndefined();
});
test("should throw error if not file-based auth", async () => {
const tokenOnlyAuth = { accessToken: "token" } as any;
vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
await expect(service.switchOrganization("org-456")).rejects.toThrow(
"Not authenticated with file-based auth",
);
});
});
describe("getAvailableOrganizations()", () => {
test("should return organizations when authenticated", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
const mockOrgs = [
{ id: "org-1", name: "Org 1", slug: "org-1" },
{ id: "org-2", name: "Org 2", slug: "org-2" },
];
vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
const orgs = await service.getAvailableOrganizations();
expect(orgs).toEqual(mockOrgs);
});
test("should return null when not authenticated", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
await service.initialize();
const orgs = await service.getAvailableOrganizations();
expect(orgs).toBeNull();
});
test("should handle errors gracefully", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
vi.mocked(listUserOrganizations).mockRejectedValue(
new Error("API error"),
);
// Add error event listener to prevent unhandled rejection
const errorHandler = vi.fn();
service.on("error", errorHandler);
const orgs = await service.getAvailableOrganizations();
expect(orgs).toBeNull();
expect(errorHandler).toHaveBeenCalledWith(expect.any(Error));
// Clean up
service.off("error", errorHandler);
});
});
describe("hasMultipleOrganizations()", () => {
test("should return true when multiple orgs available", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
vi.mocked(listUserOrganizations).mockResolvedValue([
{ id: "org-1", name: "Org 1", slug: "org-1" },
{ id: "org-2", name: "Org 2", slug: "org-2" },
]);
const hasMultiple = await service.hasMultipleOrganizations();
expect(hasMultiple).toBe(true);
});
test("should return false when no orgs available", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
await service.initialize();
vi.mocked(listUserOrganizations).mockResolvedValue([]);
const hasMultiple = await service.hasMultipleOrganizations();
expect(hasMultiple).toBe(false);
});
});
describe("refresh()", () => {
test("should reload auth state from disk", async () => {
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
await service.initialize();
// Update mock to return authenticated state
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockResolvedValue(true);
const state = await service.refresh();
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: "org-123",
});
});
});
describe("Event Emission", () => {
test("should emit stateChanged on login", async () => {
// Initialize with no auth config to simulate logged out state
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticated).mockResolvedValue(false);
await service.initialize();
const listener = vi.fn();
service.on("stateChanged", listener);
vi.mocked(login).mockResolvedValue(mockAuthConfig);
await service.login();
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
isAuthenticated: true,
authConfig: mockAuthConfig,
organizationId: "org-123",
}),
expect.objectContaining({
isAuthenticated: false,
authConfig: null,
}),
);
});
test("should emit error on login failure", async () => {
await service.initialize();
const errorListener = vi.fn();
service.on("error", errorListener);
const error = new Error("Login failed");
vi.mocked(login).mockRejectedValue(error);
await expect(service.login()).rejects.toThrow();
expect(errorListener).toHaveBeenCalledWith(error);
});
});
});

View file

@ -1,22 +1,13 @@
import { AuthenticatedConfig } from "src/auth/workos-types.js";
import {
login as doLogin,
logout as doLogout,
ensureOrganization,
isAuthenticated,
listUserOrganizations,
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import { loadAuthConfig } from "../auth/workos.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { AuthServiceState } from "./types.js";
/**
* Service for managing authentication state and operations
* Encapsulates all auth logic and provides reactive updates
* Service for managing authentication state.
* Hub/WorkOS auth has been removed - this is a minimal stub that always
* reports unauthenticated.
*/
export class AuthService extends BaseService<AuthServiceState> {
constructor() {
@ -26,184 +17,49 @@ export class AuthService extends BaseService<AuthServiceState> {
});
}
/**
* Initialize the auth service by loading current config
*/
async doInitialize(): Promise<AuthServiceState> {
const authConfig = loadAuthConfig();
const authenticated = await isAuthenticated();
const state: AuthServiceState = {
authConfig,
isAuthenticated: authenticated,
organizationId: authConfig?.organizationId || undefined,
authConfig: null,
isAuthenticated: false,
};
logger.debug("AuthService initialized", {
authenticated,
hasConfig: !!authConfig,
orgId: state.organizationId,
});
logger.debug("AuthService initialized (no auth)");
return state;
}
/**
* Perform login flow
*/
async login(): Promise<AuthServiceState> {
logger.debug("Starting login flow");
try {
const newAuthConfig = await doLogin();
this.setState({
authConfig: newAuthConfig,
isAuthenticated: true,
organizationId: newAuthConfig?.organizationId || undefined,
});
logger.debug("Login successful", {
orgId: this.currentState.organizationId,
});
return this.getState();
} catch (error: any) {
logger.error("Login failed:", error);
this.emit("error", error);
throw error;
}
}
/**
* Perform logout
*/
async logout(): Promise<AuthServiceState> {
logger.debug("Logging out");
doLogout();
this.setState({
authConfig: null,
isAuthenticated: false,
organizationId: undefined,
});
logger.debug("Logout complete");
return this.getState();
}
/**
* Ensure organization is selected, prompting if necessary
*/
async ensureOrganization(
isHeadless: boolean = false,
cliOrganizationSlug?: string,
): Promise<AuthServiceState> {
if (!this.currentState.authConfig) {
throw new Error("Not authenticated - cannot ensure organization");
}
logger.debug("Ensuring organization is selected", {
currentOrgId: this.currentState.organizationId,
isHeadless,
cliOrganizationSlug,
});
const updatedConfig = await ensureOrganization(
this.currentState.authConfig,
isHeadless,
cliOrganizationSlug,
throw new Error(
"Login is not available. Hub authentication has been removed.",
);
}
this.setState({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: updatedConfig?.organizationId || undefined,
});
logger.debug("Organization ensured", {
orgId: this.currentState.organizationId,
});
async logout(): Promise<AuthServiceState> {
logger.debug("Logout (no-op)");
return this.getState();
}
/**
* Switch to a different organization
*/
async switchOrganization(
organizationId: string | null,
async ensureOrganization(
_isHeadless: boolean = false,
_cliOrganizationSlug?: string,
): Promise<AuthServiceState> {
if (
!this.currentState.authConfig ||
!("userId" in this.currentState.authConfig)
) {
throw new Error(
"Not authenticated with file-based auth - cannot switch organizations",
);
}
logger.debug("Switching organization", {
from: this.currentState.organizationId,
to: organizationId,
});
const authenticatedConfig = this.currentState
.authConfig as AuthenticatedConfig;
const updatedConfig: AuthenticatedConfig = {
...authenticatedConfig,
organizationId,
};
saveAuthConfig(updatedConfig);
this.setState({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: organizationId || undefined,
});
logger.debug("Organization switched", {
newOrgId: this.currentState.organizationId,
});
return this.getState();
}
/**
* Get available organizations for the current user
*/
async getAvailableOrganizations(): Promise<
{ id: string; name: string }[] | null
> {
if (!this.currentState.isAuthenticated) {
return null;
}
try {
return await listUserOrganizations();
} catch (error: any) {
logger.error("Failed to list organizations:", error);
this.emit("error", error);
return null;
}
async switchOrganization(
_organizationId: string | null,
): Promise<AuthServiceState> {
return this.getState();
}
async getAvailableOrganizations(): Promise<null> {
return null;
}
/**
* Check if the current user has multiple organizations available
*/
async hasMultipleOrganizations(): Promise<boolean> {
const orgs = await this.getAvailableOrganizations();
return orgs !== null && orgs.length > 0;
return false;
}
/**
* Refresh auth state from disk (useful after external changes)
*/
async refresh(): Promise<AuthServiceState> {
logger.debug("Refreshing auth state from disk");
return this.reload();
}
}

View file

@ -224,8 +224,8 @@ export class ConfigService
try {
const modelConfig = await unrollPackageIdentifiersAsConfigYaml(
[DEFAULT_MODEL_IDENTIFIER],
authConfig?.accessToken ?? null,
authConfig?.organizationId ?? null,
null,
null,
apiClient,
);
const defaultModel = modelConfig?.models?.[0];

View file

@ -2,9 +2,6 @@ import { decodeFQSN, getTemplateVariables } from "@continuedev/config-yaml";
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { isAuthenticated, loadAuthConfig } from "src/auth/workos.js";
import { get } from "../util/apiClient.js";
import { getErrorString } from "../util/error.js";
import { logger } from "../util/logger.js";
@ -176,65 +173,8 @@ export class MCPService
return await operation();
}
try {
// Try the operation first
return await operation();
} catch (error: unknown) {
// If not a 401 error, rethrow
if (!isAuthError(error)) {
throw error;
}
// Check if user is signed in
const isAuthed = await isAuthenticated();
if (!isAuthed) {
throw error;
}
const authConfig = loadAuthConfig();
// Clear cached token since it's invalid
this.apiKeyCache.delete(serverName);
// Fetch OAuth token from backend
const organizationSlug = authConfig?.organizationId;
let token: string | null = null;
try {
const params = new URLSearchParams({
url: serverConfig.url,
});
if (organizationSlug) {
params.set("organizationSlug", organizationSlug);
}
if (serverConfig.sourceSlug) {
params.set("slug", serverConfig.sourceSlug);
}
const response = await get<{
configured: boolean;
hasCredentials: boolean;
accessToken?: string;
expiresAt?: string;
expired?: boolean;
}>(`/ide/mcp-auth?${params.toString()}`);
if (response.data.hasCredentials && response.data.accessToken) {
token = response.data.accessToken;
this.apiKeyCache.set(serverName, token);
}
} catch {
logger.debug("Failed to fetch mcp oauth credentials");
}
if (!token) {
throw error;
}
this.apiKeyCache.set(serverConfig.name, token);
return await operation();
}
// No auth/token refresh available - just execute the operation directly
return await operation();
}
/**

View file

@ -9,8 +9,6 @@ vi.mock("../hubLoader.js", () => ({
loadPackageFromHub: vi.fn(),
loadPackagesFromHub: vi.fn(),
loadModelFromHub: vi.fn(),
mcpProcessor: {},
modelProcessor: {},
processRule: vi.fn(),
isStringRule: vi.fn(),
agentFileProcessor: {
@ -80,7 +78,7 @@ describe("Agent file Integration Tests", () => {
let mockProcessRule: any;
let mockCreateLlmApi: any;
let mockGetLlmApi: any;
let mockModelProcessor: any;
// modelProcessor removed (Hub integration removed)
let mockDecodePackageIdentifier: any;
let mockLoadModelFromHub: any;
let mockIsStringRule: any;
@ -123,7 +121,7 @@ describe("Agent file Integration Tests", () => {
mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any;
mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any;
mockProcessRule = hubLoaderModule.processRule as any;
mockModelProcessor = hubLoaderModule.modelProcessor;
// mockModelProcessor removed (Hub integration removed)
mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any;
mockIsStringRule = hubLoaderModule.isStringRule as any;
mockCreateLlmApi = configModule.createLlmApi as any;

View file

@ -1,4 +1,3 @@
import { loadAuthConfig } from "../auth/workos.js";
import { HookService } from "../hooks/HookService.js";
import { initializeWithOnboarding } from "../onboarding.js";
import {
@ -74,8 +73,7 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
}
// Handle onboarding for TUI mode (headless: false) unless explicitly skipped
if (!initOptions.headless && !initOptions.skipOnboarding) {
const authConfig = loadAuthConfig();
await initializeWithOnboarding(authConfig, commandOptions.config);
await initializeWithOnboarding(null, commandOptions.config);
}
// Handle ANTHROPIC_API_KEY in headless mode when no config path is provided
@ -201,17 +199,6 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
serviceContainer.get<AgentFileServiceState>(SERVICE_NAMES.AGENT_FILE),
]);
// Ensure organization is selected if authenticated
let finalAuthState = authState;
if (authState.authConfig) {
finalAuthState = await authService.ensureOrganization(
initOptions.headless ?? false,
commandOptions.org,
);
// Update the auth service state in container
serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState);
}
if (!apiClientState.apiClient) {
throw new Error("API client not available");
}
@ -220,28 +207,15 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
// otherwise use initial options.config (for first initialization)
// IMPORTANT: Always prefer explicit --config flag over saved state
const currentState = configService.getState();
let configPath =
const configPath =
commandOptions.config ||
(currentState.configPath === undefined
? undefined
: currentState.configPath);
// If no config path is available, check for saved config URI in auth config
if (!configPath) {
const { getConfigUri } = await import("../auth/workos.js");
const { uriToPath, uriToSlug } = await import("../auth/uriUtils.js");
const configUri = getConfigUri(finalAuthState.authConfig);
if (configUri) {
const filePath = uriToPath(configUri);
const slug = uriToSlug(configUri);
configPath = filePath || slug || undefined;
}
}
return await configService.initialize({
authConfig: finalAuthState.authConfig,
authConfig: authState.authConfig,
configPath,
// organizationId: finalAuthState.organizationId || null,
apiClient: apiClientState.apiClient,
agentFileState,
injectedConfigOptions: commandOptions,

View file

@ -10,7 +10,7 @@ import { AssistantConfig } from "@continuedev/sdk";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { AuthConfig } from "../auth/workos.js";
import type { AuthConfig } from "../auth/workos.js";
import { BaseCommandOptions } from "../commands/BaseCommandOptions.js";
import { PermissionMode } from "../permissions/types.js";

View file

@ -12,11 +12,6 @@ import type {
import historyManager from "core/util/history.js";
import { v4 as uuidv4 } from "uuid";
import {
getAccessToken,
isAuthenticatedConfig,
loadAuthConfig,
} from "./auth/workos.js";
import { DEFAULT_SESSION_TITLE } from "./constants/session.js";
import { env } from "./env.js";
import { logger } from "./util/logger.js";
@ -421,45 +416,10 @@ function getSessionMetadataWithPreview(
}
/**
* Fetch remote agents/sessions from the API
* Remote sessions are no longer available (Hub integration removed).
*/
export async function getRemoteSessions(): Promise<ExtendedSessionMetadata[]> {
try {
const authConfig = loadAuthConfig();
const accessToken = getAccessToken(authConfig);
if (!accessToken || !isAuthenticatedConfig(authConfig)) {
return [];
}
const response = await fetch(new URL("agents", env.apiBase), {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
logger.error(`Failed to fetch remote agents: ${response.status}`);
return [];
}
const agents = await response.json();
return agents.map((agent: any) => ({
sessionId: `remote-${agent.id}`,
title: agent.name || "Remote Agent",
dateCreated: new Date(agent.create_time_ms).toISOString(),
workspaceDirectory: "",
isRemote: true,
remoteId: agent.id,
firstUserMessage: "Remote agent session",
}));
} catch (error) {
logger.error("Error fetching remote sessions:", error);
return [];
}
return [];
}
/**

View file

@ -8,7 +8,7 @@ import {
type MockedFunction,
} from "vitest";
import { AuthenticatedConfig } from "./auth/workos-types.js";
import { AuthenticatedConfig } from "./auth/workos.js";
import type { AuthConfig } from "./auth/workos.js";
import type { ConfigServiceState } from "./services/types.js";
import { handleSlashCommands } from "./slashCommands.js";
@ -52,7 +52,6 @@ vi.mock("./util/logger.js", () => ({
vi.mock("./env.js", () => ({
env: {
continueHome: "/home/test/.continue",
appUrl: "https://continue.dev",
},
}));

View file

@ -1,11 +1,6 @@
import { type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import {
isAuthenticated,
isAuthenticatedConfig,
loadAuthConfig,
} from "./auth/workos.js";
import { getAllSlashCommands } from "./commands/commands.js";
import { handleInit } from "./commands/init.js";
import { handleInfoSlashCommand } from "./infoScreen.js";
@ -53,66 +48,24 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
}
async function handleLogin() {
try {
const newAuthState = await services.auth.login();
await reloadService(SERVICE_NAMES.AUTH);
const userInfo =
newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
: "user";
console.info(chalk.green(`\nLogged in as ${userInfo}`));
return {
exit: false,
output: "Login successful! All services updated automatically.",
};
} catch (error: any) {
console.error(chalk.red(`\nLogin failed: ${error.message}`));
return {
exit: false,
output: `Login failed: ${error.message}`,
};
}
return {
exit: false,
output: "Login is not available. Hub authentication has been removed.",
};
}
async function handleLogout() {
try {
await services.auth.logout();
return {
exit: true,
output: "Logged out successfully",
};
} catch {
return {
exit: true,
output: "Logged out successfully",
};
}
return {
exit: false,
output: "Logout is not available. Hub authentication has been removed.",
};
}
async function handleWhoami() {
const authed = await isAuthenticated();
if (authed) {
const config = loadAuthConfig(); // TODO duplicate auth config loading
if (config && isAuthenticatedConfig(config)) {
return {
exit: false,
output: `Logged in as ${config.userEmail || config.userId}`,
};
} else {
return {
exit: false,
output: "Authenticated via environment variable",
};
}
} else {
return {
exit: false,
output: "Not logged in. Use /login to authenticate.",
};
}
return {
exit: false,
output: "Not logged in. Hub authentication has been removed.",
};
}
async function handleFork() {

View file

@ -3,7 +3,6 @@ import * as path from "path";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { logger } from "../util/logger.js";
import { Tool } from "./types.js";
@ -61,13 +60,12 @@ export const uploadArtifactTool: Tool = {
);
}
// Get access token
const authConfig = loadAuthConfig();
const accessToken = getAccessToken(authConfig);
// Auth has been removed - artifact upload requires auth
const accessToken: string | null = null;
if (!accessToken) {
throw new ContinueError(
ContinueErrorReason.Unspecified,
"Authentication required. Please log in with 'cn login'.",
"Artifact upload requires authentication, which has been removed.",
);
}

View file

@ -3,14 +3,6 @@ import * as path from "path";
import React, { useEffect, useState } from "react";
import {
getAccessToken,
getAssistantSlug,
getOrganizationId,
listUserOrganizations,
loadAuthConfig,
} from "../auth/workos.js";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
import { services } from "../services/index.js";
@ -19,7 +11,7 @@ import { Selector, SelectorOption } from "./Selector.js";
interface ConfigOption extends SelectorOption {
type: "local" | "assistant" | "create";
slug?: string;
organizationId?: string | null; // null for personal, string for org
organizationId?: string | null;
}
interface ConfigSelectorProps {
@ -42,104 +34,26 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
useEffect(() => {
const loadConfigs = async () => {
try {
const authConfig = loadAuthConfig();
const accessToken = getAccessToken(authConfig);
const currentOrganizationId = getOrganizationId(authConfig);
const options: ConfigOption[] = [];
let currentId: string | null = null;
// Add local config.yaml if it exists
if (fs.existsSync(CONFIG_PATH)) {
options.push({
id: "local",
name: "[Personal] Local config.yaml",
name: "Local config.yaml",
type: "local",
organizationId: null,
});
}
// Add assistants from all organizations if authenticated
if (accessToken) {
const apiClient = getApiClient(accessToken);
try {
// Get all organizations
const organizations = await listUserOrganizations();
const allOrgs = [
{ id: null, name: "Personal" }, // Personal organization
...(organizations || []),
];
// Fetch assistants for each organization
const assistantPromises = allOrgs.map(async (org) => {
try {
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
organizationId: org.id ?? undefined,
});
return assistants.map((assistant) => {
const name =
(assistant.configResult.config as any)?.name ??
`${assistant.ownerSlug}/${assistant.packageSlug}`;
const displayName = `[${org.name}] ${name}`;
// Create unique ID that includes org info to avoid conflicts
const uniqueId = `${org.id || "personal"}-${assistant.packageSlug}`;
return {
id: uniqueId,
name: displayName,
type: "assistant" as const,
slug: `${assistant.ownerSlug}/${assistant.packageSlug}`,
organizationId: org.id,
};
});
} catch (err) {
console.error(
`Failed to load assistants for org ${org.name}:`,
err,
);
return [];
}
});
const assistantResults = await Promise.all(assistantPromises);
const allAssistants = assistantResults.flat();
options.push(...allAssistants);
} catch (err) {
console.error("Failed to load organizations or assistants:", err);
}
}
// Add "Create new assistant" option only when logged in
if (accessToken) {
options.push({
id: "create",
name: "Create new assistant",
type: "create",
displaySuffix: " (opens web)",
});
}
// Determine current config by checking both auth config and service state
const assistantSlug = getAssistantSlug(authConfig);
// Determine current config
const currentConfigState = services.config.getState();
let currentId: string | null = null;
if (assistantSlug) {
// Find the matching config by slug and organization
const matchingConfig = options.find(
(opt) =>
opt.type === "assistant" &&
opt.slug === assistantSlug &&
opt.organizationId === currentOrganizationId,
);
currentId = matchingConfig?.id || null;
} else if (
if (
currentConfigState.configPath === CONFIG_PATH &&
fs.existsSync(CONFIG_PATH)
) {
// Only mark local config as current if it's actually the active config path in the service
// This ensures we don't show a green checkmark for first-time users just because the file exists
currentId = "local";
}

View file

@ -1,108 +0,0 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
DefaultApiInterface,
GetFreeTrialStatus200Response,
} from "@continuedev/sdk/dist/api/dist/index.js";
import { Text } from "ink";
import React, { useEffect, useState } from "react";
export function isModelUsingFreeTrial(model: ModelConfig): boolean {
return (
model.provider === "continue-proxy" &&
(model as any).apiKeyLocation.startsWith("free_trial:")
);
}
interface FreeTrialStatusProps {
apiClient?: DefaultApiInterface;
onTransitionStateChange?: (isShowingTransition: boolean) => void;
model: ModelConfig;
}
const FreeTrialStatus: React.FC<FreeTrialStatusProps> = ({
apiClient,
onTransitionStateChange,
model,
}) => {
const [status, setStatus] = useState<GetFreeTrialStatus200Response | null>(
null,
);
const [loading, setLoading] = useState(true);
const fetchStatus = async () => {
try {
if (!apiClient) {
setStatus(null);
setLoading(false);
return;
}
const response = await apiClient.getFreeTrialStatus();
setStatus(response);
setLoading(false);
} catch {
// Silently handle errors - component returns null if no status
setStatus(null);
setLoading(false);
}
};
useEffect(() => {
// Initial fetch
fetchStatus();
// Don't poll in test environment
if (process.env.NODE_ENV === "test") {
return;
}
// Poll every 5 seconds
const interval = setInterval(fetchStatus, 5000);
return () => clearInterval(interval);
}, []);
// Check if user has maxed out their free trial and notify parent
useEffect(() => {
if (!status || !status.optedInToFreeTrial || loading) {
// No transition needed
if (onTransitionStateChange) {
onTransitionStateChange(false);
}
return;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Check if user has maxed out their free trial
const shouldShowTransition =
chatUsed >= chatLimit && isModelUsingFreeTrial(model);
if (onTransitionStateChange) {
onTransitionStateChange(shouldShowTransition);
}
}, [status, loading, onTransitionStateChange, model]);
// Don't render anything while loading or if no status
if (
loading ||
!status ||
!status.optedInToFreeTrial ||
!isModelUsingFreeTrial(model)
) {
return null;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Only show the normal status text - transition UI is handled by parent
return (
<Text color="dim">
{chatUsed}/{chatLimit} free trial
</Text>
);
};
export { FreeTrialStatus };

View file

@ -1,334 +0,0 @@
import * as fs from "fs";
import * as path from "path";
import { Box, Text, useInput } from "ink";
import open from "open";
import React, { useState } from "react";
import useSWR from "swr";
import { listUserOrganizations } from "../auth/workos.js";
import { env } from "../env.js";
import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "../util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js";
import { useNavigation } from "./context/NavigationContext.js";
import { defaultBoxStyles } from "./styles.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
// Helper functions for input handling
interface ChoiceInputOptions {
input: string;
key: any;
selectedOption: number;
setSelectedOption: (option: number) => void;
hasOrganizations: boolean;
handleOptionSelect: () => void;
}
function handleChoiceInput(options: ChoiceInputOptions): void {
const {
input,
key,
selectedOption,
setSelectedOption,
hasOrganizations,
handleOptionSelect,
} = options;
if (key.upArrow && selectedOption > 1) {
setSelectedOption(selectedOption - 1);
} else if (key.downArrow && selectedOption < (hasOrganizations ? 4 : 3)) {
setSelectedOption(selectedOption + 1);
} else if (input === "1") {
setSelectedOption(1);
} else if (input === "2") {
setSelectedOption(2);
} else if (input === "3") {
setSelectedOption(3);
} else if (input === "4" && hasOrganizations) {
setSelectedOption(4);
} else if (key.return) {
handleOptionSelect();
}
}
interface ApiKeyInputOptions {
input: string;
key: any;
apiKey: string;
setApiKey: (key: string) => void;
setErrorMessage: (msg: string) => void;
handleApiKeySubmit: () => void;
}
function handleApiKeyInput(options: ApiKeyInputOptions): void {
const { input, key, apiKey, setApiKey, setErrorMessage, handleApiKeySubmit } =
options;
if (key.return) {
if (isValidAnthropicApiKey(apiKey)) {
handleApiKeySubmit();
} else {
setErrorMessage(getApiKeyValidationError(apiKey));
}
} else if (key.backspace || key.delete) {
setApiKey(apiKey.slice(0, -1));
setErrorMessage("");
} else if (input && !key.ctrl && !key.meta) {
setApiKey(apiKey + input);
setErrorMessage("");
}
}
interface FreeTrialTransitionUIProps {
onReload: () => void;
}
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
onReload,
}) => {
const { navigateTo, closeCurrentScreen } = useNavigation();
const [currentStep, setCurrentStep] = useState<
"choice" | "enterApiKey" | "processing" | "success" | "error"
>("choice");
const [selectedOption, setSelectedOption] = useState(1);
const [apiKey, setApiKey] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [successMessage, setSuccessMessage] = useState("");
const [wasModelsSetup, setWasModelsSetup] = useState(false);
// Fetch organizations using SWR
const { data: organizations } = useSWR(
"organizations",
listUserOrganizations,
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
shouldRetryOnError: false,
},
);
const hasOrganizations = organizations && organizations.length > 0;
useInput((input, key) => {
// Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit
if (key.escape) {
closeCurrentScreen();
return;
}
// Handle Ctrl+C with two-stage exit (delegates to main process)
if (key.ctrl && input === "c") {
process.kill(process.pid, "SIGINT");
return;
}
if (currentStep === "choice") {
handleChoiceInput({
input,
key,
selectedOption,
setSelectedOption,
hasOrganizations: !!hasOrganizations,
handleOptionSelect,
});
} else if (currentStep === "enterApiKey") {
handleApiKeyInput({
input,
key,
apiKey,
setApiKey,
setErrorMessage,
handleApiKeySubmit,
});
} else if (currentStep === "success" || currentStep === "error") {
if (key.return) {
closeCurrentScreen();
// If user went through models setup, do a full reload to register their purchase
if (wasModelsSetup) {
onReload();
}
}
}
});
const handleOptionSelect = async () => {
if (selectedOption === 1) {
// Option 1: Open models setup page
setCurrentStep("processing");
const modelsUrl = new URL("settings/billing", env.appUrl).toString();
setWasModelsSetup(true); // Track that user went through models setup
try {
await open(modelsUrl);
setSuccessMessage(
`Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.`,
);
setCurrentStep("success");
} catch {
setErrorMessage(
`Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`,
);
setCurrentStep("error");
}
} else if (selectedOption === 2) {
// Option 2: Enter API key
setCurrentStep("enterApiKey");
setWasModelsSetup(false); // This is not models setup
} else if (selectedOption === 3) {
// Option 3: Switch to different configuration
navigateTo("config");
} else if (selectedOption === 4 && hasOrganizations) {
// Option 4: Switch to configuration (includes organization switching)
navigateTo("config");
}
};
const handleApiKeySubmit = async () => {
setCurrentStep("processing");
try {
await createOrUpdateConfig(apiKey);
setSuccessMessage(
"✓ API key saved successfully! Switching to local configuration...",
);
setCurrentStep("success");
// After a brief delay, switch to local configuration
setTimeout(() => {
closeCurrentScreen();
onReload();
}, 1000);
} catch (error) {
setErrorMessage(
`❌ Error saving API key: ${error}. Press Enter to try again.`,
);
setCurrentStep("error");
}
};
if (currentStep === "choice") {
const options = [
{ num: 1, text: "💳 Sign up for models add-on (recommended)" },
{ num: 2, text: "🔑 Enter your Anthropic API key" },
{ num: 3, text: "⚙️ Switch to a different configuration" },
];
if (hasOrganizations) {
options.push({
num: 4,
text: "🏢 Switch to organization configuration",
});
}
return (
<Box {...defaultBoxStyles("yellow")}>
<Text bold color="yellow">
🚀 Free trial limit reached!
</Text>
<Text>Choose how you'd like to continue:</Text>
<Text></Text>
{options.map((option) => (
<Text
key={option.num}
color={selectedOption === option.num ? "cyan" : "white"}
>
{selectedOption === option.num ? "➤ " : " "}
{option.num}. {option.text}
</Text>
))}
<Text></Text>
<Text color="gray">
↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select,
Enter to confirm
</Text>
</Box>
);
}
if (currentStep === "enterApiKey") {
return (
<Box {...defaultBoxStyles("yellow")}>
<Text bold color="yellow">
Enter your Anthropic API key
</Text>
<Text></Text>
<Text>API Key: {"*".repeat(apiKey.length)}</Text>
<Text></Text>
{errorMessage && <Text color="red">{errorMessage}</Text>}
<Text color="gray">
Type your API key and press Enter (must start with 'sk-ant-')
</Text>
</Box>
);
}
if (currentStep === "processing") {
return (
<Box {...defaultBoxStyles("blue")}>
<Text bold color="blue">
Processing...
</Text>
<Text>Please wait...</Text>
</Box>
);
}
if (currentStep === "success") {
return (
<Box {...defaultBoxStyles("green")}>
<Text bold color="green">
Success!
</Text>
<Text>{successMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and continue with your new subscription"
: "Press Enter to continue your conversation"}
</Text>
</Box>
);
}
if (currentStep === "error") {
return (
<Box {...defaultBoxStyles("red")}>
<Text bold color="red">
Error
</Text>
<Text>{errorMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and try again"
: "Press Enter to continue"}
</Text>
</Box>
);
}
return null;
};
export { FreeTrialTransitionUI };

View file

@ -9,7 +9,6 @@ import React, {
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { listUserOrganizations } from "../auth/workos.js";
import { useServices } from "../hooks/useService.js";
import {
ApiClientServiceState,
@ -113,40 +112,9 @@ function useTUIChatServices(remoteUrl?: string) {
return { services, allServicesReady, isRemoteMode };
}
// Custom hook to fetch organization name
function useOrganizationName(organizationId?: string): string | undefined {
const [organizationName, setOrganizationName] = useState<string | undefined>(
undefined,
);
useEffect(() => {
if (!organizationId) {
setOrganizationName(undefined);
return;
}
let isMounted = true;
async function fetchOrgName() {
try {
const orgs = await listUserOrganizations();
if (!isMounted) return;
const org = orgs?.find((o) => o.id === organizationId);
if (org) {
setOrganizationName(org.name);
}
} catch (error) {
logger.debug("Failed to fetch organization name", { error });
}
}
fetchOrgName();
return () => {
isMounted = false;
};
}, [organizationId]);
// Organization names are no longer available (Hub integration removed)
function useOrganizationName(_organizationId?: string): string | undefined {
const organizationName = undefined;
return organizationName;
}
@ -459,7 +427,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
<ResourceDebugBar visible={navState.currentScreen === "chat"} />
)}
{/* Free trial status and Continue CLI info - always show */}
{/* Bottom status bar */}
<BottomStatusBar
currentMode={services?.toolPermissions?.currentMode ?? "normal"}
remoteUrl={remoteUrl}

View file

@ -1,11 +0,0 @@
import React from "react";
// Mock FreeTrialStatus component that doesn't create any timers
const FreeTrialStatus: React.FC<any> = () => {
return null;
};
export { FreeTrialStatus };
export function isModelUsingFreeTrial(): boolean {
return false;
}

View file

@ -1,173 +0,0 @@
import { render } from "ink-testing-library";
import React from "react";
import { vi } from "vitest";
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
// Mock the 'open' module to prevent actual URL opening during tests
vi.mock("open", () => ({
default: vi.fn(),
}));
// Mock the NavigationContext
vi.mock("../context/NavigationContext.js", () => ({
useNavigation: () => ({
navigateTo: vi.fn(),
closeCurrentScreen: vi.fn(),
isScreenActive: vi.fn(() => false),
state: { currentScreen: "free-trial", screenData: null },
}),
}));
describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
const mockOnReload = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
});
describe("Initial Choice Screen Rendering", () => {
it("displays all three options with proper formatting", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toContain("🚀 Free trial limit reached!");
expect(frame).toContain("1. 💳 Sign up for models add-on");
expect(frame).toContain("2. 🔑 Enter your Anthropic API key");
expect(frame).toContain("3. ⚙️ Switch to a different configuration");
expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select");
});
it("highlights first option by default", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toContain("➤ 1. 💳 Sign up for models add-on");
expect(frame).not.toContain("➤ 2. 🔑 Enter your Anthropic API key");
expect(frame).not.toContain(
"➤ 3. ⚙️ Switch to a different configuration",
);
});
it("renders without crashing when all props are provided", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toBeDefined();
expect(frame?.length).toBeGreaterThan(0);
});
it("renders without crashing when onShowConfigSelector is not provided", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI
onReload={mockOnReload}
// onShowConfigSelector not provided
/>,
);
const frame = lastFrame();
expect(frame).toBeDefined();
expect(frame?.length).toBeGreaterThan(0);
expect(frame).toContain("3. ⚙️ Switch to a different configuration");
});
it("includes proper user instructions", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toContain("Choose how you'd like to continue:");
expect(frame).toContain(
"↑/↓ to navigate or 1/2/3 to select, Enter to confirm",
);
});
it("shows all options with proper descriptions", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toContain("Sign up for models add-on (recommended)");
expect(frame).toContain("Enter your Anthropic API key");
expect(frame).toContain("Switch to a different configuration");
});
});
describe("Component Props and Interface", () => {
it("accepts all required callback props", () => {
// Test that component accepts and renders with all props
expect(() => {
render(<FreeTrialTransitionUI onReload={mockOnReload} />);
}).not.toThrow();
});
it("accepts optional onShowConfigSelector prop", () => {
// Test that component works without onShowConfigSelector
expect(() => {
render(<FreeTrialTransitionUI onReload={mockOnReload} />);
}).not.toThrow();
});
});
describe("Visual Styling and Layout", () => {
it("renders with proper border styling", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
// Check for box border characters (unicode box drawing)
expect(frame).toMatch(/[╭╮╯╰│─]/);
});
it("displays with proper spacing and formatting", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
// Should have proper spacing between lines
expect(frame?.split("\n").length).toBeGreaterThan(5);
});
it("shows selection indicator on first option by default", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
const lines = frame?.split("\n") || [];
const modelsLine = lines.find((line) =>
line.includes("Sign up for models add-on"),
);
const apiKeyLine = lines.find((line) =>
line.includes("Enter your Anthropic API key"),
);
const configLine = lines.find((line) =>
line.includes("Switch to a different configuration"),
);
expect(modelsLine).toContain("➤");
expect(apiKeyLine).not.toContain("➤");
expect(configLine).not.toContain("➤");
});
});
describe("URL Opening Security", () => {
it("should use mocked open function to prevent actual URL opening", async () => {
// This test verifies that we properly mock the 'open' module
// to prevent actual URLs from being opened during test runs
const openModule = await import("open");
expect(openModule.default).toBeDefined();
expect(typeof openModule.default).toBe("function");
});
});
});

View file

@ -1,65 +0,0 @@
import { vi } from "vitest";
// Test URL opening behavior without complex component rendering
describe("FreeTrialTransitionUI - URL Opening Security", () => {
it("should mock URL opening to prevent actual browser launches during tests", () => {
// This test verifies that we properly mock the 'open' module
// to prevent actual URLs from being opened during test runs
// Import and check that open is mocked
const mockOpen = vi.fn();
vi.mock("open", () => mockOpen);
// Verify the mock is properly set up
expect(mockOpen).toBeDefined();
expect(typeof mockOpen).toBe("function");
});
it("should verify URL format for models setup", () => {
// Test the URL construction logic without actually opening URLs
const baseUrl = "https://test.continue.dev";
const expectedUrl = new URL("setup-models", baseUrl).toString();
expect(expectedUrl).toBe("https://test.continue.dev/setup-models");
});
it("should handle URL construction with different base URLs", () => {
// Test URL construction with various base URLs
const testCases = [
{
base: "https://continue.dev",
expected: "https://continue.dev/setup-models",
},
{
base: "https://app.continue.dev",
expected: "https://app.continue.dev/setup-models",
},
{
base: "http://localhost:3000",
expected: "http://localhost:3000/setup-models",
},
];
testCases.forEach(({ base, expected }) => {
const url = new URL("setup-models", base).toString();
expect(url).toBe(expected);
});
});
it("should validate that mocking prevents security issues in tests", () => {
// This test documents the security consideration:
// Without proper mocking, tests could open arbitrary URLs in the user's browser
// The mock ensures this doesn't happen during automated test runs
const openFunction = vi.fn();
// Simulate what would happen if URL opening was called
openFunction("https://malicious-site.com");
// Verify the mock was called instead of actual URL opening
expect(openFunction).toHaveBeenCalledWith("https://malicious-site.com");
expect(openFunction).toHaveBeenCalledTimes(1);
// In real usage, this would have opened a browser tab, but with mocking it's safe
});
});

View file

@ -1,21 +0,0 @@
// Integration tests for free trial transition - simplified version
describe("TUIChat - Free Trial Transition Integration", () => {
it("should integrate free trial transition with config selector", () => {
// This test verifies that the integration points exist
// More comprehensive integration tests would require complex mocking
// that is difficult to maintain and test reliably.
// The key integration points are:
// 1. FreeTrialTransitionUI receives onShowConfigSelector callback
// 2. TUIChat provides handleFreeTrialShowConfigSelector function
// 3. Config selector is shown when option 3 is selected
// These integration points are tested via:
// - Type checking (ensures interfaces match)
// - Manual testing during development
// - E2E tests that exercise the full flow
expect(true).toBe(true); // Placeholder test
});
});

View file

@ -1,12 +1,5 @@
// Mock API Client
export class MockApiClient {
async getFreeTrialStatus() {
return {
optedInToFreeTrial: true,
chatCount: 5,
chatLimit: 100,
};
}
async listAssistants() {
return [];
}

View file

@ -4,7 +4,6 @@ import React, { useEffect, useState } from "react";
import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js";
import type { PermissionMode } from "../../permissions/types.js";
import type { NavigationScreen } from "../context/NavigationContext.js";
import { FreeTrialStatus } from "../FreeTrialStatus.js";
import { UpdateNotification } from "../UpdateNotification.js";
import { ContextPercentageDisplay } from "./ContextPercentageDisplay.js";
@ -89,24 +88,6 @@ export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
</React.Fragment>
)}
</Box>
<Box>
{!isRemoteMode && services.model?.model && (
<FreeTrialStatus
apiClient={services.apiClient?.apiClient || undefined}
model={services.model.model}
onTransitionStateChange={(shouldShow) => {
if (shouldShow && navState.currentScreen === "chat") {
navigateTo("free-trial");
} else if (
!shouldShow &&
navState.currentScreen === "free-trial"
) {
closeCurrentScreen();
}
}}
/>
)}
</Box>
<Box marginRight={2} marginLeft={2}>
<UpdateNotification isRemoteMode={isRemoteMode} />
</Box>

View file

@ -8,7 +8,6 @@ import { ConfigSelector } from "../ConfigSelector.js";
import type { NavigationScreen } from "../context/NavigationContext.js";
import { DiffViewer } from "../DiffViewer.js";
import { EditMessageSelector } from "../EditMessageSelector.js";
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
import type {
ActivePermissionRequest,
ActiveQuizQuestion,
@ -169,11 +168,6 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
return <JobsSelector onCancel={closeCurrentScreen} />;
}
// Free trial transition UI
if (isScreenActive("free-trial")) {
return <FreeTrialTransitionUI onReload={handleReload} />;
}
// Diff viewer overlay
if (isScreenActive("diff")) {
return (

View file

@ -12,17 +12,15 @@ import React, {
*/
export type NavigationScreen =
| "chat" // Normal chat interface
| "config" // Config selector (includes organization switching)
| "config" // Config selector
| "model" // Model selector
| "free-trial" // Free trial transition UI
| "login" // Login prompt
| "mcp" // MCP selector
| "session" // Session selector
| "diff" // Full-screen diff overlay
| "update" // Update selector
| "edit" // Edit message selector
| "jobs" // Background Jobs selector
| "session"; // Session selector
| "jobs"; // Background Jobs selector;
interface NavigationState {
currentScreen: NavigationScreen;

View file

@ -78,7 +78,7 @@ describe("NavigationContext", () => {
"chat",
"config",
"model",
"free-trial",
"login",
"mcp",
];
@ -167,9 +167,12 @@ describe("NavigationContext", () => {
it("closes from any screen back to chat", () => {
const { result } = renderHook(() => useNavigation(), { wrapper });
const screens: Array<
"config" | "model" | "free-trial" | "login" | "mcp"
> = ["config", "model", "free-trial", "login", "mcp"];
const screens: Array<"config" | "model" | "login" | "mcp"> = [
"config",
"model",
"login",
"mcp",
];
screens.forEach((screen) => {
act(() => {
@ -205,7 +208,6 @@ describe("NavigationContext", () => {
expect(result.current.isScreenActive("config")).toBe(false);
expect(result.current.isScreenActive("model")).toBe(false);
expect(result.current.isScreenActive("mcp")).toBe(false);
expect(result.current.isScreenActive("free-trial")).toBe(false);
expect(result.current.isScreenActive("login")).toBe(false);
});
@ -213,14 +215,14 @@ describe("NavigationContext", () => {
const { result } = renderHook(() => useNavigation(), { wrapper });
act(() => {
result.current.navigateTo("free-trial");
result.current.navigateTo("config");
});
expect(result.current.isScreenActive("free-trial")).toBe(true);
expect(result.current.isScreenActive("config")).toBe(true);
act(() => {
result.current.navigateTo("model");
});
expect(result.current.isScreenActive("free-trial")).toBe(false);
expect(result.current.isScreenActive("config")).toBe(false);
expect(result.current.isScreenActive("model")).toBe(true);
act(() => {
@ -308,21 +310,14 @@ describe("NavigationContext", () => {
expect(result.current.isScreenActive("chat")).toBe(true);
});
it("handles free trial transition flow", () => {
it("handles config selection flow", () => {
const { result } = renderHook(() => useNavigation(), { wrapper });
// Show free trial screen
act(() => {
result.current.navigateTo("free-trial");
});
expect(result.current.isScreenActive("free-trial")).toBe(true);
// User might navigate to config from free trial
// Navigate to config
act(() => {
result.current.navigateTo("config");
});
expect(result.current.isScreenActive("config")).toBe(true);
expect(result.current.isScreenActive("free-trial")).toBe(false);
// Return to chat
act(() => {

View file

@ -78,12 +78,6 @@ export function useConfigSelector({
messageType: "system" as const,
});
// First, check if we need to switch organizations
const currentAuthState = services.auth.getState();
const currentOrgId = currentAuthState.authConfig
? (currentAuthState.authConfig.organizationId ?? null)
: null;
let targetConfigPath: string | undefined;
if (config.type === "local") {
@ -92,19 +86,7 @@ export function useConfigSelector({
targetConfigPath = config.slug;
}
// If we need to switch organizations, we'll handle both org + config switching
// using a different approach to avoid duplicate reloads
if (config.organizationId === currentOrgId) {
// Only config path is changing, no organization switch needed
await services.config.updateConfigPath(targetConfigPath);
} else {
// Switch organization first
await services.auth.switchOrganization(config.organizationId ?? null);
// Update config path THEN reload services once
// This avoids the double reload issue
await services.config.updateConfigPath(targetConfigPath);
}
await services.config.updateConfigPath(targetConfigPath);
handleClear();

View file

@ -1,5 +1,4 @@
/* eslint-disable max-classes-per-file */
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { logger } from "./logger.js";
@ -26,7 +25,9 @@ export interface ApiError extends Error {
* Authentication error thrown when user is not authenticated
*/
export class AuthenticationRequiredError extends Error {
constructor(message = "Not authenticated. Please run 'cn login' first.") {
constructor(
message = "Not authenticated. Hub integration has been removed.",
) {
super(message);
this.name = "AuthenticationRequiredError";
}
@ -53,52 +54,34 @@ export class ApiRequestError extends Error implements ApiError {
}
/**
* Make an authenticated API request to the Continue API
* Handles authentication, error handling, and response parsing
* Make an API request to the Continue API.
* Hub authentication has been removed - requests are made without auth headers.
*/
export async function makeAuthenticatedRequest<T = any>(
endpoint: string,
options: ApiRequestOptions = {},
): Promise<ApiResponse<T>> {
// Handle authentication
const authConfig = loadAuthConfig();
if (!authConfig) {
throw new AuthenticationRequiredError();
}
const accessToken = getAccessToken(authConfig);
if (!accessToken) {
throw new AuthenticationRequiredError(
"No access token available. Please run 'cn login' first.",
);
}
// Prepare request options
const { method = "GET", body, headers = {} } = options;
const requestOptions: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
...headers,
},
};
// Add body if provided
if (body) {
requestOptions.body =
typeof body === "string" ? body : JSON.stringify(body);
}
try {
// Make the request
const url = new URL(endpoint, env.apiBase);
logger.debug(`Making ${method} request to: ${url.toString()}`);
const response = await fetch(url, requestOptions);
// Handle error responses
if (!response.ok) {
const errorText = await response.text();
logger.error(`API request failed: ${response.status} ${errorText}`);
@ -109,13 +92,11 @@ export async function makeAuthenticatedRequest<T = any>(
);
}
// Parse response
let data: T;
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
data = await response.json();
} else {
// If not JSON, return the text as data
data = (await response.text()) as T;
}
@ -127,7 +108,6 @@ export async function makeAuthenticatedRequest<T = any>(
ok: response.ok,
};
} catch (error) {
// Re-throw our custom errors
if (
error instanceof AuthenticationRequiredError ||
error instanceof ApiRequestError
@ -135,7 +115,6 @@ export async function makeAuthenticatedRequest<T = any>(
throw error;
}
// Handle network/other errors
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(`Network/request error: ${errorMessage}`);
throw new Error(`Request failed: ${errorMessage}`);

View file

@ -1,25 +1,17 @@
import node_machine_id from "node-machine-id";
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
let _uniqueId: string | undefined;
/**
* - Continue user id from environment (when running as agent)
* - Continue user id if signed in locally
* - Unique machine id if not signed in
* Returns a unique identifier for the current user/machine.
* Uses CONTINUE_USER_ID env var if set, otherwise falls back to machine ID.
*/
export function getUniqueId(): string {
if (!_uniqueId) {
if (process.env.CONTINUE_USER_ID) {
_uniqueId = process.env.CONTINUE_USER_ID;
} else {
const authConfig = loadAuthConfig();
if (isAuthenticatedConfig(authConfig)) {
_uniqueId = authConfig.userId;
} else {
_uniqueId = node_machine_id.machineIdSync();
}
_uniqueId = node_machine_id.machineIdSync();
}
}
return _uniqueId;

View file

@ -4,7 +4,6 @@ import { fileURLToPath } from "url";
import node_machine_id from "node-machine-id";
import { isAuthenticatedConfig, loadAuthConfig } from "./auth/workos.js";
import { logger } from "./util/logger.js";
export function getVersion(): string {
@ -21,13 +20,6 @@ export function getVersion(): string {
}
function getEventUserId(): string {
const authConfig = loadAuthConfig();
if (isAuthenticatedConfig(authConfig)) {
return authConfig.userId;
}
// Fall back to unique machine id if not signed in
return node_machine_id.machineIdSync();
}

View file

@ -1,9 +1,7 @@
package com.github.continuedev.continueintellijextension.activities
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.auth.ControlPlaneSessionInfo
import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.*
@ -257,34 +255,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
project.getBrowser()?.sendToWebview("jetbrains/setColors", colors)
})
// Listen for clicking settings button to start the auth flow
val authService = service<ContinueAuthService>()
val initialSessionInfo = authService.loadControlPlaneSessionInfo()
if (initialSessionInfo != null) {
val data = mapOf(
"sessionInfo" to initialSessionInfo
)
continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> }
}
connection.subscribe(AuthListener.TOPIC, object : AuthListener {
override fun startAuthFlow() {
authService.startAuthFlow(project, false)
}
override fun handleUpdatedSessionInfo(sessionInfo: ControlPlaneSessionInfo?) {
val data = mapOf(
"sessionInfo" to sessionInfo
)
continuePluginService.coreMessenger?.request(
"didChangeControlPlaneSessionInfo",
data,
null
) { _ -> }
}
})
val listener =
ContinuePluginSelectionListener(
coroutineScope,

View file

@ -5,9 +5,7 @@ import com.intellij.util.messages.Topic
interface AuthListener {
fun startAuthFlow()
fun handleUpdatedSessionInfo(sessionInfo: ControlPlaneSessionInfo?)
companion object {
val TOPIC = Topic.create("StartAuthFlow", AuthListener::class.java)
}
}
}

View file

@ -1,255 +1,7 @@
package com.github.continuedev.continueintellijextension.auth
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.credentialStore.Credentials
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
import com.intellij.util.io.HttpRequests
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.minutes
@Service
class ContinueAuthService {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private val log = Logger.getInstance(ContinueAuthService::class.java)
companion object {
private const val CREDENTIALS_USER = "ContinueAuthUser"
private const val ACCESS_TOKEN_KEY = "ContinueAccessToken"
private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken"
private const val ACCOUNT_ID_KEY = "ContinueAccountId"
private const val ACCOUNT_LABEL_KEY = "ContinueAccountLabel"
}
private fun getControlPlaneUrl(): String {
val env = service<ContinueExtensionSettings>().continueState.continueTestEnvironment;
when (env) {
"none" -> return "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app"
"local" -> return "http://localhost:3001"
"production" -> return "https://api.continue.dev"
"test" -> return "https://api-test.continue.dev"
}
return "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app"
}
init {
setupRefreshTokenInterval()
}
fun startAuthFlow(project: Project, useOnboarding: Boolean) {
// Open login page
val url = openSignInPage(project, useOnboarding)
// Open a dialog where the user should paste their sign-in token
ApplicationManager.getApplication().invokeLater {
val dialog = ContinueAuthDialog(useOnboarding, url) { token ->
// Store the token
updateRefreshToken(token)
}
dialog.show()
}
}
fun signOut() {
// Clear the stored tokens
setAccessToken("")
setRefreshToken("")
setAccountId("")
setAccountLabel("")
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(null)
}
private fun updateRefreshToken(token: String) {
try {
val response = refreshToken(token)
val accountLabel = "${response.user.firstName} ${response.user.lastName}"
// Persist the session info
setRefreshToken(response.refreshToken)
val account = ControlPlaneSessionInfo.Account(response.user.email, accountLabel)
val sessionInfo = ControlPlaneSessionInfo(response.accessToken, account)
setControlPlaneSessionInfo(sessionInfo)
// Notify listeners
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(sessionInfo)
} catch (e: Exception) {
}
}
private fun setupRefreshTokenInterval() {
coroutineScope.launch {
while (true) {
val refreshToken = getRefreshToken()
if (refreshToken != null) {
updateRefreshToken(refreshToken)
}
log.info("Token refreshed, retrying in 15 minutes")
delay(15.minutes)
}
}
}
private fun refreshToken(refreshToken: String): RefreshTokenResponse {
val gson = Gson()
val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
val url = getControlPlaneUrl() + "/auth/refresh"
val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
.connect {
connection -> connection.write(jsonBody.toByteArray())
connection.readString()
}
return gson.fromJson(response, RefreshTokenResponse::class.java)
}
private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
var authUrl: String? = null
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
// Use a blocking approach to get the URL
val latch = java.util.concurrent.CountDownLatch(1)
coreMessenger?.request(
"auth/getAuthUrl", mapOf(
"useOnboarding" to useOnboarding
), null
) { response ->
authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
latch.countDown()
}
// Wait for the response with a reasonable timeout
latch.await(5, java.util.concurrent.TimeUnit.SECONDS)
// Still open the URL in the browser (keeping existing behavior)
if (authUrl != null) {
BrowserUtil.open(authUrl!!)
}
return authUrl
}
private fun retrieveSecret(key: String): String? {
return try {
val attributes = createCredentialAttributes(key, CREDENTIALS_USER)
val passwordSafe: PasswordSafe = PasswordSafe.instance
val credentials: Credentials? = passwordSafe[attributes!!]
credentials?.getPasswordAsString()
} catch (e: Exception) {
// Log the exception or handle it as needed
println("Error retrieving secret for key $key: ${e.message}")
null
}
}
private fun storeSecret(key: String, secret: String) {
try {
val attributes = createCredentialAttributes(key, CREDENTIALS_USER)
val passwordSafe: PasswordSafe = PasswordSafe.instance
val credentials = Credentials(CREDENTIALS_USER, secret)
passwordSafe.set(attributes!!, credentials)
} catch (e: Exception) {
// Log the exception or handle it as needed
println("Error storing secret for key $key: ${e.message}")
}
}
private fun getAccessToken(): String? {
return retrieveSecret(ACCESS_TOKEN_KEY)
}
private fun setAccessToken(token: String) {
storeSecret(ACCESS_TOKEN_KEY, token)
}
private fun getRefreshToken(): String? {
return retrieveSecret(REFRESH_TOKEN_KEY)
}
private fun setRefreshToken(token: String) {
storeSecret(REFRESH_TOKEN_KEY, token)
}
fun getAccountId(): String? {
return PropertiesComponent.getInstance().getValue(ACCOUNT_ID_KEY)
}
fun setAccountId(id: String) {
PropertiesComponent.getInstance().setValue(ACCOUNT_ID_KEY, id)
}
fun getAccountLabel(): String? {
return PropertiesComponent.getInstance().getValue(ACCOUNT_LABEL_KEY)
}
fun setAccountLabel(label: String) {
PropertiesComponent.getInstance().setValue(ACCOUNT_LABEL_KEY, label)
}
// New method to load all info as an object
fun loadControlPlaneSessionInfo(): ControlPlaneSessionInfo? {
val accessToken = getAccessToken()
val accountId = getAccountId()
val accountLabel = getAccountLabel()
return if ((accessToken != null && accessToken != "") && accountId != null && accountLabel != null) {
ControlPlaneSessionInfo(
accessToken = accessToken,
account = ControlPlaneSessionInfo.Account(
id = accountId,
label = accountLabel
)
)
} else {
null
}
}
// New method to set all info from a ControlPlaneSessionInfo object
fun setControlPlaneSessionInfo(info: ControlPlaneSessionInfo) {
setAccessToken(info.accessToken)
setAccountId(info.account.id)
setAccountLabel(info.account.label)
}
private data class RefreshTokenResponse(
val accessToken: String,
val refreshToken: String,
val user: User,
) {
data class User(
val firstName: String,
val lastName: String,
val email: String
)
}
}
// Data class to represent the ControlPlaneSessionInfo
data class ControlPlaneSessionInfo(
val accessToken: String,
val account: Account
) {
data class Account(
val id: String,
val label: String
)
}

View file

@ -3,7 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
@ -99,25 +99,10 @@ class IdeProtocolClient(
}
"getControlPlaneSessionInfo" -> {
val params = gsonService.gson.fromJson(
dataElement.toString(),
GetControlPlaneSessionInfoParams::class.java
)
val authService = service<ContinueAuthService>()
if (params.silent) {
val sessionInfo = authService.loadControlPlaneSessionInfo()
respond(sessionInfo)
} else {
authService.startAuthFlow(project, params.useOnboarding)
respond(null)
}
respond(null)
}
"logoutOfControlPlane" -> {
val authService = service<ContinueAuthService>()
authService.signOut()
respond(null)
}

View file

@ -1,6 +1,5 @@
package com.github.continuedev.continueintellijextension.nextEdit
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.components.Service
@ -10,7 +9,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.text.endsWith
/**
* This cache-like service is introduced to enable checking the Next Edit status in a non-blocking way (e.g., while
@ -45,16 +44,6 @@ class NextEditStatusService(private val project: Project) {
private suspend fun isNextEditEnabledAsync(project: Project): Boolean {
return try {
// NOTE: Quick filter for non-continue users.
// Remove this once we have a FIM - Next Edit toggle UI.
val authService = project.service<ContinueAuthService>()
val sessionInfo = authService.loadControlPlaneSessionInfo()
val userEmail = sessionInfo?.account?.id
if (userEmail == null || !userEmail.endsWith("@continue.dev")) {
return false
}
val profileInfoService = project.service<ProfileInfoService>()
val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull()

View file

@ -1,11 +1,6 @@
package com.github.continuedev.continueintellijextension.nextEdit
import com.github.continuedev.continueintellijextension.FimResult
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
object NextEditUtils {

View file

@ -3,8 +3,6 @@ package com.github.continuedev.continueintellijextension.protocol
import com.github.continuedev.continueintellijextension.Range
import com.github.continuedev.continueintellijextension.TerminalOptions
data class GetControlPlaneSessionInfoParams(val silent: Boolean, val useOnboarding: Boolean)
data class WriteFileParams(
val path: String,
val contents: String

View file

@ -128,16 +128,6 @@ data class DocumentSymbol(
val selectionRange: Range
)
data class ControlPlaneSessionInfo(
val accessToken: String,
val account: Account
)
data class Account(
val label: String,
val id: String
)
data class FileStats(
val lastModified: Long,
val size: Long

View file

@ -354,11 +354,9 @@ export class VsCodeExtension {
this.uriHandler.event((uri) => {
const queryParams = new URLSearchParams(uri.query);
let profileId = queryParams.get("profile_id");
let orgId = queryParams.get("org_id");
this.core.invoke("config/refreshProfiles", {
reason: "VS Code deep link",
selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
selectProfileId:
profileId === "null" ? undefined : (profileId ?? undefined),
});

View file

@ -112,27 +112,6 @@ export class VsCodeWebviewProtocol
message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`;
}
}
if (message.includes("https://proxy-server")) {
message = message.split("\n").filter((l: string) => l !== "")[1];
try {
message = JSON.parse(message).message;
} catch {}
if (message.includes("exceeded")) {
message +=
" To keep using Continue, you can set up a local model or use your own API key.";
}
vscode.window
.showInformationMessage(message, "Add API Key", "Use Local Model")
.then((selection) => {
if (selection === "Add API Key") {
this.request("setupApiKey", undefined);
} else if (selection === "Use Local Model") {
this.request("setupLocalConfig", undefined);
}
});
}
}
}
};

View file

@ -1 +1 @@
- Whenever adding links in the `gui` that direct to `continue.dev`, you should use an onClick handler that calls `ideMessenger.request("controlPlane/openUrl", { path, orgSlug: undefined });` instead of directly linking to the URL with an `href`.
- Whenever adding links in the `gui` that direct to `continue.dev`, you should use the IDE's `openUrl` command to open the URL in the user's default browser.

View file

@ -50,12 +50,12 @@ export function AssistantOption({
value={profile.id}
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
fontSizeModifier={-2}
fontSizeModifier={-4}
className={`group ${selected ? "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">
<div className="flex h-3 w-3 flex-shrink-0 items-center justify-center">
<AssistantIcon assistant={profile} />
</div>
<span

View file

@ -107,7 +107,7 @@ export function AssistantAndOrgListbox({
style={{ zIndex: 200 }}
>
<div className="flex items-center justify-between px-1.5 py-1">
<span className="text-description text-xs font-medium">
<span className="text-description text-2xs font-medium">
Configs
</span>
<div className="flex items-center gap-0.5">
@ -156,7 +156,7 @@ export function AssistantAndOrgListbox({
<div className="flex w-full items-center">
<ArrowPathIcon
className={cn(
"ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0",
"ml-1 mr-3 h-3.5 w-3.5 flex-shrink-0",
configLoading && "animate-spin-slow",
)}
/>

View file

@ -132,22 +132,6 @@ const Layout = () => {
[],
);
useWebviewListener(
"freeTrialExceeded",
async () => {
dispatch(setShowDialog(true));
onboardingCard.setActiveTab(OnboardingModes.MODELS_ADD_ON);
dispatch(
setDialogMessage(
<div className="flex-1">
<OnboardingCard isDialog />
</div>,
),
);
},
[],
);
useWebviewListener(
"setupApiKey",
async () => {

View file

@ -5,7 +5,6 @@ import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { ReusableCard } from "../ReusableCard";
import { OnboardingCardTabs } from "./components/OnboardingCardTabs";
import { OnboardingLocalTab } from "./components/OnboardingLocalTab";
import { OnboardingModelsAddOnTab } from "./components/OnboardingModelsAddOnTab";
import { OnboardingProvidersTab } from "./components/OnboardingProvidersTab";
import { useOnboardingCard } from "./hooks/useOnboardingCard";
@ -26,10 +25,9 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) {
setLocalStorage("onboardingStatus", "Started");
}
// Default to MODELS_ADD_ON tab if no active tab is set
useEffect(() => {
if (!activeTab) {
setActiveTab(OnboardingModes.MODELS_ADD_ON);
setActiveTab(OnboardingModes.API_KEY);
}
}, [activeTab, setActiveTab]);
@ -39,15 +37,12 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) {
return <OnboardingProvidersTab />;
case OnboardingModes.LOCAL:
return <OnboardingLocalTab />;
case OnboardingModes.MODELS_ADD_ON:
return <OnboardingModelsAddOnTab />;
default:
return <OnboardingModelsAddOnTab />;
return <OnboardingProvidersTab />;
}
}
// Always show tabs view, defaulting to Models Add-On
const currentTab = activeTab || OnboardingModes.MODELS_ADD_ON;
const currentTab = activeTab || OnboardingModes.API_KEY;
return (
<ReusableCard

View file

@ -26,9 +26,7 @@ function OllamaModelDownload({
return (
<div className="flex flex-col">
<p className="text-foreground mb-0 mt-4 text-base font-semibold">
{title}
</p>
<p className="text-foreground mb-1 mt-4 text-sm font-semibold">{title}</p>
{hasDownloaded ? (
<OllamaCompletedStep text={command} />
) : (

Some files were not shown because too many files have changed in this diff Show more