🔥 removing GUI client code

This commit is contained in:
Nate Sesti 2023-12-09 10:51:04 -08:00
parent 5168eaf4a4
commit c4371c2121
34 changed files with 610 additions and 1870 deletions

15
core/types.d.ts vendored Normal file
View file

@ -0,0 +1,15 @@
import { ChatHistory } from "./llm/types";
export interface PersistedSessionInfo {
history: ChatHistory;
title: string;
workspaceDirectory: string;
sessionId: string;
}
export interface SessionInfo {
sessionId: string;
title: string;
dateCreated: string;
workspaceDirectory: string;
}

View file

@ -69,10 +69,12 @@
"@anthropic-ai/sdk": "^0.10.2",
"dotenv": "^16.3.1",
"openai": "^4.20.1",
"replicate": "^0.23.0"
"replicate": "^0.23.0",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/jest": "^29.5.11",
"@types/uuid": "^9.0.7",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
}
@ -10903,11 +10905,13 @@
"requires": {
"@anthropic-ai/sdk": "^0.10.2",
"@types/jest": "^29.5.11",
"@types/uuid": "^9.0.7",
"dotenv": "^16.3.1",
"jest": "^29.7.0",
"openai": "^4.20.1",
"replicate": "^0.23.0",
"ts-jest": "^29.1.1"
"ts-jest": "^29.1.1",
"uuid": "^9.0.1"
}
},
"core-util-is": {

View file

@ -1,10 +1,10 @@
import * as vscode from "vscode";
import { getContinueServerUrl } from "./bridge";
import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
import { ideProtocolClient, windowId } from "./activation/activate";
import * as io from "socket.io-client";
import * as vscode from "vscode";
import { FileEdit } from "../schema/FileEdit";
import { ideProtocolClient, windowId } from "./activation/activate";
import { getContinueServerUrl } from "./bridge";
import VsCodeIde from "./ideProtocol";
import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
let sockets: { [url: string]: io.Socket | undefined } = {};
@ -183,10 +183,6 @@ export function getSidebarContent(
);
break;
}
case "showVirtualFile": {
ideProtocolClient.showVirtualFile(data.name, data.content);
break;
}
case "toggleDevTools": {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");

View file

@ -1,24 +1,9 @@
import {
getContinueGlobalPath,
getSessionFilePath,
getSessionsListPath,
} from "./activation/environmentSetup";
import { ChatHistory } from "core/llm/types";
import * as fs from "fs";
export interface PersistedSessionInfo {
history: ChatHistory;
title: string;
workspaceDirectory: string;
sessionId: string;
}
export interface SessionInfo {
sessionId: string;
title: string;
dateCreated: string;
workspaceDirectory: string;
}
import { PersistedSessionInfo, SessionInfo } from "core/types";
class HistoryManager {
list(): PersistedSessionInfo[] {

8
gui/package-lock.json generated
View file

@ -60,10 +60,12 @@
"@anthropic-ai/sdk": "^0.10.2",
"dotenv": "^16.3.1",
"openai": "^4.20.1",
"replicate": "^0.23.0"
"replicate": "^0.23.0",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/jest": "^29.5.11",
"@types/uuid": "^9.0.7",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
}
@ -6440,11 +6442,13 @@
"requires": {
"@anthropic-ai/sdk": "^0.10.2",
"@types/jest": "^29.5.11",
"@types/uuid": "^9.0.7",
"dotenv": "^16.3.1",
"jest": "^29.7.0",
"openai": "^4.20.1",
"replicate": "^0.23.0",
"ts-jest": "^29.1.1"
"ts-jest": "^29.1.1",
"uuid": "^9.0.1"
}
},
"cross-fetch": {

View file

@ -2,8 +2,6 @@ import GUI from "./pages/gui";
import History from "./pages/history";
import Help from "./pages/help";
import Layout from "./components/Layout";
import { createContext } from "react";
import ContinueGUIClientProtocol from "./client/ContinueGUIClientProtocol";
import { useDispatch } from "react-redux";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
import ErrorPage from "./pages/error";
@ -65,20 +63,12 @@ const router = createMemoryRouter([
},
]);
export const GUIClientContext = createContext<
ContinueGUIClientProtocol | undefined
>(undefined);
function App() {
const dispatch = useDispatch();
useSetup(dispatch);
return (
// <GUIClientContext.Provider>
<RouterProvider router={router} />
// </GUIClientContext.Provider>
);
return <RouterProvider router={router} />;
}
export default App;

View file

@ -1,62 +0,0 @@
import { ContextItem } from "../schema/ContextItem";
import { ContextItemId } from "../schema/ContextItemId";
import { ContinueConfig } from "../schema/ContinueConfig";
import { ModelDescription } from "../schema/SerializedContinueConfig";
abstract class AbstractContinueGUIClientProtocol {
abstract sendMainInput(input: string): void;
abstract reverseToIndex(index: number): void;
abstract sendRefinementInput(input: string, index: number): void;
abstract sendStepUserInput(input: string, index: number): void;
abstract onStateUpdate(state: any): void;
abstract onAvailableSlashCommands(
callback: (commands: { name: string; description: string }[]) => void
): void;
abstract sendClear(): void;
abstract retryAtIndex(index: number): void;
abstract deleteContextWithIds(ids: ContextItemId[], index?: number): void;
abstract setEditingAtIds(ids: string[]): void;
abstract toggleAddingHighlightedCode(): void;
abstract selectContextItem(id: string, query: string): void;
abstract getContextItem(id: string, query: string): Promise<ContextItem>;
abstract selectContextItemAtIndex(
id: string,
query: string,
index: number
): void;
abstract loadSession(session_id?: string): void;
abstract editStepAtIndex(userInput: string, index: number): void;
abstract setSystemMessage(message: string): void;
abstract setTemperature(temperature: number): void;
abstract addModelForRole(role: string, model: ModelDescription): void;
abstract saveContextGroup(title: string, contextItems: ContextItem[]): void;
abstract selectContextGroup(id: string): void;
abstract deleteContextGroup(id: string): void;
abstract onConfigUpdate(callback: (config: ContinueConfig) => void);
abstract deleteModelAtIndex(index: number): void;
}
export default AbstractContinueGUIClientProtocol;

View file

@ -1,295 +0,0 @@
import { SessionFullState } from "../redux/slices/sessionStateReducer";
import { ContextItem } from "../schema/ContextItem";
import { ContextItemId } from "../schema/ContextItemId";
import { ContinueConfig } from "../schema/ContinueConfig";
import { ModelDescription } from "../schema/SerializedContinueConfig";
import { SessionState, StepDescription } from "../schema/SessionState";
import { SessionUpdate } from "../schema/SessionUpdate";
import AbstractContinueGUIClientProtocol from "./AbstractContinueGUIClientProtocol";
import { Messenger } from "./messenger";
import { VscodeMessenger } from "./messenger/VscodeMessenger";
import { SocketIOMessenger } from "./messenger/SocketIOMessenger";
class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
messenger?: Messenger;
serverUrl: string;
useVscodeMessagePassing: boolean;
getSessionState: () => SessionState;
onStateUpdateCallbacks: ((state: any) => void)[] = [];
constructor(
serverUrl: string,
useVscodeMessagePassing: boolean,
getSesionState: () => SessionState
) {
super();
this.serverUrl = serverUrl;
this.useVscodeMessagePassing = useVscodeMessagePassing;
this.getSessionState = getSesionState;
this.serverUrl = serverUrl;
this.useVscodeMessagePassing = useVscodeMessagePassing;
this.messenger = useVscodeMessagePassing
? new VscodeMessenger(serverUrl)
: new SocketIOMessenger(serverUrl);
this.messenger.onClose(() => {
console.log("GUI Connection closed: ", serverUrl);
});
this.messenger.onError((error) => {
console.log("GUI Connection error: ", error);
});
this.messenger.onOpen(() => {
console.log("GUI Connection opened: ", serverUrl);
});
this.messenger.onMessage((messageType, data, acknowledge) => {
this.handleMessage(messageType, data, acknowledge);
});
}
onConnected(callback: () => void) {
this.messenger?.onOpen(callback);
}
handleMessage(
messageType: string,
data: any,
acknowledge: (data: any) => void
) {
switch (messageType) {
case "state_update":
if (data.state) {
for (const callback of this.onStateUpdateCallbacks) {
callback(data.state);
}
}
break;
case "get_session_state":
const sessionState = this.getSessionState();
acknowledge({
history: sessionState.history,
context_items: sessionState.context_items,
});
break;
default:
break;
}
}
loadSession(session_id?: string): void {
this.messenger?.send("load_session", { session_id });
}
sendMainInput(input: string) {
this.messenger?.send("main_input", { input });
}
runFromState(sessionState: SessionState) {
this.messenger?.send("run_from_state", { state: sessionState });
}
async getSessionTitle(history: StepDescription[]): Promise<string> {
return await this.messenger?.sendAndReceive("get_session_title", {
history,
});
}
reverseToIndex(index: number) {
this.messenger?.send("reverse_to_index", { index });
}
sendRefinementInput(input: string, index: number) {
this.messenger?.send("refinement_input", { input, index });
}
sendStepUserInput(input: string, index: number) {
this.messenger?.send("step_user_input", { input, index });
}
onStateUpdate(callback: (state: any) => void) {
this.messenger?.onMessageType("state_update", (data: any) => {
if (data.state) {
callback(data.state);
}
});
this.onStateUpdateCallbacks.push(callback);
}
onSessionUpdate(callback: (update: SessionUpdate) => void) {
this.messenger?.onMessageType("session_update", (data: SessionUpdate) => {
callback(data);
});
}
onIndexingProgress(callback: (progress: number) => void) {
this.messenger?.onMessageType("indexing_progress", (data: any) => {
callback(data.progress);
});
}
onConfigUpdate(callback: (config: ContinueConfig) => void) {
this.messenger?.onMessageType("config_update", (data: any) => {
callback(data);
});
}
getConfig(): Promise<ContinueConfig> {
return this.messenger?.sendAndReceive("get_config", {});
}
onAddContextItem(callback: (item: ContextItem, index: number) => void) {
this.messenger?.onMessageType("add_context_item_at_index", (data: any) => {
callback(data.item, data.index);
});
}
onAvailableSlashCommands(
callback: (commands: { name: string; description: string }[]) => void
) {
this.messenger?.onMessageType("available_slash_commands", (data: any) => {
if (data.commands) {
callback(data.commands);
}
});
}
stopSession() {
this.messenger?.send("stop_session", {});
}
sendClear() {
this.messenger?.send("clear_history", {});
}
retryAtIndex(index: number) {
this.messenger?.send("retry_at_index", { index });
}
deleteContextWithIds(ids: ContextItemId[], index?: number) {
this.messenger?.send("delete_context_with_ids", {
ids: ids.map((id) => `${id.provider_title}-${id.item_id}`),
index,
});
}
setEditingAtIds(ids: string[]) {
this.messenger?.send("set_editing_at_ids", { ids });
}
toggleAddingHighlightedCode(): void {
this.messenger?.send("toggle_adding_highlighted_code", {});
}
selectContextItem(id: string, query: string): void {
this.messenger?.send("select_context_item", { id, query });
}
async getContextItem(id: string, query: string): Promise<ContextItem> {
return await this.messenger?.sendAndReceive("get_context_item", {
id,
query,
});
}
selectContextItemAtIndex(id: string, query: string, index: number): void {
this.messenger?.send("select_context_item_at_index", {
id,
query,
index,
});
}
editStepAtIndex(userInput: string, index: number): void {
this.messenger?.send("edit_step_at_index", {
user_input: userInput,
index,
});
}
setSystemMessage(system_message: string): void {
this.messenger?.send("set_system_message", { system_message });
}
setTemperature(temperature: number): void {
this.messenger?.send("set_temperature", { temperature });
}
addModelForRole(role: string, model: ModelDescription): void {
this.messenger?.send("add_model_for_role", { role, model });
}
setModelForRoleFromTitle(role: string, title: string): void {
this.messenger?.send("set_model_for_role_from_title", { role, title });
}
saveContextGroup(title: string, contextItems: ContextItem[]): void {
this.messenger?.send("save_context_group", {
context_items: contextItems,
title,
});
}
selectContextGroup(id: string): void {
this.messenger?.send("select_context_group", { id });
}
deleteContextGroup(id: string): void {
this.messenger?.send("delete_context_group", { id });
}
deleteModelAtIndex(index: number) {
this.messenger?.send("delete_model_at_index", { index });
}
async persistSession(
currentSession: SessionFullState,
workspaceDirectory: string
) {
// Save current session
// 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) {
await fetch(`${this.serverUrl}/sessions/delete`, {
method: "POST",
body: JSON.stringify({ session_id }),
headers: {
"Content-Type": "application/json",
},
});
}
async sendPromptCompletionFeedback(
type: string,
prompt: string,
completion: string,
feedback: boolean
) {
await fetch(`${this.serverUrl}/feedback`, {
method: "POST",
body: JSON.stringify({ type, prompt, completion, feedback }),
headers: {
"Content-Type": "application/json",
},
});
}
}
export default ContinueGUIClientProtocol;

