Merge branch 'main' into pe/fallback-if-not-configured

This commit is contained in:
Patrick Erichsen 2025-04-08 13:43:27 -07:00
commit 0508eb28fe
107 changed files with 3831 additions and 1420 deletions

View file

@ -1,6 +1,9 @@
name: Create Automatic Release
on:
push:
branches:
- nate/auto-main-release-draft
schedule:
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
workflow_dispatch: # Keep manual trigger option
@ -13,30 +16,13 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Important for getting all tags and commits
- name: Get latest tag
id: get_latest_tag
- name: Get version from package.json
id: get_version
run: |
# Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists
latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" | head -n 1 || echo "v1.1.0-vscode")
echo "Latest tag: $latest_tag"
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
- name: Generate next version
id: generate_version
run: |
# Extract version numbers (handle the -vscode suffix)
version=${LATEST_TAG#v} # Remove v prefix
version=${version%-vscode} # Remove -vscode suffix
IFS='.' read -ra VERSION_PARTS <<< "$version"
# Increment patch version
((VERSION_PARTS[2]++))
# Create new version string with -vscode suffix
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-vscode"
# Read version from package.json and add -vscode suffix
version=$(node -p "require('./extensions/vscode/package.json').version")
new_version="v${version}-vscode"
echo "New version will be: $new_version"
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
@ -49,7 +35,7 @@ jobs:
--generate-notes \
--title "$NEW_VERSION" \
--draft \
--latest
--latest \
--prerelease
create-jetbrains-release:
@ -60,29 +46,14 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Important for getting all tags and commits
fetch-depth: 0
- name: Get latest tag
id: get_latest_tag
- name: Get version from gradle.properties
id: get_version
run: |
# Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists
latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" | head -n 1 || echo "v1.1.0-jetbrains")
echo "Latest tag: $latest_tag"
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
- name: Generate next version
id: generate_version
run: |
# Extract version numbers (handle the -jetbrains suffix)
version=${LATEST_TAG#v} # Remove v prefix
version=${version%-jetbrains} # Remove -jetbrains suffix
IFS='.' read -ra VERSION_PARTS <<< "$version"
# Increment patch version
((VERSION_PARTS[2]++))
# Create new version string with -jetbrains suffix
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-jetbrains"
# Read version from gradle.properties and add -jetbrains suffix
version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2)
new_version="v${version}-jetbrains"
echo "New version will be: $new_version"
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
@ -95,5 +66,5 @@ jobs:
--generate-notes \
--title "$NEW_VERSION" \
--draft \
--latest
--latest \
--prerelease

View file

@ -37,6 +37,52 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
bump-version:
runs-on: ubuntu-latest
needs:
- check_release_name
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in gradle.properties
run: |
cd extensions/intelllij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the JetBrains extension version after successful pre-release publication.
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# Prepare and publish the plugin to JetBrains Marketplace repository
build:
needs: check_release_name

View file

@ -632,6 +632,4 @@ jobs:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
allowed-failures:
allowed-skips:
jobs: ${{ toJSON(needs) }}

View file

@ -1,4 +1,4 @@
name: VS Code Extension Version Bump
name: Create VS Code main release draft
on:
schedule:
# Runs at 7 AM PST (15:00 UTC) every Friday
@ -15,6 +15,10 @@ jobs:
with:
fetch-depth: 0 # Fetch all history and tags
- name: Setup GitHub CLI
run: |
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
@ -97,6 +101,15 @@ jobs:
echo "Pushing branch to origin..."
git push origin $NEW_BRANCH
# Add release creation
echo "Creating draft release..."
gh release create "${NEW_BRANCH}" \
--title "${NEW_BRANCH}" \
--generate-notes \
--draft \
--latest \
--notes-start-tag "${LAST_1_0_TAG}"
echo "Version bump process completed successfully!"
- name: Check for errors

1
.node-version Normal file
View file

@ -0,0 +1 @@
20.11.0

View file

@ -1,6 +1,7 @@
process.env.IS_BINARY = "true";
import { Command } from "commander";
import { Core } from "core/core";
import { LLMLogFormatter } from "core/llm/logFormatter";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { IMessenger } from "core/protocol/messenger";
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
@ -33,9 +34,8 @@ program.action(async () => {
const ide = new IpcIde(messenger);
const promptLogsPath = getPromptLogsPath();
new Core(messenger, ide, async (text) => {
fs.appendFileSync(promptLogsPath, text + "\n\n");
});
const core = new Core(messenger, ide);
new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath));
console.log("[binary] Core started");
} catch (e) {

View file

@ -39,20 +39,28 @@ export class AutocompleteLruCache {
// If the query is "co" and we have "c" -> "ontinue" in the cache,
// we should return "ntinue" as the completion.
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
truncateSqliteLikePattern(prefix),
);
// Validate that the cached compeltion is a valid completion for the prefix
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
prefix,
const truncatedPrefix = truncateSqliteLikePattern(prefix);
try {
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
truncatedPrefix,
);
// And then truncate so we aren't writing something that's already there
return result.value.slice(prefix.length - result.key.length);
// Validate that the cached completion is a valid completion for the prefix
if (
result &&
result.value.startsWith(truncatedPrefix.slice(result.key.length))
) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
truncatedPrefix,
);
// And then truncate so we aren't writing something that's already there
return result.value.slice(truncatedPrefix.length - result.key.length);
}
} catch (e) {
// catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX
console.error(e);
}
return undefined;
@ -60,13 +68,15 @@ export class AutocompleteLruCache {
async put(prefix: string, completion: string) {
const release = await this.mutex.acquire();
const truncatedPrefix = truncateSqliteLikePattern(prefix);
try {
await this.db.run("BEGIN TRANSACTION");
try {
const result = await this.db.get(
"SELECT key FROM cache WHERE key = ?",
prefix,
truncatedPrefix,
);
if (result) {
@ -74,7 +84,7 @@ export class AutocompleteLruCache {
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
completion,
Date.now(),
prefix,
truncatedPrefix,
);
} else {
const count = await this.db.get(
@ -89,7 +99,7 @@ export class AutocompleteLruCache {
await this.db.run(
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
prefix,
truncatedPrefix,
completion,
Date.now(),
);

View file

@ -1,6 +1,7 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
@ -15,7 +16,16 @@ export function slashFromCustomCommand(
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
run: async function* ({ input, llm, history, ide, completionOptions }) {
run: async function* ({
input,
llm,
history,
ide,
completionOptions,
config,
selectedCode,
fetch,
}) {
// Render prompt template
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
@ -25,7 +35,21 @@ export function slashFromCustomCommand(
{ input },
);
} else {
renderedPrompt = customCommand.prompt + "\n\n" + input;
const renderedPromptFile = await renderPromptFileV2(
customCommand.prompt,
{
config,
llm,
ide,
selectedCode,
fetch,
fullInput: input,
embeddingsProvider: config.modelsByRole.embed[0],
reranker: config.modelsByRole.rerank[0],
},
);
renderedPrompt = renderedPromptFile[1];
}
// Replaces slash command messages with the rendered prompt

View file

@ -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");

View file

@ -1,4 +1,4 @@
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
import { ConfigResult } from "@continuedev/config-yaml";
import {
ControlPlaneClient,
@ -12,6 +12,7 @@ import {
IDE,
IdeSettings,
ILLM,
ILLMLogger,
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
@ -25,360 +26,297 @@ 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>,
private llmLogger: ILLMLogger,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly didSelectOrganization?: (orgId: string | null) => void,
) {
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,
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,
this.llmLogger,
),
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.llmLogger,
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.llmLogger,
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(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
this.llmLogger,
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);
}
}

View file

@ -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>;

View file

@ -27,6 +27,7 @@ import {
IdeSettings,
IdeType,
ILLM,
ILLMLogger,
LLMOptions,
ModelDescription,
RerankerDescription,
@ -222,7 +223,7 @@ async function intermediateToFinalConfig(
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
loadPromptFiles: boolean = true,
allowFreeTrial: boolean = true,
@ -238,7 +239,7 @@ async function intermediateToFinalConfig(
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
llmLogger,
config.completionOptions,
config.systemMessage,
);
@ -260,7 +261,7 @@ async function intermediateToFinalConfig(
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
llmLogger,
copyOf(config.completionOptions),
config.systemMessage,
);
@ -280,7 +281,7 @@ async function intermediateToFinalConfig(
} else {
const llm = new CustomLLMClass({
...desc,
options: { ...desc.options, writeLog } as any,
options: { ...desc.options, logger: llmLogger } as any,
});
if (llm.model === "AUTODETECT") {
try {
@ -289,7 +290,11 @@ async function intermediateToFinalConfig(
(modelName) =>
new CustomLLMClass({
...desc,
options: { ...desc.options, model: modelName, writeLog },
options: {
...desc.options,
model: modelName,
logger: llmLogger,
},
}),
);
@ -343,7 +348,7 @@ async function intermediateToFinalConfig(
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
llmLogger,
config.completionOptions,
config.systemMessage,
);
@ -832,7 +837,7 @@ async function loadContinueConfigFromJson(
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
overrideConfigJson: SerializedContinueConfig | undefined,
): Promise<ConfigResult<ContinueConfig>> {
@ -932,7 +937,7 @@ async function loadContinueConfigFromJson(
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
);
return {

View file

@ -7,6 +7,7 @@ import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
SerializedContinueConfig,
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
@ -27,7 +28,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private llmLogger: ILLMLogger,
private readonly onReload: () => void,
) {
this.description = {
@ -65,7 +66,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
this.llmLogger,
serializedConfig,
undefined,
undefined,

View file

@ -1,7 +1,7 @@
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader {
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private writeLog: (message: string) => Promise<void>,
private llmLogger: ILLMLogger,
private overrideAssistantFile?:
| { path: string; content: string }
| undefined,
@ -59,7 +59,7 @@ export default class LocalProfileLoader implements IProfileLoader {
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
this.llmLogger,
undefined,
undefined,
undefined,

View file

@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -30,7 +30,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private llmLogger: ILLMLogger,
readonly description: ProfileDescription,
private readonly orgScopeId: string | null,
) {}
@ -44,7 +44,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
controlPlaneClient: ControlPlaneClient,
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
writeLog: (message: string) => Promise<void>,
llmLogger: ILLMLogger,
rawYaml: string,
orgScopeId: string | null,
): Promise<PlatformProfileLoader> {
@ -74,7 +74,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
controlPlaneClient,
ide,
ideSettingsPromise,
writeLog,
llmLogger,
description,
orgScopeId,
);
@ -93,7 +93,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
this.llmLogger,
undefined,
this.configResult.config,
{

View file

@ -12,6 +12,7 @@ import {
ContinueRcJson,
IDE,
IdeSettings,
ILLMLogger,
SerializedContinueConfig,
Tool,
} from "../../";
@ -39,7 +40,7 @@ export default async function doLoadConfig(
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
llmLogger: ILLMLogger,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
@ -74,7 +75,7 @@ export default async function doLoadConfig(
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
overrideConfigYaml,
platformConfigMetadata,
@ -92,7 +93,7 @@ export default async function doLoadConfig(
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
overrideConfigJson,
);
@ -160,6 +161,7 @@ export default async function doLoadConfig(
const serverContextProvider = new MCPContextProvider({
submenuItems,
mcpId: server.id,
serverName: server.name,
});
newConfig.contextProviders.push(serverContextProvider);
}

View file

@ -90,7 +90,7 @@ declare global {
requestOptions?: RequestOptions;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmLogger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
@ -433,6 +433,94 @@ declare global {
export type ToastType = "info" | "error" | "warning";
export interface LLMInteractionBase {
interactionId: string;
timestamp: number;
}
export interface LLMInteractionStartChat extends LLMInteractionBase {
kind: "startChat";
messages: ChatMessage[];
options: CompletionOptions;
}
export interface LLMInteractionStartComplete extends LLMInteractionBase {
kind: "startComplete";
prompt: string;
options: CompletionOptions;
}
export interface LLMInteractionStartFim extends LLMInteractionBase {
kind: "startFim";
prefix: string;
suffix: string;
options: CompletionOptions;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
kind: "chunk";
chunk: string;
}
export interface LLMInteractionMessage extends LLMInteractionBase {
kind: "message";
message: ChatMessage;
}
export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
kind: "success";
}
export interface LLMInteractionCancel extends LLMInteractionEnd {
kind: "cancel";
}
export interface LLMInteractionError extends LLMInteractionEnd {
kind: "error";
name: string;
message: string;
}
export type LLMInteractionItem =
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim
| LLMInteractionChunk
| LLMInteractionMessage
| LLMInteractionSuccess
| LLMInteractionCancel
| LLMInteractionError;
// When we log a LLM interaction, we want to add the interactionId and timestamp
// in the logger code, so we need a type that omits these members from *each*
// member of the union. This can be done by using the distributive behavior of
// conditional types in Typescript.
//
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
export type LLMInteractionItemDetails = DistributiveOmit<
LLMInteractionItem,
"interactionId" | "timestamp"
>;
export interface ILLMInteractionLog {
logItem(item: LLMInteractionItemDetails): void;
}
export interface ILLMLogger {
createInteractionLog(): ILLMInteractionLog;
}
export interface LLMOptions {
model: string;
@ -446,7 +534,7 @@ declare global {
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
aiGatewaySlug?: string;

View file

@ -20,6 +20,7 @@ import {
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { AllRerankers } from "../../context/allRerankers";
@ -117,7 +118,7 @@ async function configYamlToContinueConfig(
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
@ -217,7 +218,7 @@ async function configYamlToContinueConfig(
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config: continueConfig,
});
@ -438,7 +439,7 @@ export async function loadContinueConfigFromYaml(
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
@ -477,7 +478,7 @@ export async function loadContinueConfigFromYaml(
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
platformConfigMetadata,
);

View file

@ -1,6 +1,12 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { ContinueConfig, IDE, IdeSettings, LLMOptions } from "../..";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
LLMOptions,
} from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
@ -25,14 +31,14 @@ async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
writeLog: (log: string) => Promise<void>;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
@ -54,7 +60,7 @@ async function modelConfigToBaseLLM({
model.defaultCompletionOptions?.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens,
},
writeLog,
logger: llmLogger,
uniqueId,
title: model.name,
systemMessage: config.systemMessage,
@ -141,7 +147,7 @@ async function autodetectModels({
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
}: {
@ -150,7 +156,7 @@ async function autodetectModels({
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
writeLog: (log: string) => Promise<void>;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
@ -171,7 +177,7 @@ async function autodetectModels({
},
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
});
@ -189,7 +195,7 @@ export async function llmsFromModelConfig({
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
}: {
@ -197,7 +203,7 @@ export async function llmsFromModelConfig({
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
writeLog: (log: string) => Promise<void>;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
@ -205,7 +211,7 @@ export async function llmsFromModelConfig({
model,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
});
@ -220,7 +226,7 @@ export async function llmsFromModelConfig({
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
config,
});

View file

@ -10,6 +10,7 @@ import { MCPManagerSingleton } from "../mcp";
interface MCPContextProviderOptions {
mcpId: string;
serverName: string;
submenuItems: ContextSubmenuItem[];
}
@ -20,6 +21,16 @@ class MCPContextProvider extends BaseContextProvider {
description: "Model Context Protocol",
type: "submenu",
};
override get description(): ContextProviderDescription {
return {
title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`,
displayTitle: this.options["serverName"]
? `${this.options["serverName"]} resources`
: "MCP",
description: "Model Context Protocol",
type: "submenu",
};
}
static encodeMCPResourceId(mcpId: string, uri: string): string {
return JSON.stringify({ mcpId, uri });

View file

@ -7,6 +7,7 @@ import {
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { LLMLogger } from "../../llm/logger";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
@ -26,13 +27,13 @@ async function getContextProviderExtras(
): Promise<ContextProviderExtras> {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
llmLogger,
Promise.resolve(undefined),
);
await configHandler.initializedPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");

View file

@ -22,6 +22,7 @@ import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -46,6 +47,7 @@ import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { MCPManagerSingleton } from "./context/mcp";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -58,6 +60,7 @@ export class Core {
codebaseIndexingState: IndexingProgressUpdate;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
private readonly indexingPauseToken = new PauseToken(
this.globalContext.get("indexingPaused") === true,
@ -85,7 +88,6 @@ export class Core {
constructor(
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
migrateV1DevDataFiles();
@ -106,13 +108,8 @@ export class Core {
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.onWrite,
this.llmLogger,
sessionInfoPromise,
(orgId: string | null) => {
void messenger.request("didSelectOrganization", {
orgId,
});
},
);
this.docsService = DocsService.createSingleton(
@ -123,8 +120,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 +128,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 +145,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 +299,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 +328,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 +460,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 +759,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 +817,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 +832,7 @@ export class Core {
msg.data.sessionInfo,
);
});
on("auth/getAuthUrl", async (msg) => {
const url = await getAuthUrlForTokenPage(
ideSettingsPromise,
@ -907,6 +890,26 @@ export class Core {
return { contextItems };
});
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
return false;
}
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
// Count the size of the file tokenwise
const tokens = countTokens(item.content);
// File exceeds context length of the model
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
return true;
}
return false;
});
}
private indexingCancellationController: AbortController | undefined;

92
core/index.d.ts vendored
View file

@ -91,7 +91,7 @@ export interface ILLM extends LLMOptions {
requestOptions?: RequestOptions;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmLogger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
@ -486,6 +486,94 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
export type ToastType = "info" | "error" | "warning";
export interface LLMInteractionBase {
interactionId: string;
timestamp: number;
}
export interface LLMInteractionStartChat extends LLMInteractionBase {
kind: "startChat";
messages: ChatMessage[];
options: CompletionOptions;
}
export interface LLMInteractionStartComplete extends LLMInteractionBase {
kind: "startComplete";
prompt: string;
options: CompletionOptions;
}
export interface LLMInteractionStartFim extends LLMInteractionBase {
kind: "startFim";
prefix: string;
suffix: string;
options: CompletionOptions;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
kind: "chunk";
chunk: string;
}
export interface LLMInteractionMessage extends LLMInteractionBase {
kind: "message";
message: ChatMessage;
}
export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
kind: "success";
}
export interface LLMInteractionCancel extends LLMInteractionEnd {
kind: "cancel";
}
export interface LLMInteractionError extends LLMInteractionEnd {
kind: "error";
name: string;
message: string;
}
export type LLMInteractionItem =
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim
| LLMInteractionChunk
| LLMInteractionMessage
| LLMInteractionSuccess
| LLMInteractionCancel
| LLMInteractionError;
// When we log a LLM interaction, we want to add the interactionId and timestamp
// in the logger code, so we need a type that omits these members from *each*
// member of the union. This can be done by using the distributive behavior of
// conditional types in Typescript.
//
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
export type LLMInteractionItemDetails = DistributiveOmit<
LLMInteractionItem,
"interactionId" | "timestamp"
>;
export interface ILLMInteractionLog {
logItem(item: LLMInteractionItemDetails): void;
}
export interface ILLMLogger {
createInteractionLog(): ILLMInteractionLog;
}
export interface LLMOptions {
model: string;
@ -499,7 +587,7 @@ export interface LLMOptions {
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
rules?: Rule[];
apiKey?: string;

View file

@ -3,6 +3,7 @@
// */
// import { ConfigHandler } from "../../config/ConfigHandler.js";
// import { SiteIndexingConfig } from "../../index.js";
// import { LLMLogger } from "../../llm/logger.js";
// import FileSystemIde from "../../util/filesystem.js";
// import { editConfigJson } from "../../util/paths.js";
@ -48,7 +49,7 @@
// configHandler = new ConfigHandler(
// ide,
// ideSettingsPromise,
// async () => {},
// new LLMLogger(),
// Promise.resolve(undefined),
// );

View file

@ -158,18 +158,21 @@ async function getAddRemoveForTag(
const updateLastUpdated: PathAndCacheKey[] = [];
// First, group items by path and find latest timestamp for each
const pathGroups = new Map<string, {
latest: { lastUpdated: number, cacheKey: string },
allVersions: Array<{ cacheKey: string }>
}>();
const pathGroups = new Map<
string,
{
latest: { lastUpdated: number; cacheKey: string };
allVersions: Array<{ cacheKey: string }>;
}
>();
for (const item of saved) {
const { lastUpdated, path, cacheKey } = item;
if (!pathGroups.has(path)) {
pathGroups.set(path, {
latest: { lastUpdated, cacheKey },
allVersions: [{ cacheKey }]
allVersions: [{ cacheKey }],
});
} else {
const group = pathGroups.get(path)!;
@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
return input.substring(startIndex, input.length);
}
export function truncateSqliteLikePattern(input: string) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH);
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
}

View file

@ -1,6 +1,7 @@
import { ChatMessage, LLMOptions } from "..";
import { BaseLLM } from ".";
import { LLMLogger } from "./logger";
class DummyLLM extends BaseLLM {
static providerName = "openai";
@ -30,7 +31,7 @@ describe("BaseLLM", () => {
const templatMessagesFunction = (messages: ChatMessage[]) => {
return messages[0]?.content.toString() ?? "";
};
const writeLogFunction = async () => {};
const llmLogger = new LLMLogger();
const options: LLMOptions = {
model: "gpt-3.5-turbo",
uniqueId: "testId",
@ -43,7 +44,7 @@ describe("BaseLLM", () => {
requestOptions: {},
promptTemplates: {},
templateMessages: templatMessagesFunction,
writeLog: writeLogFunction,
logger: llmLogger,
llmRequestHook: () => {},
apiKey: "testApiKey",
aiGatewaySlug: "testSlug",
@ -67,7 +68,7 @@ describe("BaseLLM", () => {
expect(instance.requestOptions).toEqual({});
expect(instance.promptTemplates).toEqual({});
expect(instance.templateMessages).toEqual(templatMessagesFunction);
expect(instance.writeLog).toBe(writeLogFunction);
expect(instance.logger).toBe(llmLogger);
expect(instance.apiKey).toBe("testApiKey");
expect(instance.aiGatewaySlug).toBe("testSlug");
expect(instance.apiBase).toBe("https://api.example.com/");

View file

@ -16,6 +16,8 @@ import {
Chunk,
CompletionOptions,
ILLM,
ILLMInteractionLog,
ILLMLogger,
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
@ -73,6 +75,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
}
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
export abstract class BaseLLM implements ILLM {
static providerName: string;
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
@ -130,7 +134,7 @@ export abstract class BaseLLM implements ILLM {
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
@ -221,7 +225,7 @@ export abstract class BaseLLM implements ILLM {
options.template,
) ??
undefined;
this.writeLog = options.writeLog;
this.logger = options.logger;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
@ -350,13 +354,17 @@ export abstract class BaseLLM implements ILLM {
);
}
private _logTokensGenerated(
private _logEnd(
model: string,
prompt: string,
completion: string,
) {
thinking: string | undefined,
interaction: ILLMInteractionLog | undefined,
error?: any,
): InteractionStatus {
let promptTokens = this.countTokens(prompt);
let generatedTokens = this.countTokens(completion);
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
void Telemetry.capture(
"tokens_generated",
@ -385,6 +393,37 @@ export abstract class BaseLLM implements ILLM {
generatedTokens: generatedTokens,
},
});
if (error !== undefined) {
if (error === "cancel" || error.name === "AbortError") {
interaction?.logItem({
kind: "cancel",
promptTokens,
generatedTokens,
thinkingTokens,
});
return "cancelled";
} else {
console.log(error);
interaction?.logItem({
kind: "error",
name: error.name,
message: error.message,
promptTokens,
generatedTokens,
thinkingTokens,
});
return "error";
}
} else {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
});
return "success";
}
}
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
@ -465,11 +504,7 @@ export abstract class BaseLLM implements ILLM {
throw new Error(message);
}
}
//if e instance of LLMError, rethrow
if (e instanceof LLMError) {
throw e;
}
throw new Error(e.message);
throw e;
}
};
return withExponentialBackoff<Response>(
@ -544,52 +579,89 @@ export abstract class BaseLLM implements ILLM {
): AsyncGenerator<string> {
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(fimLog, completionOptions),
);
}
interaction?.logItem({
kind: "startFim",
prefix,
suffix,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
}
}
let completion = "";
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
const stream = this.openaiAdapter.fimStream(
toFimBody(prefix, suffix, completionOptions),
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
completion += content;
yield content;
try {
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
const stream = this.openaiAdapter.fimStream(
toFimBody(prefix, suffix, completionOptions),
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
interaction?.logItem({
kind: "chunk",
chunk: content,
});
completion += content;
yield content;
}
}
} else {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
interaction?.logItem({
kind: "chunk",
chunk,
});
completion += chunk;
yield chunk;
}
}
} else {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
completion += chunk;
yield chunk;
status = this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
"cancel",
);
}
}
this._logTokensGenerated(completionOptions.model, fimLog, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
return {
prompt: fimLog,
completion,
@ -604,6 +676,10 @@ export abstract class BaseLLM implements ILLM {
) {
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
let prompt = pruneRawPromptFromTop(
completionOptions.model,
@ -617,11 +693,11 @@ export abstract class BaseLLM implements ILLM {
}
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startComplete",
prompt,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
@ -649,6 +725,10 @@ export abstract class BaseLLM implements ILLM {
)) {
const content = chunk.choices[0]?.text ?? "";
completion += content;
interaction?.logItem({
kind: "chunk",
chunk: content,
});
yield content;
}
}
@ -659,14 +739,40 @@ export abstract class BaseLLM implements ILLM {
completionOptions,
)) {
completion += chunk;
interaction?.logItem({
kind: "chunk",
chunk,
});
yield chunk;
}
}
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
@ -685,6 +791,10 @@ export abstract class BaseLLM implements ILLM {
) {
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
let prompt = pruneRawPromptFromTop(
completionOptions.model,
@ -698,34 +808,65 @@ export abstract class BaseLLM implements ILLM {
}
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startComplete",
prompt: prompt,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion: string;
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
const result = await this.openaiAdapter.completionNonStream(
{
...toCompleteBody(prompt, completionOptions),
stream: false,
},
signal,
let completion: string = "";
try {
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
const result = await this.openaiAdapter.completionNonStream(
{
...toCompleteBody(prompt, completionOptions),
stream: false,
},
signal,
);
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
}
interaction?.logItem({
kind: "chunk",
chunk: completion,
});
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
);
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
return completion;
@ -770,6 +911,10 @@ export abstract class BaseLLM implements ILLM {
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
completionOptions = this._modifyCompletionOptions(completionOptions);
@ -779,11 +924,11 @@ export abstract class BaseLLM implements ILLM {
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startChat",
messages,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
@ -791,7 +936,6 @@ export abstract class BaseLLM implements ILLM {
let thinking = "";
let completion = "";
let citations: null | string[] = null;
try {
if (this.templateMessages) {
@ -801,6 +945,10 @@ export abstract class BaseLLM implements ILLM {
completionOptions,
)) {
completion += chunk;
interaction?.logItem({
kind: "chunk",
chunk: chunk,
});
yield { role: "assistant", content: chunk };
}
} else {
@ -830,15 +978,12 @@ export abstract class BaseLLM implements ILLM {
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += result.content;
interaction?.logItem({
kind: "message",
message: result,
});
yield result;
}
if (
!citations &&
(chunk as any).citations &&
Array.isArray((chunk as any).citations)
) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -849,44 +994,56 @@ export abstract class BaseLLM implements ILLM {
)) {
if (chunk.role === "assistant") {
completion += chunk.content;
yield chunk;
} else if (chunk.role === "thinking") {
thinking += chunk.content;
}
if (chunk.role === "thinking") {
thinking += chunk.content;
yield chunk;
}
interaction?.logItem({
kind: "message",
message: chunk,
});
yield chunk;
}
}
}
} catch (error) {
console.log(error);
throw error;
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
if (thinking) {
await this.writeLog(`Thinking:\n${thinking}\n\n`);
}
/*
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
and you must include the complete unmodified block back to the API. This is critical
for maintaining the model's reasoning flow and conversation integrity.
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
requests when not using tools, so it's the simplest option to always add to history.
*/
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
status = this._logEnd(
completionOptions.model,
prompt,
completion,
thinking,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
thinking,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
/*
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
and you must include the complete unmodified block back to the API. This is critical
for maintaining the model's reasoning flow and conversation integrity.
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
requests when not using tools, so it's the simplest option to always add to history.
*/
return {
modelTitle: this.title ?? completionOptions.model,

View file

@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM {
...this.requestOptions?.headers,
};
const resp = await this.fetch(new URL("completion", this.apiBase), {
const resp = await this.fetch(new URL("completions", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({

View file

@ -2,6 +2,7 @@ import {
BaseCompletionOptions,
IdeSettings,
ILLM,
ILLMLogger,
LLMOptions,
ModelDescription,
} from "../..";
@ -115,7 +116,7 @@ export async function llmFromDescription(
readFile: (filepath: string) => Promise<string>,
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
completionOptions?: BaseCompletionOptions,
systemMessage?: string,
): Promise<BaseLLM | undefined> {
@ -145,7 +146,7 @@ export async function llmFromDescription(
cls.defaultOptions?.completionOptions?.maxTokens,
},
systemMessage,
writeLog,
logger: llmLogger,
uniqueId,
};

View file

@ -0,0 +1,315 @@
import { Buffer } from "buffer";
import { Writable } from "stream";
import { LLMLogFormatter } from "./logFormatter";
import { LLMLogger } from "./logger";
class MemoryWritable extends Writable {
data: Buffer[] = [];
constructor() {
super();
this.data = [];
}
_write(
chunk: Buffer,
encoding: BufferEncoding,
callback: (error?: Error | null) => void,
): void {
this.data.push(chunk);
callback();
}
getText() {
const decoder = new TextDecoder();
return decoder.decode(Buffer.concat(this.data as any));
}
}
describe("LLMLogFormatter", () => {
it("should format log items correctly", () => {
const logger = new LLMLogger();
const output = new MemoryWritable();
const formatter = new LLMLogFormatter(logger, output);
logger._logItem({
interactionId: "1",
timestamp: 1698765432100,
kind: "startChat",
options: {
model: "granite3.2-dense:8b",
},
messages: [
{
role: "system",
content: "You are a helpful assistant",
},
],
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433100,
kind: "message",
message: {
role: "assistant",
content: "Hello, ",
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433200,
kind: "message",
message: {
role: "assistant",
content: "world!",
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433300,
kind: "message",
message: {
role: "assistant",
content: "\nHow can I help you?",
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765434100,
kind: "success",
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
});
expect(output.getText()).toBe(
[
" 15:17:12.1 [Chat]",
" Options: {",
' "model": "granite3.2-dense:8b"',
" }",
" Role: system",
" | You are a helpful assistant",
" +1.0 Role: assistant",
" | Hello, world!",
" +1.2 | How can I help you?",
" +2.0 Success",
" Prompt Tokens: 10",
" Generated Tokens: 20",
"",
].join("\n"),
);
});
it("should format completion interactions correctly", () => {
const logger = new LLMLogger();
const output = new MemoryWritable();
const formatter = new LLMLogFormatter(logger, output);
logger._logItem({
interactionId: "1",
timestamp: 1698765432100,
kind: "startComplete",
options: {
model: "granite3.2-dense:8b",
},
prompt: "A horse is a horse",
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433100,
kind: "chunk",
chunk: ", of course, of course",
});
expect(output.getText()).toBe(
[
" 15:17:12.1 [Complete]",
" Options: {",
' "model": "granite3.2-dense:8b"',
" }",
" Prompt:",
" | A horse is a horse",
" +1.0 Result:",
" | , of course, of course",
].join("\n"),
);
});
it("should format FIM interactions correctly", () => {
const logger = new LLMLogger();
const output = new MemoryWritable();
const formatter = new LLMLogFormatter(logger, output);
logger._logItem({
interactionId: "1",
timestamp: 1698765432100,
kind: "startFim",
options: {
model: "granite3.2-dense:8b",
},
prefix: "A\nB",
suffix: "D\nE",
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433100,
kind: "chunk",
chunk: "C",
});
expect(output.getText()).toBe(
[
" 15:17:12.1 [Fim]",
" Options: {",
' "model": "granite3.2-dense:8b"',
" }",
" Prefix:",
" | A",
" | B",
" Suffix:",
" | D",
" | E",
" +1.0 Result:",
" | C",
].join("\n"),
);
});
it("should interleave log items correctly", () => {
const logger = new LLMLogger();
const output = new MemoryWritable();
const formatter = new LLMLogFormatter(logger, output);
logger._logItem({
interactionId: "1",
timestamp: 1698765433100,
kind: "message",
message: {
role: "assistant",
content: "Hello, ",
},
});
logger._logItem({
interactionId: "2",
timestamp: 1698765433200,
kind: "message",
message: {
role: "assistant",
content: "Hello, ",
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433300,
kind: "message",
message: {
role: "assistant",
content: "World!",
},
});
logger._logItem({
interactionId: "2",
timestamp: 1698765433400,
kind: "message",
message: {
role: "assistant",
content: "World!",
},
});
// Check if we end interaction 2 and start another interaction,
// it gets a different prefix marker.
logger._logItem({
interactionId: "2",
timestamp: 1698765434000,
kind: "success",
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
});
logger._logItem({
interactionId: "3",
timestamp: 1698765434100,
kind: "message",
message: {
role: "assistant",
content: "Hello, World!",
},
});
expect(output.getText()).toBe(
[
" 15:17:13.1 Role: assistant",
" | Hello, ",
"|15:17:13.2 Role: assistant",
"| | Hello, ",
" +0.2 | World!",
"| +0.2 | World!",
"| +0.8 Success",
"| Prompt Tokens: 10",
"| Generated Tokens: 20",
"&15:17:14.1 Role: assistant",
"& | Hello, World!",
].join("\n"),
);
});
it("should wrap long lines", () => {
const logger = new LLMLogger();
const output = new MemoryWritable();
const formatter = new LLMLogFormatter(logger, output, 40);
// Test a single message long enough to wrap; the input is
// "<xx...xx>", not "xxxx" to make sure we are writing the correct
// substrings.
logger._logItem({
interactionId: "1",
timestamp: 1698765433100,
kind: "message",
message: {
role: "assistant",
content: "<" + "x".repeat(58) + ">",
},
});
// Test when a first message doesn't wrap, but another message
// that continues the same line causes a wrap
logger._logItem({
interactionId: "1",
timestamp: 1698765433200,
kind: "message",
message: {
role: "assistant",
content: "\n<" + "y".repeat(29),
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433300,
kind: "message",
message: {
role: "assistant",
content: "y".repeat(29) + ">",
},
});
logger._logItem({
interactionId: "1",
timestamp: 1698765433400,
kind: "message",
message: {
role: "assistant",
content: "\n" + "Artichokes and Beans ".repeat(3),
},
});
expect(output.getText()).toBe(
[
" 15:17:13.1 Role: assistant",
" | <" + "x".repeat(39),
" . " + "x".repeat(19) + ">",
" +0.1 | <" + "y".repeat(39),
" +0.2 . " + "y".repeat(19) + ">",
" +0.3 | Artichokes and Beans Artichokes and",
" . Beans Artichokes and Beans ",
].join("\n"),
);
});
});

426
core/llm/logFormatter.ts Normal file
View file

@ -0,0 +1,426 @@
import { Writable } from "stream";
import {
AssistantChatMessage,
ChatMessage,
LLMInteractionCancel,
LLMInteractionError,
LLMInteractionItem,
LLMInteractionStartChat,
LLMInteractionStartComplete,
LLMInteractionStartFim,
LLMInteractionSuccess,
ThinkingChatMessage,
ToolCallDelta,
UserChatMessage,
} from "..";
import { LLMLogger } from "./logger";
// Markers for different overlapping interactions.
const LOG_PREFIXES = [" ", "|", "&", "%", "#"];
// Wrap wide to avoid messing up code
const DEFAULT_WRAP_WIDTH = 100;
interface InteractionData {
prefix: string;
startItem: LLMInteractionItem;
lastItem: LLMInteractionItem | null;
}
function formatTimestamp(timestamp: number) {
const date = new Date(timestamp);
const hours = date.getUTCHours().toString().padStart(2, "0");
const minutes = date.getUTCMinutes().toString().padStart(2, "0");
const seconds = date.getUTCSeconds();
const milliseconds = date.getUTCMilliseconds();
// Format seconds with one decimal place
const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`;
return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`;
}
/**
* A class that formats LLM log output as a human-readable stream.
* The general appearance of the output is something like:
*
* 01:23:45.6 [Chat]
* Options: {
* "maxTokens": 1000,
* }
* Role: system
* | You are a helpful assistant.
* Role: user
* | Who are you?
* +0.2 Role: assistant
* | How can I help you today?
* +0.3 | I can tell you about the weather or the stock mark
* +0.4 . et. [THIS LINE IS WRAPPED]
* |01:23:46.1 [Complete]
* | Options: {
* | "maxTokens": 1000,
* | }
* | Prefix:
* | | COMPLETE THIS
* +0.6 Success
* PromptTokens: 50
* GeneratedTokens: 30
* | +0.2 Result:
* | | COMPLETION
*
* The lines with | are a second interaction that starts while the
* first one is still in progress; every interaction starts with
* an absolute timestamp, and relative timestamps are included for
* separately received results in the same interaction.
*/
export class LLMLogFormatter {
// Current active interactions
private interactions: Record<string, InteractionData> = {};
private lastItem: LLMInteractionItem | null = null;
// Item that started the current line; we use this to determine
// if the next line needs a timestamp.
private lastLineStartItem: LLMInteractionItem | null = null;
private openLine: boolean = false;
private openLineChars: number = 0;
private lastFreedPrefix: string | null = null;
/**
* Creates a new LLMLogWriter.
* @param logger - The LLMLogger instance to listen to for log items
* @param output - Stream to write formatted output to
* @param wrapWidth - Maximum width of a line before wrapping
*/
constructor(
private logger: LLMLogger,
private output: Writable,
private wrapWidth: number = DEFAULT_WRAP_WIDTH,
) {
this.logger.onLogItem((item) => {
this.logItem(item);
});
}
private getInteractionData(item: LLMInteractionItem) {
let interaction = this.interactions[item.interactionId];
if (interaction !== undefined) {
return interaction;
}
let usedPrefixes = Object.values(this.interactions).map(
(interaction) => interaction.prefix,
);
// Select a prefix that is not currently in use, and is
// also not the last retired prefix - but with the
// exception that we can reuse the empty prefix " "
// immediately - this isn't confusing.
let i = 0;
let prefix;
while (true) {
const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`;
if (
!usedPrefixes.includes(candidate) &&
(candidate === " " || candidate !== this.lastFreedPrefix)
) {
prefix = candidate;
break;
}
i++;
}
this.interactions[item.interactionId] = {
prefix,
startItem: item,
lastItem: null,
};
return this.interactions[item.interactionId];
}
private formatTimestamp(
interaction: InteractionData,
item: LLMInteractionItem,
) {
if (item !== this.lastLineStartItem) {
if (item === interaction.startItem) {
return formatTimestamp(item.timestamp);
} else {
const delta = (item.timestamp - interaction.startItem.timestamp) / 1000;
return ("+" + delta.toFixed(1)).padStart(10, " ");
}
} else {
return " ";
}
}
// the implementation behind logLines and logMessageText
private logFragment(
item: LLMInteractionItem,
fragment: string,
startAt: number,
marker: string = "",
joinBefore: boolean = false,
joinAfter: boolean = false,
wrap: boolean = false,
) {
const interaction = this.getInteractionData(item);
if (
this.openLine &&
(!joinBefore || item.interactionId !== this.lastItem?.interactionId)
) {
this.openLine = false;
this.openLineChars = 0;
this.output.write("\n");
}
let continueAt = null;
if (
wrap &&
fragment.length - startAt > this.wrapWidth - this.openLineChars
) {
continueAt = startAt + this.wrapWidth - this.openLineChars;
// Look for a better line-breaking point at whitespace
const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far
for (let i = continueAt; i > searchBackwardLimit; i--) {
if (/\s/.test(fragment.charAt(i))) {
continueAt = i + 1; // Break after the whitespace
break;
}
}
// When there's whitespace immediately after the wrap width,
// the above will result in breaking *after* that, so we exceed
// the wrap width. The trimEnd() avoids that.
fragment = fragment.substring(startAt, continueAt).trimEnd();
joinAfter = false;
} else if (startAt > 0) {
fragment = fragment.substring(startAt);
}
if (!this.openLine || !this.openLine) {
let timestamp = this.formatTimestamp(interaction, item);
this.output.write(`${interaction.prefix}${timestamp} ${marker}`);
this.lastLineStartItem = item;
}
this.output.write(fragment);
this.openLine = joinAfter;
this.lastItem = item;
if (!this.openLine) {
this.output.write("\n");
this.openLineChars = 0;
} else {
this.openLineChars += fragment.length;
}
return continueAt;
}
// Use for everything but text content; a newline is
// implicitly added at the end of content
private logLines(
item: LLMInteractionItem,
content: string,
marker: string = "",
) {
for (const line of content.split("\n")) {
this.logFragment(item, line, 0, marker);
}
}
// This logs text context - as compared to logLines:
// - No newline is appended to the end of content
// - consecutive calls to logMessageText for the same interaction
// will join onto a single line
// - It will wrap text at the wrap width
private logMessageText(item: LLMInteractionItem, content: string) {
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
let startAt: number | null = 0;
let marker = "| ";
while (startAt !== null) {
// When wrapping, the next start position is turned;
// null means we've written everything
startAt = this.logFragment(
item,
lines[i],
startAt,
marker,
true,
i === lines.length - 1,
true,
);
marker = ". ";
}
}
}
private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) {
for (const toolCall of toolsCalls) {
this.logLines(
item,
`Tool call: ${JSON.stringify(toolCall, undefined, 2)}`,
);
}
}
private logMessageContent(
item: LLMInteractionItem,
message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage,
) {
if (typeof message.content === "string") {
this.logMessageText(item, message.content);
} else {
for (const part of message.content) {
if (part.type === "text") {
this.logMessageText(item, part.text);
} else {
this.logLines(item, `Image: ${part.imageUrl.url}`);
}
}
}
}
private logMessage(
item: LLMInteractionItem,
message: ChatMessage,
forceRole: boolean = false,
) {
let showRole = true;
if (
!forceRole &&
(message.role === "assistant" || message.role === "thinking")
) {
const interaction = this.getInteractionData(item);
const lastMessage =
interaction.lastItem?.kind === "message"
? interaction.lastItem.message
: null;
if (message.role === lastMessage?.role) {
showRole = false;
}
}
if (showRole) {
this.logLines(item, "Role: " + message.role);
}
switch (message.role) {
case "assistant":
if (message.toolCalls) {
this.logToolcalls(item, message.toolCalls);
}
this.logMessageContent(item, message);
break;
case "thinking":
if (message.toolCalls) {
this.logToolcalls(item, message.toolCalls);
}
this.logMessageContent(item, message);
if (message.redactedThinking) {
this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`);
}
if (message.signature) {
this.logLines(item, `Signature: ${message.signature}`);
}
break;
case "user":
this.logMessageContent(item, message);
break;
case "system":
this.logMessageText(item, message.content);
break;
case "tool":
this.logLines(item, `Tool Call ID: ${message.toolCallId}`);
this.logMessageText(item, message.content);
break;
}
}
private logTokens(
item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel,
) {
this.logLines(item, `Prompt Tokens: ${item.promptTokens}`);
this.logLines(item, `Generated Tokens: ${item.generatedTokens}`);
if (item.thinkingTokens > 0) {
this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`);
}
}
private logOptions(
item:
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim,
) {
this.logLines(
item,
"Options: " + JSON.stringify(item.options, undefined, 2),
);
}
private logItem(item: LLMInteractionItem) {
const interaction = this.getInteractionData(item);
switch (item.kind) {
case "startChat":
this.logLines(item, "[Chat]");
this.logOptions(item);
let lastMessage = null;
for (let message of item.messages) {
this.logMessage(item, message, true);
}
break;
case "startComplete":
this.logLines(item, "[Complete]");
this.logOptions(item);
this.logLines(item, "Prompt:");
this.logLines(item, item.prompt, "| ");
break;
case "startFim":
this.logLines(item, "[Fim]");
this.logOptions(item);
this.logLines(item, "Prefix:");
this.logLines(item, item.prefix, "| ");
this.logLines(item, "Suffix:");
this.logLines(item, item.suffix, "| ");
break;
case "chunk":
if (interaction.lastItem?.kind !== "chunk") {
this.logLines(item, "Result:");
}
this.logMessageText(item, item.chunk);
break;
case "message":
this.logMessage(item, item.message);
break;
case "cancel":
this.logLines(item, "Cancelled");
this.logTokens(item);
break;
case "error":
this.logLines(item, "Error");
this.logTokens(item);
break;
case "success":
this.logLines(item, "Success");
this.logTokens(item);
break;
}
if (
item.kind === "cancel" ||
item.kind === "error" ||
item.kind === "success"
) {
if (interaction.prefix !== " ") {
this.lastFreedPrefix = interaction.prefix;
}
delete this.interactions[item.interactionId];
} else {
interaction.lastItem = item;
}
}
}

43
core/llm/logger.ts Normal file
View file

@ -0,0 +1,43 @@
import {
ILLMLogger,
ILLMInteractionLog,
LLMInteractionItem,
LLMInteractionItemDetails,
} from "..";
type LLMLogItemFunction = (item: LLMInteractionItem) => void;
export class LLMLogger implements ILLMLogger {
private nextId = 0;
public createInteractionLog(): LLMInteractionLog {
return new LLMInteractionLog(this, (this.nextId++).toString());
}
private logItemListeners: LLMLogItemFunction[] = [];
onLogItem(listener: LLMLogItemFunction) {
this.logItemListeners.push(listener);
}
public _logItem(item: LLMInteractionItem) {
for (const listener of this.logItemListeners) {
listener(item);
}
}
}
export class LLMInteractionLog implements ILLMInteractionLog {
constructor(
private logger: LLMLogger,
public interactionId: string,
) {}
logItem(item: LLMInteractionItemDetails) {
this.logger._logItem({
...item,
interactionId: this.interactionId,
timestamp: Date.now(),
});
}
}

View file

@ -2,6 +2,7 @@ import { ContinueSDK, SlashCommand } from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { getLastNPathParts } from "../../util/uri";
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
import { renderPromptFileV2 } from "../v2/renderPromptFile";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
@ -67,7 +68,17 @@ export function slashCommandFromPromptFileV1(
context.llm.systemMessage = systemMessage;
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPromptV1(prompt, context, userInput);
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
config: context.config,
fullInput: userInput,
embeddingsProvider: context.config.modelsByRole.embed[0],
reranker: context.config.modelsByRole.rerank[0],
llm: context.llm,
ide: context.ide,
selectedCode: context.selectedCode,
fetch: context.fetch,
});
const messages = replaceSlashCommandWithPromptInChatHistory(
context.history,
name,

View file

@ -66,7 +66,7 @@ export async function renderPromptFileV2(
rawContent: string,
extras: ContextProviderExtras,
): Promise<[ContextItem[], string]> {
const [preamble, body] = getPreambleAndBody(rawContent);
const [_, body] = getPreambleAndBody(rawContent);
const contextItemsPromises: Promise<ContextItem[]>[] = [];
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
@ -75,6 +75,10 @@ export async function renderPromptFileV2(
});
const contextItems = (await Promise.all(contextItemsPromises)).flat();
const renderedPrompt =
contextItems.map((item) => item.content).join("\n\n") +
"\n\n" +
renderedBody;
return [contextItems, renderedBody];
return [contextItems, renderedPrompt];
}

View file

@ -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,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
"controlPlane/listOrganizations": [undefined, OrganizationDescription[]];
isItemTooBig: [
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
boolean,
];
};

View file

@ -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;

View file

@ -107,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = {
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,
];
didChangeIdeSettings: [{ settings: IdeSettings }, void];
};

View file

@ -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,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"controlPlane/listOrganizations",
"isItemTooBig",
];
// Message types to pass through from core to webview
@ -75,10 +74,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"didCloseFiles",
"didSelectOrganization",
];

View file

@ -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,
];

View file

@ -1,6 +1,7 @@
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import Mock from "../llm/llms/Mock";
import { LLMLogger } from "../llm/logger";
import FileSystemIde from "../util/filesystem";
import { TEST_DIR } from "./testDir";
@ -17,7 +18,7 @@ export const testControlPlaneClient = new ControlPlaneClient(
export const testConfigHandler = new ConfigHandler(
testIde,
ideSettingsPromise,
async (text) => {},
new LLMLogger(),
Promise.resolve(undefined),
);

View file

@ -530,10 +530,6 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### Prompt Files
See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers.
### `@Issue`
Reference the conversation in a GitHub issue.
@ -883,7 +879,6 @@ You can override this query by setting the `issueQuery` parameter.
You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
### `@Discord`
Reference the messages in a Discord channel.

View file

@ -1,69 +0,0 @@
---
title: Prompt files
---
Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub.
:::info
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
:::
## Quick start
Below is a quick example of setting up a prompt file:
1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File").
2. Add a file called `rails.prompt` to this folder.
3. Write the following contents to `rails.prompt` and save.
```.prompt
name: Rails Project
description: Information about this project
---
Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb
```
Now to use this prompt, you can highlight code and use <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> to select it in the Continue sidebar.
Then, type <kbd>/</kbd> and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file.
## Format
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
:::info
The current state of this format is experimental and subject to change
:::
### Preamble
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
- `name` - The display title
- `description` - The description you will see in the dropdown
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
### Context
Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
- `@terminal` - The contents of the terminal
- `@currentFile` - The currently active file
- `@open` - All open files
- `@os` - Information about the operating system
- `@problems` - Problems reported by the language server in the active file
- `@repo-map` - A map of files in the repository
- `@tree` - A tree view of the repository structure
Or you can directly type URLs and file paths:
- `@https://github.com/continuedev/continue` - The contents of a URL
- `@src/index.ts` - The contents of a file (VS Code only)
All references will be attached as context items, rather than injected directly inline.
## Feedback
If you have ideas about how to improve the `.prompt` file format, please reach out on [Discord](https://discord.gg/NWtdYexhMs).

View file

@ -0,0 +1,97 @@
---
title: Prompts
---
Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
:::info
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
:::
## Examples
Below are some examples to get you started.
### Security review
```text title="Security best practices review"
@open - Review these files for the following security best practices:
- Does the architecture follow security-by-design principles?
- Are there potential security vulnerabilities in the system design?
- Is sensitive data handled appropriately throughout the lifecycle?
```
### Reference best practice guides
```text title="Redux best practices review"
@https://redux.js.org/style-guide/
@currentFile
Review this code for adherence to Redux best practices.
```
### Pull in commonly used files for tasks
```text title="Generate a new TypeORM entity"
@src/db/dataSource.ts @src/db/entity/SampleEntity.ts
Use these files to generate a new TypeORM entity based on the following requirements:
```
## Including Context Providers in your prompts
Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
- `@terminal` - The contents of the terminal
- `@currentFile` - The currently active file
- `@open` - All open files
- `@os` - Information about the operating system
- `@problems` - Problems reported by the language server in the active file
- `@repo-map` - A map of files in the repository
- `@tree` - A tree view of the repository structure
Or you can directly type URLs and file paths:
- `@https://github.com/continuedev/continue` - The contents of a URL
- `@src/index.ts` - The contents of a file (VS Code only)
All references will be attached as context items, rather than injected directly inline.
## Local `.prompt` files
In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub.
### Quick Start
Below is a quick example of setting up a prompt file:
1. Create a folder called `.continue/prompts` at the top level of your workspace
2. Add a file called `test.prompt` to this folder.
3. Write the following contents to `test.prompt` and save.
```.prompt
name: Current file prompt
description: A test prompt using the current file context provider
---
@currentFile
```
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and add type out some additional text such as "Review the code for any issues".
### Format
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
:::info
The current state of this format is experimental and subject to change
:::
### Preamble
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
- `name` - The display title
- `description` - The description you will see in the dropdown
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.

View file

@ -26,7 +26,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/
It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
Learn more about prompt files [here](./prompt-files.md)
Learn more about prompt files [here](./prompts.md)
### MCP Server prompts

View file

@ -14,7 +14,7 @@ To make common use cases even more accessible, we provide a handful of other way
## Quick actions
Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompt-files.md) to perform custom actions.
Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions.
![quick-actions](/img/quick-actions.png)

View file

@ -50,7 +50,7 @@ Then, create a server that responds to requests as are made from [HttpContextPro
The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body.
:::info
The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompt files](../deep-dives/prompt-files.md) where possible.
The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible.
:::
## Using CustomContextProvider

View file

@ -3,7 +3,7 @@ title: Build your own slash command
---
:::info
Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality.
Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompts.md) to achieve similar functionality.
:::
There are two ways to add custom slash commands:

View file

@ -45,13 +45,15 @@ import TabItem from "@theme/TabItem";
"apiBase": "https://codestral.mistral.ai/v1"
}
],
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "<YOUR_CODESTRAL_API_KEY>",
"apiBase": "https://codestral.mistral.ai/v1"
}
"tabAutocompleteModel": [
{
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "<YOUR_CODESTRAL_API_KEY>",
"apiBase": "https://codestral.mistral.ai/v1"
}
]
}
```
</TabItem>

View file

@ -41,12 +41,7 @@ Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and vi
Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files:
1. Currently, prompt blocks cannot use context providers
2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and
The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts).
Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts).
## Data

View file

@ -142,6 +142,7 @@ The `models` section defines the language models used in your configuration. Mod
- `name` (**required**): A unique name to identify the model within your configuration.
- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`).
- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`).
- `apiBase`: Can be used to override the default API base that is specified per model
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:
@ -474,7 +475,8 @@ models:
- name: qwen2.5-coder-7b
<<: *model_defaults
model: qwen2.5-coder-7b
useLegacyCompletionsEndpoint: false
env:
useLegacyCompletionsEndpoint: false
roles:
- autocomplete
```

View file

@ -286,7 +286,7 @@ const config = {
],
},
{
to: "/customize/deep-dives/prompt-files",
to: "/customize/deep-dives/prompts",
from: ["/walkthroughs/prompt-files", "/features/prompt-files"],
},
// TODO - actions redirects
@ -489,6 +489,10 @@ const config = {
to: "/getting-started/install",
from: "/getting-started",
},
{
to: "/customize/deep-dives/prompts",
from: "/customize/deep-dives/prompt-files",
},
],
},
],

View file

@ -13,7 +13,7 @@ Continue 有一个大的内置斜杠命令库,但是当你首次安装时,
有两种方法添加定制斜杠命令:
1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。
1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompts.md) 查看完整参考。
2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数
### 使用 `config.ts` 定制斜杠命令

View file

@ -24,7 +24,7 @@ Actions 是常见用例的快捷方式。例如,你可能想要审查代码,
通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。
完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。
完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt.md) 。
:::tip[Prompt 库]
为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求!

View file

@ -8022,9 +8022,10 @@
}
},
"node_modules/estree-util-value-to-estree": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.2.1.tgz",
"integrity": "sha512-Vt2UOjyPbNQQgT5eJh+K5aATti0OjCIAGc9SgMdOFYbohuifsWclR74l0iZTJwePMgWYdX1hlVS+dedH9XV8kw==",
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.3.3.tgz",
"integrity": "sha512-Db+m1WSD4+mUO7UgMeKkAwdbfNWwIxLt48XF2oFU9emPfXkIu+k5/nlOj313v7wqtAPo0f9REhUvznFrPkG8CQ==",
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
},

View file

@ -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)
}
})

View file

@ -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,7 @@ class MessageTypes {
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"controlPlane/listOrganizations"
"isItemTooBig",
)
}
}

View file

@ -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)
}

View file

@ -16,8 +16,12 @@ export class GUIActions {
await GUIActions.toggleGui();
await TestUtils.waitForSuccess(async () => {
await new Workbench().executeCommand("View: Move View");
await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(4);
await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(14);
await (
await InputBox.create(DEFAULT_TIMEOUT.MD)
).selectQuickPick("Continue");
await (
await InputBox.create(DEFAULT_TIMEOUT.MD)
).selectQuickPick("New Secondary Side Bar Entry");
});
// first call focuses the input

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.21",
"version": "1.1.22",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -127,6 +127,11 @@
"default": false,
"markdownDescription": "Pause Continue's codebase index on start."
},
"continue.enableConsole": {
"type": "boolean",
"default": false,
"markdownDescription": "Enable a console to log and explore model inputs and outputs. It can be found in the bottom panel."
},
"continue.remoteConfigServerUrl": {
"type": "string",
"default": null,
@ -252,6 +257,13 @@
"title": "View History",
"group": "Continue"
},
{
"command": "continue.clearConsole",
"category": "Continue",
"title": "Clear Console",
"icon": "$(clear-all)",
"group": "Continue"
},
{
"command": "continue.navigateTo",
"category": "Continue",
@ -505,6 +517,11 @@
"command": "continue.openConfigPage",
"group": "navigation@4",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.clearConsole",
"group": "navigation@1",
"when": "view == continue.continueConsoleView"
}
],
"editor/title": [
@ -533,6 +550,13 @@
"title": "Continue",
"icon": "media/sidebar-icon.png"
}
],
"panel": [
{
"id": "continueConsole",
"title": "Continue Console",
"icon": "$(window)"
}
]
},
"views": {
@ -544,6 +568,16 @@
"icon": "media/sidebar-icon.png",
"visibility": "visible"
}
],
"continueConsole": [
{
"type": "webview",
"id": "continue.continueConsoleView",
"name": "Continue Console",
"icon": "$(window)",
"visibility": "visible",
"when": "config.continue.enableConsole"
}
]
},
"jsonValidation": [

View file

@ -0,0 +1,221 @@
import { LLMInteractionItem } from "core";
import { EXTENSION_NAME } from "core/control-plane/env";
import { LLMLogger } from "core/llm/logger";
import * as vscode from "vscode";
import { getExtensionUri, getNonce } from "./util/vscode";
interface FromConsoleView {
type: "start" | "stop";
uuid: string;
}
// Maximum interactions we retain; when we exceed this, we drop the
// oldest and also send a message to the view to do the same.
const MAX_INTERACTIONS = 50;
export class ContinueConsoleWebviewViewProvider
implements vscode.WebviewViewProvider
{
public static readonly viewType = "continue.continueConsoleView";
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
): void | Thenable<void> {
this._webviewView = webviewView;
this._webview = webviewView.webview;
this._webviewView.onDidDispose(() => {
this._webviewView = undefined;
this._webview = undefined;
});
webviewView.webview.html = this.getSidebarContent(
this.extensionContext,
webviewView,
);
this._webview.onDidReceiveMessage((message: FromConsoleView) => {
if (message.type === "start") {
this._currentUuid = message.uuid;
this._webview?.postMessage({
type: "init",
uuid: this._currentUuid,
items: this.getAllItems(),
});
}
});
this._webviewView.onDidDispose(() => {
this._webview = undefined;
this._webviewView = undefined;
this._currentUuid = undefined;
});
}
private _webview?: vscode.Webview;
private _webviewView?: vscode.WebviewView;
private _currentUuid?: string;
private _currentInteractions = new Map<string, LLMInteractionItem[]>();
private _completedInteractions: LLMInteractionItem[][] = [];
private _saveLog;
constructor(
private readonly windowId: string,
private readonly extensionContext: vscode.ExtensionContext,
private readonly llmLogger: LLMLogger,
) {
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
this._saveLog = config.get<boolean>("enableConsole");
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(`${EXTENSION_NAME}.enableConsole`)) {
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
this._saveLog = config.get<boolean>("enableConsole");
if (!this._saveLog) {
this.clearLog();
}
}
});
llmLogger.onLogItem((item) => this.addItem(item));
}
private addItem(item: LLMInteractionItem) {
if (!this._saveLog) {
return;
}
let iteractionItems = this._currentInteractions.get(item.interactionId);
if (iteractionItems === undefined) {
iteractionItems = [];
this._currentInteractions.set(item.interactionId, iteractionItems);
}
iteractionItems.push(item);
switch (item.kind) {
case "success":
case "cancel":
case "error":
this._completedInteractions.push(iteractionItems);
this._currentInteractions.delete(item.interactionId);
break;
default:
break;
}
if (this._currentUuid) {
this._webview?.postMessage({
type: "item",
uuid: this._currentUuid,
item,
});
}
while (
this._completedInteractions.length > 0 &&
this._completedInteractions.length + this._currentInteractions.size >
MAX_INTERACTIONS
) {
let toRemove = this._completedInteractions.shift();
this._webview?.postMessage({
type: "remove",
uuid: this._currentUuid,
interactionId: toRemove![0].interactionId,
});
}
}
private getAllItems() {
let items = this._completedInteractions.flat();
for (const interactionItems of this._currentInteractions.values()) {
items.push(...interactionItems);
}
return items;
}
clearLog() {
this._completedInteractions = [];
this._currentInteractions = new Map();
if (this._currentUuid) {
this._webview?.postMessage({
type: "clear",
uuid: this._currentUuid,
});
}
}
private getSidebarContent(
context: vscode.ExtensionContext | undefined,
panel: vscode.WebviewPanel | vscode.WebviewView,
page: string | undefined = undefined,
): string {
const extensionUri = getExtensionUri();
let scriptUri: string;
let styleMainUri: string;
const inDevelopmentMode =
context?.extensionMode === vscode.ExtensionMode.Development;
if (!inDevelopmentMode) {
scriptUri = panel.webview
.asWebviewUri(
vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.js"),
)
.toString();
styleMainUri = panel.webview
.asWebviewUri(
vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.css"),
)
.toString();
} else {
scriptUri = "http://localhost:5173/src/console.tsx";
styleMainUri = "http://localhost:5173/src/indexConsole.css";
}
panel.webview.options = {
enableScripts: true,
localResourceRoots: [
vscode.Uri.joinPath(extensionUri, "gui"),
vscode.Uri.joinPath(extensionUri, "assets"),
],
enableCommandUris: true,
portMapping: [
{
webviewPort: 65433,
extensionHostPort: 65433,
},
],
};
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>const vscode = acquireVsCodeApi();</script>
<link href="${styleMainUri}" rel="stylesheet">
<title>Continue</title>
</head>
<body>
<div id="root"></div>
${
inDevelopmentMode
? `<script type="module">
import RefreshRuntime from "http://localhost:5173/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>`
: ""
}
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
}

