⚡️ refactoring redux store

This commit is contained in:
Nate Sesti 2023-12-06 10:43:03 -08:00
parent 552b4e3586
commit 9d8a25c0b0
12 changed files with 584 additions and 299 deletions

View file

@ -22,6 +22,10 @@ Reasons to avoid Python
TODO:
Little stuff:
- create_client_session -> createAxiosConfig from requestOptions
Imports
- tiktoken

View file

@ -0,0 +1,19 @@
import { ChatHistory, ChatMessage } from "./types";
export function constructMessages(history: ChatHistory): ChatMessage[] {
const msgs: ChatMessage[] = [];
for (const historyItem of history) {
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);
}
return msgs;
}

View file

@ -1,4 +1,4 @@
import { CONTEXT_LENGTH_FOR_MODEL } from "./constants";
import { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS } from "./constants";
import {
compileChatMessages,
countTokens,
@ -6,14 +6,14 @@ import {
} from "./countTokens";
import { CompletionOptions, RequestOptions, ChatMessage } from "./types";
interface ILLM {
interface LLMOptions {
title?: string;
uniqueId?: string;
model: string;
uniqueId: string;
model?: string;
systemMessage?: string;
contextLength: number;
completionOptions: CompletionOptions;
requestOptions: RequestOptions;
contextLength?: number;
completionOptions?: CompletionOptions;
requestOptions?: RequestOptions;
promptTemplates?: Record<string, string>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
@ -37,9 +37,9 @@ interface LLMFullCompletionOptions {
maxTokens?: number;
}
abstract class AbstractLLM implements ILLM {
export abstract class LLM implements LLMOptions {
title?: string;
uniqueId?: string;
uniqueId: string;
model: string;
systemMessage?: string;
contextLength: number;
@ -52,7 +52,7 @@ abstract class AbstractLLM implements ILLM {
apiKey?: string;
apiBase?: string;
constructor(options: ILLM) {
constructor(options: LLMOptions) {
this.title = options.title;
this.uniqueId = options.uniqueId;
this.model = options.model;
@ -251,7 +251,7 @@ abstract class AbstractLLM implements ILLM {
completionOptions
)) {
completion += chunk;
yield chunk;
yield { role: "assistant", content: chunk, summary: chunk };
}
} else {
for await (const chunk of this._streamChat(messages, completionOptions)) {
@ -263,11 +263,14 @@ abstract class AbstractLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, completion);
}
private async *_streamComplete(prompt: string, options: CompletionOptions) {
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
throw new Error("Not implemented");
}
private async *_streamChat(
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
@ -285,7 +288,7 @@ abstract class AbstractLLM implements ILLM {
}
}
private async _complete(prompt: string, options: CompletionOptions) {
protected async _complete(prompt: string, options: CompletionOptions) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, options)) {
completion += chunk;
@ -296,4 +299,12 @@ abstract class AbstractLLM implements ILLM {
countTokens(text: string): number {
return countTokens(text, this.model);
}
protected collectArgs(options: CompletionOptions): any {
return {
...DEFAULT_ARGS,
// model: this.model,
...options,
};
}
}

128
core/llm/llms/FreeTrial.ts Normal file
View file

@ -0,0 +1,128 @@
import { LLM } from "..";
import { ChatMessage, CompletionOptions } from "../types";
import axios from "axios";
// const SERVER_URL = "http://127.0.0.1:8080"
const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app";
class FreeTrial extends LLM {
private _getHeaders() {
return { uniqueId: this.uniqueId || "None" };
}
protected async _complete(
prompt: string,
options: CompletionOptions
): Promise<string> {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/complete`,
{
messages: [{ role: "user", content: prompt }],
...args,
},
{
headers: this._getHeaders(),
// proxy: this.requestOptions.proxy,
}
);
if (response.status != 200) {
throw new Error(response.data);
}
return response.data;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/stream_complete`,
{
messages: [{ role: "user", content: prompt }],
...args,
},
{
headers: this._getHeaders(),
responseType: "stream",
// proxy: this.requestOptions.proxy,
}
);
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");
yield decodedChunk;
}
}
}
}
async function* streamChat(messages: ChatMessage[], options: any) {
const args = this.collectArgs(options);
const response = await axios.post(
`${SERVER_URL}/stream_chat`,
{
messages,
...args,
},
{
headers: this.getHeaders(),
// proxy: requestOptions.proxy,
responseType: "stream",
}
);
if (response.status !== 200) {
throw new Error(await streamToString(response.data));
}
for await (const chunk of response.data) {
if (chunk) {
const jsonChunk = chunk.toString("utf-8");
const chunks = jsonChunk.split("\n");
for (const chunk of chunks) {
if (chunk.trim() !== "") {
const loadedChunk = JSON.parse(chunk);
yield {
role: "assistant",
content: loadedChunk.content || "",
};
if (this.model === "gpt-4") {
await delay(0.03);
} else {
await delay(0.01);
}
}
}
}
}
}
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;

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

@ -27,4 +27,27 @@ interface ChatMessage {
summary: string;
}
export { CompletionOptions, RequestOptions, ChatMessage, ChatMessageRole };
interface ContextItem {
content: string;
name: string;
description: string;
providerTitle: string;
itemId: string;
}
interface ChatHistoryItem {
message: ChatMessage;
contextItems: ContextItem[];
}
type ChatHistory = ChatHistoryItem[];
export {
CompletionOptions,
RequestOptions,
ChatMessage,
ChatMessageRole,
ChatHistory,
ChatHistoryItem,
ContextItem,
};

106
core/package-lock.json generated Normal file
View file

@ -0,0 +1,106 @@
{
"name": "core",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "core",
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"axios": "^1.6.2"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz",
"integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==",
"dependencies": {
"follow-redirects": "^1.15.0",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/follow-redirects": {
"version": "1.15.3",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz",
"integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
}
}
}

14
core/package.json Normal file
View file

@ -0,0 +1,14 @@
{
"name": "core",
"version": "1.0.0",
"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"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"axios": "^1.6.2"
}
}

View file

@ -19,9 +19,10 @@ 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";
interface StepContainerProps {
step: StepDescription;
item: ChatHistoryItem;
onReverse: () => void;
onUserInput: (input: string) => void;
onRetry: () => void;
@ -35,10 +36,6 @@ interface StepContainerProps {
// #region styled components
const MainDiv = styled.div<{
stepDepth: number;
}>``;
const ButtonsDiv = styled.div`
display: flex;
gap: 2px;
@ -69,7 +66,7 @@ function StepContainer(props: StepContainerProps) {
const [isHovered, setIsHovered] = useState(false);
const naturalLanguageInputRef = useRef<HTMLTextAreaElement>(null);
const userInputRef = useRef<HTMLInputElement>(null);
const isUserInput = props.step.name === "UserInputStep";
const isUserInput = props.item.message.role === "user";
const sessionHistory = useSelector(
(store: RootStore) => store.sessionState.history
);
@ -96,7 +93,7 @@ function StepContainer(props: StepContainerProps) {
const logs = sessionHistory[props.index].logs;
if (!logs || logs.length < 1) return;
const prompt = logs[0].split("#########\n")[1];
const completion = props.step.description;
const completion = props.item.message.content;
console.log(prompt, completion, client);
@ -104,20 +101,18 @@ function StepContainer(props: StepContainerProps) {
};
return (
<MainDiv
stepDepth={(props.step.depth as any) || 0}
<div
onMouseEnter={() => {
setIsHovered(true);
}}
onMouseLeave={() => {
setIsHovered(false);
}}
hidden={props.step.hide as any}
>
<div className="relative">
{isHovered && (props.step.error || props.noUserInputParent) && (
{isHovered && (false || props.noUserInputParent) && (
<ButtonsDiv>
{props.step.error &&
{false &&
((
<HeaderButtonWithText
text="Retry"
@ -157,7 +152,7 @@ function StepContainer(props: StepContainerProps) {
isUserInput={isUserInput}
fontSize={getFontSize()}
>
<StyledMarkdownPreview source={props.step.description} />
<StyledMarkdownPreview source={props.item.message.content} />
</ContentDiv>
{(isHovered || typeof feedback !== "undefined") && !active && (
<div className="flex items-center gap-2 bottom-0 right-2 absolute">
@ -192,7 +187,7 @@ function StepContainer(props: StepContainerProps) {
</div>
)}
</div>
</MainDiv>
</div>
);
}

View file

@ -4,6 +4,7 @@ import styled from "styled-components";
import { ChatBubbleOvalLeftIcon } from "@heroicons/react/24/outline";
import { getFontSize } from "../../util";
import { StepDescription } from "../../schema/SessionState";
import { ChatHistoryItem } from "../../../../core/llm/types";
const CollapseButton = styled.div`
background-color: ${vscBackground};
@ -28,7 +29,7 @@ const CollapsedDiv = styled.div<{ fontSize?: number }>`
`;
interface TimelineItemProps {
step: StepDescription;
item: ChatHistoryItem;
open: boolean;
onToggle: () => void;
children: any;
@ -50,7 +51,8 @@ function TimelineItem(props: TimelineItemProps) {
)}
</CollapseButton>
<span style={{ color: lightGray }}>
{props.step.error ? props.step.error.title : props.step.name}
{props.item.message.name || props.item.message.summary}
{/* {props.step.error ? props.step.error.title : props.step.name} */}
</span>
</CollapsedDiv>
);

View file

@ -57,6 +57,14 @@ import {
setTitle,
} from "../redux/slices/sessionStateReducer";
import { StepDescription } from "../schema/SessionState";
import FreeTrial from "../../../core/llm/llms/FreeTrial";
import { constructMessages } from "../../../core/llm/constructMessages";
import {
ChatHistory,
ChatHistoryItem,
ChatMessage,
} from "../../../core/llm/types";
import { streamUpdate, submitMessage } from "../redux/slices/stateSlice";
const TopGuiDiv = styled.div`
overflow-y: scroll;
@ -179,9 +187,7 @@ function GUI(props: GUIProps) {
// #endregion
// #region State
const [waitingForSteps, setWaitingForSteps] = useState(false);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const [waitingForClient, setWaitingForClient] = useState(true);
const [showLoading, setShowLoading] = useState(false);
useEffect(() => {
@ -218,6 +224,8 @@ function GUI(props: GUIProps) {
const [userScrolledAwayFromBottom, setUserScrolledAwayFromBottom] =
useState<boolean>(false);
const state = useSelector((state: RootStore) => state.state);
useEffect(() => {
const handleScroll = () => {
// Scroll only if user is within 200 pixels of the bottom of the window.
@ -295,51 +303,25 @@ function GUI(props: GUIProps) {
}
}
setWaitingForSteps(true);
// TODO: Sagas or something might be better?
const newHistory = [
...sessionState.history,
{
name: "User Input",
description: input,
observations: [],
logs: [],
step_type: "UserInputStep",
params: {
user_input: input,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
];
const state = {
history: newHistory,
context_items: sessionState.context_items,
const message: ChatMessage = {
role: "user",
content: input,
summary: input,
};
client.runFromState(state);
newHistory.push({
name: "Generating Response...",
description: " ",
observations: [],
logs: [],
step_type: "SimpleChatStep",
params: {},
hide: false,
depth: 0,
});
dispatch(setHistory(newHistory));
dispatch(setActive(true));
for (let contextItem of sessionState.context_items) {
dispatch(
addContextItemAtIndex({
item: contextItem,
index: newHistory.length - 1,
})
);
}
dispatch(clearContextItems());
const historyItem: ChatHistoryItem = {
message,
contextItems: state.contextItems,
};
const messages = constructMessages([...state.history, historyItem]);
dispatch(submitMessage(message));
const llm = new FreeTrial({ uniqueId: "None" });
(async () => {
for await (const update of llm.streamChat(messages)) {
dispatch(streamUpdate(update.content));
}
})();
// Increment localstorage counter for popup
const counter = localStorage.getItem("mainTextEntryCounter");
@ -415,7 +397,13 @@ function GUI(props: GUIProps) {
localStorage.setItem("mainTextEntryCounter", "1");
}
},
[client, sessionState.history, sessionState.context_items, defaultModel]
[
client,
sessionState.history,
sessionState.context_items,
defaultModel,
state,
]
);
const persistSession = useCallback(() => {
@ -591,236 +579,154 @@ function GUI(props: GUIProps) {
}
}}
>
{takenAction && showLoading && typeof client === "undefined" && (
<>
<RingLoader size={32} />
<p
style={{
textAlign: "center",
margin: "0px",
fontSize: "14px",
}}
>
{serverStatusMessage}
</p>
<div className="flex mx-8 my-2">
<p
style={{
margin: "auto",
textAlign: "center",
marginTop: "4px",
fontSize: "12px",
cursor: "pointer",
opacity: 0.7,
}}
>
<u>
<a
style={{ color: "inherit" }}
href="https://continue.dev/docs/troubleshooting"
target="_blank"
>
Troubleshooting help
</a>
</u>
</p>
<p
style={{
margin: "auto",
textAlign: "center",
marginTop: "4px",
fontSize: "12px",
cursor: "pointer",
opacity: 0.7,
}}
onClick={() => {
postToIde("toggleDevTools", {});
}}
>
<u>View logs</u>
</p>
<p
style={{
margin: "auto",
textAlign: "center",
marginTop: "4px",
fontSize: "12px",
cursor: "pointer",
opacity: 0.7,
}}
>
<u>
<a
style={{ color: "inherit" }}
href="https://continue.dev/docs/walkthroughs/manually-run-continue#recommended-use-the-continuedev-pypi-package"
target="_blank"
>
Manually start server
</a>
</u>
</p>
</div>
</>
)}
<div className="max-w-3xl m-auto">
<StepsDiv>
{sessionState?.history?.map(
(step: StepDescription, index: number) => {
if (step.hide) return null;
return (
<Fragment key={index}>
<ErrorBoundary
FallbackComponent={fallbackRender}
onReset={() => {
client?.stopSession();
dispatch(newSession());
}}
>
{step.name === "User Input" ? (
step.hide || (
<ComboBox
isMainInput={false}
value={step.description as string}
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,
{state.history.map((item, index: number) => {
return (
<Fragment key={index}>
<ErrorBoundary
FallbackComponent={fallbackRender}
onReset={() => {
client?.stopSession();
dispatch(newSession());
}}
>
{item.message.role === "user" ? (
<ComboBox
isMainInput={false}
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,
};
dispatch(clearContextItems());
},
hide: false,
depth: 0,
},
];
dispatch(setHistory(newHistory));
dispatch(setActive(true));
const state = {
history: newHistory,
context_items: sessionState.context_items,
};
dispatch(clearContextItems());
client.runFromState(state);
}
e?.stopPropagation();
e?.preventDefault();
client.runFromState(state);
}
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
item={item}
iconElement={
false ? (
<CodeBracketSquareIcon width="16px" height="16px" />
) : false ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
)
}
open={
typeof stepsOpen[index] === "undefined"
? false
? false
: true
: stepsOpen[index]!
}
onToggle={() => onToggleAtIndex(index)}
>
{false ? ( // Most of these falses were previously (step.error)
<ErrorStepContainer
onClose={() => onToggleAtIndex(index)}
error={undefined}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
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={
/>
) : (
<StepContainer
index={index}
isLast={index === sessionState.history.length - 1}
isFirst={index === 0}
open={
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));
});
key={index}
onUserInput={(input: string) => {
onStepUserInput(input, index);
}}
item={item}
onReverse={() => {
client?.reverseToIndex(index);
}}
onRetry={() => {
client?.retryAtIndex(index);
}}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
noUserInputParent={
getStepsInUserInputGroup(index).length === 0
}
/>
)
) : (
<TimelineItem
step={step}
iconElement={
step.step_type === "DefaultModelEditCodeStep" ? (
<CodeBracketSquareIcon width="16px" height="16px" />
) : step.error ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon
width="16px"
height="16px"
/>
)
}
open={
typeof stepsOpen[index] === "undefined"
? step.error
? false
: true
: stepsOpen[index]!
}
onToggle={() => onToggleAtIndex(index)}
>
{step.error ? (
<ErrorStepContainer
onClose={() => onToggleAtIndex(index)}
error={step.error}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
/>
) : (
<StepContainer
index={index}
isLast={index === sessionState.history.length - 1}
isFirst={index === 0}
open={
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
key={index}
onUserInput={(input: string) => {
onStepUserInput(input, index);
}}
step={step}
onReverse={() => {
client?.reverseToIndex(index);
}}
onRetry={() => {
client?.retryAtIndex(index);
setWaitingForSteps(true);
}}
onDelete={() => {
dispatch(deleteAtIndex(index));
}}
noUserInputParent={
getStepsInUserInputGroup(index).length === 0
}
/>
)}
</TimelineItem>
)}
{/* <div className="h-2"></div> */}
</ErrorBoundary>
</Fragment>
);
}
)}
)}
</TimelineItem>
)}
{/* <div className="h-2"></div> */}
</ErrorBoundary>
</Fragment>
);
})}
</StepsDiv>
<div ref={aboveComboBoxDivRef} />

View file

@ -0,0 +1,67 @@
import { createSlice } from "@reduxjs/toolkit";
import { RootStore } from "../store";
const initialState: RootStore["state"] = {
history: [],
contextItems: [],
active: false,
};
export const stateSlice = createSlice({
name: "state",
initialState,
reducers: {
addContextItemAtIndex: (state, action) => {
if (action.payload.index < state.history.length) {
state.history[action.payload.index].contextItems.push(
action.payload.contextItem
);
}
},
appendMessage: (state, action) => {
state.history.push(action.payload);
},
addContextItem: (state, action) => {
state.contextItems.push(action.payload);
},
submitMessage: (state, action) => {
state.history.push({
message: {
role: "user",
content: action.payload,
summary: action.payload,
},
contextItems: state.contextItems,
});
state.history.push({
message: {
role: "assistant",
content: "",
summary: "",
},
contextItems: [],
});
state.contextItems = [];
state.active = true;
},
setInactive: (state) => {
state.active = false;
},
streamUpdate: (state, action) => {
if (state.history.length > 0) {
state.history[state.history.length - 1].message.content +=
action.payload;
}
},
},
});
export const {
addContextItemAtIndex,
appendMessage,
addContextItem,
submitMessage,
setInactive,
streamUpdate,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -3,16 +3,19 @@ import configReducer from "./slices/configSlice";
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 "../schema/ContextItem";
import { ContextItem } from "../../../core/llm/types";
import { ContextProviderDescription } from "../schema/ContextProviderDescription";
import { SlashCommandDescription } from "../schema/SlashCommandDescription";
import storage from "redux-persist/lib/storage";
import { persistReducer, persistStore, createTransform } from "redux-persist";
import { ChatHistory } from "../../../core/llm/types";
export interface ChatMessage {
role: "system" | "user" | "assistant";
@ -20,6 +23,12 @@ export interface ChatMessage {
}
export interface RootStore {
state: {
history: ChatHistory;
contextItems: ContextItem[];
active: boolean;
};
config: {
vscMachineId: string | undefined;
};
@ -39,7 +48,7 @@ export interface RootStore {
serverState: {
meilisearchUrl: string | undefined;
slashCommands: SlashCommandDescription[];
selectedContextItems: ContextItem[];
selectedContextItems: any[];
config: ContinueConfig;
contextProviders: ContextProviderDescription[];
savedContextGroups: any[]; // TODO: Context groups
@ -48,6 +57,7 @@ export interface RootStore {
}
const rootReducer = combineReducers({
state: stateReducer,
config: configReducer,
misc: miscReducer,
uiState: uiStateReducer,