View file

@ -1,207 +0,0 @@
import socketIOClient, { Socket } from "socket.io-client";
import { v4 } from "uuid";
import { Messenger } from ".";
export class SocketIOMessenger extends Messenger {
private socket: Socket;
constructor(endpoint: string) {
super();
console.log(
"Connecting to socket.io endpoint: ",
endpoint,
(window as any).windowId
);
this.socket = socketIOClient(
`${endpoint}?window_id=${(window as any).windowId}`,
{
path: "/gui/socket.io",
transports: ["websocket", "polling", "flashsocket"],
reconnectionDelayMax: 1000,
}
);
}
send(messageType: string, data: object): void {
this.socket.emit("message", {
message_type: messageType,
data,
message_id: v4(),
});
}
ackWithMessageMetadata(
ack: (data: any) => void,
messageId: string,
messageType: string
): (data: any) => void {
return (data: any) => {
ack({ message_id: messageId, message_type: messageType, data });
};
}
onMessageType(
messageType: string,
callback: (data: object, acknowledge?: (data: any) => void) => void
): void {
this.socket.on("message", ({ message_type, data }, ack) => {
if (messageType === message_type) {
callback(data, this.ackWithMessageMetadata(ack, "lolidk", messageType));
}
});
}
onMessage(
callback: (
messageType: string,
data: any,
acknowledge?: (data: any) => void
) => void
): void {
this.socket.on("message", ({ message_type, data }, ack) => {
callback(
message_type,
data,
this.ackWithMessageMetadata(ack, "lolidk", message_type)
);
});
}
onOpen(callback: () => void): void {
this.socket.on("connect", callback);
}
onClose(callback: () => void): void {
this.socket.on("disconnect", callback);
}
async sendAndReceive(messageType: string, data: any): Promise<any> {
return new Promise((resolve, reject) => {
this.socket.emit(
"message",
{ message_type: messageType, data, message_id: v4() },
(response: any) => {
if (response && response.error) {
reject(response.error);
} else {
resolve(response);
}
}
);
});
}
onError(callback: (error: any) => void): void {
this.socket.on("error", callback);
}
close(): void {
this.socket.disconnect();
}
}
export class WebsocketMessenger extends Messenger {
websocket: WebSocket;
private onMessageListeners: {
[messageType: string]: ((data: object) => void)[];
} = {};
private onErrorListeners: ((error: any) => void)[] = [];
private onOpenListeners: (() => void)[] = [];
private onCloseListeners: (() => void)[] = [];
private serverUrl: string;
_newWebsocket(): WebSocket {
const newWebsocket = new WebSocket(this.serverUrl);
for (const listener of this.onOpenListeners) {
this.onOpen(listener);
}
for (const listener of this.onCloseListeners) {
this.onClose(listener);
}
for (const messageType in this.onMessageListeners) {
for (const listener of this.onMessageListeners[messageType]) {
this.onMessageType(messageType, listener);
}
}
for (const listener of this.onErrorListeners) {
this.onError(listener);
}
return newWebsocket;
}
constructor(serverUrl: string) {
super();
this.serverUrl = serverUrl;
this.websocket = this._newWebsocket();
}
send(messageType: string, data: object) {
const payload = JSON.stringify({ messageType, data });
if (this.websocket.readyState === this.websocket.OPEN) {
this.websocket.send(payload);
} else {
if (this.websocket.readyState !== this.websocket.CONNECTING) {
this.websocket = this._newWebsocket();
}
this.websocket.addEventListener("open", () => {
this.websocket.send(payload);
});
}
}
sendAndReceive(messageType: string, data: any): Promise<any> {
return new Promise((resolve, reject) => {
const eventListener = (data: any) => {
// THIS ISN"T GETTING CALLED
resolve(data);
this.websocket.removeEventListener("message", eventListener);
};
this.websocket.addEventListener("message", (event: any) => {
const msg = JSON.parse(event.data);
if (msg.messageType === messageType) {
eventListener(msg.data);
}
});
this.send(messageType, data);
});
}
onMessageType(messageType: string, callback: (data: any) => void): void {
this.websocket.addEventListener("message", (event: any) => {
const msg = JSON.parse(event.data);
if (msg.messageType === messageType) {
callback(msg.data);
}
});
this.onMessageListeners[messageType] = [
...(this.onMessageListeners[messageType] || []),
callback,
];
}
onMessage(callback: (messageType: string, data: any) => void): void {
this.websocket.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
callback(msg.messageType, msg.data);
});
}
onOpen(callback: () => void): void {
this.websocket.addEventListener("open", callback);
this.onOpenListeners.push(callback);
}
onClose(callback: () => void): void {
this.websocket.addEventListener("close", callback);
this.onCloseListeners.push(callback);
}
onError(callback: (error: any) => void): void {
this.websocket.addEventListener("error", callback);
this.onErrorListeners.push(callback);
}
close(): void {
this.websocket.close();
}
}

View file

@ -1,82 +0,0 @@
import { postToIde } from "../../util/ide";
import { Messenger } from ".";
export class VscodeMessenger extends Messenger {
serverUrl: string;
constructor(serverUrl: string) {
super();
this.serverUrl = serverUrl;
postToIde("websocketForwardingOpen", { url: this.serverUrl });
}
send(messageType: string, data: object) {
postToIde("websocketForwardingMessage", {
message: { messageType, data },
url: this.serverUrl,
});
}
onMessageType(messageType: string, callback: (data: object) => void): void {
window.addEventListener("message", (event: any) => {
if (event.data.type === "websocketForwardingMessage") {
const data = JSON.parse(event.data.data);
if (data.messageType === messageType) {
callback(data.data);
}
}
});
}
onMessage(callback: (messageType: string, data: any) => void): void {
window.addEventListener("message", (event: any) => {
if (event.data.type === "websocketForwardingMessage") {
const data = JSON.parse(event.data.data);
callback(data.messageType, data.data);
}
});
}
onError(callback: (error: any) => void): void {
window.addEventListener("message", (event: any) => {
if (event.data.type === "websocketForwardingError") {
callback(event.data.error);
}
});
}
sendAndReceive(messageType: string, data: any): Promise<any> {
return new Promise((resolve) => {
const handler = (event: any) => {
if (event.data.type === "websocketForwardingMessage") {
const data = JSON.parse(event.data.data);
if (data.messageType === messageType) {
window.removeEventListener("message", handler);
resolve(data.data);
}
}
};
window.addEventListener("message", handler);
this.send(messageType, data);
});
}
onOpen(callback: () => void): void {
window.addEventListener("message", (event: any) => {
if (event.data.type === "websocketForwardingOpen") {
callback();
}
});
}
onClose(callback: () => void): void {
window.addEventListener("message", (event: any) => {
if (event.data.type === "websocketForwardingClose") {
callback();
}
});
}
close(): void {
postToIde("websocketForwardingClose", { url: this.serverUrl });
}
}

View file

@ -1,26 +0,0 @@
export abstract class Messenger {
abstract send(messageType: string, data: object): void;
abstract onMessageType(
messageType: string,
callback: (data: object) => void
): void;
abstract onMessage(
callback: (
messageType: string,
data: any,
ack?: (data: any) => void
) => void
): void;
abstract onOpen(callback: () => void): void;
abstract onClose(callback: () => void): void;
abstract sendAndReceive(messageType: string, data: any): Promise<any>;
abstract onError(callback: (error: any) => void): void;
abstract close(): void;
}

View file