View file

@ -27,6 +27,7 @@ import {
setupStatusBar,
StatusBarStatus,
} from "./autocomplete/statusBar";
import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
import { VerticalDiffManager } from "./diff/vertical/manager";
@ -318,6 +319,7 @@ const getCommandsMap: (
ide: VsCodeIde,
extensionContext: vscode.ExtensionContext,
sidebar: ContinueGUIWebviewViewProvider,
consoleView: ContinueConsoleWebviewViewProvider,
configHandler: ConfigHandler,
verticalDiffManager: VerticalDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
@ -329,6 +331,7 @@ const getCommandsMap: (
ide,
extensionContext,
sidebar,
consoleView,
configHandler,
verticalDiffManager,
continueServerClientPromise,
@ -672,6 +675,9 @@ const getCommandsMap: (
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
);
},
"continue.clearConsole": async () => {
consoleView.clearLog();
},
"continue.viewLogs": async () => {
captureCommandTelemetry("viewLogs");
vscode.commands.executeCommand("workbench.action.toggleDevTools");
@ -1088,6 +1094,7 @@ export function registerAllCommands(
ide: VsCodeIde,
extensionContext: vscode.ExtensionContext,
sidebar: ContinueGUIWebviewViewProvider,
consoleView: ContinueConsoleWebviewViewProvider,
configHandler: ConfigHandler,
verticalDiffManager: VerticalDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
@ -1103,6 +1110,7 @@ export function registerAllCommands(
ide,
extensionContext,
sidebar,
consoleView,
configHandler,
verticalDiffManager,
continueServerClientPromise,

View file

@ -21,6 +21,7 @@ import {
StatusBarStatus,
} from "../autocomplete/statusBar";
import { registerAllCommands } from "../commands";
import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
@ -48,6 +49,7 @@ export class VsCodeExtension {
private configHandler: ConfigHandler;
private extensionContext: vscode.ExtensionContext;
private ide: VsCodeIde;
private consoleView: ContinueConsoleWebviewViewProvider;
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
private editDecorationManager: EditDecorationManager;
@ -106,10 +108,6 @@ export class VsCodeExtension {
);
resolveWebviewProtocol(this.sidebar.webviewProtocol);
// Config Handler with output channel
const outputChannel = vscode.window.createOutputChannel(
"Continue - LLM Prompt/Completion",
);
const inProcessMessenger = new InProcessMessenger<
ToCoreProtocol,
FromCoreProtocol
@ -125,19 +123,12 @@ export class VsCodeExtension {
this.editDecorationManager,
);
this.core = new Core(inProcessMessenger, this.ide, async (log: string) => {
outputChannel.appendLine(
"==========================================================================",
);
outputChannel.appendLine(
"==========================================================================",
);
outputChannel.append(log);
});
this.core = new Core(inProcessMessenger, this.ide);
this.configHandler = this.core.configHandler;
resolveConfigHandler?.(this.configHandler);
this.configHandler.loadConfig();
this.verticalDiffManager = new VerticalDiffManager(
this.configHandler,
this.sidebar.webviewProtocol,
@ -202,16 +193,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 +206,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,
});
@ -253,12 +235,27 @@ export class VsCodeExtension {
this.fileSearch,
);
// LLM Log view
this.consoleView = new ContinueConsoleWebviewViewProvider(
this.windowId,
this.extensionContext,
this.core.llmLogger,
);
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
"continue.continueConsoleView",
this.consoleView,
),
);
// Commands
registerAllCommands(
context,
this.ide,
context,
this.sidebar,
this.consoleView,
this.configHandler,
this.verticalDiffManager,
this.core.continueServerClientPromise,
@ -334,14 +331,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 +404,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);
}
});
}

13
gui/indexConsole.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/play_button.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Continue</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/console.tsx"></script>
</body>
</html>

54
gui/package-lock.json generated
View file

@ -25,7 +25,6 @@
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/uuid": "^10.0.0",
"@types/vscode-webview": "^1.57.1",
"clsx": "^2.1.1",
"core": "file:../core",
"dompurify": "^3.0.6",
@ -63,8 +62,7 @@
"tailwind-merge": "^3.0.2",
"tippy.js": "^6.3.7",
"unist-util-visit": "^5.0.0",
"uuid": "^9.0.1",
"vscode-webview": "^1.0.1-beta.1"
"uuid": "^9.0.1"
},
"devDependencies": {
"@swc/cli": "^0.3.14",
@ -3237,11 +3235,6 @@
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="
},
"node_modules/@types/vscode-webview": {
"version": "1.57.5",
"resolved": "https://registry.npmjs.org/@types/vscode-webview/-/vscode-webview-1.57.5.tgz",
"integrity": "sha512-iBAUYNYkz+uk1kdsq05fEcoh8gJmwT3lqqFPN7MGyjQ3HVloViMdo7ZJ8DFIP8WOK74PjOEilosqAyxV2iUFUw=="
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.16.0.tgz",
@ -5960,19 +5953,6 @@
"url": "https://github.com/sponsors/rawify"
}
},
"node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@ -6176,11 +6156,6 @@
"url": "https://github.com/sindresorhus/got?sponsor=1"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
},
"node_modules/graphemer": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
@ -7667,17 +7642,6 @@
"node": ">=6"
}
},
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/jsx-ast-utils": {
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
@ -12180,14 +12144,6 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/update-browserslist-db": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz",
@ -13429,14 +13385,6 @@
}
}
},
"node_modules/vscode-webview": {
"version": "1.0.1-beta.1",
"resolved": "https://registry.npmjs.org/vscode-webview/-/vscode-webview-1.0.1-beta.1.tgz",
"integrity": "sha512-8H2icqlb93qIvZs7Me/0sALMqJrX2e2W7JVE0mfK8exUPETP9Bmg+feivaByd1Xbg78lcKaNF9ZRrIFSenUVxQ==",
"dependencies": {
"fs-extra": "^10.0.0"
}
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",

View file

@ -33,7 +33,6 @@
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/uuid": "^10.0.0",
"@types/vscode-webview": "^1.57.1",
"clsx": "^2.1.1",
"core": "file:../core",
"dompurify": "^3.0.6",
@ -71,8 +70,7 @@
"tailwind-merge": "^3.0.2",
"tippy.js": "^6.3.7",
"unist-util-visit": "^5.0.0",
"uuid": "^9.0.1",
"vscode-webview": "^1.0.1-beta.1"
"uuid": "^9.0.1"
},
"devDependencies": {
"@swc/cli": "^0.3.14",

View file

@ -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);
}

