diff --git a/.continue/prompts/core-unit-test.prompt b/.continue/prompts/core-unit-test.prompt index 42ecef7bb..1a08945b4 100644 --- a/.continue/prompts/core-unit-test.prompt +++ b/.continue/prompts/core-unit-test.prompt @@ -4,7 +4,7 @@ description: Generate unit tests for core utilities Write jest tests for the provided code. Use jest version ^29 (e.g. jest 29.7.0) -Use best practices. Be clear and consise. +Use best practices. Be clear and concise. Aim for 100% code coverage where reasonable. Multiple tests can be written, split up tests for best clarity and readability. Only use typescript, and if the file/code is not typescript, warn the user. @@ -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 accesed via a remote "control plane" using the `ControlPlaneClient` +- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient` 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. @@ -31,7 +31,7 @@ Jest testing setup includes Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests. -IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. +IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. Instead, generate actual mock files and data for operations Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 84ee4e60f..e40d9d054 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -71,7 +71,27 @@ } ] }, - // Build the React app. It gets bundled into the extension as a file resource and has a seprate build step + { + "label": "vscode-extension:package", + "dependsOn": ["vscode-extension:esbuild"], + "type": "npm", + "script": "package", + "path": "extensions/vscode", + "problemMatcher": [ + { + "pattern": [ + { + "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + ] + } + ] + }, { "label": "vscode-extension:continue-ui:build", "type": "shell", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b69b1fd44..4f7e1634f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,7 +128,7 @@ nvm use 1. The new VS Code window with the extension is referred to as the _Host VS Code_ 2. The window you started debugging from is referred to as the _Main VS Code_ -3. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX". +3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX". ##### Debugging diff --git a/binary/package.json b/binary/package.json index 426127922..e698b9d2d 100644 --- a/binary/package.json +++ b/binary/package.json @@ -23,6 +23,7 @@ "scripts": { "test": "jest", "build": "node build.js", + "quick-build": "node quick-build.js --target darwin-arm64", "build:darwin-x64": "node build.js --os darwin-x64" }, "license": "Apache-2.0", diff --git a/binary/quick-build.js b/binary/quick-build.js new file mode 100644 index 000000000..a9a2e57d0 --- /dev/null +++ b/binary/quick-build.js @@ -0,0 +1,86 @@ +const esbuild = require("esbuild"); +const fs = require("fs"); +const path = require("path"); +const { + execCmdSync, + validateFilesPresent, + autodetectPlatformAndArch, +} = require("../scripts/util"); + +// Paths +const bin = path.join(__dirname, "bin"); +const esbuildOutputFile = "out/index.js"; +let targets = [ + "darwin-x64", + "darwin-arm64", + "linux-x64", + "linux-arm64", + "win32-x64", +]; + +for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i - 1] === "--target") { + targets = [process.argv[i]]; + } +} + +// Cleanup +for (const target of targets) { + const exe = target.startsWith("win") ? ".exe" : ""; + const targetDir = path.join(bin, target); + fs.rmSync(path.join(targetDir, `continue-binary${exe}`), { force: true }); +} + +// Validate files to ensure prerequisites are available +const filesToValidate = [ + "src/index.ts", + "../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js", + "../core/llm/tiktokenWorkerPool.mjs", + "../core/llm/llamaTokenizerWorkerPool.mjs", +]; +validateFilesPresent(filesToValidate); + +// Quick Build +(async () => { + console.log("[info] Building with esbuild..."); + await esbuild.build({ + entryPoints: ["src/index.ts"], + bundle: true, + outfile: esbuildOutputFile, + external: [ + "esbuild", + "./xhr-sync-worker.js", + "llamaTokenizerWorkerPool.mjs", + "tiktokenWorkerPool.mjs", + "vscode", + "./index.node", + ], + format: "cjs", + platform: "node", + sourcemap: true, + minify: true, + treeShaking: true, + loader: { ".node": "file" }, + inject: ["./importMetaUrl.js"], + define: { "import.meta.url": "importMetaUrl" }, + }); + + console.log("[info] Building binaries with pkg..."); + for (const target of targets) { + const targetDir = path.join(bin, target); + fs.mkdirSync(targetDir, { recursive: true }); + console.log(`[info] Building ${target}...`); + execCmdSync( + `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`, + ); + } + + // Validate only continue-binary files + const pathsToVerify = targets.map((target) => { + const exe = target.startsWith("win") ? ".exe" : ""; + return path.join(bin, target, `continue-binary${exe}`); + }); + validateFilesPresent(pathsToVerify); + + console.log("[info] Quick build completed!"); +})(); diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index d51fe1f1f..82b169677 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -240,6 +240,14 @@ export const Solidity = { endOfLine: [";"], }; +// Lua +export const Lua = { + name: "Lua", + topLevelKeywords: ["function"], + singleLineComment: "--", + endOfLine: [], +}; + // YAML export const YAML: AutocompleteLanguageInfo = { name: "YAML", @@ -367,6 +375,8 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { yaml: YAML, yml: YAML, md: Markdown, + lua: Lua, + luau: Lua, }; export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo { diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 7f5366df0..2c8b12a31 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -399,7 +399,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { lowerCaseModel.includes("gpt") || lowerCaseModel.includes("davinci-002") || lowerCaseModel.includes("claude") || - lowerCaseModel.includes("granite3") + lowerCaseModel.includes("granite3") || + lowerCaseModel.includes("granite-3") ) { return holeFillerTemplate; } diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index d0ce96207..eadaa137f 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -10,8 +10,8 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { const profiles = testConfigHandler.listProfiles(); - expect(profiles.length).toBe(1); - expect(profiles[0].id).toBe("local"); + expect(profiles?.length).toBe(1); + expect(profiles?.[0].id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; expect(currentProfile?.profileDescription.id).toBe("local"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 939362948..659584056 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -47,59 +47,76 @@ type ConfigUpdateFunction = (payload: ConfigResult) => void; export class ConfigHandler { private readonly globalContext = new GlobalContext(); private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[]; - private selectedProfileId: string | null; - private selectedOrgId: string | null; + private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded + private selectedProfileId: string | null = null; private localProfileManager: ProfileLifecycleManager; + private controlPlaneClient: ControlPlaneClient; + + initializedPromise: Promise; constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => Promise, - private controlPlaneClient: ControlPlaneClient, + sessionInfoPromise: Promise, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; this.writeLog = writeLog; + this.controlPlaneClient = new ControlPlaneClient( + sessionInfoPromise, + ideSettingsPromise, + ); // Set local profile as default const localProfileLoader = new LocalProfileLoader( ide, ideSettingsPromise, - controlPlaneClient, + this.controlPlaneClient, writeLog, ); this.localProfileManager = new ProfileLifecycleManager( localProfileLoader, this.ide, ); - this.profiles = [this.localProfileManager]; - this.selectedProfileId = localProfileLoader.description.id; - this.selectedOrgId = null; - void this.init(); + // Profiles are loaded asynchronously + this.initializedPromise = new Promise((resolve, reject) => { + this.init() + .then(() => { + resolve(); + }) + .catch((e) => { + reject(e); + }); + }); + } + + /** + * 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); } private async init() { - // Always load local profile immediately in case control plane doesn't load try { - await this.loadConfig(); + await this.fetchControlPlaneProfiles(); + } catch (e) { + // If this fails, make sure at least local profile is loaded + console.error("Failed to fetch control plane profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } + try { + const configResult = await this.loadConfig(); + this.notifyConfigListeners(configResult); } catch (e) { console.error("Failed to load config: ", e); } - - const workspaceId = await this.getWorkspaceId(); - const lastSelectedOrgIds = - this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - const selectedOrgId = lastSelectedOrgIds[workspaceId]; - - // We want to set the org ID before fetching control plane profiles - if (selectedOrgId) { - this.selectedOrgId = selectedOrgId; - } - - // Load control plane profiles - void this.fetchControlPlaneProfiles(); } get currentProfile() { @@ -110,14 +127,14 @@ export class ConfigHandler { // 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( + this.profiles?.find( (p) => p.profileDescription.id === this.selectedProfileId, - ) ?? this.profiles[0] + ) ?? null ); } get inactiveProfiles() { - return this.profiles.filter( + return (this.profiles ?? []).filter( (p) => p.profileDescription.id !== this.selectedProfileId, ); } @@ -138,73 +155,83 @@ export class ConfigHandler { } } - async loadPlatformProfiles() { + async listOrganizations() { + return await this.controlPlaneClient.listOrganizations(); + } + + async loadAssistantsForSelectedOrg() { // Get the profiles and create their lifecycle managers - this.controlPlaneClient - .listAssistants(this.selectedOrgId) - .then(async (assistants) => { - const hubProfiles = await Promise.all( - assistants.map(async (assistant) => { - let renderedConfig: AssistantUnrolled | undefined = undefined; - if (assistant.configResult.config) { - renderedConfig = await clientRenderHelper( - { - ownerSlug: assistant.ownerSlug, - packageSlug: assistant.packageSlug, - }, - YAML.stringify(assistant.configResult.config), - this.ide, - this.controlPlaneClient, - ); - } + const userId = await this.controlPlaneClient.userId; + const selectedOrgId = await this.getSelectedOrgId(); - const profileLoader = new PlatformProfileLoader( - { ...assistant.configResult, config: renderedConfig }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, + let profiles: ProfileLifecycleManager[] | null = null; + if (!userId) { + // Not logged in + profiles = [this.localProfileManager]; + } else { + // Logged in + const assistants = + await this.controlPlaneClient.listAssistants(selectedOrgId); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + let renderedConfig: AssistantUnrolled | undefined = undefined; + if (assistant.configResult.config) { + renderedConfig = await clientRenderHelper( + { + ownerSlug: assistant.ownerSlug, + packageSlug: assistant.packageSlug, + }, + YAML.stringify(assistant.configResult.config), this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), + this.controlPlaneClient, ); + } - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); - - this.profiles = - this.selectedOrgId === null - ? [this.localProfileManager, ...hubProfiles] - : hubProfiles; - - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), - ); - - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - - const selectedProfileId = lastSelectedIds[workspaceId]; - if (selectedProfileId) { - this.selectedProfileId = selectedProfileId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedIds, + const profileLoader = new PlatformProfileLoader( + { ...assistant.configResult, config: renderedConfig }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), ); - } - }) - .catch((e) => { - console.error("Failed to list assistants: ", e); - }); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); + + if (selectedOrgId === null) { + // Personal + profiles = [...hubProfiles, this.localProfileManager]; + } else { + // Organization + profiles = hubProfiles; + } + } + + await this.updateAvailableProfiles(profiles); + } + + 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(); + const selectedProfileId = + 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; @@ -230,8 +257,9 @@ export class ConfigHandler { } private async reloadHubAssistants() { + const selectedOrgId = await this.getSelectedOrgId(); const newFullSlugsList = - await this.controlPlaneClient.listAssistantFullSlugs(this.selectedOrgId); + await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId); if (newFullSlugsList) { const shouldReload = this.fullSlugsListsDiffer( @@ -239,7 +267,7 @@ export class ConfigHandler { this.lastFullSlugsList, ); if (shouldReload) { - await this.loadPlatformProfiles(); + await this.loadAssistantsForSelectedOrg(); } this.lastFullSlugsList = newFullSlugsList; } @@ -248,7 +276,7 @@ export class ConfigHandler { private async fetchControlPlaneProfiles() { if (await useHub(this.ideSettingsPromise)) { clearInterval(this.platformProfilesRefreshInterval); - await this.loadPlatformProfiles(); + 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 @@ -257,54 +285,45 @@ export class ConfigHandler { PlatformProfileLoader.RELOAD_INTERVAL, ); } else { - this.controlPlaneClient - .listWorkspaces() - .then(async (workspaces) => { - this.profiles = [this.localProfileManager]; - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - this.profiles.push( - new ProfileLifecycleManager(profileLoader, this.ide), - ); - }); - - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), + try { + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = [this.localProfileManager]; + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), ); - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - const selectedProfileId = lastSelectedIds[workspaceId]; - if (selectedProfileId) { - this.selectedProfileId = selectedProfileId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedIds, - ); - } - }) - .catch((e) => { - console.error(e); + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); + + await this.updateAvailableProfiles(profiles); + } catch (e: any) { + console.error("Failed to load profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } } } + async getPersistedSelectedProfileId(): Promise { + const workspaceId = await this.getWorkspaceId(); + const lastSelectedIds = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + return lastSelectedIds[workspaceId] ?? null; + } + + async getSelectedOrgId(): Promise { + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + return selectedOrgs[await this.getWorkspaceId()] ?? null; + } + async setSelectedOrgId(orgId: string | null) { - this.selectedOrgId = orgId; const selectedOrgs = this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; selectedOrgs[await this.getWorkspaceId()] = orgId; @@ -348,16 +367,25 @@ export class ConfigHandler { }); } - private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = []; + private profilesListeners: (( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void)[] = []; onDidChangeAvailableProfiles( - listener: (profiles: ProfileDescription[]) => void, + listener: ( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void, ) { this.profilesListeners.push(listener); } - private notifyProfileListeners(profiles: ProfileDescription[]) { + private notifyProfileListeners( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) { for (const listener of this.profilesListeners) { - listener(profiles); + listener(profiles, selectedProfileId); } } @@ -410,8 +438,8 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] { - return this.profiles.map((p) => p.profileDescription); + listProfiles(): ProfileDescription[] | null { + return this.profiles?.map((p) => p.profileDescription) ?? null; } async loadConfig(): Promise> { diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 22f1dffbc..e877c10e7 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -7,7 +7,6 @@ import { IContextProvider, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { ControlPlaneClient } from "../../control-plane/client"; import { TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; @@ -31,8 +30,9 @@ async function getContextProviderExtras( ide, ideSettingsPromise, async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise), + Promise.resolve(undefined), ); + await configHandler.initializedPromise; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); diff --git a/core/core.ts b/core/core.ts index 6bbc34006..8a9df812e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -17,7 +17,6 @@ import { addContextProvider, addModel, deleteModel } from "./config/util"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; -import { ControlPlaneClient } from "./control-plane/client"; import { getControlPlaneEnv } from "./control-plane/env"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; @@ -63,7 +62,6 @@ export class Core { completionProvider: CompletionProvider; continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; - controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -110,16 +108,11 @@ export class Core { useOnboarding: false, }); - this.controlPlaneClient = new ControlPlaneClient( - sessionInfoPromise, - ideSettingsPromise, - ); - this.configHandler = new ConfigHandler( this.ide, ideSettingsPromise, this.onWrite, - this.controlPlaneClient, + sessionInfoPromise, ); this.docsService = DocsService.createSingleton( @@ -135,10 +128,22 @@ export class Core { profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, }); + + // update additional submenu context providers registered via VSCode API + const additionalProviders = this.configHandler.getAdditionalSubmenuContextProviders(); + if (additionalProviders.length > 0) { + this.messenger.send("refreshSubmenuItems", { + providers: additionalProviders, + }); + } }); - this.configHandler.onDidChangeAvailableProfiles((profiles) => - this.messenger.send("didChangeAvailableProfiles", { profiles }), + this.configHandler.onDidChangeAvailableProfiles( + (profiles, selectedProfileId) => + this.messenger.send("didChangeAvailableProfiles", { + profiles, + selectedProfileId, + }), ); // Codebase Indexer and ContinueServerClient depend on IdeSettings @@ -319,7 +324,7 @@ export class Core { }); on("controlPlane/listOrganizations", async (msg) => { - return await this.controlPlaneClient.listOrganizations(); + return await this.configHandler.listOrganizations(); }); // Context providers @@ -936,7 +941,7 @@ export class Core { on("didChangeSelectedOrg", (msg) => { void this.configHandler.setSelectedOrgId(msg.data.id); void this.configHandler.reloadConfig(); - void this.configHandler.loadPlatformProfiles(); + void this.configHandler.loadAssistantsForSelectedOrg(); }); on("didChangeControlPlaneSessionInfo", async (msg) => { diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 0064f064c..682b76a23 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -2,7 +2,6 @@ * @jest-environment jsdom */ import { ConfigHandler } from "../../config/ConfigHandler.js"; -import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; @@ -50,16 +49,7 @@ describe.skip("DocsService Integration Tests", () => { ide, ideSettingsPromise, async () => {}, - new ControlPlaneClient( - Promise.resolve({ - accessToken: "", - account: { - id: "", - label: "", - }, - }), - ideSettingsPromise, - ), + Promise.resolve(undefined), ); docsService = DocsService.createSingleton(configHandler, ide); diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 428bae967..aba1da6b0 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -139,24 +139,35 @@ export async function htmlPageToArticleWithChunks( return undefined; } + const title = readability.title || subpath; + const titles = Array.from(dom.window.document.querySelectorAll("h2")); - const article_components = titles.map((titleElement) => { - const title = titleElement.textContent || ""; - let body = ""; - let nextSibling = titleElement.nextElementSibling; - while (nextSibling && nextSibling.tagName !== "H2") { - body += nextSibling.textContent || ""; - nextSibling = nextSibling.nextElementSibling; - } + const article_components = + titles.length > 0 + ? titles.map((titleElement) => { + const title = titleElement.textContent || ""; + let body = ""; + let nextSibling = titleElement.nextElementSibling; - return { title, body }; - }); + while (nextSibling && nextSibling.tagName !== "H2") { + body += nextSibling.textContent || ""; + nextSibling = nextSibling.nextElementSibling; + } + + return { title, body }; + }) + : [ + { + title: title, + body: readability.textContent, + }, + ]; const article = { url, subpath, - title: readability.title, + title: title, article_components, }; return { diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 4b0c12fee..5342396fd 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -358,6 +358,11 @@ const preIndexedDocs: Record< startUrl: "https://angular.dev/", rootUrl: "https://angular.dev/", }, + "https://docs.djangoproject.com/": { + title: "Django", + startUrl: "https://docs.djangoproject.com/", + rootUrl: "https://docs.djangoproject.com/", + } }; export default preIndexedDocs; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 8ef09d107..34eef180f 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -375,7 +375,7 @@ class VertexAI extends BaseLLM { } const resp = await this.fetch( - new URL(this.apiBase + `publishers/google/models/${this.model}:predict`), + new URL(`publishers/google/models/${this.model}:predict`, this.apiBase), { method: "POST", body: JSON.stringify({ diff --git a/core/protocol/core.ts b/core/protocol/core.ts index c3084f6b8..96eebce84 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -14,11 +14,11 @@ import type { ContextSubmenuItem, DiffLine, DocsIndexingDetails, + ExperimentalModelRoles, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, ModelDescription, - ExperimentalModelRoles, PromptLog, RangeInFile, SerializedContinueConfig, @@ -68,7 +68,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/deleteModel": [{ title: string }, void]; "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [undefined, ProfileDescription[]]; + "config/listProfiles": [undefined, ProfileDescription[] | null]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, void]; "context/getContextItems": [ diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index ff99acd03..67b5919a4 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -8,5 +8,8 @@ export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedOrg: [{ id: string | null }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [{ profiles: ProfileDescription[] }, void]; + didChangeAvailableProfiles: [ + { profiles: ProfileDescription[]; selectedProfileId: string | null }, + void, + ]; }; diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index 4f8601303..ae54b03db 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -18,7 +18,7 @@ export const testConfigHandler = new ConfigHandler( testIde, ideSettingsPromise, async (text) => {}, - testControlPlaneClient, + Promise.resolve(undefined), ); export const testLLM = new Mock({ diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 067445994..df1296e0c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -93,6 +93,7 @@ export const supportedLanguages: { [key: string]: LanguageName } = { htm: LanguageName.HTML, java: LanguageName.JAVA, lua: LanguageName.LUA, + luau: LanguageName.LUA, ocaml: LanguageName.OCAML, ml: LanguageName.OCAML, mli: LanguageName.OCAML, diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index d4ae3acac..427d3e865 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -320,6 +320,46 @@ mcpServers: PORT: "3000" ``` +## Using YAML anchors to avoid config duplication + +You can also use node anchors to avoid duplication of properties. To do so, +adding the YAML version header `%YAML 1.1` is needed, here's an example of +a `config.yaml` configuration file using anchors: + +```yaml title="config.yaml" +%YAML 1.1 +--- +name: MyProject +version: 0.0.1 + +model_defaults: &model_defaults + provider: openai + apiKey: my-api-key + apiBase: https://api.example.com/llm + +models: +- name: mistral + <<: *model_defaults + model: mistral-7b-instruct + roles: + - chat + - edit + +- name: qwen2.5-coder-7b-instruct + <<: *model_defaults + model: qwen2.5-coder-7b-instruct + roles: + - chat + - edit + +- name: qwen2.5-coder-7b + <<: *model_defaults + model: qwen2.5-coder-7b + useLegacyCompletionsEndpoint: false + roles: + - autocomplete +``` + ### Fully deprecated settings Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt index 93eb805b3..8b5159d4d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.autocomplete +import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys @@ -27,4 +28,8 @@ class CancelAutocompleteAction : AnAction() { val editor: Editor? = e.getData(CommonDataKeys.EDITOR) return project != null && editor != null && editor.contentComponent.hasFocus() } + + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.BGT + } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 9b8f558c2..c56b9fa43 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -428,7 +428,7 @@ class IdeProtocolClient( if (editor.document.text.trim().isEmpty()) { WriteCommandAction.runWriteCommandAction(project) { - editor.document.insertString(0, msg) + editor.document.insertString(0, params.text) } respond(null) return@launch diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index 8fcaf590a..faaf7d058 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -137,7 +137,10 @@ fun openInlineEdit(project: Project?, editor: Editor) { modelTitles.addAll(models.map { it["title"] as String }) } - val maxWaitTime = 200 + // This is a hacky way to not complicate getting model titles with coroutines + // 1500 feels like way upper limit of "would be weird if panel showed up after that long" + // And should always allow enough time to load config + val maxWaitTime = 1500 val startTime = System.currentTimeMillis() while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { Thread.sleep(20) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index e121e5687..035c52db8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -192,10 +192,12 @@ class VerticalDiffBlock( private fun revertDiff() { WriteCommandAction.runWriteCommandAction(project) { - // Delete the added lines val startOffset = editor.document.getLineStartOffset(startLine) - val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1 - editor.document.deleteString(startOffset, endOffset) + // Delete the added lines + if (addedLines.isNotEmpty()) { + val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1 + editor.document.deleteString(startOffset, endOffset) + } // Add the deleted lines back if (deletedLines.isNotEmpty()) { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 5372a9c97..57f283f76 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.266", + "version": "0.9.268", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.266", + "version": "0.9.268", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 65f55c990..a25aecbd5 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.268", + "version": "0.9.269", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 2254bb1f3..c4d392cfa 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -504,21 +504,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { async function copyScripts() { process.chdir(path.join(continueDir, "extensions", "vscode")); console.log("[info] Copying scripts from core"); - await new Promise((resolve, reject) => { - ncp( - path.join(__dirname, "../../../core/scripts"), - path.join(__dirname, "../out"), - { dereference: true }, - (error) => { - if (error) { - console.warn("[error] Error copying script files", error); - reject(error); - } else { - resolve(); - } - }, - ); - }); + fs.copyFileSync( + path.join(__dirname, "../../../core/util/start_ollama.sh"), + path.join(__dirname, "../out/start_ollama.sh"), + ); + console.log("[info] Copied script files"); } module.exports = { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index d99bbd5ae..e745e2a30 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1056,7 +1056,7 @@ export function registerAllCommands( core: Core, editDecorationManager: EditDecorationManager, ) { - // registerCopyBufferSpy(context, core); + registerCopyBufferSpy(context, core); for (const [command, callback] of Object.entries( getCommandsMap( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index bdfe15ba6..69264eb35 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -109,7 +109,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { hideImageUpload: false, hideUseCodebase: true, hideSelectModel: false, - hideTools: true, enterText: editModeState.editStatus === "accepting" ? "Retry" : "Edit", } : {}; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index a6b92ab90..2f7c6a3b1 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -67,7 +67,6 @@ export interface ToolbarOptions { hideAddContext?: boolean; enterText?: string; hideSelectModel?: boolean; - hideTools?: boolean; } interface InputToolbarProps { @@ -91,10 +90,7 @@ function InputToolbar(props: InputToolbarProps) { const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; - const toolsSupported = - defaultModel && - modelSupportsTools(defaultModel) && - !props.toolbarOptions?.hideTools; + const toolsSupported = defaultModel && modelSupportsTools(defaultModel); const supportsImages = defaultModel && @@ -110,7 +106,6 @@ function InputToolbar(props: InputToolbarProps) {
diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 3265b2778..20dae9160 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -14,6 +14,7 @@ import InfoHover from "../../InfoHover"; import HoverItem from "./HoverItem"; import PopoverTransition from "./PopoverTransition"; import ToolDropdownItem from "./ToolDropdownItem"; +import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; interface ToolDropdownProps { disabled: boolean; @@ -28,6 +29,7 @@ export default function ToolDropdown(props: ToolDropdownProps) { const useTools = useAppSelector((state) => state.ui.useTools); const availableTools = useAppSelector((state) => state.config.config.tools); const [showAbove, setShowAbove] = useState(false); + const isInEditMode = useAppSelector(selectIsInEditMode); const ToolsIcon = useTools ? WrenchScrewdriverIconSolid @@ -48,33 +50,37 @@ export default function ToolDropdown(props: ToolDropdownProps) { } }, [isDropdownOpen]); + const isDisabled = props.disabled || isInEditMode; + return ( - !props.disabled && dispatch(toggleUseTools())}> + !isDisabled && dispatch(toggleUseTools())}>
!props.disabled && setIsHovered(true)} - onMouseLeave={() => !props.disabled && setIsHovered(false)} + onMouseEnter={() => !isDisabled && setIsHovered(true)} + onMouseLeave={() => !isDisabled && setIsHovered(false)} /> - {props.disabled && ( + {isDisabled && ( - This model does not support tool use + {isInEditMode + ? "Tool use not supported in edit mode" + : "This model does not support tool use"} )} - {!useTools && !props.disabled && ( + {!useTools && !isDisabled && ( Enable tool usage )} - {useTools && !props.disabled && ( + {useTools && !isDisabled && ( <> Tools @@ -84,7 +90,7 @@ export default function ToolDropdown(props: ToolDropdownProps) { onChange={() => {}} as="div" onClick={(e) => e.stopPropagation()} - disabled={props.disabled} + disabled={isDisabled} > {({ open }) => ( <> @@ -95,7 +101,7 @@ export default function ToolDropdown(props: ToolDropdownProps) { setDropdownOpen(!isDropdownOpen); }} className="text-lightgray flex cursor-pointer items-center border-none bg-transparent px-0 outline-none" - aria-disabled={props.disabled} + aria-disabled={isDisabled} > @@ -147,7 +153,7 @@ export default function ToolDropdown(props: ToolDropdownProps) { />
-
+
{availableTools.map((tool: any) => ( { if (queryInputRef.current) { queryInputRef.current.focus(); } - }, [querySubmenuItem]); + }, [querySubmenuItem, queryInputRef]); const selectItem = (index: number) => { const item = allItems[index]; @@ -378,6 +378,9 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { {querySubmenuItem ? ( { + e.stopPropagation(); + }} rows={1} ref={queryInputRef} placeholder={querySubmenuItem.description} @@ -436,7 +439,10 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ref={(el) => (itemRefs.current[index] = el)} className={`item cursor-pointer ${isSelected ? "is-selected" : ""}`} key={index} - onClick={() => selectItem(index)} + onClick={(e) => { + e.stopPropagation(); + selectItem(index); + }} onMouseEnter={() => setSelectedIndex(index)} data-testid="context-provider-dropdown-item" > diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 51fb3e91f..35e993a54 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -591,11 +591,12 @@ function TipTapEditor(props: TipTapEditorProps) { useEffect(() => { if (editor) { const handleFocus = () => { - debouncedShouldHideToolbar(false); + setShouldHideToolbar(false); }; const handleBlur = () => { - debouncedShouldHideToolbar(true); + // TODO - make toolbar auto-hiding work without breaking tool dropdown focus + // debouncedShouldHideToolbar(true); }; editor.on("focus", handleFocus); diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index efa717a0b..92a37928f 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -10,6 +10,7 @@ import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscInputBackground } from ".."; +import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppSelector } from "../../redux/hooks"; @@ -219,9 +220,7 @@ function ModelSelect() { const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); + const { selectedProfile } = useAuth(); // Sort so that options without an API key are at the end useEffect(() => { @@ -351,7 +350,7 @@ function ModelSelect() {
- {selectedProfileId === "local" && ( + {selectedProfile?.id === "local" && ( <> +
+ +
+ + {getProfileDisplayText(props.selectedProfile)} + +
+ ); +} + export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile, selectedOrganization } = useAuth(); + const { selectedProfile, selectedOrganization, profiles } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); useEffect(() => { @@ -68,18 +83,7 @@ export default function AssistantSelect() { className="text-lightgray cursor-pointer border-none bg-transparent hover:brightness-125" style={{ fontSize: `${getFontSize() - 2}px` }} > -
-
- -
- - {getProfileDisplayText(selectedProfile)} - -
+ diff --git a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx index 755e0570b..aef66670a 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx @@ -1,17 +1,17 @@ import { BuildingOfficeIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { ProfileDescription } from "core/config/ConfigHandler"; import { useContext } from "react"; import { useNavigate } from "react-router-dom"; import { lightGray } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; +import { selectProfileThunk } from "../../../redux/thunks/profileAndOrg"; import { getFontSize, getMetaKeyLabel, isLocalProfile } from "../../../util"; import { ROUTES } from "../../../util/navigation"; import AssistantIcon from "./AssistantIcon"; import { Divider, Option, OptionDiv } from "./shared"; import { getProfileDisplayText } from "./utils"; -import { ProfileDescription } from "core/config/ConfigHandler"; -import { selectProfileThunk } from "../../../redux/thunks/profileAndOrg"; interface AssistantSelectOptionsProps { onClose: () => void; @@ -43,6 +43,10 @@ export function AssistantSelectOptions({ onClose(); } + if (!profiles) { + return null; + } + return (
@@ -73,8 +77,6 @@ export function AssistantSelectOptions({ style={{ fontSize: getFontSize() - 2 }} > {getProfileDisplayText(profile)} - {profile.fullSlug.versionSlug && - ` (${profile.fullSlug.versionSlug})`}
@@ -107,7 +109,10 @@ export function AssistantSelectOptions({ onClick={() => navigate(ROUTES.CONFIG)} > {selectedOrganization?.iconUrl ? ( - + ) : ( )} diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 82aafc928..03856874a 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -15,18 +15,18 @@ import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; -import { IdeMessengerContext } from "./IdeMessenger"; import { updateOrgsThunk, updateProfilesThunk, } from "../redux/thunks/profileAndOrg"; +import { IdeMessengerContext } from "./IdeMessenger"; interface AuthContextType { session: ControlPlaneSessionInfo | undefined; logout: () => void; login: (useOnboarding: boolean) => Promise; selectedProfile: ProfileDescription | null; - profiles: ProfileDescription[]; + profiles: ProfileDescription[] | null; controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; selectedOrganization: OrganizationDescription | null; @@ -59,15 +59,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ // Profiles const profiles = useAppSelector((store) => store.session.availableProfiles); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, + const selectedProfile = useAppSelector( + (store) => store.session.selectedProfile, ); - const selectedProfile = useMemo(() => { - if (!selectedProfileId) { - return null; - } - return profiles.find((p) => p.id === selectedProfileId) ?? null; - }, [profiles, selectedProfileId]); const login: AuthContextType["login"] = (useOnboarding: boolean) => { return new Promise((resolve) => { @@ -111,6 +105,10 @@ 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(() => { @@ -149,8 +147,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ dispatch(updateOrgsThunk([])); } }); - } else { - dispatch(updateOrgsThunk([])); } }, [session]); @@ -169,7 +165,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ useEffect(() => { ideMessenger.request("config/listProfiles", undefined).then((result) => { if (result.status === "success") { - dispatch(updateProfilesThunk(result.content)); + console.log("PROFILES: ", result.content); + dispatch( + updateProfilesThunk({ + profiles: result.content, + selectedProfileId: null, + }), + ); } }); }, []); @@ -177,7 +179,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ useWebviewListener( "didChangeAvailableProfiles", async (data) => { - dispatch(updateProfilesThunk(data.profiles)); + console.log("AVAILABLE: ", data.profiles, data.selectedProfileId); + dispatch( + updateProfilesThunk({ + profiles: data.profiles, + selectedProfileId: data.selectedProfileId, + }), + ); }, [], ); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 7f349bc73..714f4ed75 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -13,13 +13,13 @@ import { setInactive, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { selectProfileThunk } from "../redux/thunks/profileAndOrg"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; -import { selectProfileThunk } from "../redux/thunks/profileAndOrg"; function useSetup() { const dispatch = useAppDispatch(); @@ -45,6 +45,7 @@ function useSetup() { } hasLoadedConfig.current = true; dispatch(setConfigResult(configResult)); + console.log("selecting 1", profileId); dispatch(selectProfileThunk(profileId)); // Perform any actions needed with the config @@ -94,6 +95,7 @@ function useSetup() { useWebviewListener( "configUpdate", async (update) => { + console.log("CONFIG UPDATE: ", update); if (!update) { return; } diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 6a00aa8cc..56fe464f7 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -1,16 +1,16 @@ +import { Listbox, Transition } from "@headlessui/react"; +import { ChevronUpDownIcon, PlusCircleIcon } from "@heroicons/react/24/outline"; import { Fragment, useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; +import { SecondaryButton } from "../../components"; import PageHeader from "../../components/PageHeader"; +import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { useAppDispatch } from "../../redux/hooks"; -import { SecondaryButton } from "../../components"; -import { useAuth } from "../../context/Auth"; +import { selectProfileThunk } from "../../redux/thunks/profileAndOrg"; import { ScopeSelect } from "./ScopeSelect"; import UserSettingsUI from "./UserSettings"; -import { Listbox, Transition } from "@headlessui/react"; -import { ChevronUpDownIcon, PlusCircleIcon } from "@heroicons/react/24/outline"; -import { selectProfileThunk } from "../../redux/thunks/profileAndOrg"; function ConfigPage() { useNavigationListener(); @@ -29,6 +29,7 @@ function ConfigPage() { } = useAuth(); const changeProfileId = (id: string) => { + console.log("selecting 2", id); dispatch(selectProfileThunk(id)); }; @@ -97,74 +98,80 @@ function ConfigPage() {

Configuration

- - {({ open }) => ( -
- - - {selectedProfile?.title ?? "No Assistant Selected"} - -
-
-
+ {profiles ? ( + <> + + {({ open }) => ( +
+ + + {selectedProfile?.title ?? "No Assistant Selected"} + +
+
+
- - - {profiles.map((option, idx) => ( - - - {option.title} - - - ))} - {hubEnabled && ( - { - ideMessenger.post("controlPlane/openUrl", { - path: "new", - orgSlug: selectedOrganization?.slug, - }); - }} - > - - - Create new Assistant - - - )} - - -
- )} -
- {selectedProfile && ( - - {selectedProfile.id === "local" - ? "Open Config File" - : hubEnabled - ? "Open Assistant" - : "Open Workspace"} - + + + {profiles.map((option, idx) => ( + + + {option.title} + + + ))} + {hubEnabled && ( + { + ideMessenger.post("controlPlane/openUrl", { + path: "new", + orgSlug: selectedOrganization?.slug, + }); + }} + > + + + Create new Assistant + + + )} + + +
+ )} +
+ {selectedProfile && ( + + {selectedProfile.id === "local" + ? "Open Config File" + : hubEnabled + ? "Open Assistant" + : "Open Workspace"} + + )} + + ) : ( +
Loading...
)}
diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index e8939e81d..604f583e4 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -26,7 +26,7 @@ const initialState: ConfigState = { contextProviders: [], models: [], tools: [], - usePlatform: false, + usePlatform: true, }, }; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index f3642629a..c70de4035 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -22,6 +22,7 @@ import { ToolCallState, } from "core"; import { ProfileDescription } from "core/config/ConfigHandler"; +import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -30,7 +31,6 @@ import { v4 as uuidv4 } from "uuid"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findCurrentToolCall } from "../util"; -import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -45,14 +45,14 @@ type SessionState = { isStreaming: boolean; title: string; id: string; - availableProfiles: ProfileDescription[]; - selectedProfileId: string | null; + /** null indicates loading state */ + availableProfiles: ProfileDescription[] | null; + selectedProfile: ProfileDescription | null; organizations: OrganizationDescription[]; selectedOrganizationId: string | null; streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; - currentMainEditorContent?: JSONContent; mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; @@ -88,21 +88,8 @@ const initialState: SessionState = { isStreaming: false, title: NEW_SESSION_TITLE, id: uuidv4(), - selectedProfileId: "local", - availableProfiles: [ - { - id: "local", - title: "Local", - errors: undefined, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - }, - ], + selectedProfile: null, + availableProfiles: null, organizations: [], selectedOrganizationId: "", curCheckpointIndex: 0, @@ -547,15 +534,15 @@ export const sessionSlice = createSlice({ }, // Important: these reducers don't handle selected profile/organization fallback logic // That is done in thunks - setSelectedProfileId: ( + setSelectedProfile: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { - state.selectedProfileId = payload; + state.selectedProfile = payload; }, setAvailableProfiles: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { state.availableProfiles = payload; }, @@ -771,7 +758,7 @@ export const { setNewestCodeblocksForInput, setAvailableProfiles, - setSelectedProfileId, + setSelectedProfile, setOrganizations, setSelectedOrganizationId, } = sessionSlice.actions; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index d716a6446..f137cbe7b 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -1,5 +1,4 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit"; -import miscReducer from "./slices/miscSlice"; import { createMigrate, MigrationManifest, @@ -10,9 +9,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 editModeStateReducer from "./slices/editModeState"; 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 uiReducer from "./slices/uiSlice"; @@ -33,9 +33,24 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ "history", - "sessionId", "selectedOrganizationId", - "selectedProfileId", + "selectedProfile", + "id", + "lastSessionId", + "title", + + // Persist edit mode in case closes in middle + "mode", + "codeToEdit", + + // TODO consider removing persisted profiles/orgs + "availableProfiles", + "organizations", + + // higher risk to persist + // codeBlockApplyStates + // symbols + // curCheckpointIndex ]), // Don't persist any of the edit state for now createFilter("editModeState", []), diff --git a/gui/src/redux/thunks/profileAndOrg.ts b/gui/src/redux/thunks/profileAndOrg.ts index 2ca7382a7..6632b77ab 100644 --- a/gui/src/redux/thunks/profileAndOrg.ts +++ b/gui/src/redux/thunks/profileAndOrg.ts @@ -1,14 +1,13 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ProfileDescription } from "core/config/ConfigHandler"; +import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; import { setAvailableProfiles, setOrganizations, setSelectedOrganizationId, - setSelectedProfileId, + setSelectedProfile, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { ProfileDescription } from "core/config/ConfigHandler"; -import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; -import { isLocalProfile } from "../../util"; export const selectProfileThunk = createAsyncThunk< void, @@ -16,10 +15,22 @@ export const selectProfileThunk = createAsyncThunk< ThunkApiType >("profiles/select", async (id, { dispatch, extra, getState }) => { const state = getState(); - const initialId = state.session.selectedProfileId; + + if (state.session.availableProfiles === null) { + // Currently in loading state + return; + } + + const initialId = state.session.selectedProfile?.id; let newId = id; + console.log( + "Running Thunk: ", + initialId, + newId, + state.session.availableProfiles, + ); // If no profiles, force clear if (state.session.availableProfiles.length === 0) { newId = null; @@ -32,19 +43,24 @@ export const selectProfileThunk = createAsyncThunk< } if (!newId) { // At this point if null ID and there ARE profiles, - // Fallback to a profile, prioritizing local - const localProfile = state.session.availableProfiles.find(isLocalProfile); - if (localProfile) { - newId = localProfile.id; - } else { - newId = state.session.availableProfiles[0].id; - } + // Fallback to a profile, prioritizing the first in the list + newId = state.session.availableProfiles[0].id; } } // Only update if there's a change - if (newId !== initialId) { - dispatch(setSelectedProfileId(newId)); + console.log( + "update selected profile?", + newId, + initialId, + state.session.availableProfiles, + ); + if ((newId ?? null) !== (initialId ?? null)) { + dispatch( + setSelectedProfile( + state.session.availableProfiles.find((p) => p.id === newId) ?? null, + ), + ); extra.ideMessenger.post("didChangeSelectedProfile", { id: newId, }); @@ -55,6 +71,11 @@ export const cycleProfile = createAsyncThunk( "profiles/cycle", async (_, { dispatch, getState }) => { const state = getState(); + + if (state.session.availableProfiles === null) { + return; + } + const profileIds = state.session.availableProfiles.map( (profile) => profile.id, ); @@ -63,8 +84,8 @@ export const cycleProfile = createAsyncThunk( return; } let nextId = profileIds[0]; - if (state.session.selectedProfileId) { - const curIndex = profileIds.indexOf(state.session.selectedProfileId); + if (state.session.selectedProfile) { + const curIndex = profileIds.indexOf(state.session.selectedProfile?.id); const nextIndex = (curIndex + 1) % profileIds.length; nextId = profileIds[nextIndex]; } @@ -74,14 +95,16 @@ export const cycleProfile = createAsyncThunk( export const updateProfilesThunk = createAsyncThunk< void, - ProfileDescription[], + { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, ThunkApiType ->("profiles/update", async (profiles, { dispatch, extra, getState }) => { - const state = getState(); +>("profiles/update", async (data, { dispatch, extra, getState }) => { + const { profiles, selectedProfileId } = data; + dispatch(setAvailableProfiles(profiles)); // This will trigger reselection if needed - dispatch(selectProfileThunk(state.session.selectedProfileId)); + console.log("selecting 3", selectedProfileId); + dispatch(selectProfileThunk(selectedProfileId)); }); export const selectOrgThunk = createAsyncThunk< @@ -106,7 +129,7 @@ export const selectOrgThunk = createAsyncThunk< // Fallback to Personal (org = null) if (initialId !== newId) { - dispatch(setAvailableProfiles([])); + dispatch(setAvailableProfiles(null)); dispatch(setSelectedOrganizationId(newId)); extra.ideMessenger.post("didChangeSelectedOrg", { id: newId, diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 1bd82a030..fe20fa550 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -27,7 +27,10 @@ export const streamNormalInput = createAsyncThunk< throw new Error("Default model not defined"); } - const includeTools = useTools && modelSupportsTools(defaultModel); + const includeTools = + useTools && + modelSupportsTools(defaultModel) && + state.session.mode === "chat"; // Send request const gen = extra.ideMessenger.llmStreamChat( diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 09f933d42..b6de2b8a1 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.31", + "version": "1.0.35", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/interfaces/SecretResult.ts b/packages/config-yaml/src/interfaces/SecretResult.ts index b15940d6e..0c34eae68 100644 --- a/packages/config-yaml/src/interfaces/SecretResult.ts +++ b/packages/config-yaml/src/interfaces/SecretResult.ts @@ -5,6 +5,8 @@ export enum SecretType { Package = "package", Organization = "organization", NotFound = "not_found", + ModelsAddOn = "models_add_on", + FreeTrial = "free_trial", } export interface OrgSecretLocation { @@ -25,6 +27,16 @@ export interface UserSecretLocation { secretName: string; } +export interface ModelsAddOnSecretLocation { + secretType: SecretType.ModelsAddOn; + secretName: string; +} + +export interface FreeTrialSecretLocation { + secretType: SecretType.FreeTrial; + secretName: string; +} + /** * If not found in user/package/org secrets, then there's a chance it's in * - the on-prem proxy @@ -40,7 +52,9 @@ export type SecretLocation = | OrgSecretLocation | PackageSecretLocation | UserSecretLocation - | NotFoundSecretLocation; + | NotFoundSecretLocation + | ModelsAddOnSecretLocation + | FreeTrialSecretLocation; export function encodeSecretLocation(secretLocation: SecretLocation): string { if (secretLocation.secretType === SecretType.Organization) { @@ -51,6 +65,10 @@ export function encodeSecretLocation(secretLocation: SecretLocation): string { return `${SecretType.Package}:${encodePackageSlug(secretLocation.packageSlug)}/${secretLocation.secretName}`; } else if (secretLocation.secretType === SecretType.NotFound) { return `${SecretType.NotFound}:${secretLocation.secretName}`; + } else if (secretLocation.secretType === SecretType.ModelsAddOn) { + return `${SecretType.ModelsAddOn}:${secretLocation.secretName}`; + } else if (secretLocation.secretType === SecretType.FreeTrial) { + return `${SecretType.FreeTrial}:${secretLocation.secretName}`; } else { throw new Error(`Invalid secret type: ${secretLocation}`); } @@ -85,6 +103,16 @@ export function decodeSecretLocation(secretLocation: string): SecretLocation { secretType: SecretType.NotFound, secretName, }; + case SecretType.ModelsAddOn: + return { + secretType: SecretType.ModelsAddOn, + secretName, + }; + case SecretType.FreeTrial: + return { + secretType: SecretType.FreeTrial, + secretName, + }; default: throw new Error(`Invalid secret type: ${secretType}`); } @@ -98,7 +126,11 @@ export interface NotFoundSecretResult { export interface FoundSecretResult { found: true; - secretLocation: OrgSecretLocation | PackageSecretLocation; + secretLocation: + | OrgSecretLocation + | PackageSecretLocation + | ModelsAddOnSecretLocation + | FreeTrialSecretLocation; fqsn: FQSN; } diff --git a/packages/config-yaml/src/interfaces/index.ts b/packages/config-yaml/src/interfaces/index.ts index f8db8b1d4..d57dbf587 100644 --- a/packages/config-yaml/src/interfaces/index.ts +++ b/packages/config-yaml/src/interfaces/index.ts @@ -1,5 +1,5 @@ import { SecretLocation, SecretResult, SecretType } from "./SecretResult.js"; -import { FQSN, FullSlug } from "./slugs.js"; +import { FQSN, FullSlug, PackageSlug, packageSlugsEqual } from "./slugs.js"; /** * A registry stores the content of packages @@ -27,34 +27,138 @@ export interface PlatformSecretStore { ): Promise; } +export function getLocationsToLook( + assistantSlug: PackageSlug, + blockSlug: PackageSlug | undefined, + currentUserSlug: string, + secretName: string, +): SecretLocation[] { + const locationsToLook: SecretLocation[] = [ + // Models Add-On + { + secretType: SecretType.ModelsAddOn as const, + secretName, + }, + // Block + ...(blockSlug + ? [ + { + secretType: SecretType.Package as const, + packageSlug: blockSlug, + secretName, + }, + ] + : []), + // Assistant + { + secretType: SecretType.Package as const, + packageSlug: assistantSlug, + secretName, + }, + // Organization that owns assistant (org secrets can only be used in assistants owned by that org) + { + secretType: SecretType.Organization as const, + orgSlug: assistantSlug.ownerSlug, + secretName, + }, + // User + { + secretType: SecretType.User as const, + userSlug: currentUserSlug, + secretName, + }, + // Free Trial + { + secretType: SecretType.FreeTrial as const, + secretName, + }, + ]; + return locationsToLook; +} + +export function listAvailableSecrets( + userSecretNames: string[], + orgSecretNames: string[], + assistantSecretNames: string[], + blockSecretNames: string[], + assistantSlug: PackageSlug, + blockSlug: PackageSlug | undefined, + currentUserSlug: string, +): SecretLocation[] { + // Create a set of all secret names + const allSecretNames = new Set([ + ...userSecretNames, + ...orgSecretNames, + ...assistantSecretNames, + ...blockSecretNames, + ]); + + // Use the resolution order to get a single SecretLocation for each secret name + const secretLocations: SecretLocation[] = []; + for (const secretName of allSecretNames) { + // Get the order of places to look + const locationsToLook = getLocationsToLook( + assistantSlug, + blockSlug, + currentUserSlug, + secretName, + ); + + // Go through the locations one by one + for (const secretLocation of locationsToLook) { + // "Looking in a location" in this case means looking through one of the lists of secret names + // First we get that list of secret names + let secretNamesList: string[] = []; + switch (secretLocation.secretType) { + case SecretType.User: + secretNamesList = userSecretNames; + break; + case SecretType.Organization: + secretNamesList = orgSecretNames; + break; + case SecretType.Package: + if (packageSlugsEqual(secretLocation.packageSlug, assistantSlug)) { + secretNamesList = assistantSecretNames; + } else if ( + blockSlug && + packageSlugsEqual(secretLocation.packageSlug, blockSlug) + ) { + secretNamesList = blockSecretNames; + } + break; + } + + // Then we look through that list for the matching secret name + if (secretNamesList) { + const matchingSecretName = secretNamesList.find( + (secretName) => secretName === secretLocation.secretName, + ); + if (matchingSecretName) { + // If we find a matching secret name, we add the location to the list + secretLocations.push(secretLocation); + break; + } + } + } + } + + return secretLocations; +} + export async function resolveFQSN( currentUserSlug: string, fqsn: FQSN, platformSecretStore: PlatformSecretStore, ): Promise { // First create the list of secret locations to try in order - const reversedSlugs = [...fqsn.packageSlugs].reverse(); - - const locationsToLook: SecretLocation[] = [ - // Organization first - ...reversedSlugs.map((slug) => ({ - secretType: SecretType.Organization as const, - orgSlug: slug.ownerSlug, - secretName: fqsn.secretName, - })), - // Then packages - ...reversedSlugs.map((slug) => ({ - secretType: SecretType.Package as const, - packageSlug: slug, - secretName: fqsn.secretName, - })), - // Then user - { - secretType: SecretType.User as const, - userSlug: currentUserSlug, - secretName: fqsn.secretName, - }, - ]; + const assistantSlug = fqsn.packageSlugs[0]; + const blockSlug = fqsn.packageSlugs[1]; + const locationsToLook = getLocationsToLook( + assistantSlug, + blockSlug, + currentUserSlug, + fqsn.secretName, + ); // Then try to get the secret from each location for (const secretLocation of locationsToLook) { diff --git a/packages/config-yaml/src/interfaces/slugs.ts b/packages/config-yaml/src/interfaces/slugs.ts index a6926fb5b..dd225aa10 100644 --- a/packages/config-yaml/src/interfaces/slugs.ts +++ b/packages/config-yaml/src/interfaces/slugs.ts @@ -26,6 +26,16 @@ export function encodeFullSlug(fullSlug: FullSlug): string { return `${fullSlug.ownerSlug}/${fullSlug.packageSlug}@${fullSlug.versionSlug}`; } +export function packageSlugsEqual( + pkgSlug1: PackageSlug, + pkgSlug2: PackageSlug, +): boolean { + return ( + pkgSlug1.ownerSlug === pkgSlug2.ownerSlug && + pkgSlug1.packageSlug === pkgSlug2.packageSlug + ); +} + export function decodeFullSlug(fullSlug: string): FullSlug { const [ownerSlug, packageSlug, versionSlug] = fullSlug.split(/[/@]/); return { diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index 1746be516..e5cc38fd0 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -71,7 +71,7 @@ export async function clientRender( return finalConfig; } -function getUnrenderedSecretLocation( +export function getUnrenderedSecretLocation( value: string | undefined, ): SecretLocation | undefined { if (!value) return undefined;