@ -1,28 +1,26 @@
import {
Cog6ToothIcon,
QuestionMarkCircleIcon,
SparklesIcon,
} from "@heroicons/react/24/outline";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import styled from "styled-components";
import { defaultBorderRadius, secondaryDark, vscForeground } from ".";
import { Outlet } from "react-router-dom";
import TextDialog from "./dialogs";
import { useContext, useEffect } from "react";
import { GUIClientContext } from "../App";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { newSession } from "../redux/slices/stateSlice";
import {
setBottomMessage,
setBottomMessageCloseTimeout,
setShowDialog,
} from "../redux/slices/uiStateSlice";
import {
SparklesIcon,
Cog6ToothIcon,
QuestionMarkCircleIcon,
} from "@heroicons/react/24/outline";
import HeaderButtonWithText from "./HeaderButtonWithText";
import { useNavigate, useLocation } from "react-router-dom";
import ModelSelect from "./modelSelection/ModelSelect";
import ProgressBar from "./loaders/ProgressBar";
import { RootStore } from "../redux/store";
import { getFontSize } from "../util";
import HeaderButtonWithText from "./HeaderButtonWithText";
import TextDialog from "./dialogs";
import IndexingProgressBar from "./loaders/IndexingProgressBar";
import { newSession } from "../redux/slices/stateSlice";
import ProgressBar from "./loaders/ProgressBar";
import ModelSelect from "./modelSelection/ModelSelect";
// #region Styled Components
const FOOTER_HEIGHT = "1.8em";
@ -100,7 +98,6 @@ const DropdownPortalDiv = styled.div`
const Layout = () => {
const navigate = useNavigate();
const location = useLocation();
const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const dialogMessage = useSelector(
(state: RootStore) => state.uiState.dialogMessage
@ -124,11 +121,7 @@ const Layout = () => {
(state: RootStore) => state.uiState.displayBottomMessageOnBottom
);
const timeline = useSelector(
(state: RootStore) => state.sessionState.history
);
const workspacePaths = (window as any).workspacePaths || [];
const sessionState = useSelector((state: RootStore) => state.sessionState);
const timeline = useSelector((state: RootStore) => state.state.history);
// #endregion
@ -149,7 +142,20 @@ const Layout = () => {
navigator.clipboard.writeText(selection);
}, 100);
}
} else if (event.metaKey && event.code === "KeyN") {
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [timeline]);
useEffect(() => {
// Override the VS Code shortcut so that highlighted but unfocused code isn't added
const handleKeyDown = (event: any) => {
if (event.metaKey && event.code === "KeyM") {
dispatch(newSession());
}
};
@ -159,7 +165,7 @@ const Layout = () => {
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [client, timeline]);
}, []);
useEffect(() => {
const handler = (event: any) => {

View file

@ -1,256 +0,0 @@
import React, { useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import {
StyledTooltip,
defaultBorderRadius,
lightGray,
secondaryDark,
vscForeground,
} from "..";
import {
PaperAirplaneIcon,
SparklesIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import HeaderButtonWithText from "../HeaderButtonWithText";
import { getFontSize } from "../../util";
import { usePostHog } from "posthog-js/react";
const Div = styled.div<{ isDisabled: boolean }>`
border-radius: ${defaultBorderRadius};
cursor: ${(props) => (props.isDisabled ? "not-allowed" : "pointer")};
padding: 8px 8px;
background-color: ${secondaryDark};
border: 1px solid transparent;
display: flex;
justify-content: space-between;
align-items: center;
color: ${(props) => (props.isDisabled ? lightGray : vscForeground)};
&:hover {
border: ${(props) =>
props.isDisabled ? "1px solid transparent" : `1px solid ${lightGray}`};
}
`;
const P = styled.p<{ fontSize: number }>`
font-size: ${(props) => props.fontSize}px;
margin: 0;
`;
interface SuggestionsDivProps {
title: string;
description: string;
textInput: string;
onClick?: () => void;
disabled: boolean;
}
function SuggestionsDiv(props: SuggestionsDivProps) {
const [isHovered, setIsHovered] = useState(false);
return (
<>
<Div
data-tooltip-id={`suggestion-disabled-${props.textInput.replace(
" ",
""
)}`}
onClick={props.onClick}
onMouseEnter={() => {
if (props.disabled) return;
setIsHovered(true);
}}
onMouseLeave={() => setIsHovered(false)}
isDisabled={props.disabled}
>
<P fontSize={getFontSize()}>{props.description}</P>
<PaperAirplaneIcon
width="1.6em"
height="1.6em"
style={{
opacity: isHovered ? 1 : 0,
backgroundColor: secondaryDark,
boxShadow: `1px 1px 10px ${secondaryDark}`,
borderRadius: defaultBorderRadius,
}}
/>
</Div>
<StyledTooltip
id={`suggestion-disabled-${props.textInput.replace(" ", "")}`}
place="bottom"
hidden={!props.disabled}
>
Must highlight code first
</StyledTooltip>
</>
);
}
const stageDescriptions = [
<p>Ask a question</p>,
<p>
1. Highlight code in the editor
<br />
2. Press {localStorage.getItem("ide") === "jetbrains"
? "cmd+J"
: "cmd+M"}{" "}
to select the code
<br />
3. Ask a question
</p>,
<p>
1. Highlight code in the editor
<br />
2. Press{" "}
{localStorage.getItem("ide") === "jetbrains"
? "cmd+shift+J"
: "cmd+shift+M"}{" "}
to select the code
<br />
3. Request an edit
</p>,
];
const suggestionsStages: any[][] = [
// [
// {
// title: stageDescriptions[0],
// description: "How does merge sort work?",
// textInput: "How does merge sort work?",
// },
// {
// title: stageDescriptions[0],
// description: "How do I sum over a column in SQL?",
// textInput: "How do I sum over a column in SQL?",
// },
// ],
[
{
title: stageDescriptions[1],
description: "Is there any way to make this code more efficient?",
textInput: "Is there any way to make this code more efficient?",
},
{
title: stageDescriptions[1],
description: "What does this function do?",
textInput: "What does this function do?",
},
],
[
{
title: stageDescriptions[2],
description: "/edit write comments for this code",
textInput: "/edit write comments for this code",
},
{
title: stageDescriptions[2],
description: "/edit make this code more efficient",
textInput: "/edit make this code more efficient",
},
],
];
const NUM_STAGES = suggestionsStages.length;
const TutorialDiv = styled.div`
margin: 4px;
margin-left: 8px;
margin-right: 8px;
position: relative;
background-color: #ff02;
border-radius: ${defaultBorderRadius};
padding: 8px 4px;
`;
function SuggestionsArea(props: { onClick: (textInput: string) => void }) {
const posthog = usePostHog();
const [stage, setStage] = useState(
parseInt(localStorage.getItem("stage") || "0")
);
const timeline = useSelector(
(state: RootStore) => state.sessionState.history
);
const codeIsHighlighted = useSelector((state: RootStore) =>
state.serverState.selectedContextItems.some(
(item) => item.description.id.provider_title === "code"
)
);
const [hide, setHide] = useState(false);
const [numTutorialInputs, setNumTutorialInputs] = useState(0);
const inputsAreOnlyTutorial = useCallback(() => {
const inputs = timeline.filter(
(step) => !step.hide && step.name === "User Input"
);
return inputs.length - numTutorialInputs <= 0;
}, [timeline, numTutorialInputs]);
return (
<>
{hide ||
stage > NUM_STAGES - 1 ||
!inputsAreOnlyTutorial() ||
parseInt(localStorage.getItem("tutorialClosedCount") || "0") > 0 || (
<TutorialDiv>
<div className="flex">
<SparklesIcon width="1.3em" height="1.3em" color="yellow" />
<b className="ml-1">
Tutorial ({stage + 1}/{NUM_STAGES})
</b>
</div>
<div style={{ color: vscForeground, paddingLeft: "4px" }}>
{stage < suggestionsStages.length &&
suggestionsStages[stage][0]?.title}
</div>
<HeaderButtonWithText
className="absolute right-1 top-1 cursor-pointer"
text="Close Tutorial"
onClick={() => {
setHide(true);
const tutorialClosedCount = parseInt(
localStorage.getItem("tutorialClosedCount") || "0"
);
localStorage.setItem(
"tutorialClosedCount",
(tutorialClosedCount + 1).toString()
);
posthog?.capture("tutorial_closed", {
stage,
tutorialClosedCount,
});
}}
>
<XMarkIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
<div className="grid grid-cols-2 gap-2 mt-2">
{suggestionsStages[stage]?.map((suggestion, idx) => (
<SuggestionsDiv
key={idx}
disabled={!codeIsHighlighted}
{...suggestion}
onClick={() => {
if (!codeIsHighlighted) return;
props.onClick(suggestion.textInput);
posthog?.capture("tutorial_stage_complete", { stage });
setStage(stage + 1);
localStorage.setItem("stage", (stage + 1).toString());
setHide(true);
setNumTutorialInputs((prev) => prev + 1);
}}
/>
))}
</div>
</TutorialDiv>
)}
</>
);
}
export default SuggestionsArea;

View file

@ -1,7 +1,5 @@
import { useContext } from "react";
import { Button, Input } from "..";
import { GUIClientContext } from "../../App";
import { useDispatch } from "react-redux";
import { Button, Input } from "..";
import {
setDialogMessage,
setShowDialog,
@ -14,7 +12,6 @@ function AddContextGroupDialog({
selectedContextItems: ContextItem[];
}) {
const dispatch = useDispatch();
const client = useContext(GUIClientContext);
let inputElement: HTMLInputElement | null = null;
@ -22,7 +19,7 @@ function AddContextGroupDialog({
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
const title = inputElement ? inputElement.value : "My Context Group";
client?.saveContextGroup(title, selectedContextItems);
// TODO
};
return (

View file

@ -1,9 +1,8 @@
import React, { useContext } from "react";
import React from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { Button, Input } from "..";
import { useNavigate } from "react-router-dom";
import { GUIClientContext } from "../../App";
import { useDispatch } from "react-redux";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
const GridDiv = styled.div`
@ -16,7 +15,6 @@ const GridDiv = styled.div`
function FTCDialog() {
const navigate = useNavigate();
const [apiKey, setApiKey] = React.useState("");
const client = useContext(GUIClientContext);
const dispatch = useDispatch();
return (
@ -55,12 +53,13 @@ function FTCDialog() {
<Button
disabled={!apiKey}
onClick={() => {
client?.addModelForRole("*", {
model: "gpt-4",
api_key: apiKey,
title: "GPT-4",
provider: "openai",
});
// TODO: Edit the config to add this model.
// client?.addModelForRole("*", {
// model: "gpt-4",
// api_key: apiKey,
// title: "GPT-4",
// provider: "openai",
// });
dispatch(setShowDialog(false));
}}
>

View file

@ -1,13 +1,6 @@
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import { useContext } from "react";
import { GUIClientContext } from "../../App";
import { TrashIcon } from "@heroicons/react/24/outline";
import HeaderButtonWithText from "../HeaderButtonWithText";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import {
Button,
defaultBorderRadius,
@ -15,7 +8,12 @@ import {
vscBackground,
vscForeground,
} from "..";
import styled from "styled-components";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { RootStore } from "../../redux/store";
import HeaderButtonWithText from "../HeaderButtonWithText";
const MiniPillSpan = styled.span`
padding: 3px;
@ -54,7 +52,6 @@ function SelectContextGroupDialog() {
const savedContextGroups = useSelector(
(state: RootStore) => state.serverState.savedContextGroups
);
const client = useContext(GUIClientContext);
return (
<div className="p-4">
@ -69,7 +66,8 @@ function SelectContextGroupDialog() {
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
client?.selectContextGroup(key);
// TODO
// client?.selectContextGroup(key);
}}
>
<b>{key}: </b>
@ -83,7 +81,8 @@ function SelectContextGroupDialog() {
text="Delete"
onClick={(e) => {
e.stopPropagation();
client?.deleteContextGroup(key);
// TODO
// client?.deleteContextGroup(key);
}}
>
<TrashIcon width="1.4em" height="1.4em" />

View file

@ -1,4 +1,10 @@
import { useContext, useEffect, useRef, useState } from "react";
import {
HandThumbDownIcon,
HandThumbUpIcon,
} from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core/llm/types";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import {
defaultBorderRadius,
@ -6,20 +12,9 @@ import {
secondaryDark,
vscBackground,
} from "..";
import {
ArrowPathIcon,
HandThumbDownIcon,
HandThumbUpIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import HeaderButtonWithText from "../HeaderButtonWithText";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { getFontSize } from "../../util";
import { StepDescription } from "../../schema/SessionState";
import { useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import { GUIClientContext } from "../../App";
import { ChatHistoryItem } from "core/llm/types";
import { getFontSize } from "../../util";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
interface StepContainerProps {
item: ChatHistoryItem;
@ -31,7 +26,6 @@ interface StepContainerProps {
isFirst: boolean;
isLast: boolean;
index: number;
noUserInputParent: boolean;
}
// #region styled components
@ -67,11 +61,8 @@ function StepContainer(props: StepContainerProps) {
const naturalLanguageInputRef = useRef<HTMLTextAreaElement>(null);
const userInputRef = useRef<HTMLInputElement>(null);
const isUserInput = props.item.message.role === "user";
const sessionHistory = useSelector(
(store: RootStore) => store.sessionState.history
);
const active = useSelector((store: RootStore) => store.sessionState.active);
const client = useContext(GUIClientContext);
const sessionHistory = useSelector((store: RootStore) => store.state.history);
const active = useSelector((store: RootStore) => store.state.active);
useEffect(() => {
if (userInputRef?.current) {
@ -88,16 +79,15 @@ function StepContainer(props: StepContainerProps) {
const [feedback, setFeedback] = useState<boolean | undefined>(undefined);
const sendFeedback = (feedback: boolean) => {
setFeedback(feedback);
console.log(sessionHistory, props.index);
const logs = sessionHistory[props.index].logs;
if (!logs || logs.length < 1) return;
const prompt = logs[0].split("#########\n")[1];
const completion = props.item.message.content;
console.log(prompt, completion, client);
client?.sendPromptCompletionFeedback("chat", prompt, completion, feedback);
// TODO: Feedback
// setFeedback(feedback);
// console.log(sessionHistory, props.index);
// const logs = sessionHistory[props.index].logs;
// if (!logs || logs.length < 1) return;
// const prompt = logs[0].split("#########\n")[1];
// const completion = props.item.message.content;
// console.log(prompt, completion, client);
// client?.sendPromptCompletionFeedback("chat", prompt, completion, feedback);
};
return (
@ -110,43 +100,6 @@ function StepContainer(props: StepContainerProps) {
}}
>
<div className="relative">
{isHovered && (false || props.noUserInputParent) && (
<ButtonsDiv>
{false &&
((
<HeaderButtonWithText
text="Retry"
onClick={(e) => {
e.stopPropagation();
props.onRetry();
}}
>
<ArrowPathIcon
width="1.4em"
height="1.4em"
onClick={props.onRetry}
/>
</HeaderButtonWithText>
) as any)}
{props.noUserInputParent && (
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete();
}}
>
<XMarkIcon
width="1.4em"
height="1.4em"
onClick={props.onRetry}
/>
</HeaderButtonWithText>
)}
</ButtonsDiv>
)}
<ContentDiv
hidden={!props.open}
isUserInput={isUserInput}

View file

@ -1,33 +1,13 @@
import React, {
useCallback,
useContext,
useEffect,
useImperativeHandle,
useLayoutEffect,
useState,
} from "react";
import { useCombobox } from "downshift";
import styled, { keyframes } from "styled-components";
import {
buttonColor,
defaultBorderRadius,
lightGray,
secondaryDark,
vscBackground,
vscForeground,
} from "..";
import PillButton from "./PillButton";
import HeaderButtonWithText from "../HeaderButtonWithText";
import {
ArrowLeftIcon,
ArrowRightIcon,
ArrowUpLeftIcon,
ArrowUpOnSquareIcon,
BeakerIcon,
ChevronDownIcon,
ChevronRightIcon,
Cog6ToothIcon,
CommandLineIcon,
ExclamationCircleIcon,
ExclamationTriangleIcon,
FolderIcon,
FolderOpenIcon,
@ -38,30 +18,31 @@ import {
PlusIcon,
SparklesIcon,
TrashIcon,
ExclamationCircleIcon,
} from "@heroicons/react/24/outline";
import { postToIde } from "../../util/ide";
import { GUIClientContext } from "../../App";
import { ContextItem } from "core/llm/types";
import { useCombobox } from "downshift";
import { MeiliSearch } from "meilisearch";
import { setBottomMessage } from "../../redux/slices/uiStateSlice";
import React, {
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import styled, { keyframes } from "styled-components";
import {
getFontSize,
getMarkdownLanguageTagForFile,
getMetaKeyLabel,
getPlatform,
} from "../../util";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { setTakenActionTrue } from "../../redux/slices/miscSlice";
import {
handleKeyDownJetBrains,
handleKeyDownJetBrainsMac,
} from "../../util/jetbrains";
import FileIcon from "../FileIcon";
import RingLoader from "../loaders/RingLoader";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
buttonColor,
defaultBorderRadius,
lightGray,
secondaryDark,
vscBackground,
vscForeground,
} from "..";
import useContextProviders from "../../hooks/useContextProviders";
import useHistory from "../../hooks/useHistory";
import { contextLengthSelector } from "../../redux/selectors/configSelectors";
import { setTakenActionTrue } from "../../redux/slices/miscSlice";
import {
addContextItems,
addContextItemsAtIndex,
@ -69,8 +50,25 @@ import {
newSession,
setInactive,
} from "../../redux/slices/stateSlice";
import { ContextItem } from "core/llm/types";
import useContextProviders from "../../hooks/useContextProviders";
import { setBottomMessage } from "../../redux/slices/uiStateSlice";
import { RootStore } from "../../redux/store";
import {
getFontSize,
getMarkdownLanguageTagForFile,
getMetaKeyLabel,
getPlatform,
} from "../../util";
import { postToIde } from "../../util/ide";
import {
handleKeyDownJetBrains,
handleKeyDownJetBrainsMac,
} from "../../util/jetbrains";
import FileIcon from "../FileIcon";
import HeaderButtonWithText from "../HeaderButtonWithText";
import RingLoader from "../loaders/RingLoader";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import PillButton from "./PillButton";
const SEARCH_INDEX_NAME = "continue_context_items";
@ -387,10 +385,9 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
setSearchClient(client);
}, [meilisearchUrl]);
const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const workspacePaths = (window as any).workspacePaths || [];
const sessionState = useSelector((state: RootStore) => state.sessionState);
const state = useSelector((state: RootStore) => state.state);
const [history, setHistory] = React.useState<string[]>([]);
// The position of the current command you are typing now, so the one that will be appended to history once you press enter
@ -437,10 +434,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
});
const timeline = useSelector(
(state: RootStore) => state.sessionState.history
);
const active = useSelector((state: RootStore) => state.sessionState.active);
const active = useSelector((state: RootStore) => state.state.active);
useEffect(() => {
if (!currentlyInContextQuery) {
@ -492,7 +486,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
dispatch(addContextItemsAtIndex({ contextItems, index: props.index }));
}
},
[client, props.index, getContextItems]
[props.index, getContextItems]
);
const onInputValueChangeCallback = useCallback(
@ -733,9 +727,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
};
}, []);
const persistSession = () => {
client?.persistSession(sessionState, workspacePaths[0] || "");
};
const { saveSession } = useHistory();
useEffect(() => {
if (!inputRef.current || !props.isMainInput) {
@ -747,18 +739,15 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const handler = (event: any) => {
if (event.data.type === "focusContinueInput") {
inputRef.current!.focus();
console.log(sessionState.history.length, "OHPOI");
if (sessionState.history.length > 0) {
client?.stopSession();
persistSession();
if (state.history.length > 0) {
saveSession();
dispatch(newSession());
}
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "focusContinueInputWithEdit") {
inputRef.current!.focus();
if (sessionState.history.length > 0) {
client?.stopSession();
persistSession();
if (state.history.length > 0) {
saveSession();
dispatch(newSession());
}
@ -767,8 +756,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "focusContinueInputWithNewSession") {
client?.stopSession();
persistSession();
saveSession();
dispatch(newSession());
dispatch(setTakenActionTrue(null));
}
@ -777,7 +765,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
return () => {
window.removeEventListener("message", handler);
};
}, [inputRef.current, props.isMainInput, sessionState.history.length]);
}, [inputRef.current, props.isMainInput, state.history.length]);
const deleteButtonDivRef = React.useRef<HTMLDivElement>(null);
const stickyDropdownHeaderDiv = React.useRef<HTMLDivElement>(null);
@ -1215,8 +1203,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
ref={divRef}
>
<GradientBorder
// loading={props.active}
loading={false}
loading={props.active}
isFirst={false}
isLast={false}
borderColor={props.active ? undefined : vscBackground}
@ -1465,7 +1452,6 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
// }
onClick={() => {
if (active) {
client?.stopSession();
dispatch(setInactive());
} else {
props.onEnter?.(undefined);
@ -1676,11 +1662,10 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
<br />
<br />
</>
) : sessionState.history.length > 0 ? (
) : state.history.length > 0 ? (
<NewSessionButton
onClick={() => {
client?.stopSession();
persistSession();
saveSession();
dispatch(newSession());
}}
className="mr-auto"

View file

@ -1,4 +1,11 @@
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import {
ExclamationTriangleIcon,
PaintBrushIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { ContextItem } from "core/llm/types";
import { useCallback, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import {
StyledTooltip,
@ -7,20 +14,12 @@ import {
secondaryDark,
vscForeground,
} from "..";
import {
TrashIcon,
PaintBrushIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { GUIClientContext } from "../../App";
import { getFontSize } from "../../util";
import HeaderButtonWithText from "../HeaderButtonWithText";
import FileIcon from "../FileIcon";
import { ContextItem } from "core/llm/types";
import { postToIde } from "../../util/ide";
import { useDispatch, useSelector } from "react-redux";
import { setEditingAtIds } from "../../redux/slices/sessionStateReducer";
import { setEditingAtIds } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import { getFontSize } from "../../util";
import { postToIde } from "../../util/ide";
import FileIcon from "../FileIcon";
import HeaderButtonWithText from "../HeaderButtonWithText";
const Button = styled.button<{ fontSize?: number }>`
border: none;
@ -145,7 +144,6 @@ const ClickableInsidePillButton = styled(HeaderButtonWithText)<{
const PillButton = (props: PillButtonProps) => {
const [isHovered, setIsHovered] = useState(false);
const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const [warning, setWarning] = useState<string | undefined>(undefined);
@ -179,7 +177,7 @@ const PillButton = (props: PillButtonProps) => {
const buttonRef = useRef<HTMLButtonElement>(null);
const selectedContextItems = useSelector(
(store: RootStore) => store.sessionState.context_items
(store: RootStore) => store.state.contextItems
);
return (

View file

@ -12,7 +12,7 @@ import {
ChevronUpIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { deleteContextWithIds } from "../../redux/slices/sessionStateReducer";
import { deleteContextWithIds } from "../../redux/slices/stateSlice";
import { useDispatch } from "react-redux";
import StyledMarkdownPreview from "./StyledMarkdownPreview";

View file

@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useState } from "react";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, secondaryDark } from "..";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import { postToIde } from "../../util/ide";
@ -19,7 +19,7 @@ const StyledCode = styled.code<{ link: boolean }>`
function LinkableCode(props: any) {
const contextItems = useSelector(
(store: RootStore) => store.sessionState.context_items
(store: RootStore) => store.state.contextItems
);
const [linkingDone, setLinkingDone] = useState(false);

View file

@ -1,3 +1,13 @@
import { Listbox, Transition } from "@headlessui/react";
import {
ChevronUpDownIcon,
PlusIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { Fragment, useEffect, useState } from "react";
import ReactDOM from "react-dom";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import {
buttonColor,
@ -7,21 +17,10 @@ import {
vscBackground,
vscForeground,
} from "..";
import React, { Fragment, useContext, useEffect, useState } from "react";
import { GUIClientContext } from "../../App";
import { RootStore } from "../../redux/store";
import { useSelector } from "react-redux";
import {
ChevronUpDownIcon,
PlusIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { useNavigate } from "react-router-dom";
import { Listbox, Transition } from "@headlessui/react";
import ReactDOM from "react-dom";
import HeaderButtonWithText from "../HeaderButtonWithText";
import { defaultModelSelector } from "../../redux/selectors/configSelectors";
import { RootStore } from "../../redux/store";
import { getMetaKeyLabel } from "../../util";
import HeaderButtonWithText from "../HeaderButtonWithText";
const GridDiv = styled.div`
display: grid;
@ -136,7 +135,6 @@ const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>`
`;
function ListBoxOption({ option, idx }: { option: Option; idx: number }) {
const client = useContext(GUIClientContext);
const [hovered, setHovered] = useState(false);
return (
@ -163,7 +161,8 @@ function ListBoxOption({ option, idx }: { option: Option; idx: number }) {
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
client?.deleteModelAtIndex(idx - 1); // -1 because 0 is default, not in saved array
// TODO
// client?.deleteModelAtIndex(idx - 1); // -1 because 0 is default, not in saved array
e.stopPropagation();
e.preventDefault();
}}
@ -196,7 +195,6 @@ interface Option {
}
function ModelSelect(props: {}) {
const client = useContext(GUIClientContext);
const defaultModel = useSelector(defaultModelSelector);
const allModels = useSelector(
(state: RootStore) => state.serverState.config.models
@ -234,7 +232,8 @@ function ModelSelect(props: {}) {
(option) => option.value === defaultModel?.title
);
const nextIndex = (currentIndex + 1) % options.length;
client?.setModelForRoleFromTitle("default", options[nextIndex].value);
// TODO
// client?.setModelForRoleFromTitle("default", options[nextIndex].value);
}
};
@ -251,7 +250,8 @@ function ModelSelect(props: {}) {
value={"GPT-4"}
onChange={(val: string) => {
if (val === defaultModel?.title) return;
client?.setModelForRoleFromTitle("default", val);
// TODO
// client?.setModelForRoleFromTitle("default", val);
}}
defaultValue={"GPT-4"}
>

View file

@ -0,0 +1,34 @@
import { ideRequest } from "core/ide/messaging";
import { PersistedSessionInfo, SessionInfo } from "core/types";
import { useSelector } from "react-redux";
import { RootStore } from "../redux/store";
function useHistory() {
const state = useSelector((state: RootStore) => state.state);
async function getHistory(): Promise<SessionInfo[]> {
return await ideRequest("history", {});
}
async function saveSession() {
const sessionInfo: PersistedSessionInfo = {
history: state.history,
title: state.title,
sessionId: state.sessionId,
workspaceDirectory: (window as any).workspacePaths?.[0] || "",
};
return await ideRequest("saveSession", sessionInfo);
}
async function deleteSession(sessionId: string) {
return await ideRequest("deleteSession", { sessionId });
}
async function loadSession(sessionId: string): Promise<PersistedSessionInfo> {
return await ideRequest("loadSession", { sessionId });
}
return { getHistory, saveSession, deleteSession, loadSession };
}
export default useHistory;

View file

@ -1,15 +1,12 @@
import { Dispatch } from "@reduxjs/toolkit";
import { useEffect } from "react";
import {
addHighlightedCode,
setActive,
} from "../redux/slices/sessionStateReducer";
import { setServerStatusMessage } from "../redux/slices/miscSlice";
import { postToIde } from "../util/ide";
import { setVscMachineId } from "../redux/slices/configSlice";
import { ExtensionIde } from "core/ide/index";
import { setConfig } from "../redux/slices/serverStateReducer";
import { addHighlightedCode, setInactive } from "../redux/slices/stateSlice";
function useSetup(dispatch: Dispatch<any>) {
// Load config from the IDE
@ -21,7 +18,7 @@ function useSetup(dispatch: Dispatch<any>) {
useEffect(() => {
// Override persisted state
dispatch(setActive(false));
dispatch(setInactive());
// Tell JetBrains the webview is ready
postToIde("onLoad", {});

View file

@ -2,7 +2,10 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import { store, persistor } from "./redux/store";
import {
store,
// persistor
} from "./redux/store";
import "./index.css";
import { PersistGate } from "redux-persist/integration/react";

View file

@ -1,6 +1,6 @@
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { newSession } from "../redux/slices/sessionStateReducer";
import { newSession } from "../redux/slices/stateSlice";
import ContinueButton from "../components/mainInput/ContinueButton";
import { vscBackground } from "../components";

View file

@ -1,29 +1,44 @@
import {
ChatBubbleOvalLeftIcon,
CodeBracketSquareIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { constructMessages } from "core/llm/constructMessages";
import { ChatHistoryItem, ChatMessage } from "core/llm/types";
import { usePostHog } from "posthog-js/react";
import {
Fragment,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { ErrorBoundary } from "react-error-boundary";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import {
Button,
Input,
defaultBorderRadius,
lightGray,
vscBackground,
} from "../components";
import { ErrorBoundary } from "react-error-boundary";
import {
useEffect,
useRef,
useState,
useContext,
useLayoutEffect,
useCallback,
Fragment,
} from "react";
import FTCDialog from "../components/dialogs/FTCDialog";
import ErrorStepContainer from "../components/gui/ErrorStepContainer";
import StepContainer from "../components/gui/StepContainer";
import { GUIClientContext } from "../App";
import TimelineItem from "../components/gui/TimelineItem";
import ComboBox from "../components/mainInput/ComboBox";
import { usePostHog } from "posthog-js/react";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { postToIde } from "../util/ide";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../util";
import useHistory from "../hooks/useHistory";
import useModels from "../hooks/useModels";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
import {
newSession,
resubmitAtIndex,
setInactive,
streamUpdate,
submitMessage,
} from "../redux/slices/stateSlice";
import {
setBottomMessage,
setDialogEntryOn,
@ -31,33 +46,8 @@ import {
setDisplayBottomMessageOnBottom,
setShowDialog,
} from "../redux/slices/uiStateSlice";
import RingLoader from "../components/loaders/RingLoader";
import TimelineItem from "../components/gui/TimelineItem";
import ErrorStepContainer from "../components/gui/ErrorStepContainer";
import {
ArrowsPointingInIcon,
ArrowsPointingOutIcon,
ChatBubbleOvalLeftIcon,
CodeBracketSquareIcon,
ExclamationTriangleIcon,
FolderIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import FTCDialog from "../components/dialogs/FTCDialog";
import HeaderButtonWithText from "../components/HeaderButtonWithText";
import { useNavigate } from "react-router-dom";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
import FreeTrial from "core/llm/llms/FreeTrial";
import { constructMessages } from "core/llm/constructMessages";
import { ChatHistory, ChatHistoryItem, ChatMessage } from "core/llm/types";
import {
resubmitAtIndex,
streamUpdate,
submitMessage,
newSession,
setInactive,
} from "../redux/slices/stateSlice";
import useModels from "../hooks/useModels";
import { RootStore } from "../redux/store";
import { isMetaEquivalentKeyPressed } from "../util";
const TopGuiDiv = styled.div`
overflow-y: scroll;
@ -131,7 +121,6 @@ interface GUIProps {
function GUI(props: GUIProps) {
// #region Hooks
const client = useContext(GUIClientContext);
const posthog = usePostHog();
const dispatch = useDispatch();
const navigate = useNavigate();
@ -139,15 +128,13 @@ function GUI(props: GUIProps) {
// #endregion
// #region Selectors
const sessionState = useSelector((state: RootStore) => state.sessionState);
const sessionState = useSelector((state: RootStore) => state.state);
const workspacePaths = (window as any).workspacePaths || [];
const { defaultModel } = useModels();
const sessionTitle = useSelector(
(state: RootStore) => state.sessionState.title
);
const active = useSelector((state: RootStore) => state.sessionState.active);
const sessionTitle = useSelector((state: RootStore) => state.state.title);
const active = useSelector((state: RootStore) => state.state.active);
// #endregion
@ -230,7 +217,6 @@ function GUI(props: GUIProps) {
isMetaEquivalentKeyPressed(e) &&
!e.shiftKey
) {
client?.stopSession();
dispatch(setInactive());
} else if (e.key === "Escape") {
dispatch(setBottomMessage(undefined));
@ -241,7 +227,7 @@ function GUI(props: GUIProps) {
return () => {
window.removeEventListener("keydown", listener);
};
}, [client, active]);
}, [active]);
// #endregion
@ -284,6 +270,7 @@ function GUI(props: GUIProps) {
for await (const update of defaultModel.streamChat(messages)) {
dispatch(streamUpdate(update.content));
}
dispatch(setInactive());
})();
// Increment localstorage counter for popup
@ -360,24 +347,15 @@ function GUI(props: GUIProps) {
localStorage.setItem("mainTextEntryCounter", "1");
}
},
[
client,
sessionState.history,
sessionState.context_items,
defaultModel,
state,
]
[sessionState.history, sessionState.contextItems, defaultModel, state]
);
const persistSession = useCallback(() => {
client?.persistSession(sessionState, workspacePaths[0] || "");
}, [client, sessionState, workspacePaths]);
const { saveSession } = useHistory();
useEffect(() => {
const handler = (event: any) => {
if (event.data.type === "newSession") {
client?.stopSession();
persistSession();
saveSession();
dispatch(newSession());
mainTextInputRef.current?.focus?.();
}
@ -422,11 +400,6 @@ function GUI(props: GUIProps) {
}
};
const onStepUserInput = (input: string, index: number) => {
if (!client) return;
client.sendStepUserInput(input, index);
};
const isLastUserInput = useCallback(
(index: number): boolean => {
let foundLaterUserInput = false;
@ -441,41 +414,6 @@ function GUI(props: GUIProps) {
[state.history]
);
const getStepsInUserInputGroup = useCallback(
(index: number): number[] => {
// index is the index in the entire timeline, hidden steps included
const stepsInUserInputGroup: number[] = [];
// First find the closest above UserInputStep
let userInputIndex = -1;
for (let i = index; i >= 0; i--) {
if (
typeof sessionState.history[i] !== "undefined" &&
sessionState.history[i].name === "User Input" &&
sessionState.history[i].hide === false
) {
stepsInUserInputGroup.push(i);
userInputIndex = i;
break;
}
}
if (stepsInUserInputGroup.length === 0) return [];
for (let i = userInputIndex + 1; i < sessionState.history.length; i++) {
if (
typeof sessionState.history[i] !== "undefined" &&
sessionState.history[i].name === "User Input" &&
sessionState.history[i].hide === false
) {
break;
}
stepsInUserInputGroup.push(i);
}
return stepsInUserInputGroup;
},
[sessionState.history]
);
useEffect(() => {
if (sessionTitle) {
setSessionTitleInput(sessionTitle);
@ -503,7 +441,6 @@ function GUI(props: GUIProps) {
<ErrorBoundary
FallbackComponent={fallbackRender}
onReset={() => {
client?.stopSession();
dispatch(newSession());
}}
>
@ -570,20 +507,11 @@ function GUI(props: GUIProps) {
: stepsOpen[index]!
}
key={index}
onUserInput={(input: string) => {
onStepUserInput(input, index);
}}
onUserInput={(input: string) => {}}
item={item}
onReverse={() => {
client?.reverseToIndex(index);
}}
onRetry={() => {
client?.retryAtIndex(index);
}}
onReverse={() => {}}
onRetry={() => {}}
onDelete={() => {}}
noUserInputParent={
getStepsInUserInputGroup(index).length === 0
}
/>
)}
</TimelineItem>
@ -599,7 +527,6 @@ function GUI(props: GUIProps) {
{active ? (
<StopButton
onClick={() => {
client?.stopSession();
dispatch(setInactive());
}}
>
@ -616,9 +543,7 @@ function GUI(props: GUIProps) {
e?.preventDefault();
}}
onInputValueChange={() => {}}
onToggleAddContext={() => {
client?.toggleAddingHighlightedCode();
}}
onToggleAddContext={() => {}}
/>
)}
</div>

View file

@ -1,17 +1,15 @@
import React, { Fragment, useContext, useEffect, useState } from "react";
import { SessionInfo } from "../schema/SessionInfo";
import { GUIClientContext } from "../App";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { useNavigate } from "react-router-dom";
import { lightGray, secondaryDark, vscBackground } from "../components";
import styled from "styled-components";
import { ArrowLeftIcon, TrashIcon } from "@heroicons/react/24/outline";
import { PersistedSessionInfo, SessionInfo } from "core/types";
import React, { Fragment, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { lightGray, secondaryDark, vscBackground } from "../components";
import CheckDiv from "../components/CheckDiv";
import { getFontSize } from "../util";
import { newSession } from "../redux/slices/sessionStateReducer";
import { PersistedSessionInfo } from "../schema/PersistedSessionInfo";
import HeaderButtonWithText from "../components/HeaderButtonWithText";
import useHistory from "../hooks/useHistory";
import { newSession } from "../redux/slices/stateSlice";
import { getFontSize } from "../util";
const Tr = styled.tr`
&:hover {
@ -64,12 +62,12 @@ function TableRow({
}) {
const dispatch = useDispatch();
const navigate = useNavigate();
const client = useContext(GUIClientContext);
const apiUrl = (window as any).serverUrl;
const currentSession = useSelector((state: RootStore) => state.sessionState);
const workspacePaths = (window as any).workspacePaths || [""];
const [hovered, setHovered] = useState(false);
const { saveSession, deleteSession } = useHistory();
return (
<td
onMouseEnter={() => setHovered(true)}
@ -79,17 +77,16 @@ function TableRow({
<TdDiv
onClick={async () => {
// Save current session
client?.persistSession(currentSession, workspacePaths[0]);
saveSession();
// Load new session
const response = await fetch(
`${apiUrl}/sessions/${session.session_id}`
`${apiUrl}/sessions/${session.sessionId}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json: PersistedSessionInfo = await response.json();
client?.stopSession();
dispatch(newSession(json));
navigate("/");
}}
@ -105,7 +102,7 @@ function TableRow({
hour12: true,
})}
{" | "}
{lastPartOfPath(session.workspace_directory || "")}/
{lastPartOfPath(session.workspaceDirectory || "")}/
</div>
</TdDiv>
@ -114,8 +111,8 @@ function TableRow({
className="mr-2"
text="Delete"
onClick={async () => {
client?.deleteSession(session.session_id);
onDelete(session.session_id);
deleteSession(session.sessionId);
onDelete(session.sessionId);
}}
>
<TrashIcon width="1.3em" height="1.3em" />
@ -137,13 +134,12 @@ function History() {
const [filteredAndSortedSessions, setFilteredAndSortedSessions] = useState<
SessionInfo[]
>([]);
const client = useContext(GUIClientContext);
const apiUrl = (window as any).serverUrl;
const workspacePaths = (window as any).workspacePaths || [];
const deleteSessionInUI = async (sessionId: string) => {
setSessions((prev) =>
prev.filter((session) => session.session_id !== sessionId)
prev.filter((session) => session.sessionId !== sessionId)
);
};
@ -151,20 +147,15 @@ function History() {
const stickyHistoryHeaderRef = React.useRef<HTMLDivElement>(null);
const [headerHeight, setHeaderHeight] = useState(0);
const { getHistory } = useHistory();
useEffect(() => {
const fetchSessions = async () => {
if (!apiUrl) {
return;
}
const response = await fetch(`${apiUrl}/sessions/list`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
setSessions(json);
const sessions = await getHistory();
setSessions(sessions);
};
fetchSessions();
}, [client]);
}, []);
useEffect(() => {
setFilteredAndSortedSessions(
@ -173,22 +164,22 @@ function History() {
if (
!filteringByWorkspace ||
typeof workspacePaths === "undefined" ||
typeof session.workspace_directory === "undefined"
typeof session.workspaceDirectory === "undefined"
) {
return true;
}
return workspacePaths.includes(session.workspace_directory);
return workspacePaths.includes(session.workspaceDirectory);
})
.sort(
(a, b) =>
parseDate(b.date_created).getTime() -
parseDate(a.date_created).getTime()
parseDate(b.dateCreated).getTime() -
parseDate(a.dateCreated).getTime()
)
);
}, [filteringByWorkspace, sessions]);
useEffect(() => {
setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100);
setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100);
}, [stickyHistoryHeaderRef.current]);
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
@ -198,7 +189,11 @@ function History() {
return (
<div className="overflow-y-scroll" style={{ fontSize: getFontSize() }}>
<div ref={stickyHistoryHeaderRef} className="sticky top-0" style={{ backgroundColor: vscBackground }}>
<div
ref={stickyHistoryHeaderRef}
className="sticky top-0"
style={{ backgroundColor: vscBackground }}
>
<div
className="items-center flex m-0 p-0"
style={{
@ -228,11 +223,11 @@ function History() {
if (
!filteringByWorkspace ||
typeof workspacePaths === "undefined" ||
typeof session.workspace_directory === "undefined"
typeof session.workspaceDirectory === "undefined"
) {
return true;
}
return workspacePaths.includes(session.workspace_directory);
return workspacePaths.includes(session.workspaceDirectory);
}).length === 0 && (
<div className="text-center m-4">
No past sessions found. To start a new session, either click the "+"
@ -246,30 +241,36 @@ function History() {
{filteredAndSortedSessions.map((session, index) => {
const prevDate =
index > 0
? parseDate(filteredAndSortedSessions[index - 1].date_created)
? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
: earlier;
const date = parseDate(session.date_created);
const date = parseDate(session.dateCreated);
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<SectionHeader style={{ top: `${headerHeight}px` }}>Today</SectionHeader>
<SectionHeader style={{ top: `${headerHeight}px` }}>
Today
</SectionHeader>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<SectionHeader style={{ top: `${headerHeight}px` }}>This Week</SectionHeader>
<SectionHeader style={{ top: `${headerHeight}px` }}>
This Week
</SectionHeader>
)}
{date < lastWeek &&
date > lastMonth &&
prevDate > lastWeek && (
<SectionHeader style={{ top: `${headerHeight}px` }}>This Month</SectionHeader>
<SectionHeader style={{ top: `${headerHeight}px` }}>
This Month
</SectionHeader>
)}
<Tr key={index}>
<TableRow
session={session}
date={date}
onDelete={() => deleteSessionInUI(session.session_id)}
onDelete={() => deleteSessionInUI(session.sessionId)}
></TableRow>
</Tr>
</Fragment>

View file

@ -1,26 +1,23 @@
import React, { useCallback, useContext, useEffect, useState } from "react";
import ModelCard from "../components/modelSelection/ModelCard";
import styled from "styled-components";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { useCallback, useEffect, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import styled from "styled-components";
import {
Input,
defaultBorderRadius,
lightGray,
vscBackground,
} from "../components";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { GUIClientContext } from "../App";
import { useParams } from "react-router-dom";
import StyledMarkdownPreview from "../components/markdown/StyledMarkdownPreview";
import ModelCard from "../components/modelSelection/ModelCard";
import {
PROVIDER_INFO,
MODEL_PROVIDER_TAG_COLORS,
ModelInfo,
PROVIDER_INFO,
updatedObj,
} from "../util/modelData";
import StyledMarkdownPreview from "../components/markdown/StyledMarkdownPreview";
import { FormProvider, useForm } from "react-hook-form";
import _ from "lodash";
const GridDiv = styled.div`
display: grid;
@ -67,7 +64,6 @@ function ModelConfig() {
}
}, [modelName]);
const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const navigate = useNavigate();
const vscMediaUrl = (window as any).vscMediaUrl;
@ -229,21 +225,22 @@ function ModelConfig() {
});
}
client?.addModelForRole("default", {
...pkg.params,
...modelInfo.params,
..._.merge(
{},
...(pkg.dimensions?.map((dimension, i) => {
if (!dimensionChoices?.[i]) return {};
return {
...dimension.options[dimensionChoices[i]],
};
}) || [])
),
...formParams,
provider: modelInfo.provider,
});
// TODO
// client?.addModelForRole("default", {
// ...pkg.params,
// ...modelInfo.params,
// ..._.merge(
// {},
// ...(pkg.dimensions?.map((dimension, i) => {
// if (!dimensionChoices?.[i]) return {};
// return {
// ...dimension.options[dimensionChoices[i]],
// };
// }) || [])
// ),
// ...formParams,
// provider: modelInfo.provider,
// });
navigate("/");
}}
/>
@ -262,11 +259,12 @@ function ModelConfig() {
: parseFloat(formMethods.watch(d.key));
}
client?.addModelForRole("default", {
...modelInfo.packages[0]?.params,
...modelInfo.params,
...formParams,
});
// TODO
// client?.addModelForRole("default", {
// ...modelInfo.packages[0]?.params,
// ...modelInfo.params,
// ...formParams,
// });
navigate("/");
}}
>

View file

@ -1,14 +1,12 @@
import React, { useContext } from "react";
import ModelCard from "../components/modelSelection/ModelCard";
import styled from "styled-components";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { lightGray, vscBackground } from "../components";
import React from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { GUIClientContext } from "../App";
import { MODEL_INFO, PROVIDER_INFO } from "../util/modelData";
import styled from "styled-components";
import { lightGray, vscBackground } from "../components";
import ModelCard from "../components/modelSelection/ModelCard";
import Toggle from "../components/modelSelection/Toggle";
import _ from "lodash";
import { MODEL_INFO, PROVIDER_INFO } from "../util/modelData";
const GridDiv = styled.div`
display: grid;
@ -21,7 +19,6 @@ const GridDiv = styled.div`
function Models() {
const navigate = useNavigate();
const client = useContext(GUIClientContext);
const [providersSelected, setProvidersSelected] = React.useState(true);
@ -78,19 +75,20 @@ function Models() {
dimensions={pkg.dimensions}
providerOptions={pkg.providerOptions}
onClick={(e, dimensionChoices, selectedProvider) => {
client?.addModelForRole("*", {
...pkg.params,
..._.merge(
{},
...(pkg.dimensions?.map((dimension, i) => {
if (!dimensionChoices?.[i]) return {};
return {
...dimension.options[dimensionChoices[i]],
};
}) || [])
),
provider: PROVIDER_INFO[selectedProvider].provider,
});
// TODO
// client?.addModelForRole("*", {
// ...pkg.params,
// ..._.merge(
// {},
// ...(pkg.dimensions?.map((dimension, i) => {
// if (!dimensionChoices?.[i]) return {};
// return {
// ...dimension.options[dimensionChoices[i]],
// };
// }) || [])
// ),
// provider: PROVIDER_INFO[selectedProvider].provider,
// });
navigate("/");
}}
/>

View file

@ -1,9 +1,9 @@
import React, { useContext, useEffect } from "react";
import { GUIClientContext } from "../App";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { useEffect } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { useNavigate } from "react-router-dom";
import { ContinueConfig } from "../schema/ContinueConfig";
import styled from "styled-components";
import {
Button,
NumberInput,
@ -13,11 +13,10 @@ import {
vscBackground,
vscForeground,
} from "../components";
import styled from "styled-components";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import Loader from "../components/loaders/Loader";
import InfoHover from "../components/InfoHover";
import { FormProvider, useForm } from "react-hook-form";
import Loader from "../components/loaders/Loader";
import { RootStore } from "../redux/store";
import { ContinueConfig } from "../schema/ContinueConfig";
import { getFontSize, getPlatform } from "../util";
import { postToIde } from "../util/ide";
@ -100,22 +99,19 @@ function Settings() {
const onSubmit = (data: ContinueConfig) => console.log(data);
const navigate = useNavigate();
const client = useContext(GUIClientContext);
const config = useSelector((state: RootStore) => state.serverState.config);
const dispatch = useDispatch();
const submitChanges = () => {
if (!client) return;
const systemMessage = formMethods.watch("system_message") as
| string
| undefined;
const temperature = formMethods.watch("temperature") as number | undefined;
// const models = formMethods.watch("models");
client.setSystemMessage(systemMessage || "");
if (temperature) client.setTemperature(temperature);
// TODO
// if (!client) return;
// const systemMessage = formMethods.watch("system_message") as
// | string
// | undefined;
// const temperature = formMethods.watch("temperature") as number | undefined;
// // const models = formMethods.watch("models");
// client.setSystemMessage(systemMessage || "");
// if (temperature) client.setTemperature(temperature);
// if (models) {
// for (const role of ALL_MODEL_ROLES) {
// if (models[role]) {

View file

@ -1,417 +0,0 @@
import { createSlice } from "@reduxjs/toolkit";
import { StepDescription } from "../../schema/SessionState";
import { SessionUpdate } from "../../schema/SessionUpdate";
import { ContextItem } from "core/llm/types";
import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
import { v4 } from "uuid";
import { ContextItemId } from "core/llm/types";
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: "test.py",
name: "test.py",
id: {
itemId: "test.py",
providerTitle: "file",
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: "test.js",
name: "test.js",
id: {
itemId: "test.js",
providerTitle: "file",
},
},
];
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
params: { context_items: TEST_CONTEXT_ITEMS },
hide: false,
depth: 0,
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
params: {},
hide: false,
depth: 0,
},
{
description: "Now write it in Rust",
name: "User Input",
params: {},
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
hide: false,
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
depth: 0,
},
];
export interface SessionFullState {
history: StepDescription[];
context_items: ContextItem[];
active: boolean;
title: string;
session_id: string;
}
export const sessionStateSlice = createSlice({
name: "sessionState",
initialState: {
history: [],
context_items: [],
active: false,
title: "New Session",
session_id: v4(),
},
reducers: {
processSessionUpdate: (
state: SessionFullState,
{ payload }: { payload: SessionUpdate }
) => {
let active = state.active;
if (typeof payload.stop === "boolean") {
active = !payload.stop;
} else {
active = true;
}
let step: StepDescription | undefined = undefined;
if (payload.index > state.history.length) {
// Partial above to allow here
step = {
...(payload.update as StepDescription),
};
} else if (payload.delta === true) {
step = {
...state.history[payload.index],
};
if (payload.update.name) {
step.name = (step.name ?? "") + payload.update.name;
}
if (payload.update.description) {
step.description =
(step.description ?? "") + payload.update.description;
}
if (payload.update.observations) {
step.observations = [
...(step.observations ?? []),
...(payload.update.observations as any),
];
}
if (payload.update.logs) {
step.logs = [...(step.logs ?? []), ...(payload.update.logs as any)];
}
} else if (payload.delta === false) {
step = {
...state.history[payload.index],
...payload.update,
};
}
let history = [...state.history];
if (step) {
if (payload.index >= history.length) {
history.push(step);
} else {
history[payload.index] = step;
}
}
return {
...state,
history,
active,
};
},
newSession: (
state: SessionFullState,
{ payload }: { payload: PersistedSessionInfo | undefined }
) => {
if (payload) {
return {
...state,
history: payload.session_state.history,
context_items: payload.session_state.context_items,
contextItemsAtIndex: {},
active: false,
title: payload.title,
session_id: payload.session_id,
};
}
return {
...state,
history: [],
context_items: [],
contextItemsAtIndex: {},
active: false,
title: "New Session",
session_id: v4(),
};
},
setTitle: (state: SessionFullState, { payload }: { payload: string }) => {
return {
...state,
title: payload,
};
},
setActive: (state: SessionFullState, { payload }: { payload: boolean }) => {
return {
...state,
active: payload,
};
},
setHistory: (
state: SessionFullState,
{ payload }: { payload: StepDescription[] }
) => {
return {
...state,
history: payload,
};
},
deleteAtIndex: (
state: SessionFullState,
{ payload }: { payload: number }
) => {
let newHistory = [...state.history];
newHistory[payload] = {
...newHistory[payload],
hide: true,
};
return { ...state, history: newHistory };
},
addContextItem: (
state: SessionFullState,
{ payload }: { payload: ContextItem }
) => {
return {
...state,
context_items: [...state.context_items, payload],
};
},
addContextItemAtIndex: (
state: SessionFullState,
{ payload }: { payload: { item: ContextItem; index: number } }
) => {
let history = [...state.history];
history[payload.index] = {
...history[payload.index],
params: {
...history[payload.index].params,
context_items: [
...((history[payload.index].params?.context_items as any) || []),
payload.item,
],
},
};
return {
...state,
history,
};
},
addHighlightedCode: (
state: SessionFullState,
{
payload,
}: {
payload: { rangeInFileWithContents: any; edit: boolean };
}
) => {
let contextItems = [...state.context_items].map((item) => {
return { ...item, editing: false };
});
const base = payload.rangeInFileWithContents.filepath
.split(/[\\/]/)
.pop();
// Merge if there is overlap
for (let i = 0; i < contextItems.length; i++) {
const item = contextItems[i];
if (item.description === payload.rangeInFileWithContents.filepath) {
let newStart = payload.rangeInFileWithContents.range.start.line;
let newEnd = payload.rangeInFileWithContents.range.end.line;
let [oldStart, oldEnd] = item.name
.split("(")[1]
.split(")")[0]
.split("-")
.map((x: string) => parseInt(x) - 1);
if (newStart > oldEnd || newEnd < oldStart) {
continue;
}
const startLine = Math.min(newStart, oldStart);
const endLine = Math.max(newEnd, oldEnd);
// const oldContents = item.content.split("\n");
// const newContents =
// payload.rangeInFileWithContents.contents.split("\n");
// const finalContents = [];
contextItems[i] = {
...item,
name: `${base} (${startLine + 1}-${endLine + 1})`,
content: payload.rangeInFileWithContents.contents,
editing: true,
editable: true,
};
return { ...state, context_items: contextItems };
}
}
const lineNums = `(${
payload.rangeInFileWithContents.range.start.line + 1
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
contextItems.push({
name: `${base} ${lineNums}`,
description: payload.rangeInFileWithContents.filepath,
id: {
providerTitle: "code",
itemId: v4(),
},
content: payload.rangeInFileWithContents.contents,
editing: true,
editable: true,
});
return { ...state, context_items: contextItems };
},
deleteContextWithIds: (
state: SessionFullState,
{
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
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.id.providerTitle}-${item.id.itemId}`)
),
};
} else {
return {
...state,
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).filter(
(item: ContextItem) =>
!ids.includes(
`${item.id.providerTitle}-${item.id.itemId}`
)
),
},
};
}
return step;
}),
};
}
},
clearContextItems: (state: SessionFullState) => {
return {
...state,
context_items: [],
};
},
setEditingAtIds: (
state: SessionFullState,
{
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
const ids = payload.ids.map((id) => id.itemId);
if (typeof payload.index === "undefined") {
return {
...state,
context_items: state.context_items.map((item) => {
return {
...item,
editing: ids.includes(item.id.itemId),
};
}),
};
} else {
return {
...state,
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).map(
(item: ContextItem) => {
return {
...item,
editing: ids.includes(item.id.itemId),
};
}
),
},
};
}
return step;
}),
};
}
},
},
});
export const {
setActive,
setHistory,
processSessionUpdate,
newSession,
deleteAtIndex,
addContextItem,
addContextItemAtIndex,
addHighlightedCode,
deleteContextWithIds,
setTitle,
setEditingAtIds,
clearContextItems,
} = sessionStateSlice.actions;
export default sessionStateSlice.reducer;

View file

@ -1,12 +1,91 @@
import { createSlice } from "@reduxjs/toolkit";
import { RootStore } from "../store";
import { ContextItemId } from "core/llm/types";
import { ContextItem, ContextItemId } from "core/llm/types";
import defaultConfig from "core/config/default";
import { v4 } from "uuid";
import { PersistedSessionInfo } from "core/types";
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: "test.py",
name: "test.py",
id: {
itemId: "test.py",
providerTitle: "file",
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: "test.js",
name: "test.js",
id: {
itemId: "test.js",
providerTitle: "file",
},
},
];
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
params: { context_items: TEST_CONTEXT_ITEMS },
hide: false,
depth: 0,
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
params: {},
hide: false,
depth: 0,
},
{
description: "Now write it in Rust",
name: "User Input",
params: {},
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
hide: false,
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
depth: 0,
},
];
const initialState: RootStore["state"] = {
history: [],
contextItems: [],
active: false,
config: defaultConfig,
title: "New Session",
sessionId: v4(),
};
export const stateSlice = createSlice({
@ -14,7 +93,10 @@ export const stateSlice = createSlice({
initialState,
reducers: {
setConfig: (state, action) => {
state.config = action.payload;
return {
...state,
config: action.payload,
};
},
addContextItemsAtIndex: (state, action) => {
if (action.payload.index < state.history.length) {
@ -73,7 +155,10 @@ export const stateSlice = createSlice({
state.active = true;
},
setInactive: (state) => {
state.active = false;
return {
...state,
active: false,
};
},
streamUpdate: (state, action) => {
if (state.history.length > 0) {
@ -81,10 +166,26 @@ export const stateSlice = createSlice({
action.payload;
}
},
newSession: (state) => {
state.history = [];
state.contextItems = [];
state.active = false;
newSession: (
state,
{ payload }: { payload: PersistedSessionInfo | undefined }
) => {
if (payload) {
return {
...state,
history: payload.history,
title: payload.title,
sessionId: payload.sessionId,
};
}
return {
...state,
history: [],
contextItems: [],
active: false,
title: "New Session",
sessionId: v4(),
};
},
deleteContextWithIds: (
state,
@ -120,6 +221,109 @@ export const stateSlice = createSlice({
};
}
},
addHighlightedCode: (
state,
{
payload,
}: {
payload: { rangeInFileWithContents: any; edit: boolean };
}
) => {
let contextItems = [...state.contextItems].map((item) => {
return { ...item, editing: false };
});
const base = payload.rangeInFileWithContents.filepath
.split(/[\\/]/)
.pop();
// Merge if there is overlap
for (let i = 0; i < contextItems.length; i++) {
const item = contextItems[i];
if (item.description === payload.rangeInFileWithContents.filepath) {
let newStart = payload.rangeInFileWithContents.range.start.line;
let newEnd = payload.rangeInFileWithContents.range.end.line;
let [oldStart, oldEnd] = item.name
.split("(")[1]
.split(")")[0]
.split("-")
.map((x: string) => parseInt(x) - 1);
if (newStart > oldEnd || newEnd < oldStart) {
continue;
}
const startLine = Math.min(newStart, oldStart);
const endLine = Math.max(newEnd, oldEnd);
// const oldContents = item.content.split("\n");
// const newContents =
// payload.rangeInFileWithContents.contents.split("\n");
// const finalContents = [];
contextItems[i] = {
...item,
name: `${base} (${startLine + 1}-${endLine + 1})`,
content: payload.rangeInFileWithContents.contents,
editing: true,
editable: true,
};
return { ...state, contextItems };
}
}
const lineNums = `(${
payload.rangeInFileWithContents.range.start.line + 1
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
contextItems.push({
name: `${base} ${lineNums}`,
description: payload.rangeInFileWithContents.filepath,
id: {
providerTitle: "code",
itemId: v4(),
},
content: payload.rangeInFileWithContents.contents,
editing: true,
editable: true,
});
return { ...state, contextItems };
},
setEditingAtIds: (
state,
{
payload,
}: { payload: { ids: ContextItemId[]; index: number | undefined } }
) => {
const ids = payload.ids.map((id) => id.itemId);
if (typeof payload.index === "undefined") {
return {
...state,
contextItems: state.contextItems.map((item) => {
return {
...item,
editing: ids.includes(item.id.itemId),
};
}),
};
} else {
return {
...state,
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...step,
contextItems: step.contextItems.map((item) => {
return {
...item,
editing: ids.includes(item.id.itemId),
};
}),
};
}
return step;
}),
};
}
},
},
});
@ -133,5 +337,7 @@ export const {
newSession,
deleteContextWithIds,
resubmitAtIndex,
addHighlightedCode,
setEditingAtIds,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -4,11 +4,7 @@ import miscReducer from "./slices/miscSlice";
import uiStateReducer from "./slices/uiStateSlice";
import serverStateReducer from "./slices/serverStateReducer";
import stateReducer from "./slices/stateSlice";
import sessionStateReducer, {
SessionFullState,
} from "./slices/sessionStateReducer";
import { ContinueConfig } from "../schema/ContinueConfig";
// import { ContextItem } from "../schema/ContextItem";
import { ContextItem } from "core/llm/types";
import { ContextProviderDescription } from "../schema/ContextProviderDescription";
import { SlashCommandDescription } from "../schema/SlashCommandDescription";
@ -29,6 +25,8 @@ export interface RootStore {
contextItems: ContextItem[];
active: boolean;
config: SerializedContinueConfig;
title: string;
sessionId: string;
};
config: {
@ -46,7 +44,6 @@ export interface RootStore {
dialogMessage: string | JSX.Element;
dialogEntryOn: boolean;
};
sessionState: SessionFullState;
serverState: {
meilisearchUrl: string | undefined;
slashCommands: SlashCommandDescription[];
@ -63,7 +60,6 @@ const rootReducer = combineReducers({
config: configReducer,
misc: miscReducer,
uiState: uiStateReducer,
sessionState: sessionStateReducer,
serverState: serverStateReducer,
});