View file

@ -0,0 +1,116 @@
import { useEffect, useRef } from "react";
import { LLMInteraction } from "../../hooks/useLLMLog";
import useLLMSummary from "../../hooks/useLLMSummary";
import End from "./End";
import ResultGroup from "./ResultGroup";
import Start from "./Start";
import StatusIcon from "./StatusIcon";
export interface DetailsProps {
interaction: LLMInteraction;
}
function renderCell(children: React.ReactNode) {
return (
<div className="border-0 border-r-2 border-solid border-[color:var(--vscode-panel-border)] pl-2 pr-2 text-sm">
{children}
</div>
);
}
/**
* A cell of statistics at the top of the details view
*/
function Cell({
label,
value,
format,
}: {
label: string;
value: any;
format?: (value: any) => string;
}) {
return renderCell(
value != undefined ? `${label}: ${format ? format(value) : value}` : "",
);
}
/**
* A cell of statistics at the top of the details view with custom content
*/
function CustomCell({ children }: { children: React.ReactNode }) {
return renderCell(children);
}
function formatSeconds(milliseconds: number) {
return (milliseconds / 1000).toFixed(2) + "s";
}
export default function Details({ interaction }: DetailsProps) {
const scrollTop = useRef<HTMLDivElement>(null);
const lastResult = useRef<any>(null);
const summary = useLLMSummary(interaction);
useEffect(() => {
if (interaction.end) {
return;
}
const last = interaction.results[interaction.results.length - 1];
if (last != lastResult.current) {
lastResult.current = last;
const lastChild = scrollTop.current?.lastChild;
if (lastChild) {
(lastChild as HTMLElement).scrollIntoView({
behavior: "auto",
block: "end",
});
}
}
});
return (
<div className="m-0 flex min-w-0 flex-1 shrink grow flex-col">
<div className="shrink-0 text-base">
<div className="columns-3 gap-0 border-0 border-b-2 border-solid border-[color:var(--vscode-panel-border)] p-0">
<Cell label="Type" value={summary.type}></Cell>
<CustomCell>
Result: <StatusIcon interaction={interaction}></StatusIcon>
{summary.result}
</CustomCell>
</div>
<div className="columns-3 gap-0 border-0 border-b-2 border-solid border-[color:var(--vscode-panel-border)] p-0">
<Cell label="Prompt Tokens" value={summary.promptTokens}></Cell>
<Cell label="Generated Tokens" value={summary.generatedTokens}></Cell>
<Cell label="ThinkingTokens" value={summary.thinkingTokens}></Cell>
</div>
<div className="columns-3 gap-0 border-0 border-b-2 border-solid border-[color:var(--vscode-panel-border)] p-0">
<Cell
label="Total Time"
value={summary.totalTime}
format={formatSeconds}
></Cell>
<Cell
label="To First Token"
value={summary.toFirstToken}
format={formatSeconds}
></Cell>
<Cell
label="Tokens/s"
value={summary.tokensPerSecond}
format={(v: number) => v.toFixed(1)}
></Cell>
</div>
</div>
<div ref={scrollTop} className="grow overflow-auto">
{interaction.start ? <Start item={interaction.start}></Start> : ""}
<div className="whitespace-pre-wrap p-2">
{interaction.results.map((group, i) => {
return <ResultGroup key={i} group={group}></ResultGroup>;
})}
</div>
{interaction.end ? <End item={interaction.end}></End> : ""}
</div>
</div>
);
}

