Merge pull request #5013 from continuedev/dallin/assistant-switch-fixes
Config Loading and Org/Profile Selection Fixes
This commit is contained in:
commit
8acc20ab3e
32 changed files with 750 additions and 960 deletions
|
|
@ -9,9 +9,9 @@ import { defaultConfig } from "./default";
|
|||
|
||||
describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
||||
test("should show only local profile", () => {
|
||||
const profiles = testConfigHandler.listProfiles();
|
||||
const profiles = testConfigHandler.currentOrg.profiles;
|
||||
expect(profiles?.length).toBe(1);
|
||||
expect(profiles?.[0].id).toBe("local");
|
||||
expect(profiles?.[0].profileDescription.id).toBe("local");
|
||||
|
||||
const currentProfile = testConfigHandler.currentProfile;
|
||||
expect(currentProfile?.profileDescription.id).toBe("local");
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
ControlPlaneClient,
|
||||
|
|
@ -25,32 +25,31 @@ import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
|
|||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
OrganizationDescription,
|
||||
OrgWithProfiles,
|
||||
ProfileDescription,
|
||||
ProfileLifecycleManager,
|
||||
SerializedOrgWithProfiles,
|
||||
} from "./ProfileLifecycleManager.js";
|
||||
|
||||
export type { ProfileDescription };
|
||||
|
||||
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
|
||||
|
||||
// Separately manages saving/reloading each profile
|
||||
|
||||
export class ConfigHandler {
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
|
||||
private selectedProfileId: string | null = null;
|
||||
private localProfileManager: ProfileLifecycleManager;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private globalLocalProfileManager: ProfileLifecycleManager;
|
||||
|
||||
initializedPromise: Promise<void>;
|
||||
private organizations: OrgWithProfiles[] = [];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
currentOrg: OrgWithProfiles;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
private readonly didSelectOrganization?: (orgId: string | null) => void,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
|
|
@ -60,34 +59,233 @@ export class ConfigHandler {
|
|||
ideSettingsPromise,
|
||||
);
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.localProfileManager = new ProfileLifecycleManager(
|
||||
localProfileLoader,
|
||||
// This profile manager will always be available
|
||||
this.globalLocalProfileManager = new ProfileLifecycleManager(
|
||||
new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
writeLog,
|
||||
),
|
||||
this.ide,
|
||||
);
|
||||
|
||||
// Profiles are loaded asynchronously
|
||||
this.initializedPromise = new Promise((resolve, reject) => {
|
||||
this.init()
|
||||
.then(() => {
|
||||
resolve();
|
||||
})
|
||||
.catch((e) => {
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
// Just to be safe, always force a default personal org with local profile manager
|
||||
this.currentProfile = this.globalLocalProfileManager;
|
||||
const personalOrg: OrgWithProfiles = {
|
||||
currentProfile: this.globalLocalProfileManager,
|
||||
profiles: [this.globalLocalProfileManager],
|
||||
...this.PERSONAL_ORG_DESC,
|
||||
};
|
||||
|
||||
this.currentOrg = personalOrg;
|
||||
this.organizations = [personalOrg];
|
||||
|
||||
void this.cascadeInit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
private async getLocalAssistantProfiles() {
|
||||
private workspaceDirs: string[] | null = null;
|
||||
async getWorkspaceId() {
|
||||
if (!this.workspaceDirs) {
|
||||
this.workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
}
|
||||
return this.workspaceDirs.join("&");
|
||||
}
|
||||
|
||||
async getProfileKey(orgId: string) {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
private async cascadeInit() {
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
const orgs = await this.getOrgs();
|
||||
|
||||
// Figure out selected org
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
selectedOrg = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
private async getOrgs(): Promise<OrgWithProfiles[]> {
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
if (userId) {
|
||||
const orgDescs = await this.controlPlaneClient.listOrganizations();
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
} else {
|
||||
// Should only ever be one teams org. Will be removed soon anyways
|
||||
return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org)));
|
||||
}
|
||||
} else {
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
}
|
||||
|
||||
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 async getHubProfiles(orgScopeId: string | null) {
|
||||
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
|
||||
|
||||
return await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
assistant.rawYaml,
|
||||
orgScopeId,
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profiles = await this.getHubProfiles(org.id);
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private PERSONAL_ORG_DESC: OrganizationDescription = {
|
||||
iconUrl: "",
|
||||
id: "personal",
|
||||
name: "Personal",
|
||||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
private async getLocalOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
|
||||
}
|
||||
|
||||
async getTeamsOrg(org: OrganizationDescription): Promise<OrgWithProfiles> {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
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) {
|
||||
currentProfile = fallback;
|
||||
} else {
|
||||
const match = profiles.find(
|
||||
(profile) => profile.profileDescription.id === currentSelection,
|
||||
);
|
||||
if (match) {
|
||||
currentProfile = match;
|
||||
} else {
|
||||
currentProfile = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentProfile) {
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: selectedProfiles.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...org,
|
||||
profiles,
|
||||
currentProfile,
|
||||
};
|
||||
}
|
||||
|
||||
async getAllLocalProfiles() {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
|
|
@ -98,287 +296,27 @@ export class ConfigHandler {
|
|||
assistant,
|
||||
);
|
||||
});
|
||||
return profiles.map(
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
return [this.globalLocalProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
//////////////////
|
||||
// External actions that can cause a cascading config refresh
|
||||
// Should not be used internally
|
||||
//////////////////
|
||||
async refreshAll() {
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
private async init() {
|
||||
try {
|
||||
await this.fetchControlPlaneProfiles();
|
||||
} catch (e) {
|
||||
// If this fails, make sure at least local profile is loaded
|
||||
console.error("Failed to fetch control plane profiles in init: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
|
||||
try {
|
||||
const configResult = await this.loadConfig();
|
||||
this.notifyConfigListeners(configResult);
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
get currentProfile() {
|
||||
if (!this.selectedProfileId) {
|
||||
return null;
|
||||
}
|
||||
// IMPORTANT
|
||||
// We must fall back to null, not the first or local profiles
|
||||
// Because GUI must be the source of truth for selected profile
|
||||
return (
|
||||
this.profiles?.find(
|
||||
(p) => p.profileDescription.id === this.selectedProfileId,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
get inactiveProfiles() {
|
||||
return (this.profiles ?? []).filter(
|
||||
(p) => p.profileDescription.id !== this.selectedProfileId,
|
||||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
const profile = this.profiles?.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async listOrganizations() {
|
||||
return await this.controlPlaneClient.listOrganizations();
|
||||
}
|
||||
|
||||
async loadAssistantsForSelectedOrg() {
|
||||
// Get the profiles and create their lifecycle managers
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
|
||||
let profiles: ProfileLifecycleManager[] | null = null;
|
||||
if (!userId) {
|
||||
// Not logged in
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...allLocalProfiles];
|
||||
} else {
|
||||
// Logged in
|
||||
const assistants =
|
||||
await this.controlPlaneClient.listAssistants(selectedOrgId);
|
||||
|
||||
const hubProfiles = await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
assistant.rawYaml,
|
||||
selectedOrgId,
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
|
||||
if (selectedOrgId === null) {
|
||||
// Personal
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
} else {
|
||||
// Organization
|
||||
profiles = hubProfiles;
|
||||
}
|
||||
}
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
}
|
||||
|
||||
private async getAllLocalProfiles() {
|
||||
const localAssistantProfiles = await this.getLocalAssistantProfiles();
|
||||
return [this.localProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
private async loadLocalProfilesOnly() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
await this.updateAvailableProfiles(allLocalProfiles);
|
||||
}
|
||||
|
||||
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
|
||||
this.profiles = profiles;
|
||||
|
||||
// If the last selected profile is in the list choose that
|
||||
// Otherwise, choose the first profile
|
||||
const previouslySelectedProfileId =
|
||||
await this.getPersistedSelectedProfileId();
|
||||
|
||||
// Check if the previously selected profile exists in the current profiles
|
||||
const profileExists = profiles.some(
|
||||
(profile) =>
|
||||
profile.profileDescription.id === previouslySelectedProfileId,
|
||||
);
|
||||
|
||||
const selectedProfileId = profileExists
|
||||
? previouslySelectedProfileId
|
||||
: (profiles[0]?.profileDescription.id ?? null);
|
||||
|
||||
// Notify listeners
|
||||
const profileDescriptions = profiles.map(
|
||||
(profile) => profile.profileDescription,
|
||||
);
|
||||
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
|
||||
await this.setSelectedProfile(selectedProfileId);
|
||||
}
|
||||
|
||||
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
|
||||
// We use this to keep track of whether we should reload the assistants
|
||||
private lastFullSlugsList: FullSlug[] = [];
|
||||
|
||||
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
|
||||
if (a.length !== b.length) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i].ownerSlug !== b[i].ownerSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].packageSlug !== b[i].packageSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].versionSlug !== b[i].versionSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async reloadHubAssistants() {
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
const newFullSlugsList =
|
||||
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
|
||||
|
||||
if (newFullSlugsList) {
|
||||
const shouldReload = this.fullSlugsListsDiffer(
|
||||
newFullSlugsList,
|
||||
this.lastFullSlugsList,
|
||||
);
|
||||
if (shouldReload) {
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
}
|
||||
this.lastFullSlugsList = newFullSlugsList;
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchControlPlaneProfiles() {
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
clearInterval(this.platformProfilesRefreshInterval);
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
|
||||
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
|
||||
// If so, we do the full (more expensive) reload
|
||||
this.platformProfilesRefreshInterval = setInterval(
|
||||
this.reloadHubAssistants.bind(this),
|
||||
PlatformProfileLoader.RELOAD_INTERVAL,
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
} catch (e: any) {
|
||||
console.error("Failed to load profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getPersistedSelectedProfileId(): Promise<string | null> {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const lastSelectedIds =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
return lastSelectedIds[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async getSelectedOrgId(): Promise<string | null> {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return selectedOrgs[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async setSelectedOrgId(orgId: string | null) {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
selectedOrgs[await this.getWorkspaceId()] = orgId;
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
|
||||
this.didSelectOrganization?.(orgId);
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string | null) {
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
this.notifyConfigListeners(result);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
selectedProfiles[await this.getWorkspaceId()] = profileId;
|
||||
this.globalContext.update(
|
||||
"lastSelectedProfileForWorkspace",
|
||||
selectedProfiles,
|
||||
);
|
||||
}
|
||||
|
||||
// A unique ID for the current workspace, built from folder names
|
||||
private async getWorkspaceId(): Promise<string> {
|
||||
const dirs = await this.ide.getWorkspaceDirs();
|
||||
return dirs.join("&");
|
||||
}
|
||||
|
||||
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
|
||||
updateIdeSettings(ideSettings: IdeSettings) {
|
||||
// Ide settings change: refresh session and cascade refresh from the top
|
||||
async updateIdeSettings(ideSettings: IdeSettings) {
|
||||
this.ideSettingsPromise = Promise.resolve(ideSettings);
|
||||
void this.reloadConfig();
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
// Session change: refresh session and cascade refresh from the top
|
||||
async updateControlPlaneSessionInfo(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
) {
|
||||
|
|
@ -386,38 +324,97 @@ export class ConfigHandler {
|
|||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
);
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
this.fetchControlPlaneProfiles().catch(async (e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
await this.reloadConfig();
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
|
||||
private profilesListeners: ((
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void)[] = [];
|
||||
onDidChangeAvailableProfiles(
|
||||
listener: (
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void,
|
||||
) {
|
||||
this.profilesListeners.push(listener);
|
||||
}
|
||||
this.currentOrg = org;
|
||||
|
||||
private notifyProfileListeners(
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) {
|
||||
for (const listener of this.profilesListeners) {
|
||||
listener(profiles, selectedProfileId);
|
||||
if (profileId) {
|
||||
this.setSelectedProfileId(profileId);
|
||||
} else {
|
||||
this.currentProfile = org.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// Profile id: check id validity, save selection, switch and reload
|
||||
async setSelectedProfileId(profileId: string) {
|
||||
if (
|
||||
this.currentProfile &&
|
||||
profileId === this.currentProfile.profileDescription.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(profile) => profile.profileDescription.id === profileId,
|
||||
);
|
||||
if (!profile) {
|
||||
throw new Error(`Profile ${profileId} not found in current org`);
|
||||
}
|
||||
|
||||
const profileKey = await this.getProfileKey(this.currentOrg.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: profileId,
|
||||
});
|
||||
|
||||
this.currentProfile = profile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
// Bottom level of cascade: refresh the current profile
|
||||
// IMPORTANT - must always refresh when switching profiles
|
||||
// Because of e.g. MCP singleton and docs service using things from config
|
||||
// Could improve this
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
for (const org of this.organizations) {
|
||||
for (const profile of org.profiles) {
|
||||
if (
|
||||
profile.profileDescription.id !==
|
||||
this.currentProfile.profileDescription.id
|
||||
) {
|
||||
profile.clearConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Listeners setup - can listen to current profile updates
|
||||
private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
|
||||
// Notify listeners that config changed
|
||||
for (const listener of this.updateListeners) {
|
||||
listener(result);
|
||||
}
|
||||
|
|
@ -429,27 +426,9 @@ export class ConfigHandler {
|
|||
this.updateListeners.push(listener);
|
||||
}
|
||||
|
||||
// TODO: this isn't right, there are two different senses in which you want to "reload"
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
if (config) {
|
||||
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
|
||||
}
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Methods for loading (without reloading) config
|
||||
// Serialized for passing to GUI
|
||||
// Load for just awaiting current config load promise for the profile
|
||||
async getSerializedConfig(): Promise<
|
||||
ConfigResult<BrowserSerializedContinueConfig>
|
||||
> {
|
||||
|
|
@ -465,10 +444,6 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
listProfiles(): ProfileDescription[] | null {
|
||||
return this.profiles?.map((p) => p.profileDescription) ?? null;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
|
|
@ -482,6 +457,23 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
|
||||
if (!openProfileId) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Only used till we move to using selectedModelByRole.chat
|
||||
async llmFromTitle(title?: string): Promise<ILLM> {
|
||||
const { config } = await this.loadConfig();
|
||||
const model = config?.models.find((m) => m.title === title);
|
||||
|
|
@ -502,8 +494,20 @@ export class ConfigHandler {
|
|||
return model;
|
||||
}
|
||||
|
||||
// Ancient method of adding custom providers through vs code
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
this.additionalContextProviders.push(contextProvider);
|
||||
void this.reloadConfig();
|
||||
}
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ export interface OrganizationDescription {
|
|||
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
|
||||
}
|
||||
|
||||
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>;
|
||||
|
|
|
|||
|
|
@ -32,7 +32,6 @@ async function getContextProviderExtras(
|
|||
async (text) => {},
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
await configHandler.initializedPromise;
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not found");
|
||||
|
|
|
|||
61
core/core.ts
61
core/core.ts
|
|
@ -108,11 +108,6 @@ export class Core {
|
|||
ideSettingsPromise,
|
||||
this.onWrite,
|
||||
sessionInfoPromise,
|
||||
(orgId: string | null) => {
|
||||
void messenger.request("didSelectOrganization", {
|
||||
orgId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
|
|
@ -123,8 +118,6 @@ export class Core {
|
|||
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.onConnectionsRefreshed = async () => {
|
||||
// This ensures that it triggers a NEW load after waiting for config promise to finish
|
||||
await this.configHandler.loadConfig();
|
||||
await this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
|
|
@ -133,7 +126,11 @@ export class Core {
|
|||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
this.configHandler.currentProfile?.profileDescription.id || null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
});
|
||||
|
||||
// update additional submenu context providers registered via VSCode API
|
||||
|
|
@ -146,14 +143,6 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
this.configHandler.onDidChangeAvailableProfiles(
|
||||
(profiles, selectedProfileId) =>
|
||||
this.messenger.send("didChangeAvailableProfiles", {
|
||||
profiles,
|
||||
selectedProfileId,
|
||||
}),
|
||||
);
|
||||
|
||||
// Dev Data Logger
|
||||
const dataLogger = DataLogger.getInstance();
|
||||
dataLogger.core = this;
|
||||
|
|
@ -308,15 +297,8 @@ export class Core {
|
|||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
||||
on("config/listProfiles", async (msg) => {
|
||||
const profiles = this.configHandler.listProfiles();
|
||||
const selectedProfileId =
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null;
|
||||
return { profiles, selectedProfileId };
|
||||
});
|
||||
|
||||
on("config/refreshProfiles", async (msg) => {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
await this.configHandler.refreshAll();
|
||||
});
|
||||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
|
|
@ -344,10 +326,6 @@ export class Core {
|
|||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/listOrganizations", async (msg) => {
|
||||
return await this.configHandler.listOrganizations();
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
mcpManager.refreshConnection(msg.data.id);
|
||||
});
|
||||
|
|
@ -480,6 +458,10 @@ export class Core {
|
|||
result: await this.configHandler.getSerializedConfig(),
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -775,11 +757,15 @@ export class Core {
|
|||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalAssistantFile(uri)) {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
localAssistantCreated = true;
|
||||
}
|
||||
}
|
||||
if (localAssistantCreated) {
|
||||
await this.configHandler.refreshAll();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -829,20 +815,14 @@ export class Core {
|
|||
//
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
await this.configHandler.setSelectedProfile(msg.data.id);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.setSelectedProfileId(msg.data.id);
|
||||
});
|
||||
|
||||
on("didChangeSelectedOrg", async (msg) => {
|
||||
await this.configHandler.setSelectedOrgId(msg.data.id);
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
if (msg.data.profileId) {
|
||||
this.invoke("didChangeSelectedProfile", {
|
||||
id: msg.data.profileId,
|
||||
});
|
||||
} else {
|
||||
await this.configHandler.reloadConfig();
|
||||
}
|
||||
await this.configHandler.setSelectedOrgId(
|
||||
msg.data.id,
|
||||
msg.data.profileId,
|
||||
);
|
||||
});
|
||||
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
|
|
@ -850,6 +830,7 @@ export class Core {
|
|||
msg.data.sessionInfo,
|
||||
);
|
||||
});
|
||||
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage(
|
||||
ideSettingsPromise,
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
import { OrganizationDescription } from "../config/ProfileLifecycleManager";
|
||||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
|
|
@ -32,6 +30,7 @@ import type {
|
|||
SlashCommandDescription,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
|
||||
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
|
||||
|
||||
|
|
@ -66,14 +65,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/listProfiles": [
|
||||
undefined,
|
||||
{ profiles: ProfileDescription[] | null; selectedProfileId: string | null },
|
||||
];
|
||||
"config/refreshProfiles": [undefined, void];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
|
|
@ -198,5 +196,4 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
"controlPlane/listOrganizations": [undefined, OrganizationDescription[]];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,19 +1,8 @@
|
|||
import { ProfileDescription } from "../config/ConfigHandler.js";
|
||||
|
||||
import { ToCoreFromIdeOrWebviewProtocol } from "./core.js";
|
||||
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
|
||||
|
||||
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
|
||||
didChangeSelectedProfile: [{ id: string | null }, void];
|
||||
didChangeSelectedOrg: [
|
||||
{ id: string | null; profileId?: string | null },
|
||||
void,
|
||||
];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
didChangeAvailableProfiles: [
|
||||
{ profiles: ProfileDescription[]; selectedProfileId: string | null },
|
||||
void,
|
||||
];
|
||||
didSelectOrganization: [{ orgId: string | null }, void];
|
||||
didChangeSelectedProfile: [{ id: string }, void];
|
||||
didChangeSelectedOrg: [{ id: string; profileId?: string }, void];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol;
|
||||
|
|
|
|||
|
|
@ -107,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = {
|
|||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
didChangeIdeSettings: [{ settings: IdeSettings }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"config/ideSettingsUpdate",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/listProfiles",
|
||||
"config/refreshProfiles",
|
||||
"config/openProfile",
|
||||
"config/updateSharedConfig",
|
||||
|
|
@ -60,7 +59,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
"controlPlane/listOrganizations",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
@ -75,10 +73,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
|||
"addContextItem",
|
||||
"refreshSubmenuItems",
|
||||
"isContinueInputFocused",
|
||||
"didChangeAvailableProfiles",
|
||||
"setTTSActive",
|
||||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
ContextProviderName,
|
||||
IndexingProgressUpdate,
|
||||
IndexingStatus,
|
||||
PackageDocsResult,
|
||||
} from "../index.js";
|
||||
|
||||
export type ToWebviewFromIdeOrCoreProtocol = {
|
||||
|
|
@ -13,6 +13,9 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string | null;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -153,17 +153,12 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
val connection = ApplicationManager.getApplication().messageBus.connect()
|
||||
connection.subscribe(SettingsListener.TOPIC, object : SettingsListener {
|
||||
override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) {
|
||||
continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> }
|
||||
continuePluginService.sendToWebview(
|
||||
"didChangeIdeSettings", mapOf(
|
||||
"settings" to mapOf(
|
||||
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
|
||||
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
|
||||
"userToken" to settings.userToken,
|
||||
"enableControlServerBeta" to settings.enableContinueTeamsBeta
|
||||
)
|
||||
)
|
||||
)
|
||||
continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf(
|
||||
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
|
||||
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
|
||||
"userToken" to settings.userToken,
|
||||
"enableControlServerBeta" to settings.enableContinueTeamsBeta
|
||||
), null) { _ -> }
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -239,7 +234,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
"sessionInfo" to initialSessionInfo
|
||||
)
|
||||
continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> }
|
||||
continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data)
|
||||
}
|
||||
|
||||
connection.subscribe(AuthListener.TOPIC, object : AuthListener {
|
||||
|
|
@ -256,7 +250,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
data,
|
||||
null
|
||||
) { _ -> }
|
||||
continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data)
|
||||
}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -66,12 +66,10 @@ class MessageTypes {
|
|||
"addContextItem",
|
||||
"refreshSubmenuItems",
|
||||
"isContinueInputFocused",
|
||||
"didChangeAvailableProfiles",
|
||||
"setTTSActive",
|
||||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization"
|
||||
)
|
||||
|
||||
// Note: If updating these values, make a corresponding update in
|
||||
|
|
@ -88,7 +86,6 @@ class MessageTypes {
|
|||
"config/ideSettingsUpdate",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/listProfiles",
|
||||
"config/refreshProfiles",
|
||||
"config/openProfile",
|
||||
"config/updateSharedConfig",
|
||||
|
|
@ -129,8 +126,6 @@ class MessageTypes {
|
|||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
"controlPlane/listOrganizations"
|
||||
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -115,7 +115,7 @@ class IdeProtocolClient(
|
|||
.handleUpdatedSessionInfo(null)
|
||||
|
||||
// Tell the webview that session info changed
|
||||
continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", null, uuid())
|
||||
continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", null, null) { _ -> }
|
||||
|
||||
respond(null)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -202,16 +202,10 @@ export class VsCodeExtension {
|
|||
let profileId = queryParams.get("profile_id");
|
||||
let orgId = queryParams.get("org_id");
|
||||
|
||||
if (orgId) {
|
||||
if (orgId === "null") {
|
||||
orgId = null;
|
||||
}
|
||||
if (orgId && orgId !== "null") {
|
||||
// In case org id is passed with profile id
|
||||
// Make sure org is updated before profile is set
|
||||
if (profileId) {
|
||||
if (profileId === "null") {
|
||||
profileId = null;
|
||||
}
|
||||
if (profileId && profileId !== "null") {
|
||||
this.core.invoke("didChangeSelectedOrg", {
|
||||
id: orgId,
|
||||
profileId,
|
||||
|
|
@ -221,10 +215,7 @@ export class VsCodeExtension {
|
|||
id: orgId,
|
||||
});
|
||||
}
|
||||
} else if (profileId) {
|
||||
if (profileId === "null") {
|
||||
profileId = null;
|
||||
}
|
||||
} else if (profileId && profileId !== "null") {
|
||||
this.core.invoke("didChangeSelectedProfile", {
|
||||
id: profileId,
|
||||
});
|
||||
|
|
@ -334,14 +325,6 @@ export class VsCodeExtension {
|
|||
);
|
||||
|
||||
const sessionInfo = await getControlPlaneSessionInfo(true, false);
|
||||
this.webviewProtocolPromise.then(async (webviewProtocol) => {
|
||||
void webviewProtocol.request("didChangeControlPlaneSessionInfo", {
|
||||
sessionInfo,
|
||||
});
|
||||
|
||||
// To make sure continue-proxy models and anything else requiring it get updated access token
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
void this.core.invoke("didChangeControlPlaneSessionInfo", {
|
||||
sessionInfo,
|
||||
});
|
||||
|
|
@ -415,10 +398,7 @@ export class VsCodeExtension {
|
|||
vscode.workspace.onDidChangeConfiguration(async (event) => {
|
||||
if (event.affectsConfiguration(EXTENSION_NAME)) {
|
||||
const settings = await this.ide.getIdeSettings();
|
||||
const webviewProtocol = await this.webviewProtocolPromise;
|
||||
void webviewProtocol.request("didChangeIdeSettings", {
|
||||
settings,
|
||||
});
|
||||
void this.core.invoke("config/ideSettingsUpdate", settings);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import { useContext } from "react";
|
|||
import { Button, ButtonSubtext } from "../../..";
|
||||
import { useAuth } from "../../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
|
||||
import { selectCurrentOrg } from "../../../../redux";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { hasPassedFTL } from "../../../../util/freeTrial";
|
||||
import ContinueLogo from "../../../gui/ContinueLogo";
|
||||
import { useOnboardingCard } from "../../hooks";
|
||||
|
|
@ -17,6 +19,7 @@ export default function MainTab({
|
|||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const onboardingCard = useOnboardingCard();
|
||||
const auth = useAuth();
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
|
||||
function onGetStarted() {
|
||||
auth.login(true).then((success) => {
|
||||
|
|
@ -29,7 +32,7 @@ export default function MainTab({
|
|||
function openPastFreeTrialOnboarding() {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "setup-models",
|
||||
orgSlug: auth.selectedOrganization?.slug,
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
onboardingCard.close(isDialog);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,32 +97,36 @@ export function BlockSettingsTopToolbar() {
|
|||
|
||||
return (
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="xs:flex hidden items-center justify-center text-gray-400">
|
||||
<BlockSettingsToolbarIcon
|
||||
className="-ml-1.5"
|
||||
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={isToolbarExpanded ? "Collapse sections" : "Expand sections"}
|
||||
isSelected={false}
|
||||
onClick={handleEllipsisClick}
|
||||
/>
|
||||
<div
|
||||
className="flex overflow-hidden transition-all duration-200"
|
||||
style={{ width: isToolbarExpanded ? `160px` : "0px" }}
|
||||
>
|
||||
<div className="flex">
|
||||
{sections.map((section) => (
|
||||
<BlockSettingsToolbarIcon
|
||||
key={section.id}
|
||||
icon={section.icon}
|
||||
tooltip={section.tooltip}
|
||||
isSelected={selectedSection === section.id}
|
||||
onClick={() =>
|
||||
setSelectedSection(
|
||||
selectedSection === section.id ? null : section.id,
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
<div className="flex flex-row">
|
||||
<div className="xs:flex hidden items-center justify-center text-gray-400">
|
||||
<BlockSettingsToolbarIcon
|
||||
className="-ml-1.5"
|
||||
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={
|
||||
isToolbarExpanded ? "Collapse sections" : "Expand sections"
|
||||
}
|
||||
isSelected={false}
|
||||
onClick={handleEllipsisClick}
|
||||
/>
|
||||
<div
|
||||
className="flex overflow-hidden transition-all duration-200"
|
||||
style={{ width: isToolbarExpanded ? `160px` : "0px" }}
|
||||
>
|
||||
<div className="flex">
|
||||
{sections.map((section) => (
|
||||
<BlockSettingsToolbarIcon
|
||||
key={section.id}
|
||||
icon={section.icon}
|
||||
tooltip={section.tooltip}
|
||||
isSelected={selectedSection === section.id}
|
||||
onClick={() =>
|
||||
setSelectedSection(
|
||||
selectedSection === section.id ? null : section.id,
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,12 @@
|
|||
import { parseConfigYaml } from "@continuedev/config-yaml";
|
||||
import { IndexingStatus } from "core";
|
||||
import { useMemo } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useAuth } from "../../../../../context/Auth";
|
||||
import { useAppSelector } from "../../../../../redux/hooks";
|
||||
import { ExploreBlocksButton } from "../ExploreBlocksButton";
|
||||
import DocsIndexingStatus from "./DocsIndexingStatus";
|
||||
|
||||
function DocsIndexingStatuses() {
|
||||
const dispatch = useDispatch();
|
||||
const config = useAppSelector((store) => store.config.config);
|
||||
const indexingStatuses = useAppSelector(
|
||||
(store) => store.indexing.indexing.statuses,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {
|
||||
ArrowPathRoundedSquareIcon,
|
||||
ArrowTopRightOnSquareIcon,
|
||||
BuildingOfficeIcon,
|
||||
ChevronDownIcon,
|
||||
|
|
@ -9,8 +10,12 @@ import {
|
|||
import { useContext, useEffect, useMemo, useRef } from "react";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { cycleProfile, selectProfileThunk } from "../../../redux";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
setSelectedOrgId,
|
||||
setSelectedProfile,
|
||||
} from "../../../redux";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import {
|
||||
fontSize,
|
||||
getMetaKeyLabel,
|
||||
|
|
@ -57,7 +62,12 @@ const AssistantSelectOption = ({
|
|||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
function handleOptionClick() {
|
||||
dispatch(selectProfileThunk(profile.id));
|
||||
// optimistic update
|
||||
dispatch(setSelectedProfile(profile.id));
|
||||
// notify core which will handle actual update
|
||||
ideMessenger.post("didChangeSelectedProfile", {
|
||||
id: profile.id,
|
||||
});
|
||||
onClick();
|
||||
}
|
||||
|
||||
|
|
@ -148,7 +158,9 @@ const AssistantSelectOption = ({
|
|||
export default function AssistantSelect() {
|
||||
const dispatch = useAppDispatch();
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const { selectedProfile, selectedOrganization } = useAuth();
|
||||
const { selectedProfile, refreshProfiles } = useAuth();
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const orgs = useAppSelector((store) => store.profiles.organizations);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { isToolbarExpanded } = useLump();
|
||||
|
||||
|
|
@ -163,14 +175,14 @@ export default function AssistantSelect() {
|
|||
function onNewAssistant() {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "new",
|
||||
orgSlug: selectedOrganization?.slug,
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
close();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let lastToggleTime = 0;
|
||||
const DEBOUNCE_MS = 500;
|
||||
const DEBOUNCE_MS = 800;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
|
|
@ -181,8 +193,24 @@ export default function AssistantSelect() {
|
|||
const now = Date.now();
|
||||
|
||||
if (now - lastToggleTime >= DEBOUNCE_MS) {
|
||||
dispatch(cycleProfile());
|
||||
lastToggleTime = now;
|
||||
|
||||
const profileIds = profiles?.map((profile) => profile.id) ?? [];
|
||||
// In case of 1 or 0 profiles just does nothing
|
||||
if (profileIds.length < 2) {
|
||||
return;
|
||||
}
|
||||
let nextId = profileIds[0];
|
||||
if (selectedProfile) {
|
||||
const curIndex = profileIds.indexOf(selectedProfile.id);
|
||||
const nextIndex = (curIndex + 1) % profileIds.length;
|
||||
nextId = profileIds[nextIndex];
|
||||
}
|
||||
// Optimistic update
|
||||
dispatch(setSelectedProfile(nextId));
|
||||
ideMessenger.post("didChangeSelectedProfile", {
|
||||
id: nextId,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -191,7 +219,25 @@ export default function AssistantSelect() {
|
|||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
}, [currentOrg, selectedProfile]);
|
||||
|
||||
const cycleOrgs = () => {
|
||||
const orgIds = orgs.map((org) => org.id);
|
||||
if (orgIds.length < 2) {
|
||||
return;
|
||||
}
|
||||
let nextId = orgIds[0];
|
||||
if (currentOrg) {
|
||||
const curIndex = orgIds.indexOf(currentOrg.id);
|
||||
const nextIndex = (curIndex + 1) % orgIds.length;
|
||||
nextId = orgIds[nextIndex];
|
||||
}
|
||||
// Optimistic update
|
||||
dispatch(setSelectedOrgId(nextId));
|
||||
ideMessenger.post("didChangeSelectedOrg", {
|
||||
id: nextId,
|
||||
});
|
||||
};
|
||||
|
||||
const tinyFont = useFontSize(-4);
|
||||
const smallFont = useFontSize(-3);
|
||||
|
|
@ -202,7 +248,7 @@ export default function AssistantSelect() {
|
|||
onClick={() => {
|
||||
ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/new?type=assistant",
|
||||
orgSlug: selectedOrganization?.slug,
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
}}
|
||||
className="flex cursor-pointer select-none items-center gap-1 text-gray-400"
|
||||
|
|
@ -244,7 +290,7 @@ export default function AssistantSelect() {
|
|||
</ListboxButton>
|
||||
|
||||
<Transition>
|
||||
<ListboxOptions className="min-w-[200px] pb-0">
|
||||
<ListboxOptions className="pb-0">
|
||||
<div
|
||||
className={`thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto`}
|
||||
>
|
||||
|
|
@ -268,21 +314,41 @@ export default function AssistantSelect() {
|
|||
}}
|
||||
/>
|
||||
|
||||
<ListboxOption
|
||||
value={"new-assistant"}
|
||||
fontSizeModifier={-2}
|
||||
onClick={session ? onNewAssistant : () => login(false)}
|
||||
>
|
||||
<div className="flex flex-row items-center justify-between gap-1 pr-2">
|
||||
<ListboxOption
|
||||
value={"new-assistant"}
|
||||
fontSizeModifier={-2}
|
||||
onClick={session ? onNewAssistant : () => login(false)}
|
||||
>
|
||||
<div
|
||||
className="text-lightgray flex flex-row items-center gap-2"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<PlusIcon className="ml-0.5 h-3 w-3 flex-shrink-0" />
|
||||
New Assistant
|
||||
</div>
|
||||
</ListboxOption>
|
||||
<div
|
||||
className="text-lightgray flex flex-row items-center gap-2"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
refreshProfiles();
|
||||
buttonRef.current?.click();
|
||||
}}
|
||||
>
|
||||
<PlusIcon className="ml-0.5 h-3 w-3 flex-shrink-0" />
|
||||
New Assistant
|
||||
<ArrowPathRoundedSquareIcon className="h-3 w-3" />
|
||||
<span
|
||||
className="hidden sm:flex"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</span>
|
||||
</div>
|
||||
</ListboxOption>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="my-0 h-[0.5px]"
|
||||
|
|
@ -307,11 +373,11 @@ export default function AssistantSelect() {
|
|||
</span>
|
||||
<div
|
||||
className="ml-auto flex items-center gap-1"
|
||||
onClick={() => navigate(ROUTES.CONFIG)}
|
||||
onClick={cycleOrgs}
|
||||
>
|
||||
{selectedOrganization?.iconUrl ? (
|
||||
{currentOrg?.iconUrl ? (
|
||||
<img
|
||||
src={selectedOrganization.iconUrl}
|
||||
src={currentOrg.iconUrl}
|
||||
className="h-3 w-3 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
|
|
@ -323,7 +389,7 @@ export default function AssistantSelect() {
|
|||
fontSize: tinyFont - 1,
|
||||
}}
|
||||
>
|
||||
{selectedOrganization?.name || "Personal"}
|
||||
{currentOrg?.name || "Personal"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -5,17 +5,20 @@ import {
|
|||
import { ControlPlaneSessionInfo } from "core/control-plane/client";
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import ConfirmationDialog from "../components/dialogs/ConfirmationDialog";
|
||||
import { useWebviewListener } from "../hooks/useWebviewListener";
|
||||
import { updateOrgsThunk, updateProfilesThunk } from "../redux";
|
||||
import { selectSelectedProfile } from "../redux/";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
selectSelectedProfile,
|
||||
setOrganizations,
|
||||
setSelectedOrgId,
|
||||
} from "../redux/";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice";
|
||||
import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice";
|
||||
import { IdeMessengerContext } from "./IdeMessenger";
|
||||
|
||||
|
|
@ -28,7 +31,6 @@ interface AuthContextType {
|
|||
refreshProfiles: () => void;
|
||||
controlServerBetaEnabled: boolean;
|
||||
organizations: OrganizationDescription[];
|
||||
selectedOrganization: OrganizationDescription | null;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
|
@ -38,26 +40,16 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
}) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
// Session
|
||||
const [session, setSession] = useState<ControlPlaneSessionInfo | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Orgs
|
||||
const orgs = useAppSelector((store) => store.organizations.organizations);
|
||||
const selectedOrgId = useAppSelector(
|
||||
(store) => store.organizations.selectedOrganizationId,
|
||||
);
|
||||
const selectedOrganization = useMemo(() => {
|
||||
if (!selectedOrgId) {
|
||||
return null;
|
||||
}
|
||||
return orgs.find((p) => p.id === selectedOrgId) ?? null;
|
||||
}, [orgs, selectedOrgId]);
|
||||
const orgs = useAppSelector((store) => store.profiles.organizations);
|
||||
|
||||
// Profiles
|
||||
const profiles = useAppSelector((store) => store.profiles.availableProfiles);
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const selectedProfile = useAppSelector(selectSelectedProfile);
|
||||
|
||||
const login: AuthContextType["login"] = (useOnboarding: boolean) => {
|
||||
|
|
@ -90,6 +82,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
text="Are you sure you want to log out of Continue?"
|
||||
onConfirm={() => {
|
||||
ideMessenger.post("logoutOfControlPlane", undefined);
|
||||
dispatch(
|
||||
setOrganizations(orgs.filter((org) => org.id === "personal")),
|
||||
);
|
||||
dispatch(setSelectedOrgId("personal"));
|
||||
}}
|
||||
onCancel={() => {
|
||||
dispatch(setDialogMessage(undefined));
|
||||
|
|
@ -100,79 +96,40 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
);
|
||||
};
|
||||
|
||||
useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => {
|
||||
setSession(data.sessionInfo);
|
||||
// On logout, clear the list of orgs
|
||||
if (!data.sessionInfo) {
|
||||
dispatch(updateOrgsThunk([]));
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
ideMessenger
|
||||
.request("getControlPlaneSessionInfo", {
|
||||
async function init() {
|
||||
const result = await ideMessenger.request("getControlPlaneSessionInfo", {
|
||||
silent: true,
|
||||
useOnboarding: false,
|
||||
})
|
||||
.then(
|
||||
(result) => result.status === "success" && setSession(result.content),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const [controlServerBetaEnabled, setControlServerBetaEnabled] =
|
||||
useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
ideMessenger.ide
|
||||
.getIdeSettings()
|
||||
.then(({ enableControlServerBeta, continueTestEnvironment }) => {
|
||||
setControlServerBetaEnabled(enableControlServerBeta);
|
||||
dispatch(
|
||||
setLastControlServerBetaEnabledStatus(enableControlServerBeta),
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
ideMessenger
|
||||
.request("controlPlane/listOrganizations", undefined)
|
||||
.then((result) => {
|
||||
if (result.status === "success") {
|
||||
dispatch(updateOrgsThunk(result.content));
|
||||
} else {
|
||||
dispatch(updateOrgsThunk([]));
|
||||
}
|
||||
});
|
||||
if (result.status === "success") {
|
||||
setSession(result.content);
|
||||
}
|
||||
}
|
||||
}, [session]);
|
||||
void init();
|
||||
}, []);
|
||||
|
||||
useWebviewListener(
|
||||
"didChangeIdeSettings",
|
||||
async (msg) => {
|
||||
const { settings } = msg;
|
||||
setControlServerBetaEnabled(settings.enableControlServerBeta);
|
||||
dispatch(
|
||||
setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta),
|
||||
);
|
||||
"didChangeControlPlaneSessionInfo",
|
||||
async (data) => {
|
||||
setSession(data.sessionInfo);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ideMessenger.request("config/listProfiles", undefined).then((result) => {
|
||||
if (result.status === "success") {
|
||||
dispatch(
|
||||
updateProfilesThunk({
|
||||
profiles: result.content.profiles,
|
||||
selectedProfileId: result.content.selectedProfileId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
const [controlServerBetaEnabled, setControlServerBetaEnabled] =
|
||||
useState(false);
|
||||
|
||||
const refreshProfiles = async () => {
|
||||
// Hacky, remove once continue for teams is deprecated
|
||||
useWebviewListener(
|
||||
"configUpdate",
|
||||
async (msg) => {
|
||||
setControlServerBetaEnabled(msg.usingContinueForTeams);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const refreshProfiles = useCallback(async () => {
|
||||
try {
|
||||
await ideMessenger.request("config/refreshProfiles", undefined);
|
||||
ideMessenger.post("showToast", ["info", "Config refreshed"]);
|
||||
|
|
@ -180,20 +137,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
console.error("Failed to refresh profiles", e);
|
||||
ideMessenger.post("showToast", ["error", "Failed to refresh config"]);
|
||||
}
|
||||
};
|
||||
|
||||
useWebviewListener(
|
||||
"didChangeAvailableProfiles",
|
||||
async (data) => {
|
||||
dispatch(
|
||||
updateProfilesThunk({
|
||||
profiles: data.profiles,
|
||||
selectedProfileId: data.selectedProfileId,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
}, [ideMessenger]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
|
|
@ -202,9 +146,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
logout,
|
||||
login,
|
||||
selectedProfile,
|
||||
profiles,
|
||||
profiles: currentOrg?.profiles ?? [],
|
||||
refreshProfiles,
|
||||
selectedOrganization,
|
||||
organizations: orgs,
|
||||
controlServerBetaEnabled,
|
||||
}}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@ import { useCallback, useContext, useEffect, useRef } from "react";
|
|||
import { VSC_THEME_COLOR_VARS } from "../components";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { BrowserSerializedContinueConfig } from "core";
|
||||
import { FromCoreProtocol } from "core/protocol";
|
||||
import {
|
||||
initializeProfilePreferencesThunk,
|
||||
selectProfileThunk,
|
||||
selectSelectedProfileId,
|
||||
initializeProfilePreferences,
|
||||
setOrganizations,
|
||||
setSelectedOrgId,
|
||||
setSelectedProfile,
|
||||
} from "../redux";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import {
|
||||
|
|
@ -36,30 +36,38 @@ function useSetup() {
|
|||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const history = useAppSelector((store) => store.session.history);
|
||||
const defaultModel = useAppSelector(selectDefaultModel);
|
||||
const selectedProfileId = useAppSelector(selectSelectedProfileId);
|
||||
const selectedProfileId = useAppSelector(
|
||||
(store) => store.profiles.selectedProfileId,
|
||||
);
|
||||
|
||||
const hasLoadedConfig = useRef(false);
|
||||
const hasDoneInitialConfigLoad = useRef(false);
|
||||
|
||||
const handleConfigUpdate = useCallback(
|
||||
async (
|
||||
initial: boolean,
|
||||
result: {
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
},
|
||||
) => {
|
||||
const { result: configResult, profileId } = result;
|
||||
if (initial && hasLoadedConfig.current) {
|
||||
async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => {
|
||||
const {
|
||||
result: configResult,
|
||||
profileId,
|
||||
organizations,
|
||||
selectedOrgId,
|
||||
} = result;
|
||||
if (isInitial && hasDoneInitialConfigLoad.current) {
|
||||
return;
|
||||
}
|
||||
hasLoadedConfig.current = true;
|
||||
hasDoneInitialConfigLoad.current = true;
|
||||
dispatch(setOrganizations(organizations));
|
||||
dispatch(setSelectedOrgId(selectedOrgId));
|
||||
dispatch(setSelectedProfile(profileId));
|
||||
dispatch(setConfigResult(configResult));
|
||||
dispatch(selectProfileThunk(profileId));
|
||||
|
||||
const isNewProfileId = profileId && profileId !== selectedProfileId;
|
||||
|
||||
if (isNewProfileId) {
|
||||
dispatch(initializeProfilePreferencesThunk({ profileId }));
|
||||
dispatch(
|
||||
initializeProfilePreferences({
|
||||
defaultSlashCommands: [],
|
||||
profileId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Perform any actions needed with the config
|
||||
|
|
@ -68,28 +76,31 @@ function useSetup() {
|
|||
document.body.style.fontSize = `${configResult.config.ui.fontSize}px`;
|
||||
}
|
||||
},
|
||||
[dispatch, hasLoadedConfig],
|
||||
[dispatch, hasDoneInitialConfigLoad],
|
||||
);
|
||||
|
||||
const loadConfig = useCallback(
|
||||
const initialLoadAuthAndConfig = useCallback(
|
||||
async (initial: boolean) => {
|
||||
// const authResult = await ideMessenger.request(
|
||||
// "auth/getState",
|
||||
// undefined
|
||||
// )
|
||||
const result = await ideMessenger.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
undefined,
|
||||
);
|
||||
if (result.status === "error") {
|
||||
return;
|
||||
if (result.status === "success") {
|
||||
await handleConfigUpdate(initial, result.content);
|
||||
}
|
||||
await handleConfigUpdate(initial, result.content);
|
||||
},
|
||||
[ideMessenger, handleConfigUpdate],
|
||||
);
|
||||
|
||||
// Load config from the IDE
|
||||
useEffect(() => {
|
||||
loadConfig(true);
|
||||
initialLoadAuthAndConfig(true);
|
||||
const interval = setInterval(() => {
|
||||
if (hasLoadedConfig.current) {
|
||||
if (hasDoneInitialConfigLoad.current) {
|
||||
// Init to run on initial config load
|
||||
ideMessenger.post("docs/initStatuses", undefined);
|
||||
dispatch(updateFileSymbolsFromHistory());
|
||||
|
|
@ -97,13 +108,13 @@ function useSetup() {
|
|||
|
||||
// This triggers sending pending status to the GUI for relevant docs indexes
|
||||
clearInterval(interval);
|
||||
return;
|
||||
} else {
|
||||
initialLoadAuthAndConfig(true);
|
||||
}
|
||||
loadConfig(true);
|
||||
}, 2_000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [hasLoadedConfig, loadConfig, ideMessenger]);
|
||||
}, [hasDoneInitialConfigLoad, initialLoadAuthAndConfig, ideMessenger]);
|
||||
|
||||
useWebviewListener(
|
||||
"configUpdate",
|
||||
|
|
@ -113,7 +124,7 @@ function useSetup() {
|
|||
}
|
||||
await handleConfigUpdate(false, update);
|
||||
},
|
||||
[loadConfig],
|
||||
[handleConfigUpdate],
|
||||
);
|
||||
|
||||
// Load symbols for chat on any session change
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { UserCircleIcon } from "@heroicons/react/24/solid";
|
||||
|
||||
import { useState } from "react";
|
||||
import { SecondaryButton } from "../../components";
|
||||
import {
|
||||
Popover,
|
||||
|
|
@ -8,13 +9,14 @@ import {
|
|||
Transition,
|
||||
} from "../../components/ui";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { selectSelectedOrganization } from "../../redux";
|
||||
import { selectCurrentOrg } from "../../redux";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { ScopeSelect } from "./ScopeSelect";
|
||||
|
||||
export function AccountButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { session, logout, login, organizations } = useAuth();
|
||||
const selectedOrg = useAppSelector(selectSelectedOrganization);
|
||||
const selectedOrg = useAppSelector(selectCurrentOrg);
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
|
|
@ -29,40 +31,44 @@ export function AccountButton() {
|
|||
|
||||
return (
|
||||
<Popover className="relative">
|
||||
<PopoverButton className="bg-vsc-background hover:bg-vsc-input-background text-vsc-foreground my-0.5 flex cursor-pointer rounded-md border-none px-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-medium">
|
||||
{selectedOrg === null ? "Personal" : selectedOrg.name}
|
||||
</span>
|
||||
<UserCircleIcon className="h-6 w-6" />{" "}
|
||||
</div>
|
||||
</PopoverButton>
|
||||
|
||||
<Transition>
|
||||
<PopoverPanel className="bg-vsc-input-background xs:p-4 absolute right-0 mt-1 rounded-md border border-zinc-700 p-2 shadow-lg">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{session.account.label}</span>
|
||||
<span className="text-lightgray text-sm">
|
||||
{session.account.id}
|
||||
{({ close }) => (
|
||||
<>
|
||||
<PopoverButton className="bg-vsc-background hover:bg-vsc-input-background text-vsc-foreground my-0.5 flex cursor-pointer rounded-md border-none px-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-medium">
|
||||
{selectedOrg === null ? "Personal" : selectedOrg.name}
|
||||
</span>
|
||||
<UserCircleIcon className="h-6 w-6" />{" "}
|
||||
</div>
|
||||
</PopoverButton>
|
||||
|
||||
{organizations.length > 0 && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-vsc-foreground text-xs">
|
||||
Organization
|
||||
</label>
|
||||
<ScopeSelect />
|
||||
<Transition>
|
||||
<PopoverPanel className="bg-vsc-input-background xs:p-4 absolute right-0 mt-1 rounded-md border border-zinc-700 p-2 shadow-lg">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{session.account.label}</span>
|
||||
<span className="text-lightgray text-sm">
|
||||
{session.account.id}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{organizations.length > 0 && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-vsc-foreground text-xs">
|
||||
Organization
|
||||
</label>
|
||||
<ScopeSelect onSelect={close} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SecondaryButton onClick={logout} className="!mx-0 w-full">
|
||||
Sign out
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SecondaryButton onClick={logout} className="!mx-0 w-full">
|
||||
Sign out
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
</PopoverPanel>
|
||||
</Transition>
|
||||
</PopoverPanel>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ChevronUpDownIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { UserCircleIcon } from "@heroicons/react/24/solid";
|
||||
import { useContext } from "react";
|
||||
import {
|
||||
Listbox,
|
||||
ListboxButton,
|
||||
|
|
@ -10,30 +11,39 @@ import {
|
|||
ListboxOptions,
|
||||
} from "../../components/ui/Listbox";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { useWebviewListener } from "../../hooks/useWebviewListener";
|
||||
import { selectOrgThunk } from "../../redux";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
setSelectedOrgId,
|
||||
} from "../../redux/slices/profiles/slice";
|
||||
|
||||
export function ScopeSelect() {
|
||||
const { organizations, selectedOrganization } = useAuth();
|
||||
interface ScopeSelectProps {
|
||||
onSelect?: () => void;
|
||||
}
|
||||
export function ScopeSelect({ onSelect }: ScopeSelectProps) {
|
||||
const { organizations } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const selectedOrgId = useAppSelector(
|
||||
(state) => state.organizations.selectedOrganizationId,
|
||||
(state) => state.profiles.selectedOrganizationId,
|
||||
);
|
||||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const handleChange = (newValue: string | null) => {
|
||||
dispatch(selectOrgThunk(newValue));
|
||||
const handleChange = (newValue: string) => {
|
||||
// optimisitic update
|
||||
dispatch(setSelectedOrgId(newValue));
|
||||
ideMessenger.post("didChangeSelectedOrg", {
|
||||
id: newValue,
|
||||
});
|
||||
onSelect?.();
|
||||
};
|
||||
|
||||
useWebviewListener("didSelectOrganization", async (data) => {
|
||||
handleChange(data.orgId);
|
||||
});
|
||||
|
||||
const CurScopeEntityFallBackIcon = selectedOrgId
|
||||
? BuildingOfficeIcon
|
||||
: UserCircleIcon;
|
||||
|
||||
const selectedDisplay = selectedOrganization ?? {
|
||||
const selectedDisplay = currentOrg ?? {
|
||||
name: "Personal",
|
||||
iconUrl: null,
|
||||
};
|
||||
|
|
@ -68,17 +78,6 @@ export function ScopeSelect() {
|
|||
</div>
|
||||
</ListboxOption>
|
||||
))}
|
||||
|
||||
{!!organizations.length && (
|
||||
<div className="bg-lightgray mx-1 my-1 h-px" />
|
||||
)}
|
||||
|
||||
<ListboxOption value={null}>
|
||||
<div className="flex items-center gap-2">
|
||||
<UserCircleIcon className="h-5 w-5" />
|
||||
<span>Personal</span>
|
||||
</div>
|
||||
</ListboxOption>
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { getFontSize } from "../../util";
|
|||
export function UserSettingsForm() {
|
||||
/////// User settings section //////
|
||||
const dispatch = useAppDispatch();
|
||||
const { selectedProfile, controlServerBetaEnabled } = useAuth();
|
||||
const { controlServerBetaEnabled } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const config = useAppSelector((state) => state.config.config);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,2 +1 @@
|
|||
export * from "./organizations";
|
||||
export * from "./profiles";
|
||||
|
|
|
|||
|
|
@ -1,27 +0,0 @@
|
|||
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
|
||||
import { PackageDocsResult } from "core";
|
||||
|
||||
export type MiscState = {
|
||||
lastControlServerBetaEnabledStatus: boolean;
|
||||
};
|
||||
|
||||
const initialState: MiscState = {
|
||||
lastControlServerBetaEnabledStatus: false,
|
||||
};
|
||||
|
||||
export const miscSlice = createSlice({
|
||||
name: "misc",
|
||||
initialState,
|
||||
reducers: {
|
||||
setLastControlServerBetaEnabledStatus: (
|
||||
state,
|
||||
action: PayloadAction<boolean>,
|
||||
) => {
|
||||
state.lastControlServerBetaEnabledStatus = action.payload;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const { setLastControlServerBetaEnabledStatus } = miscSlice.actions;
|
||||
|
||||
export default miscSlice.reducer;
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
export * from "./slice";
|
||||
export * from "./thunks";
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
||||
import { OrganizationDescription } from "core/config/ProfileLifecycleManager";
|
||||
|
||||
export interface OrganizationsState {
|
||||
organizations: OrganizationDescription[];
|
||||
selectedOrganizationId: string | null;
|
||||
}
|
||||
|
||||
const initialState: OrganizationsState = {
|
||||
organizations: [],
|
||||
selectedOrganizationId: null,
|
||||
};
|
||||
|
||||
export const organizationsSlice = createSlice({
|
||||
name: "organizations",
|
||||
initialState,
|
||||
reducers: {
|
||||
setOrganizations: (
|
||||
state,
|
||||
{ payload }: PayloadAction<OrganizationDescription[]>,
|
||||
) => {
|
||||
state.organizations = payload;
|
||||
},
|
||||
setSelectedOrganizationId: (
|
||||
state,
|
||||
{ payload }: PayloadAction<string | null>,
|
||||
) => {
|
||||
state.selectedOrganizationId = payload;
|
||||
},
|
||||
},
|
||||
selectors: {
|
||||
selectOrganizations: (state) => state.organizations,
|
||||
selectSelectedOrganizationId: (state) => state.selectedOrganizationId,
|
||||
selectSelectedOrganization: (state) =>
|
||||
state.organizations.find(
|
||||
(org) => org.id === state.selectedOrganizationId,
|
||||
) ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
export const { setOrganizations, setSelectedOrganizationId } =
|
||||
organizationsSlice.actions;
|
||||
|
||||
export const {
|
||||
selectOrganizations,
|
||||
selectSelectedOrganizationId,
|
||||
selectSelectedOrganization,
|
||||
} = organizationsSlice.selectors;
|
||||
|
||||
export const { reducer: organizationsReducer } = organizationsSlice;
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { OrganizationDescription } from "core/config/ProfileLifecycleManager";
|
||||
import { ThunkApiType } from "../../store";
|
||||
import { setAvailableProfiles } from "../profiles/slice";
|
||||
import { setOrganizations, setSelectedOrganizationId } from "./slice";
|
||||
|
||||
export const selectOrgThunk = createAsyncThunk<
|
||||
void,
|
||||
string | null,
|
||||
ThunkApiType
|
||||
>("organizations/select", async (id, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
const initialId = state.organizations.selectedOrganizationId;
|
||||
let newId = id;
|
||||
|
||||
// If no orgs, force clear
|
||||
if (state.organizations.organizations.length === 0) {
|
||||
newId = null;
|
||||
} else if (newId) {
|
||||
// If new id doesn't match an existing org, clear it
|
||||
if (!state.organizations.organizations.find((o) => o.id === newId)) {
|
||||
newId = null;
|
||||
}
|
||||
}
|
||||
// Unlike profiles, don't fallback to the first org,
|
||||
// Fallback to Personal (org = null)
|
||||
|
||||
if (initialId !== newId) {
|
||||
dispatch(setAvailableProfiles(null));
|
||||
dispatch(setSelectedOrganizationId(newId));
|
||||
extra.ideMessenger.post("didChangeSelectedOrg", {
|
||||
id: newId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateOrgsThunk = createAsyncThunk<
|
||||
void,
|
||||
OrganizationDescription[],
|
||||
ThunkApiType
|
||||
>("organizations/update", async (orgs, { dispatch, getState }) => {
|
||||
const state = getState();
|
||||
dispatch(setOrganizations(orgs));
|
||||
|
||||
// This will trigger reselection if needed
|
||||
dispatch(selectOrgThunk(state.organizations.selectedOrganizationId));
|
||||
});
|
||||
|
|
@ -1,2 +1 @@
|
|||
export * from "./slice";
|
||||
export * from "./thunks";
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
||||
import { SlashCommandDescription } from "core";
|
||||
import { ProfileDescription } from "core/config/ConfigHandler";
|
||||
import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
|
||||
|
||||
const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5;
|
||||
|
||||
|
|
@ -13,15 +13,40 @@ export interface PreferencesState {
|
|||
}
|
||||
|
||||
export interface ProfilesState {
|
||||
availableProfiles: ProfileDescription[] | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedProfileId: string | null;
|
||||
selectedOrganizationId: string | null;
|
||||
preferencesByProfileId: Record<string, PreferencesState>;
|
||||
}
|
||||
|
||||
const initialState: ProfilesState = {
|
||||
availableProfiles: null,
|
||||
selectedProfileId: null,
|
||||
preferencesByProfileId: {},
|
||||
selectedProfileId: null,
|
||||
selectedOrganizationId: null,
|
||||
organizations: [
|
||||
{
|
||||
id: "personal",
|
||||
profiles: [
|
||||
{
|
||||
title: "Local Assistant",
|
||||
id: "local",
|
||||
errors: [],
|
||||
profileType: "local",
|
||||
uri: "",
|
||||
iconUrl: "",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
},
|
||||
],
|
||||
slug: "",
|
||||
selectedProfileId: "local",
|
||||
name: "Personal",
|
||||
iconUrl: "",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const profilesSlice = createSlice({
|
||||
|
|
@ -30,12 +55,27 @@ export const profilesSlice = createSlice({
|
|||
reducers: {
|
||||
setSelectedProfile: (state, { payload }: PayloadAction<string | null>) => {
|
||||
state.selectedProfileId = payload;
|
||||
const currentOrg = state.organizations.find(
|
||||
(o) => o.id === state.selectedOrganizationId,
|
||||
);
|
||||
if (currentOrg) {
|
||||
currentOrg.selectedProfileId = payload;
|
||||
}
|
||||
},
|
||||
setAvailableProfiles: (
|
||||
setOrganizations: (
|
||||
state,
|
||||
{ payload }: PayloadAction<ProfileDescription[] | null>,
|
||||
{ payload }: PayloadAction<SerializedOrgWithProfiles[]>,
|
||||
) => {
|
||||
state.availableProfiles = payload;
|
||||
state.organizations = payload;
|
||||
},
|
||||
setSelectedOrgId: (state, { payload }: PayloadAction<string | null>) => {
|
||||
state.selectedOrganizationId = payload;
|
||||
const org = state.organizations.find((o) => o.id === payload);
|
||||
if (org) {
|
||||
state.selectedProfileId = org.selectedProfileId;
|
||||
} else {
|
||||
state.selectedProfileId = null;
|
||||
}
|
||||
},
|
||||
initializeProfilePreferences: (
|
||||
state,
|
||||
|
|
@ -102,15 +142,27 @@ export const profilesSlice = createSlice({
|
|||
},
|
||||
selectors: {
|
||||
selectSelectedProfile: (state) => {
|
||||
return (
|
||||
state.availableProfiles?.find(
|
||||
const selectedOrg = state.organizations.find(
|
||||
(org) => org.id === state.selectedOrganizationId,
|
||||
);
|
||||
if (selectedOrg) {
|
||||
const profile = selectedOrg.profiles.find(
|
||||
(profile) => profile.id === state.selectedProfileId,
|
||||
);
|
||||
return profile ?? null;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
selectCurrentOrg: (state) => {
|
||||
return (
|
||||
state.organizations.find(
|
||||
(org) => org.id === state.selectedOrganizationId,
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
|
||||
selectSelectedProfileId: (state) => state.selectedProfileId,
|
||||
|
||||
selectBookmarkedSlashCommands: (state) => {
|
||||
if (!state.selectedProfileId) return [];
|
||||
const preferences = state.preferencesByProfileId[state.selectedProfileId];
|
||||
|
|
@ -122,18 +174,19 @@ export const profilesSlice = createSlice({
|
|||
});
|
||||
|
||||
export const {
|
||||
setAvailableProfiles,
|
||||
setSelectedProfile,
|
||||
bookmarkSlashCommand,
|
||||
unbookmarkSlashCommand,
|
||||
initializeProfilePreferences,
|
||||
setOrganizations,
|
||||
setSelectedOrgId,
|
||||
} = profilesSlice.actions;
|
||||
|
||||
export const {
|
||||
selectSelectedProfile,
|
||||
selectSelectedProfileId,
|
||||
selectBookmarkedSlashCommands,
|
||||
selectPreferencesByProfileId,
|
||||
selectCurrentOrg,
|
||||
} = profilesSlice.selectors;
|
||||
|
||||
export const { reducer: profilesReducer } = profilesSlice;
|
||||
|
|
|
|||
|
|
@ -1,108 +0,0 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { ProfileDescription } from "core/config/ConfigHandler";
|
||||
import { ThunkApiType } from "../../store";
|
||||
import {
|
||||
initializeProfilePreferences,
|
||||
setAvailableProfiles,
|
||||
setSelectedProfile,
|
||||
} from "./slice";
|
||||
|
||||
export const selectProfileThunk = createAsyncThunk<
|
||||
void,
|
||||
string | null,
|
||||
ThunkApiType
|
||||
>("profiles/select", async (id, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
|
||||
if (state.profiles.availableProfiles === null) {
|
||||
// Currently in loading state
|
||||
return;
|
||||
}
|
||||
|
||||
const initialId = state.profiles.selectedProfileId;
|
||||
|
||||
let newId = id;
|
||||
|
||||
// If no profiles, force clear
|
||||
if (state.profiles.availableProfiles.length === 0) {
|
||||
newId = null;
|
||||
} else {
|
||||
// If new id doesn't match an existing profile, clear it
|
||||
if (newId) {
|
||||
if (!state.profiles.availableProfiles.find((p) => p.id === newId)) {
|
||||
newId = null;
|
||||
}
|
||||
}
|
||||
if (!newId) {
|
||||
// At this point if null ID and there ARE profiles,
|
||||
// Fallback to a profile, prioritizing the first in the list
|
||||
newId = state.profiles.availableProfiles[0].id;
|
||||
}
|
||||
}
|
||||
|
||||
// Only update if there's a change
|
||||
if ((newId ?? null) !== (initialId ?? null)) {
|
||||
dispatch(setSelectedProfile(newId));
|
||||
|
||||
extra.ideMessenger.post("didChangeSelectedProfile", {
|
||||
id: newId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const cycleProfile = createAsyncThunk<void, undefined, ThunkApiType>(
|
||||
"profiles/cycle",
|
||||
async (_, { dispatch, getState }) => {
|
||||
const state = getState();
|
||||
|
||||
if (state.profiles.availableProfiles === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const profileIds = state.profiles.availableProfiles.map(
|
||||
(profile) => profile.id,
|
||||
);
|
||||
// In case of no profiles just does nothing
|
||||
if (profileIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
let nextId = profileIds[0];
|
||||
if (state.profiles.selectedProfileId) {
|
||||
const curIndex = profileIds.indexOf(state.profiles.selectedProfileId);
|
||||
const nextIndex = (curIndex + 1) % profileIds.length;
|
||||
nextId = profileIds[nextIndex];
|
||||
}
|
||||
await dispatch(selectProfileThunk(nextId));
|
||||
},
|
||||
);
|
||||
|
||||
export const updateProfilesThunk = createAsyncThunk<
|
||||
void,
|
||||
{ profiles: ProfileDescription[] | null; selectedProfileId: string | null },
|
||||
ThunkApiType
|
||||
>("profiles/update", async (data, { dispatch, extra, getState }) => {
|
||||
const { profiles, selectedProfileId } = data;
|
||||
|
||||
dispatch(setAvailableProfiles(profiles));
|
||||
|
||||
// This will trigger reselection if needed
|
||||
dispatch(selectProfileThunk(selectedProfileId));
|
||||
});
|
||||
|
||||
export const initializeProfilePreferencesThunk = createAsyncThunk<
|
||||
void,
|
||||
{ profileId: string },
|
||||
ThunkApiType
|
||||
>(
|
||||
"profiles/initializeProfilePreferences",
|
||||
async (data, { getState, dispatch }) => {
|
||||
const { profileId } = data;
|
||||
|
||||
dispatch(
|
||||
initializeProfilePreferences({
|
||||
defaultSlashCommands: [],
|
||||
profileId,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -10,11 +10,10 @@ import { createFilter } from "redux-persist-transform-filter";
|
|||
import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2";
|
||||
import storage from "redux-persist/lib/storage";
|
||||
import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger";
|
||||
import { organizationsReducer, profilesReducer } from "./slices";
|
||||
import { profilesReducer } from "./slices";
|
||||
import configReducer from "./slices/configSlice";
|
||||
import editModeStateReducer from "./slices/editModeState";
|
||||
import indexingReducer from "./slices/indexingSlice";
|
||||
import miscReducer from "./slices/miscSlice";
|
||||
import sessionReducer from "./slices/sessionSlice";
|
||||
import tabsReducer from "./slices/tabsSlice";
|
||||
import uiReducer from "./slices/uiSlice";
|
||||
|
|
@ -26,14 +25,12 @@ export interface ChatMessage {
|
|||
|
||||
const rootReducer = combineReducers({
|
||||
session: sessionReducer,
|
||||
misc: miscReducer,
|
||||
ui: uiReducer,
|
||||
editModeState: editModeStateReducer,
|
||||
config: configReducer,
|
||||
indexing: indexingReducer,
|
||||
tabs: tabsReducer,
|
||||
profiles: profilesReducer,
|
||||
organizations: organizationsReducer,
|
||||
});
|
||||
|
||||
const saveSubsetFilters = [
|
||||
|
|
@ -47,10 +44,6 @@ const saveSubsetFilters = [
|
|||
"mode",
|
||||
"codeToEdit",
|
||||
|
||||
// TODO consider removing persisted profiles/orgs
|
||||
"availableProfiles",
|
||||
"organizations",
|
||||
|
||||
// higher risk to persist
|
||||
// codeBlockApplyStates
|
||||
// symbols
|
||||
|
|
@ -62,8 +55,12 @@ const saveSubsetFilters = [
|
|||
createFilter("ui", ["toolSettings", "toolGroupSettings"]),
|
||||
createFilter("indexing", []),
|
||||
createFilter("tabs", ["tabs"]),
|
||||
createFilter("organizations", ["selectedOrganizationId"]),
|
||||
createFilter("profiles", ["preferencesByProfileId", "selectedProfileId"]),
|
||||
createFilter("profiles", [
|
||||
"preferencesByProfileId",
|
||||
"selectedProfileId",
|
||||
"selectedOrganizationId",
|
||||
"organizations",
|
||||
]),
|
||||
];
|
||||
|
||||
const migrations: MigrationManifest = {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue