🚧 basic chat working with free trial

This commit is contained in:
Nate Sesti 2023-12-07 00:06:19 -08:00
parent 32051b0ad7
commit aef1b66246
30 changed files with 4189 additions and 573 deletions

14
.vscode/launch.json vendored
View file

@ -21,6 +21,16 @@
}
],
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest All",
"program": "${workspaceFolder}/core/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
},
{
"type": "chrome",
"request": "attach",
@ -32,8 +42,8 @@
},
"port": 9222,
// "runtimeArgs": ["--remote-debugging-port=9222"],
"sourceMaps": true,
"preLaunchTask": "gui:dev"
"sourceMaps": true
// "preLaunchTask": "gui:dev"
},
{
"name": "Pytest",

3
.vscode/tasks.json vendored
View file

@ -115,7 +115,8 @@
"cwd": "gui"
},
"args": ["run", "dev"],
"isBackground": true
"isBackground": true,
"problemMatcher": ["$tsc"]
}
]
}

29
core/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,29 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"name": "vscode-jest-tests.v2.core",
"request": "launch",
"args": [
"--runInBand",
"--watchAll=false"
// "--testNamePattern",
// "${jest.testNamePattern}",
// "--runTestsByPath",
// "${jest.testFile}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"program": "${workspaceFolder}/node_modules/.bin/jest",
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
]
}

16
core/context/index.ts Normal file
View file

@ -0,0 +1,16 @@
import { ContextItem } from "../llm/types";
// TODO:
export async function getContextItem(id: string, query: string) {
const item: ContextItem = {
id: {
providerTitle: "TODO",
itemId: id,
},
name: "TODO",
description: "TODO",
content: query,
};
return item;
}

8
core/jest.config.js Normal file
View file

@ -0,0 +1,8 @@
module.exports = {
roots: ["<rootDir>"],
transform: {
"^.+\\.ts?$": "ts-jest",
},
// testRegex: ".+\\.test\\.ts$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};

View file

@ -7,9 +7,7 @@ export function constructMessages(history: ChatHistory): ChatMessage[] {
for (const ctxItem of historyItem.contextItems) {
msgs.push({
role: historyItem.message.role,
name: ctxItem.name,
content: ctxItem.content,
summary: ctxItem.description,
});
}
msgs.push(historyItem.message);

View file

@ -72,6 +72,10 @@ function pruneRawPromptFromTop(
return pruneStringFromTop(modelName, maxTokens, prompt);
}
function summarize(message: string): string {
return message.substring(0, 100) + "...";
}
function pruneChatHistory(
modelName: string,
chatHistory: ChatMessage[],
@ -118,8 +122,8 @@ function pruneChatHistory(
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[0];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(message.summary, modelName);
message.content = message.summary;
totalTokens += countTokens(summarize(message.content), modelName);
message.content = summarize(message.content);
i++;
}
@ -142,8 +146,8 @@ function pruneChatHistory(
) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(message.summary, modelName);
message.content = message.summary;
totalTokens += countTokens(summarize(message.content), modelName);
message.content = summarize(message.content);
i++;
}
@ -183,7 +187,6 @@ function compileChatMessages(
const promptMsg: ChatMessage = {
role: "user",
content: prompt,
summary: prompt,
};
msgsCopy.push(promptMsg);
}
@ -193,7 +196,6 @@ function compileChatMessages(
const systemChatMsg: ChatMessage = {
role: "system",
content: renderedSystemMessage,
summary: renderedSystemMessage,
};
// Insert as second to last
// Later moved to top, but want second-priority to last user message

View file

@ -6,6 +6,15 @@ import {
} from "./countTokens";
import { CompletionOptions, RequestOptions, ChatMessage } from "./types";
async function streamToString(stream: any) {
let decoder = new TextDecoder("utf-8");
let result = "";
for await (const chunk of stream) {
result += decoder.decode(chunk);
}
return result;
}
interface LLMOptions {
title?: string;
uniqueId: string;
@ -58,7 +67,10 @@ export abstract class LLM implements LLMOptions {
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength;
this.completionOptions = options.completionOptions;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
};
this.requestOptions = options.requestOptions;
this.promptTemplates = options.promptTemplates;
this.templateMessages = options.templateMessages;
@ -102,13 +114,11 @@ export abstract class LLM implements LLMOptions {
return prompt;
}
const msgs: ChatMessage[] = [
{ role: "user", content: prompt, summary: prompt },
];
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
const systemMessage = this._getSystemMessage();
if (systemMessage) {
msgs.unshift({ role: "system", content: systemMessage, summary: "" });
msgs.unshift({ role: "system", content: systemMessage });
}
return this.templateMessages(msgs);
@ -245,19 +255,27 @@ export abstract class LLM implements LLMOptions {
let completion = "";
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
completionOptions
)) {
completion += chunk;
yield { role: "assistant", content: chunk, summary: chunk };
}
} else {
for await (const chunk of this._streamChat(messages, completionOptions)) {
completion += chunk.content;
yield chunk;
try {
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
completionOptions
)) {
completion += chunk;
yield { role: "assistant", content: chunk };
}
} else {
for await (const chunk of this._streamChat(
messages,
completionOptions
)) {
completion += chunk.content;
yield chunk;
}
}
} catch (error) {
console.log(error);
throw error;
}
this._logTokensGenerated(completionOptions.model, completion);
@ -276,7 +294,7 @@ export abstract class LLM implements LLMOptions {
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
throw new Error(
"You must either implement template_messages or _stream_chat"
"You must either implement templateMessages or _streamChat"
);
}
@ -284,7 +302,7 @@ export abstract class LLM implements LLMOptions {
this.templateMessages(messages),
options
)) {
yield { role: "assistant", content: chunk, summary: chunk };
yield { role: "assistant", content: chunk };
}
}

View file

@ -1,13 +1,15 @@
import { LLM } from "..";
import { ChatMessage, CompletionOptions } from "../types";
import axios from "axios";
// const SERVER_URL = "http://127.0.0.1:8080"
// const SERVER_URL = "http://localhost:8080";
const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app";
class FreeTrial extends LLM {
private _getHeaders() {
return { uniqueId: this.uniqueId || "None" };
return {
uniqueId: this.uniqueId || "None",
"Content-Type": "application/json",
};
}
protected async _complete(
@ -16,23 +18,17 @@ class FreeTrial extends LLM {
): Promise<string> {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/complete`,
{
const response = await fetch(`${SERVER_URL}/complete`, {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({
messages: [{ role: "user", content: prompt }],
...args,
},
{
headers: this._getHeaders(),
// proxy: this.requestOptions.proxy,
}
);
}),
// proxy: this.requestOptions.proxy,
});
if (response.status != 200) {
throw new Error(response.data);
}
return response.data;
return await response.json();
}
protected async *_streamComplete(
@ -41,70 +37,71 @@ class FreeTrial extends LLM {
): AsyncGenerator<string> {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/stream_complete`,
{
const response = await fetch(`${SERVER_URL}/stream_complete`, {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({
messages: [{ role: "user", content: prompt }],
...args,
},
{
headers: this._getHeaders(),
responseType: "stream",
// proxy: this.requestOptions.proxy,
}),
});
const reader = response.body.getReader();
let decoder = new TextDecoder("utf-8");
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
);
if (response.status != 200) {
throw new Error(await streamToString(response.data));
}
for await (const chunk of response.data) {
if (chunk) {
let decodedChunk = chunk.toString("utf-8");
if (value) {
let decodedChunk = decoder.decode(value);
yield decodedChunk;
}
}
}
}
async function* streamChat(messages: ChatMessage[], options: any) {
const args = this.collectArgs(options);
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/stream_chat`,
{
messages,
...args,
},
{
headers: this.getHeaders(),
// proxy: requestOptions.proxy,
responseType: "stream",
}
);
const response = await fetch(`${SERVER_URL}/stream_chat`, {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({
messages,
...args,
}),
});
if (response.status !== 200) {
throw new Error(await streamToString(response.data));
}
const reader = response.body.getReader();
let decoder = new TextDecoder("utf-8");
for await (const chunk of response.data) {
if (chunk) {
const jsonChunk = chunk.toString("utf-8");
const chunks = jsonChunk.split("\n");
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
if (value) {
let decodedChunk = decoder.decode(value);
const chunks = decodedChunk.split("\n");
for (const chunk of chunks) {
if (chunk.trim() !== "") {
const loadedChunk = JSON.parse(chunk);
for (const chunk of chunks) {
if (chunk.trim() !== "") {
const loadedChunk = JSON.parse(chunk);
yield {
role: "assistant",
content: loadedChunk.content || "",
};
yield {
role: "assistant",
content: loadedChunk.content || "",
};
if (this.model === "gpt-4") {
await delay(0.03);
} else {
await delay(0.01);
if (this.model === "gpt-4") {
await delay(0.03);
} else {
await delay(0.01);
}
}
}
}
@ -116,13 +113,4 @@ async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
async function streamToString(stream: any) {
let decoder = new TextDecoder("utf-8");
let result = "";
for await (const chunk of stream) {
result += decoder.decode(chunk);
}
return result;
}
export default FreeTrial;

41
core/llm/test/llm.test.ts Normal file
View file

@ -0,0 +1,41 @@
import FreeTrial from "../llms/FreeTrial";
describe("FreeTrial", () => {
let freeTrial: FreeTrial;
// Setup
beforeAll(() => {
freeTrial = new FreeTrial({
uniqueId: "None",
model: "gpt-3.5-turbo",
});
});
test("Stream Chat works", async () => {
let total = "";
for await (const chunk of freeTrial.streamChat([
{ role: "user", content: "Hello" },
])) {
total += chunk.content;
}
expect(total.length).toBeGreaterThan(0);
return;
});
test("Stream Complete works", async () => {
let total = "";
for await (const chunk of freeTrial.streamComplete("Hello")) {
total += chunk;
}
expect(total.length).toBeGreaterThan(0);
return;
});
test("Complete works", async () => {
const completion = await freeTrial.complete("Hello");
expect(completion.length).toBeGreaterThan(0);
return;
});
});

13
core/llm/types.d.ts vendored
View file

@ -23,16 +23,20 @@ type ChatMessageRole = "user" | "assistant" | "system";
interface ChatMessage {
role: ChatMessageRole;
content: string;
name?: string;
summary: string;
}
interface ContextItemId {
providerTitle: string;
itemId: string;
}
interface ContextItem {
content: string;
name: string;
description: string;
providerTitle: string;
itemId: string;
id: ContextItemId;
editing?: boolean;
editable?: boolean;
}
interface ChatHistoryItem {
@ -50,4 +54,5 @@ export {
ChatHistory,
ChatHistoryItem,
ContextItem,
ContextItemId,
};

3766
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -4,11 +4,13 @@
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"axios": "^1.6.2"
"devDependencies": {
"@types/jest": "^29.5.11",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
}
}

22
core/tsconfig.json Normal file
View file

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noEmitOnError": false
},
"include": [],
"references": [{ "path": "./tsconfig.node.json" }]
}

View file

@ -118,7 +118,7 @@
{
"command": "continue.toggleFullScreen",
"category": "Continue",
"title": "Toggle Full Screen (⌘ K ⌘ M)",
"title": "Toggle Full Screen",
"icon": "$(fullscreen)"
},
{

View file

@ -3,7 +3,6 @@ import History from "./pages/history";
import Help from "./pages/help";
import Layout from "./components/Layout";
import { createContext } from "react";
import useContinueGUIProtocol from "./hooks/useContinueClient";
import ContinueGUIClientProtocol from "./client/ContinueGUIClientProtocol";
import { useDispatch } from "react-redux";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
@ -71,15 +70,14 @@ export const GUIClientContext = createContext<
>(undefined);
function App() {
const client = useContinueGUIProtocol(false);
const dispatch = useDispatch();
useSetup(client, dispatch);
useSetup(dispatch);
return (
<GUIClientContext.Provider value={client}>
<RouterProvider router={router} />
</GUIClientContext.Provider>
// <GUIClientContext.Provider>
<RouterProvider router={router} />
// </GUIClientContext.Provider>
);
}

View file

@ -2,7 +2,6 @@ import { SessionFullState } from "../redux/slices/sessionStateReducer";
import { ContextItem } from "../schema/ContextItem";
import { ContextItemId } from "../schema/ContextItemId";
import { ContinueConfig } from "../schema/ContinueConfig";
import { PersistedSessionInfo } from "../schema/PersistedSessionInfo";
import { ModelDescription } from "../schema/SerializedContinueConfig";
import { SessionState, StepDescription } from "../schema/SessionState";
import { SessionUpdate } from "../schema/SessionUpdate";
@ -249,23 +248,22 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
workspaceDirectory: string
) {
// Save current session
const persistedSessionInfo: PersistedSessionInfo = {
session_state: {
history: currentSession.history,
context_items: currentSession.context_items,
},
title: currentSession.title,
workspace_directory: workspaceDirectory,
session_id: currentSession.session_id,
};
await fetch(`${this.serverUrl}/sessions/save`, {
method: "POST",
body: JSON.stringify(persistedSessionInfo),
headers: {
"Content-Type": "application/json",
},
});
// const persistedSessionInfo: PersistedSessionInfo = {
// session_state: {
// history: currentSession.history,
// context_items: [],
// },
// title: currentSession.title,
// workspace_directory: workspaceDirectory,
// session_id: currentSession.session_id,
// };
// await fetch(`${this.serverUrl}/sessions/save`, {
// method: "POST",
// body: JSON.stringify(persistedSessionInfo),
// headers: {
// "Content-Type": "application/json",
// },
// });
}
async deleteSession(session_id: string) {

View file

@ -22,6 +22,7 @@ import ModelSelect from "./modelSelection/ModelSelect";
import ProgressBar from "./loaders/ProgressBar";
import { getFontSize } from "../util";
import IndexingProgressBar from "./loaders/IndexingProgressBar";
import { newSession } from "../redux/slices/stateSlice";
// #region Styled Components
const FOOTER_HEIGHT = "1.8em";
@ -148,6 +149,8 @@ const Layout = () => {
navigator.clipboard.writeText(selection);
}, 100);
}
} else if (event.metaKey && event.code === "KeyN") {
dispatch(newSession());
}
};

View file

@ -59,17 +59,18 @@ import {
handleKeyDownJetBrainsMac,
} from "../../util/jetbrains";
import FileIcon from "../FileIcon";
import { ContextItem } from "../../schema/ContextItem";
import RingLoader from "../loaders/RingLoader";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import { contextLengthSelector } from "../../redux/selectors/configSelectors";
import { getContextItem } from "../../../../core/context";
import {
addContextItem,
addContextItemAtIndex,
deleteContextWithIds,
newSession,
setActive,
} from "../../redux/slices/sessionStateReducer";
import RingLoader from "../loaders/RingLoader";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import { contextLengthSelector } from "../../redux/selectors/configSelectors";
setInactive,
} from "../../redux/slices/stateSlice";
import { ContextItem } from "../../../../core/llm/types";
const SEARCH_INDEX_NAME = "continue_context_items";
@ -364,9 +365,6 @@ interface ComboBoxProps {
isMainInput: boolean;
value?: string;
active?: boolean;
groupIndices?: number[];
onToggle?: (arg0: boolean) => void;
onToggleAll?: (arg0: boolean) => void;
isToggleOpen?: boolean;
index?: number;
onDelete?: () => void;
@ -421,21 +419,21 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
any | undefined
>(undefined);
const availableSlashCommands = useSelector(
(state: RootStore) =>
state.serverState.slashCommands?.map((cmd) => {
return {
name: `/${cmd.name}`,
description: cmd.description,
};
}) || []
);
const availableSlashCommands = [];
// useSelector(
// (state: RootStore) =>
// state.serverState.slashCommands?.map((cmd) => {
// return {
// name: `/${cmd.name}`,
// description: cmd.description,
// };
// }) || []
// );
const selectedContextItems = useSelector((state: RootStore) => {
if (typeof props.index !== "undefined") {
return (state.sessionState.history[props.index].params["context_items"] ||
[]) as ContextItem[];
return state.state.history[props.index].contextItems;
} else {
return state.sessionState.context_items || [];
return state.state.contextItems;
}
});
@ -483,7 +481,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const timeout = setTimeout(() => {
setWaitingForContextItem(true);
}, 0.1);
const contextItem = await client?.getContextItem(id, query);
const contextItem = await getContextItem(id, query);
clearTimeout(timeout);
setWaitingForContextItem(false);
if (!contextItem) return;
@ -981,7 +979,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
onClick={() => {
dispatch(
deleteContextWithIds({
ids: selectedContextItems.map((item) => item.description.id),
ids: selectedContextItems.map((item) => item.id),
index: props.index,
})
);
@ -993,9 +991,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
if (e.key === "Backspace") {
dispatch(
deleteContextWithIds({
ids: selectedContextItems.map(
(item) => item.description.id
),
ids: selectedContextItems.map((item) => item.id),
index: props.index,
})
);
@ -1014,7 +1010,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
<PillButton
inputIndex={props.index}
areMultipleItems={selectedContextItems.length > 1}
key={`${item.description.id.item_id}${idx}`}
key={`${item.id.itemId}${idx}`}
item={item}
editing={
item.editing &&
@ -1028,21 +1024,18 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
onDelete={() => {
dispatch(
deleteContextWithIds({
ids: [item.description.id],
ids: [item.id],
index: props.index,
})
);
inputRef.current?.focus();
if (
(item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name) ||
(item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id
.provider_name ===
item.description.id.provider_name)
(item.id.itemId === focusedContextItem?.id.itemId &&
focusedContextItem?.id.providerTitle ===
item.id.providerTitle) ||
(item.id.itemId === previewingContextItem?.id.itemId &&
previewingContextItem?.id.providerTitle ===
item.id.providerTitle)
) {
setPreviewingContextItem(undefined);
setFocusedContextItem(undefined);
@ -1050,10 +1043,9 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}}
onClick={(e) => {
if (
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
item.id.itemId === focusedContextItem?.id.itemId &&
focusedContextItem?.id.providerTitle ===
item.id.providerTitle
) {
setFocusedContextItem(undefined);
} else {
@ -1067,10 +1059,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
setPreviewingContextItem((prev) => {
if (!prev) return item;
if (
prev.description.id.item_id ===
item.description.id.item_id &&
prev.description.id.provider_name ===
item.description.id.provider_name
prev.id.itemId === item.id.itemId &&
prev.id.providerTitle === item.id.providerTitle
) {
return undefined;
} else {
@ -1079,16 +1069,14 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
});
}}
previewing={
item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name
item.id.itemId === previewingContextItem?.id.itemId &&
previewingContextItem?.id.providerTitle ===
item.id.providerTitle
}
focusing={
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
item.id.itemId === focusedContextItem?.id.itemId &&
focusedContextItem?.id.providerTitle ===
item.id.providerTitle
}
prefixInputWithEdit={(should) => {
if (
@ -1184,7 +1172,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
previewingContextItem.description.description
previewingContextItem.description
)}\n${previewingContextItem.content}\n\`\`\``}
maxHeight={200}
/>
@ -1198,7 +1186,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
onClick={() => {
dispatch(
deleteContextWithIds({
ids: selectedContextItems.map((item) => item.description.id),
ids: selectedContextItems.map((item) => item.id),
index: props.index,
})
);
@ -1228,7 +1216,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
ref={divRef}
>
<GradientBorder
loading={props.active || false}
// loading={props.active}
loading={false}
isFirst={false}
isLast={false}
borderColor={props.active ? undefined : vscBackground}
@ -1478,7 +1467,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
onClick={() => {
if (active) {
client?.stopSession();
dispatch(setActive(false));
dispatch(setInactive());
} else {
props.onEnter?.(undefined);
}
@ -1493,7 +1482,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
{isHovered && (
<div className="flex">
<>
{timeline
{/* {timeline
.filter(
(h, i: number) =>
props.groupIndices?.includes(i) && h.logs
@ -1521,7 +1510,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
>
<ArrowUpLeftIcon width="1.3em" height="1.3em" />
</HeaderButtonWithText>
)}
)} */}
{/* <HeaderButtonWithText
onClick={(e) => {
e.stopPropagation();

View file

@ -16,7 +16,7 @@ import { GUIClientContext } from "../../App";
import { getFontSize } from "../../util";
import HeaderButtonWithText from "../HeaderButtonWithText";
import FileIcon from "../FileIcon";
import { ContextItem } from "../../schema/ContextItem";
import { ContextItem } from "../../../../core/llm/types";
import { postToIde } from "../../util/ide";
import { useDispatch, useSelector } from "react-redux";
import { setEditingAtIds } from "../../redux/slices/sessionStateReducer";
@ -162,7 +162,7 @@ const PillButton = (props: PillButtonProps) => {
if (!props.editing) {
dispatch(
setEditingAtIds({
ids: [props.item.description.id],
ids: [props.item.id],
index: props.inputIndex,
})
);
@ -215,23 +215,23 @@ const PillButton = (props: PillButtonProps) => {
}}
onClick={(e) => {
props.onClick?.(e);
if (props.item.description.id.provider_title === "file") {
if (props.item.id.providerTitle === "file") {
postToIde("showFile", {
filepath: props.item.description.description,
filepath: props.item.description,
});
} else if (props.item.description.id.provider_title === "code") {
const lines = props.item.description.name
} else if (props.item.id.providerTitle === "code") {
const lines = props.item.name
.split("(")[1]
.split(")")[0]
.split("-");
postToIde("showLines", {
filepath: props.item.description.description,
filepath: props.item.description,
start: parseInt(lines[0]) - 1,
end: parseInt(lines[1]) - 1,
});
} else {
postToIde("showVirtualFile", {
name: props.item.description.name,
name: props.item.name,
content: props.item.content,
});
}
@ -246,16 +246,14 @@ const PillButton = (props: PillButtonProps) => {
}}
>
<span className={(isHovered ? "underline" : "") + " flex"}>
{["file", "code"].includes(
props.item.description.id.provider_title
) && (
{["file", "code"].includes(props.item.id.providerTitle) && (
<FileIcon
height="16px"
width="16px"
filename={props.item.description.name.split(" ").at(0)}
filename={props.item.name.split(" ").at(0)}
></FileIcon>
)}
{props.item.description.name}
{props.item.name}
</span>
</StyledButton>
{(props.editingAny ||
@ -263,7 +261,7 @@ const PillButton = (props: PillButtonProps) => {
(props.editing && props.editingAny)) && (
<>
<ClickableInsidePillButton
data-tooltip-id={`circle-div-${props.item.description.name}`}
data-tooltip-id={`circle-div-${props.item.name}`}
text={
props.editing ? "Editing this range" : "Edit this range (e)"
}
@ -274,7 +272,7 @@ const PillButton = (props: PillButtonProps) => {
>
<PaintBrushIcon width="1.4em" height="1.4em" />
</ClickableInsidePillButton>
<StyledTooltip id={`circle-div-${props.item.description.name}`}>
<StyledTooltip id={`circle-div-${props.item.name}`}>
Editing this range
</StyledTooltip>
</>
@ -310,7 +308,7 @@ const PillButton = (props: PillButtonProps) => {
{props.editing && warning && (
<>
<CircleDiv
data-tooltip-id={`circle-div-${props.item.description.name}`}
data-tooltip-id={`circle-div-${props.item.name}`}
className="z-10"
>
<ExclamationTriangleIcon
@ -319,7 +317,7 @@ const PillButton = (props: PillButtonProps) => {
strokeWidth={2}
/>
</CircleDiv>
<StyledTooltip id={`circle-div-${props.item.description.name}`}>
<StyledTooltip id={`circle-div-${props.item.name}`}>
{warning}
</StyledTooltip>
</>

View file

@ -4,7 +4,7 @@ import styled from "styled-components";
import { getFontSize, getMarkdownLanguageTagForFile } from "../../util";
import FileIcon from "../FileIcon";
import HeaderButtonWithText from "../HeaderButtonWithText";
import { ContextItem } from "../../schema/ContextItem";
import { ContextItem } from "../../../../core/llm/types";
import { postToIde } from "../../util/ide";
import {
ArrowUpLeftIcon,
@ -63,23 +63,23 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
<PreviewMarkdownHeader
className="flex justify-between cursor-pointer"
onClick={() => {
if (props.item.description.id.provider_title === "file") {
if (props.item.id.providerTitle === "file") {
postToIde("showFile", {
filepath: props.item.description.description,
filepath: props.item.description,
});
} else if (props.item.description.id.provider_title === "code") {
const lines = props.item.description.name
} else if (props.item.id.providerTitle === "code") {
const lines = props.item.name
.split("(")[1]
.split(")")[0]
.split("-");
postToIde("showLines", {
filepath: props.item.description.description,
filepath: props.item.description,
start: parseInt(lines[0]) - 1,
end: parseInt(lines[1]) - 1,
});
} else {
postToIde("showVirtualFile", {
name: props.item.description.name,
name: props.item.name,
content: props.item.content,
});
}
@ -89,9 +89,9 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
<FileIcon
height="20px"
width="20px"
filename={props.item.description.name}
filename={props.item.name}
></FileIcon>
{props.item.description.name}
{props.item.name}
</div>
<div className="flex items-center">
<HeaderButtonWithText
@ -99,7 +99,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
onClick={() => {
dispatch(
deleteContextWithIds({
ids: [props.item.description.id],
ids: [props.item.id],
index: props.index,
})
);
@ -112,7 +112,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
props.item.description.description
props.item.description
)}\n${props.item.content}\n\`\`\``}
maxHeight={200}
/>

View file

@ -44,9 +44,9 @@ function LinkableCode(props: any) {
// Check if matches any context item's filepath
let link = false;
for (let contextItem of contextItems) {
if (contextItem.description.description.endsWith(filename)) {
if (contextItem.description.endsWith(filename)) {
link = true;
setFilepath(contextItem.description.description);
setFilepath(contextItem.description);
break;
}
}

View file

@ -275,7 +275,7 @@ function ModelSelect(props: {}) {
>
<StyledListboxOptions>
{options.map((option, idx) => (
<ListBoxOption option={option} idx={idx} />
<ListBoxOption option={option} idx={idx} key={idx} />
))}
<i className="text-xs ml-2" style={{ color: lightGray }}>
{getMetaKeyLabel()}' to toggle

View file

@ -1,61 +0,0 @@
import React, { useCallback, useEffect, useState } from "react";
import ContinueGUIClientProtocol from "../client/ContinueGUIClientProtocol";
import { useSelector } from "react-redux";
import { RootStore } from "../redux/store";
function useContinueGUIProtocol(useVscodeMessagePassing: boolean = true) {
// if (localStorage.getItem("ide") === "jetbrains") {
// useVscodeMessagePassing = false;
// }
const [client, setClient] = useState<ContinueGUIClientProtocol | undefined>(
undefined
);
const sessionState = useSelector((store: RootStore) => store.sessionState);
const getSessionState = () => {
return {
history: sessionState.history,
context_items: sessionState.context_items,
};
};
useEffect(() => {
if (!client) return;
client.getSessionState = getSessionState;
}, [sessionState]);
const load = () => {
const windowAny = window as any;
const serverUrl = windowAny.serverUrl;
const windowId = windowAny.windowId;
if (serverUrl === undefined || serverUrl === null) return false;
if (windowId === undefined || windowId === null) return false;
const newClient = new ContinueGUIClientProtocol(
serverUrl,
useVscodeMessagePassing,
getSessionState
);
newClient.onConnected(() => {
setClient(newClient);
});
return true;
};
useEffect(() => {
// Because sometimes window.... aren't set immediately, but they can't be used as useEffect dependencies
const interval = setInterval(() => {
if (load()) {
clearInterval(interval);
}
}, 200);
return () => clearInterval(interval);
}, []);
return client;
}
export default useContinueGUIProtocol;

View file

@ -1,5 +1,4 @@
import { Dispatch } from "@reduxjs/toolkit";
import ContinueGUIClientProtocol from "../client/ContinueGUIClientProtocol";
import { useEffect, useState } from "react";
import {
addContextItemAtIndex,
@ -20,10 +19,7 @@ import {
} from "../redux/slices/serverStateReducer";
import { setVscMachineId } from "../redux/slices/configSlice";
function useSetup(
client: ContinueGUIClientProtocol | undefined,
dispatch: Dispatch<any>
) {
function useSetup(dispatch: Dispatch<any>) {
const serverUrl = (window as any).serverUrl;
const active = useSelector((store: RootStore) => store.sessionState.active);
const title = useSelector((store: RootStore) => store.sessionState.title);
@ -39,59 +35,6 @@ function useSetup(
postToIde("onLoad", {});
}, []);
useEffect(() => {
(async () => {
if (
client &&
!requestedTitle &&
!active &&
title === "New Session" &&
history &&
history.filter((step) => !step?.hide).length >= 2
) {
setRequestedTitle(true);
const title = await client.getSessionTitle(history);
dispatch(setTitle(title));
}
})();
}, [active, history, title, client, requestedTitle]);
// Setup requiring client
useEffect(() => {
if (!client) return;
// Listen for updates to the session state
client.onSessionUpdate((update) => {
dispatch(processSessionUpdate(update));
});
client.onIndexingProgress((progress) => {
dispatch(setIndexingProgress(progress));
});
client.onAddContextItem((item, index) => {
dispatch(addContextItemAtIndex({ item, index }));
});
client.onConfigUpdate((config) => {
dispatch(setConfig(config));
});
fetch(`${serverUrl}/slash_commands`).then(async (resp) => {
if (resp.status !== 200) return;
const sc = await resp.json();
dispatch(setSlashCommands(sc));
});
fetch(`${serverUrl}/context_providers`).then(async (resp) => {
if (resp.status !== 200) return;
const cp = await resp.json();
dispatch(setContextProviders(cp));
});
client.getConfig().then((config) => {
dispatch(setConfig(config));
});
}, [client]);
// IDE event listeners
useEffect(() => {
const eventListener = (event: any) => {
@ -118,13 +61,12 @@ function useSetup(
dispatch(setServerStatusMessage(event.data.message));
break;
case "stopSession":
client?.stopSession();
break;
}
};
window.addEventListener("message", eventListener);
return () => window.removeEventListener("message", eventListener);
}, [client]);
}, []);
// Save theme colors to local storage
useEffect(() => {

View file

@ -1,7 +1,6 @@
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { newSession } from "../redux/slices/sessionStateReducer";
import useContinueGUIProtocol from "../hooks/useContinueClient";
import ContinueButton from "../components/mainInput/ContinueButton";
import { vscBackground } from "../components";
@ -9,7 +8,6 @@ export default function ErrorPage() {
const error: any = useRouteError();
console.error(error);
const dispatch = useDispatch();
const client = useContinueGUIProtocol(false);
const navigate = useNavigate();
return (
@ -29,7 +27,6 @@ export default function ErrorPage() {
disabled={false}
showStop={false}
onClick={() => {
client?.stopSession();
dispatch(newSession());
localStorage.removeItem("persist:root");
navigate("/");

View file

@ -47,16 +47,6 @@ import FTCDialog from "../components/dialogs/FTCDialog";
import HeaderButtonWithText from "../components/HeaderButtonWithText";
import { useNavigate } from "react-router-dom";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
import {
addContextItemAtIndex,
clearContextItems,
deleteAtIndex,
newSession,
setActive,
setHistory,
setTitle,
} from "../redux/slices/sessionStateReducer";
import { StepDescription } from "../schema/SessionState";
import FreeTrial from "../../../core/llm/llms/FreeTrial";
import { constructMessages } from "../../../core/llm/constructMessages";
import {
@ -64,7 +54,13 @@ import {
ChatHistoryItem,
ChatMessage,
} from "../../../core/llm/types";
import { streamUpdate, submitMessage } from "../redux/slices/stateSlice";
import {
resubmitAtIndex,
streamUpdate,
submitMessage,
newSession,
setInactive,
} from "../redux/slices/stateSlice";
const TopGuiDiv = styled.div`
overflow-y: scroll;
@ -243,7 +239,7 @@ function GUI(props: GUIProps) {
!e.shiftKey
) {
client?.stopSession();
dispatch(setActive(false));
dispatch(setInactive());
} else if (e.key === "Escape") {
dispatch(setBottomMessage(undefined));
}
@ -283,7 +279,6 @@ function GUI(props: GUIProps) {
const message: ChatMessage = {
role: "user",
content: input,
summary: input,
};
const historyItem: ChatHistoryItem = {
message,
@ -413,8 +408,9 @@ function GUI(props: GUIProps) {
}, [sendInput]);
const onMainTextInput = (event?: any) => {
console.log("onMainTextInput");
dispatch(setTakenActionTrue(null));
if (mainTextInputRef.current && client) {
if (mainTextInputRef.current) {
let input = (mainTextInputRef.current as any).inputValue;
if (input.trim() === "") return;
@ -443,18 +439,15 @@ function GUI(props: GUIProps) {
const isLastUserInput = useCallback(
(index: number): boolean => {
let foundLaterUserInput = false;
for (let i = index + 1; i < sessionState.history.length; i++) {
if (
sessionState.history[i].name === "User Input" &&
sessionState.history[i].hide === false
) {
for (let i = index + 1; i < state.history.length; i++) {
if (state.history[i].message.role === "user") {
foundLaterUserInput = true;
break;
}
}
return !foundLaterUserInput;
},
[sessionState.history]
[state.history]
);
const getStepsInUserInputGroup = useCallback(
@ -492,34 +485,6 @@ function GUI(props: GUIProps) {
[sessionState.history]
);
const onToggleAtIndex = useCallback(
(index: number) => {
// Check if all steps after the User Input are closed
const groupIndices = getStepsInUserInputGroup(index);
const userInputIndex = groupIndices[0];
setStepsOpen((prev) => {
const nextStepsOpen = [...prev];
nextStepsOpen[index] = !nextStepsOpen[index];
const allStepsAfterUserInputAreClosed = !groupIndices.some(
(i, j) => j > 0 && nextStepsOpen[i]
);
if (allStepsAfterUserInputAreClosed) {
nextStepsOpen[userInputIndex] = false;
} else {
const allStepsAfterUserInputAreOpen = !groupIndices.some(
(i, j) => j > 0 && !nextStepsOpen[i]
);
if (allStepsAfterUserInputAreOpen) {
nextStepsOpen[userInputIndex] = true;
}
}
return nextStepsOpen;
});
},
[getStepsInUserInputGroup]
);
useEffect(() => {
if (sessionTitle) {
setSessionTitleInput(sessionTitle);
@ -557,66 +522,20 @@ function GUI(props: GUIProps) {
value={item.message.content}
active={active && isLastUserInput(index)}
onEnter={(e, value) => {
if (value && client) {
client?.stopSession();
const newHistory = [
...sessionState.history.slice(0, index),
{
name: "User Input",
description: value,
observations: [],
logs: [],
step_type: "UserInputStep",
params: {
user_input: value,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
];
dispatch(setHistory(newHistory));
dispatch(setActive(true));
const state = {
history: newHistory,
context_items: sessionState.context_items,
};
dispatch(clearContextItems());
if (value) {
dispatch(resubmitAtIndex({ index, content: value }));
client.runFromState(state);
// TODO: Call the LLM
}
e?.stopPropagation();
e?.preventDefault();
}}
groupIndices={getStepsInUserInputGroup(index)}
onToggle={(isOpen: boolean) => {
// Collapse all steps in the section
setStepsOpen((prev) => {
const nextStepsOpen = [...prev];
getStepsInUserInputGroup(index).forEach((i) => {
nextStepsOpen[i] = isOpen;
});
return nextStepsOpen;
});
}}
onToggleAll={(isOpen: boolean) => {
// Collapse _all_ steps
setStepsOpen((prev) => {
return prev.map((_) => isOpen);
});
}}
isToggleOpen={
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
index={index}
onDelete={() => {
// Delete the input and all steps until the next user input
getStepsInUserInputGroup(index).forEach((i) => {
dispatch(deleteAtIndex(i));
});
}}
/>
) : (
<TimelineItem
@ -641,15 +560,13 @@ function GUI(props: GUIProps) {
: true
: stepsOpen[index]!
}
onToggle={() => onToggleAtIndex(index)}
onToggle={() => {}}
>
{false ? ( // Most of these falses were previously (step.error)
<ErrorStepContainer
onClose={() => onToggleAtIndex(index)}
onClose={() => {}}
error={undefined}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
onDelete={() => {}}
/>
) : (
<StepContainer
@ -672,9 +589,7 @@ function GUI(props: GUIProps) {
onRetry={() => {
client?.retryAtIndex(index);
}}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
onDelete={() => {}}
noUserInputParent={
getStepsInUserInputGroup(index).length === 0
}
@ -694,13 +609,14 @@ function GUI(props: GUIProps) {
<StopButton
onClick={() => {
client?.stopSession();
dispatch(setActive(false));
dispatch(setInactive());
}}
>
⌘ ⌫ Cancel
</StopButton>
) : (
<ComboBox
active={false}
isMainInput={true}
ref={mainTextInputRef}
onEnter={(e, _) => {

View file

@ -1,32 +1,30 @@
import { createSlice } from "@reduxjs/toolkit";
import { StepDescription } from "../../schema/SessionState";
import { SessionUpdate } from "../../schema/SessionUpdate";
import { ContextItem } from "../../schema/ContextItem";
import { ContextItem } from "../../../../core/llm/types";
import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
import { v4 } from "uuid";
import { ContextItemId } from "../../schema/ContextItemId";
import { ContextItemId } from "../../../../core/llm/types";
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: {
description: "test.py",
name: "test.py",
id: {
item_id: "test.py",
provider_title: "file",
},
description: "test.py",
name: "test.py",
id: {
itemId: "test.py",
providerTitle: "file",
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: {
description: "test.js",
name: "test.js",
id: {
item_id: "test.js",
provider_title: "file",
},
description: "test.js",
name: "test.js",
id: {
itemId: "test.js",
providerTitle: "file",
},
},
];
@ -265,13 +263,10 @@ export const sessionStateSlice = createSlice({
// Merge if there is overlap
for (let i = 0; i < contextItems.length; i++) {
const item = contextItems[i];
if (
item.description.description ===
payload.rangeInFileWithContents.filepath
) {
if (item.description === payload.rangeInFileWithContents.filepath) {
let newStart = payload.rangeInFileWithContents.range.start.line;
let newEnd = payload.rangeInFileWithContents.range.end.line;
let [oldStart, oldEnd] = item.description.name
let [oldStart, oldEnd] = item.name
.split("(")[1]
.split(")")[0]
.split("-")
@ -289,10 +284,7 @@ export const sessionStateSlice = createSlice({
contextItems[i] = {
...item,
description: {
...item.description,
name: `${base} (${startLine + 1}-${endLine + 1})`,
},
name: `${base} (${startLine + 1}-${endLine + 1})`,
content: payload.rangeInFileWithContents.contents,
editing: true,
editable: true,
@ -305,13 +297,11 @@ export const sessionStateSlice = createSlice({
payload.rangeInFileWithContents.range.start.line + 1
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
contextItems.push({
description: {
name: `${base} ${lineNums}`,
description: payload.rangeInFileWithContents.filepath,
id: {
provider_title: "code",
item_id: v4(),
},
name: `${base} ${lineNums}`,
description: payload.rangeInFileWithContents.filepath,
id: {
providerTitle: "code",
itemId: v4(),
},
content: payload.rangeInFileWithContents.contents,
editing: true,
@ -326,15 +316,13 @@ export const sessionStateSlice = createSlice({
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
const ids = payload.ids.map((id) => `${id.provider_title}-${id.item_id}`);
const ids = payload.ids.map((id) => `${id.providerTitle}-${id.itemId}`);
if (typeof payload.index === "undefined") {
return {
...state,
context_items: state.context_items.filter(
(item) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
)
!ids.includes(`${item.id.providerTitle}-${item.id.itemId}`)
),
};
} else {
@ -349,7 +337,7 @@ export const sessionStateSlice = createSlice({
context_items: (step.params?.context_items as any).filter(
(item: ContextItem) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
`${item.id.providerTitle}-${item.id.itemId}`
)
),
},
@ -372,7 +360,7 @@ export const sessionStateSlice = createSlice({
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
const ids = payload.ids.map((id) => id.item_id);
const ids = payload.ids.map((id) => id.itemId);
if (typeof payload.index === "undefined") {
return {
@ -380,7 +368,7 @@ export const sessionStateSlice = createSlice({
context_items: state.context_items.map((item) => {
return {
...item,
editing: ids.includes(item.description.id.item_id),
editing: ids.includes(item.id.itemId),
};
}),
};
@ -397,7 +385,7 @@ export const sessionStateSlice = createSlice({
(item: ContextItem) => {
return {
...item,
editing: ids.includes(item.description.id.item_id),
editing: ids.includes(item.id.itemId),
};
}
),

View file

@ -1,5 +1,6 @@
import { createSlice } from "@reduxjs/toolkit";
import { RootStore } from "../store";
import { ContextItemId } from "../../../../core/llm/types";
const initialState: RootStore["state"] = {
history: [],
@ -13,31 +14,56 @@ export const stateSlice = createSlice({
reducers: {
addContextItemAtIndex: (state, action) => {
if (action.payload.index < state.history.length) {
state.history[action.payload.index].contextItems.push(
action.payload.contextItem
);
return {
...state,
history: state.history.map((historyItem, i) => {
if (i === action.payload.index) {
return {
...historyItem,
contextItems: [
...historyItem.contextItems,
action.payload.contextItem,
],
};
}
return historyItem;
}),
};
}
},
appendMessage: (state, action) => {
state.history.push(action.payload);
return {
...state,
history: [...state.history, action.payload],
};
},
addContextItem: (state, action) => {
state.contextItems.push(action.payload);
return {
...state,
contextItems: [...state.contextItems, action.payload],
};
},
resubmitAtIndex: (state, action) => {
if (action.payload.index < state.history.length) {
state.history[action.payload.index].message.content =
action.payload.content;
state.history[action.payload.index].message.summary =
action.payload.summary;
// Cut off history after the resubmitted message
state.history = state.history.slice(0, action.payload.index + 1);
state.contextItems = [];
}
},
submitMessage: (state, action) => {
state.history.push({
message: {
role: "user",
content: action.payload,
summary: action.payload,
},
message: action.payload,
contextItems: state.contextItems,
});
state.history.push({
message: {
role: "assistant",
content: "",
summary: "",
},
contextItems: [],
});
@ -53,6 +79,45 @@ export const stateSlice = createSlice({
action.payload;
}
},
newSession: (state) => {
state.history = [];
state.contextItems = [];
state.active = false;
},
deleteContextWithIds: (
state,
{
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
const ids = payload.ids.map((id) => `${id.providerTitle}-${id.itemId}`);
if (typeof payload.index === "undefined") {
return {
...state,
contextItems: state.contextItems.filter(
(item) =>
!ids.includes(`${item.id.providerTitle}-${item.id.itemId}`)
),
};
} else {
return {
...state,
history: state.history.map((historyItem, i) => {
if (i === payload.index) {
return {
...historyItem,
contextItems: historyItem.contextItems.filter(
(item) =>
!ids.includes(`${item.id.providerTitle}-${item.id.itemId}`)
),
};
}
return historyItem;
}),
};
}
},
},
});
@ -63,5 +128,8 @@ export const {
submitMessage,
setInactive,
streamUpdate,
newSession,
deleteContextWithIds,
resubmitAtIndex,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -4,7 +4,7 @@ declare const vscode: any;
function _postToIde(type: string, data: any) {
if (typeof vscode === "undefined") {
if (localStorage.getItem("ide") === "jetbrains" || true) {
if (localStorage.getItem("ide") === "jetbrains") {
if ((window as any).postIntellijMessage === undefined) {
console.log(
"Unable to send message: postIntellijMessage is undefined. ",