View file

@ -0,0 +1,37 @@
import {
LLMInteractionCancel,
LLMInteractionError,
LLMInteractionSuccess,
} from "core";
import Expander from "./Expander";
import Message from "./Message";
export interface StartProps {
item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel;
}
export default function Start({ item }: StartProps) {
// <div className="border-0 border-b-2 border-solid border-[color:var(--vscode-panel-border)]">
switch (item.kind) {
case "success":
return <></>;
case "error":
return (
<div>
<span className="text-[color:var(--vscode-statusBarItem-errorForeground) m-0.5 inline-block rounded-sm bg-[color:var(--vscode-statusBarItem-errorBackground)] p-0.5">
Error
</span>
{item.message}
</div>
);
break;
case "cancel":
return (
<div>
<span className="text-[color:var(--vscode-statusBarItem-warningForeground) m-0.5 inline-block rounded-sm bg-[color:var(--vscode-statusBarItem-warningBackground)] p-0.5">
Cancelled
</span>
</div>
);
}
}

View file

@ -0,0 +1,25 @@
import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline";
import { ReactNode, useState } from "react";
export interface ExpanderProps {
label: string;
children: ReactNode;
}
export default function Expander({ label, children }: ExpanderProps) {
const [expanded, setExpanded] = useState(false);
return (
<div>
<div className="text-base" onClick={() => setExpanded(!expanded)}>
{expanded ? (
<ChevronDownIcon className="h-[16px] w-[16px]" />
) : (
<ChevronRightIcon className="h-[16px] w-[16px]" />
)}{" "}
<span className="align-top text-sm font-bold">{label}</span>
</div>
{expanded && <div>{children}</div>}
</div>
);
}

View file

@ -0,0 +1,30 @@
import { useState } from "react";
import useLLMLog from "../../hooks/useLLMLog";
import Details from "./Details";
import List from "./List";
export default function Layout() {
const llmLog = useLLMLog();
const [selectedId, setSelectedId] = useState<string | undefined>(undefined);
const interaction = selectedId
? llmLog.interactions.get(selectedId)
: undefined;
return llmLog.loading ? (
<div>Loading...</div>
) : (
<div className="flex h-full w-full">
<List
llmLog={llmLog}
onClickInteraction={(interactionId) => {
setSelectedId(interactionId);
}}
></List>
{interaction && (
<Details key="{selectedId}" interaction={interaction}></Details>
)}
</div>
);
}

View file

@ -0,0 +1,53 @@
import { useEffect, useRef, useState } from "react";
import { LLMLog } from "../../hooks/useLLMLog";
import ListItem from "./ListItem";
export interface ListProps {
llmLog: LLMLog;
onClickInteraction: (interactionId: string) => void;
}
export default function List({ llmLog, onClickInteraction }: ListProps) {
const topRef = useRef<HTMLUListElement>(null);
const [selectedId, setSelectedId] = useState<string | undefined>(undefined);
const lastSize = useRef(0);
useEffect(() => {
if (llmLog.order.length != lastSize.current) {
setSelectedId(llmLog.order[llmLog.order.length - 1]);
onClickInteraction(llmLog.order[llmLog.order.length - 1]);
lastSize.current = llmLog.order.length;
const lastChild = topRef.current?.lastChild;
if (lastChild) {
(lastChild as HTMLElement).scrollIntoView({
behavior: "smooth",
block: "end",
});
}
}
});
return (
<ul
tabIndex={1}
ref={topRef}
className="group m-0 w-[150px] flex-none list-none overflow-auto border-0 border-r-2 border-solid border-[color:var(--vscode-panel-border)] p-0"
>
{llmLog.order.map((id) => (
<ListItem
key={id}
interactionId={id}
interaction={llmLog.interactions.get(id)!}
onClickInteraction={(interactionId) => {
topRef.current?.focus();
setSelectedId(interactionId);
onClickInteraction(interactionId);
}}
selected={id == selectedId}
></ListItem>
))}
</ul>
);
}

View file

@ -0,0 +1,55 @@
import { LLMInteraction } from "../../hooks/useLLMLog";
import useLLMSummary from "../../hooks/useLLMSummary";
import StatusIcon from "./StatusIcon";
export interface ListItemProps {
interactionId: string;
interaction: LLMInteraction;
selected: boolean;
onClickInteraction: (interactionId: string) => void;
}
function formatTimestamp(timestamp: number) {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds();
const milliseconds = date.getMilliseconds();
// Format seconds with one decimal place
const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`;
return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`;
}
export default function ListItem({
interactionId,
interaction,
onClickInteraction,
selected,
}: ListItemProps) {
const summary = useLLMSummary(interaction);
return (
<li
className={
"w-full cursor-pointer pb-[3px] pl-[4px] pr-[4px] pt-[3px] " +
(selected
? "bg-[color:var(--vscode-list-inactiveSelectionBackground)]" +
" text-[color:var(--vscode-list-inctiveSelectionForeground)]" +
" group-focus-within:bg-[color:var(--vscode-list-activeSelectionBackground)]" +
" group-focus-within:text-[color:var(--vscode-list-activeSelectionForeground)]"
: "hover:bg-[color:var(--vscode-list-inactiveSelectionBackground)]")
}
key={interactionId}
onClick={() => onClickInteraction(interactionId)}
>
<StatusIcon interaction={interaction}></StatusIcon>{" "}
<span className="inline-block w-[70px]">
{interaction.start ? formatTimestamp(interaction.start.timestamp) : ""}
</span>
<span className="inline-block">{summary.type}</span>
</li>
);
}

View file

@ -0,0 +1,106 @@
import {
AssistantChatMessage,
ChatMessage,
ThinkingChatMessage,
UserChatMessage,
} from "core";
import { memo } from "react";
export interface MessageProps {
message: ChatMessage;
}
function renderMessageText(text: string) {
return <span className="whitespace-pre-wrap">{text}</span>;
}
export function renderMessageRole(role: ChatMessage["role"]) {
return (
<div>
<span className="bg-[color:var(--vscode-list-inactiveSelectionBackground)] text-xs">
{role}
</span>
</div>
);
}
function renderMessageContent(
message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage,
) {
if (typeof message.content == "string") {
return renderMessageText(message.content);
} else {
return message.content.map((part) => {
if (part.type == "text") {
return renderMessageText(part.text);
} else {
return <div>Image: {part.imageUrl.url}</div>;
}
});
}
}
export function renderMessage(message: ChatMessage, includeRole: boolean) {
switch (message.role) {
case "assistant":
return (
<>
{includeRole ? renderMessageRole(message.role) : ""}
{message.toolCalls
? message.toolCalls.map((toolCall) => (
<pre>Tool call: {JSON.stringify(toolCall, undefined, 2)}</pre>
))
: ""}
{renderMessageContent(message)}
</>
);
break;
case "thinking":
return (
<>
{includeRole ? renderMessageRole(message.role) : ""}
{message.toolCalls
? message.toolCalls.map((toolCall) => (
<pre>Tool call: {JSON.stringify(toolCall, undefined, 2)}</pre>
))
: ""}
{renderMessageContent(message)}
{message.redactedThinking && (
<pre>Redacted Thinking: {message.redactedThinking}</pre>
)}
{message.signature && <pre>Signature: {message.signature}</pre>}
</>
);
break;
case "user":
return (
<>
{includeRole ? renderMessageRole(message.role) : ""}
{renderMessageContent(message)}
</>
);
break;
case "system":
return (
<>
{includeRole ? renderMessageRole(message.role) : ""}
{renderMessageText(message.content)}
</>
);
case "tool":
return (
<>
{includeRole ? renderMessageRole(message.role) : ""}
<pre>Tool Call ID: {message.toolCallId}</pre>
{renderMessageText(message.content)}
</>
);
break;
}
}
const Message = memo(function Message({ message }: MessageProps) {
return renderMessage(message, true);
});
export default Message;

View file

@ -0,0 +1,37 @@
import { memo } from "react";
import { LLMResult } from "../../hooks/useLLMLog";
import { renderMessage } from "./Message";
interface ResultProps {
result: LLMResult;
prevResult: LLMResult | undefined;
}
const Result = memo(function Result({ result, prevResult }: ResultProps) {
switch (result.kind) {
case "chunk":
return <span>{result.chunk}</span>;
break;
case "message":
switch (result.message.role) {
case "assistant":
case "thinking":
const includeRole = !(
prevResult?.kind === "message" &&
prevResult.message.role === result.message.role
);
return renderMessage(result.message, includeRole);
default:
// We don't expect anything but AssistantChatMessages and ThinkingChatMessages in the reply
// from the LLM output, but log them if they do occur.
return (
<div className="border-[color:var(--vscode-panel-border) border-2 border-solid p-1">
{renderMessage(result.message, true)}
</div>
);
}
break;
}
});
export default Result;

View file

@ -0,0 +1,19 @@
import { memo } from "react";
import { LLMResult } from "../../hooks/useLLMLog";
import Result from "./Result";
interface ResultGroupProps {
group: LLMResult[];
}
const ResultGroup = memo(function ResultGroup({ group }: ResultGroupProps) {
return (
<>
{group.map((result, i) => (
<Result key={i} result={result} prevResult={group[i - 1]}></Result>
))}
</>
);
});
export default ResultGroup;

View file

@ -0,0 +1,73 @@
import {
LLMInteractionStartChat,
LLMInteractionStartComplete,
LLMInteractionStartFim,
} from "core";
import Expander from "./Expander";
import Message from "./Message";
export interface StartProps {
item:
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim;
}
export default function Start({ item }: StartProps) {
return (
<div className="border-0 border-b-2 border-solid border-[color:var(--vscode-panel-border)] p-1">
{(() => {
switch (item.kind) {
case "startChat":
return (
<>
<Expander label="Prompt">
<div className="p-1">
{item.messages.map((message, i) => (
<Message key={i} message={message}></Message>
))}
</div>
</Expander>
<Expander label="Options">
<pre className="m-0">
{JSON.stringify(item.options, undefined, 2)}
</pre>
</Expander>
</>
);
break;
case "startComplete":
return (
<>
<Expander label="Prompt">
<pre className="m-0">{item.prompt}</pre>
</Expander>
<Expander label="Options">
<pre className="m-0">
{JSON.stringify(item.options, undefined, 2)}
</pre>
</Expander>
</>
);
break;
case "startFim":
return (
<>
<Expander label="Prefix">
<pre className="m-0">{item.prefix}</pre>
</Expander>
<Expander label="Suffix">
<pre className="m-0">{item.suffix}</pre>
</Expander>
<Expander label="Options">
<pre className="m-0">
{JSON.stringify(item.options, undefined, 2)}
</pre>
</Expander>
</>
);
}
})()}
</div>
);
}

View file

@ -0,0 +1,34 @@
import {
CheckIcon,
EllipsisHorizontalIcon,
StopCircleIcon,
XCircleIcon,
} from "@heroicons/react/24/outline";
import { LLMInteraction } from "../../hooks/useLLMLog";
export interface StatusIconProps {
interaction: LLMInteraction;
}
export default function StatusIcon({ interaction }: StatusIconProps) {
if (interaction.end) {
switch (interaction.end.kind) {
case "success":
return (
<CheckIcon className="relative top-[2px] -mt-[2px] h-[16px] w-[16px] pr-[2px] text-[color:var(--vscode-charts-green)]" />
);
case "cancel":
return (
<StopCircleIcon className="relative top-[2px] -mt-[2px] h-[16px] w-[16px] pr-[2px] text-[color:var(--vscode-list-warningForeground)]" />
);
case "error":
return (
<XCircleIcon className="relative top-[2px] -mt-[2px] h-[16px] w-[16px] pr-[2px] text-[color:var(--vscode-list-errorForeground)]" />
);
}
} else {
return (
<EllipsisHorizontalIcon className="relative top-[2px] -mt-[2px] h-[16px] w-[16px] pr-[2px]" />
);
}
}

View file

@ -5,6 +5,7 @@ import {
PlusIcon,
} from "@heroicons/react/24/outline";
import { Editor } from "@tiptap/react";
import { RangeInFile } from "core";
import {
forwardRef,
useContext,
@ -24,6 +25,7 @@ import {
vscQuickInputBackground,
} from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import FileIcon from "../../FileIcon";
@ -138,11 +140,31 @@ interface AtMentionDropdownProps {
onClose: () => void;
}
const formatFileSize = (fileSize: number) => {
const KB = 1000;
const MB = 1000_000;
const GB = 1000_000_000;
if (fileSize > GB) {
return `${(fileSize / GB).toFixed(1)} GB`;
} else if (fileSize > MB) {
return `${(fileSize / MB).toFixed(1)} MB`;
} else if (fileSize > KB) {
return `${(fileSize / KB).toFixed(1)} KB`;
}
return `${fileSize} byte${fileSize > 1 ? "s" : ""}`;
};
const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const selectedModelTitle = useAppSelector(
(store) => store.config.defaultModelTitle,
);
const [selectedIndex, setSelectedIndex] = useState(0);
const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
@ -157,6 +179,88 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const [allItems, setAllItems] = useState<ComboBoxItem[]>([]);
async function isItemTooBig(
name: string,
query: string,
): Promise<[boolean, number]> {
const selectedCode: RangeInFile[] = [];
// Get context item from core
const contextResult = await ideMessenger.request(
"context/getContextItems",
{
name,
query,
fullInput: "",
selectedCode,
selectedModelTitle: selectedModelTitle ?? "",
},
);
if (contextResult.status === "error") {
return [false, -1];
}
const item = contextResult.content[0];
// Check if the context item exceeds the context length of the selected model
const result = await ideMessenger.request("isItemTooBig", {
item,
selectedModelTitle: selectedModelTitle,
});
if (result.status === "error") {
return [false, -1];
}
const size = new Blob([item.content]).size;
return [result.content, size];
}
function handleItemTooBig(
fileExceeds: boolean,
fileSize: number,
item: ComboBoxItem,
) {
if (fileExceeds) {
props.editor
.chain()
.focus()
.command(({ tr, state }) => {
const text = state.doc.textBetween(
0,
state.selection.from,
"\n",
"\n",
); // Get the text before the cursor
const lastAtIndex = text.lastIndexOf("@");
if (lastAtIndex !== -1) {
// Delete text after the last "@"
tr.delete(lastAtIndex + 1, state.selection.from);
return true;
}
return false;
})
.run();
// Trigger warning message
ideMessenger.ide.showToast(
"warning",
fileSize > 0 ? "File exceeds context length" : "Can't load the file",
{
modal: true,
detail:
fileSize > 0
? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model`
: `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
},
);
} else {
props.command({ ...item, itemType: item.type });
}
}
useEffect(() => {
const items = [...props.items];
if (subMenuTitle === "Type to search docs") {
@ -243,7 +347,13 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
}
if (item) {
props.command({ ...item, itemType: item.type });
if (item.type === "file" && item.query) {
isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) =>
handleItemTooBig(fileExceeds, fileSize, item),
);
} else {
props.command({ ...item, itemType: item.type });
}
}
};

View file

@ -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>

View file

@ -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,

View file

@ -122,19 +122,16 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) {
const [hidden, setHidden] = useState(calculatedInitiallyHidden);
const [isExpanded, setIsExpanded] = useState(false);
// Track if user has manually toggled visibility
const [userToggled, setUserToggled] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
const [contentDims, setContentDims] = useState({ width: 0, height: 0 });
useEffect(() => {
// Only update hidden state from props if user hasn't manually toggled
// or if initiallyHidden isn't explicitly set to false
if (!userToggled || props.initiallyHidden !== false) {
// Only update hidden state from props if initiallyHidden isn't explicitly set to false
if (props.initiallyHidden !== false) {
setHidden(calculatedInitiallyHidden);
}
}, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]);
}, [calculatedInitiallyHidden, props.initiallyHidden]);
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
setContentDims({
@ -166,7 +163,6 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) {
fontSize: getFontSize() - 3,
}}
onClick={() => {
setUserToggled(true);
setHidden(!hidden);
}}
>

View file

@ -1,4 +1,4 @@
import { Editor } from "@tiptap/core";
import { Editor, JSONContent } from "@tiptap/core";
import Document from "@tiptap/extension-document";
import History from "@tiptap/extension-history";
import Image from "@tiptap/extension-image";
@ -48,6 +48,28 @@ export function getPlaceholderText(
: "Ask a follow-up";
}
/**
* Checks if the editor content is valid for submission.
* A valid submission can contain either text content or prompt/code blocks
*
* @param json The editor JSON content
* @returns true if the content is valid for submission, false otherwise
*/
export function hasValidEditorContent(json: JSONContent): boolean {
// Check for prompt or code blocks
const hasPromptOrCodeBlock = json.content?.some(
(c) =>
c.type === ContinueExtensions.PromptBlock.name ||
c.type === ContinueExtensions.CodeBlock.name,
);
// Check for text content
const hasTextContent = json.content?.some((c) => c.content);
// Content is valid if it has either text or special blocks
return hasTextContent || hasPromptOrCodeBlock || false;
}
/**
* This function is called only once, so we need to use refs to pass in the latest values
*/
@ -367,8 +389,8 @@ export function createEditorConfig(options: {
const json = editor.getJSON();
// Don't do anything if input box is empty
if (!json.content?.some((c) => c.content)) {
// Don't do anything if input box doesn't have valid content
if (!hasValidEditorContent(json)) {
return;
}

View file

@ -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>

12
gui/src/console.tsx Normal file
View file

@ -0,0 +1,12 @@
import React from "react";
import ReactDOM from "react-dom/client";
import Layout from "./components/console/Layout";
import "./indexConsole.css";
(async () => {
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Layout></Layout>
</React.StrictMode>,
);
})();

View file

@ -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,
}}

View file

@ -15,7 +15,6 @@ import {
} from "core/protocol/util";
import { createContext } from "react";
import { v4 as uuidv4 } from "uuid";
import "vscode-webview";
import { isJetBrains } from "../util";
interface vscode {

View file

@ -50,6 +50,7 @@ export const SubmenuContextProvidersProvider = ({
}) => {
const ideMessenger = useContext(IdeMessengerContext);
const submenuContextProviders = useAppSelector(selectSubmenuContextProviders);
const lastProviders = useRef(submenuContextProviders);
const disableIndexing = useAppSelector(
(store) => store.config.config.disableIndexing,
);
@ -356,15 +357,22 @@ export const SubmenuContextProvidersProvider = ({
);
// Reload all submenu items on the initial config load
// TODO - could refresh on any change
const initialLoad = useRef(false);
useEffect(() => {
if (!submenuContextProviders.length || initialLoad.current) {
if (!submenuContextProviders.length) {
return;
}
void loadSubmenuItems("all");
initialLoad.current = true;
}, [loadSubmenuItems, submenuContextProviders, initialLoad]);
// Refresh submenu items when new titles detected
const newTitles = submenuContextProviders
.filter(
(provider) =>
!lastProviders.current.find((p) => p.title === provider.title),
)
.map((provider) => provider.title);
if (newTitles.length > 0) {
loadSubmenuItems(newTitles);
}
lastProviders.current = submenuContextProviders;
}, [loadSubmenuItems, submenuContextProviders]);
return (
<SubmenuContextProvidersContext.Provider

252
gui/src/hooks/useLLMLog.ts Normal file
View file

@ -0,0 +1,252 @@
import {
LLMInteractionCancel,
LLMInteractionChunk,
LLMInteractionError,
LLMInteractionItem,
LLMInteractionMessage,
LLMInteractionStartChat,
LLMInteractionStartComplete,
LLMInteractionStartFim,
LLMInteractionSuccess,
} from "core";
import { useEffect, useReducer } from "react";
declare const vscode: any;
export type LLMResult = LLMInteractionMessage | LLMInteractionChunk;
const MAX_GROUP_LENGTH = 32;
interface ToConsoleViewInit {
type: "init";
uuid: string;
items: LLMInteractionItem[];
}
interface ToConsoleViewItem {
type: "item";
uuid: string;
item: LLMInteractionItem;
}
interface ToConsoleViewRemove {
type: "remove";
uuid: string;
interactionId: string;
}
interface ToConsoleViewClear {
type: "clear";
uuid: string;
}
type ToConsoleView =
| ToConsoleViewInit
| ToConsoleViewItem
| ToConsoleViewRemove
| ToConsoleViewClear;
/**
* Represents a linear list of LLMInteractionItem, transformed into
* a form that is more convenient for rendering.
*/
export interface LLMInteraction {
start?:
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim;
// We use an array-of-arrays for efficiency when rendering a streamed result
// with lots and lots of separate tokens; instead of having a linear list
// of 1024 Result components, we have 32 ResultGroup components each rendering
// 32 Results.
//
// Inline content can split between one group and the next - we'll let the
// browser engine sort that out.
results: LLMResult[][];
end?: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel;
}
export interface LLMLog {
loading: boolean;
interactions: Map<string, LLMInteraction>;
order: string[];
}
/**
* Appends a new result item (chunk or message) to an interaction,
* existing iteractions must already have been copied with
* copyInteractionForMutation().
*/
function appendItemToInteractionResult(
interaction: LLMInteraction,
item: LLMInteractionMessage | LLMInteractionChunk,
) {
let lastGroup = interaction.results[interaction.results.length - 1];
if (lastGroup == undefined || lastGroup.length == MAX_GROUP_LENGTH) {
interaction.results.push([item]);
} else {
lastGroup.push(item);
}
}
/**
* Makes a copy of an interaction that can be mutated without changing
* any objects/arrays that are part of the old state. We always make
* a copy of the last (open) result group, so that we can simply append
* to it; this is very slightly inefficient for the case where we're
* handling a single end item with no results, but makes things simpler.
*/
function copyInteractionForMutation(oldInteraction: LLMInteraction) {
const oldResults = oldInteraction.results;
let oldLastGroup = oldInteraction.results[oldInteraction.results.length - 1];
let newResults;
if (oldLastGroup == undefined || oldLastGroup.length == MAX_GROUP_LENGTH) {
newResults = [...oldInteraction.results];
} else {
newResults = oldInteraction.results.slice(0, -1);
newResults.push([...oldLastGroup]);
}
return { ...oldInteraction, results: newResults };
}
function appendItemsToLLMLog(
oldLog: LLMLog,
items: LLMInteractionItem[],
): LLMLog {
const oldInteractions = oldLog.interactions;
const newInteractions: Map<string, LLMInteraction> = new Map();
let order = oldLog.order;
let interactionsAdded = false;
// Add the new items to the log, making mutable copies of old
// LLMInteraction as necessary
for (const item of items) {
let interaction = newInteractions.get(item.interactionId);
if (interaction === undefined) {
const oldInteraction = oldInteractions.get(item.interactionId);
if (oldInteraction) {
interaction = copyInteractionForMutation(oldInteraction);
} else {
interaction = {
results: [],
};
if (interactionsAdded) {
order.push(item.interactionId);
} else {
order = [...order, item.interactionId];
interactionsAdded = true;
}
}
newInteractions.set(item.interactionId, interaction);
}
switch (item.kind) {
case "startChat":
case "startComplete":
case "startFim":
interaction.start = item;
break;
case "chunk":
case "message":
appendItemToInteractionResult(interaction, item);
break;
case "success":
case "error":
case "cancel":
interaction.end = item;
break;
}
}
// Copy over unchanged interactions
for (const interactionId of oldInteractions.keys()) {
if (!newInteractions.has(interactionId)) {
newInteractions.set(interactionId, oldInteractions.get(interactionId)!);
}
}
return {
loading: false,
interactions: newInteractions,
order,
};
}
function removeInteractionFromLLMLog(
llmLog: LLMLog,
interactionId: string,
): LLMLog {
const newInteractions = new Map(llmLog.interactions);
newInteractions.delete(interactionId);
const newOrder = llmLog.order.filter((id) => id !== interactionId);
return {
loading: false,
interactions: newInteractions,
order: newOrder,
};
}
/**
* Hook to accumulate log data structures based on messages passed
* from the core. Note that each call site will create an independent
* data structure, so this should be only used once at a toplevel
* component.
* @returns currently log datastructure.
*/
export default function useLLMLog() {
const [llmLog, dispatchLlmLog] = useReducer(
(llmLog: LLMLog, message: ToConsoleView) => {
switch (message.type) {
case "init":
return appendItemsToLLMLog(llmLog, message.items);
case "item":
return appendItemsToLLMLog(llmLog, [message.item]);
case "remove":
return removeInteractionFromLLMLog(llmLog, message.interactionId);
case "clear":
return {
loading: false,
interactions: new Map(),
order: [],
};
}
},
{
loading: true,
interactions: new Map(),
order: [],
},
);
useEffect(function () {
// The uuid here marks the "generation" when the webview is
// reloaded, so we don't get confused if there are inflight
// messages from the previous generation. In particular, this
// avoids problems when React.StrictMode runs this effect
// twice - we don't want to process two "init" messages.
const uuid = crypto.randomUUID();
const onMessage = (event: MessageEvent<ToConsoleView>) => {
if (event.data.uuid !== uuid) {
return;
}
dispatchLlmLog(event.data);
};
window.addEventListener("message", onMessage);
vscode.postMessage({ type: "start", uuid });
return () => {
vscode.postMessage({ type: "stop", uuid });
window.removeEventListener("message", onMessage);
};
}, []);
return llmLog;
}

View file

@ -0,0 +1,76 @@
import { useMemo } from "react";
import { LLMInteraction } from "./useLLMLog";
/**
* Hook returning memoized information about single logged prompt/response
* query to the LLM.
*/
export default function useLLMSummary(interaction: LLMInteraction) {
return useMemo(() => {
if (interaction.start == undefined) {
return {
result: "",
type: "",
};
}
const type = interaction.start.kind.slice(5);
let result;
switch (interaction.end?.kind) {
case "cancel":
result = "Cancelled";
break;
case "error":
result = "Error";
break;
case "success":
result = "Success";
break;
case undefined:
result = "";
}
let totalTime,
toFirstToken,
tokensPerSecond,
promptTokens,
generatedTokens,
thinkingTokens;
if (interaction.start != undefined && interaction.results.length > 0) {
const firstGroup = interaction.results[0];
const firstItem = firstGroup ? firstGroup[0] : undefined;
toFirstToken = firstItem
? firstItem.timestamp - interaction.start.timestamp
: undefined;
}
if (interaction.end != undefined) {
totalTime = interaction.end.timestamp - interaction.start.timestamp;
promptTokens = interaction.end.promptTokens;
generatedTokens = interaction.end.generatedTokens;
thinkingTokens = interaction.end.thinkingTokens;
if (toFirstToken != undefined) {
tokensPerSecond =
(generatedTokens + thinkingTokens) /
((totalTime - toFirstToken) / 1000);
}
} else {
const lastGroup = interaction.results[interaction.results.length - 1];
const lastItem = lastGroup ? lastGroup[lastGroup.length - 1] : undefined;
totalTime = lastItem
? lastItem.timestamp - interaction.start.timestamp
: undefined;
}
return {
result,
type,
totalTime,
toFirstToken,
tokensPerSecond,
promptTokens,
generatedTokens,
thinkingTokens,
};
}, [interaction]);
}

View file

@ -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

9
gui/src/indexConsole.css Normal file
View file

@ -0,0 +1,9 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body,
#root {
height: 100%;
}

View file

@ -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>
);
}

View file

@ -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>

View file

@ -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);

View file

@ -1,2 +1 @@
export * from "./organizations";
export * from "./profiles";

View file

@ -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;

View file

@ -1,2 +0,0 @@
export * from "./slice";
export * from "./thunks";

View file

@ -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;

View file

@ -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));
});

View file

@ -1,2 +1 @@
export * from "./slice";
export * from "./thunks";

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