clearer session types, fix update/delete

This commit is contained in:
Dallin Romney 2024-11-24 17:49:32 -08:00
parent 2c597764ca
commit 36fc4a5da0
15 changed files with 127 additions and 207 deletions

View file

@ -176,7 +176,7 @@ declare global {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface PersistedSessionInfo {
export interface Session {
history: ChatHistory;
title: string;
workspaceDirectory: string;

10
core/index.d.ts vendored
View file

@ -237,15 +237,15 @@ export interface Checkpoint {
[filepath: string]: string;
}
export interface PersistedSessionInfo {
history: ChatHistory;
export interface Session {
sessionId: string;
title: string;
workspaceDirectory: string;
sessionId: string;
history: ChatHistoryItem[];
checkpoints?: Checkpoint[];
}
export interface SessionInfo {
export interface SessionMetadata {
sessionId: string;
title: string;
dateCreated: string;
@ -357,8 +357,6 @@ export interface ChatHistoryItem {
promptLogs?: PromptLog[];
}
export type ChatHistory = ChatHistoryItem[];
// LLM
export interface LLMFullCompletionOptions extends BaseCompletionOptions {

View file

@ -1,4 +1,4 @@
import { ChatHistory, ChatMessage, MessagePart } from "../index.js";
import { ChatHistoryItem, ChatMessage, MessagePart } from "../index.js";
const SYSTEM_MESSAGE = `When generating new code:
@ -70,7 +70,7 @@ function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean {
}
export function constructMessages(
history: ChatHistory,
history: ChatHistoryItem[],
model: string,
): ChatMessage[] {
const msgs = [];

View file

@ -14,10 +14,10 @@ import type {
MessageContent,
ModelDescription,
ModelRoles,
PersistedSessionInfo,
Session,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
SessionMetadata,
SiteIndexingConfig,
} from "../";
@ -47,10 +47,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
abort: [undefined, void];
// History
"history/list": [ListHistoryOptions, SessionInfo[]];
"history/list": [ListHistoryOptions, SessionMetadata[]];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, PersistedSessionInfo];
"history/save": [PersistedSessionInfo, void];
"history/load": [{ id: string }, Session];
"history/save": [Session, void];
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [

View file

@ -1,11 +1,11 @@
import { v4 as uuidv4 } from "uuid";
import { PersistedSessionInfo } from "../..";
import { Session } from "../..";
import historyManager from "../../util/history";
import { getSessionFilePath } from "../../util/paths";
const sessionId = uuidv4();
const testSession: PersistedSessionInfo = {
const testSession: Session = {
history: [],
title: `${sessionId} title`,
workspaceDirectory: "workspaceDir",
@ -43,7 +43,9 @@ describe("Full session lifecycle", () => {
// save and list
historyManager.save(testSession);
const sessions = historyManager.list({});
const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId);
const sessionExists = sessions.some(
(session) => session?.sessionId === testSession.sessionId,
);
expect(sessionExists).toBe(true);
});
@ -90,7 +92,9 @@ describe("Many sessions created", () => {
const offset = 10;
const sessions = historyManager.list({ offset: offset, limit: limit });
const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString());
const sessionIds = Array.from({ length: limit }, (_, i) =>
(i + offset).toString(),
);
const isSessionIdInList = (sessionId: string) =>
sessions.some((session) => session.sessionId === sessionId);
expect(sessionIds.every(isSessionIdInList)).toBe(true);
@ -111,8 +115,9 @@ describe("Many sessions created", () => {
const offset = 75;
const sessions = historyManager.list({ offset: offset });
const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) =>
(i + offset).toString(),
const sessionIds = Array.from(
{ length: sessions.length - offset },
(_, i) => (i + offset).toString(),
);
const isSessionIdInList = (sessionId: string) =>

View file

@ -1,6 +1,6 @@
import * as fs from "fs";
import { PersistedSessionInfo, SessionInfo } from "../index.js";
import { Session, SessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
@ -18,14 +18,14 @@ function safeParseArray<T>(
}
class HistoryManager {
list(options: ListHistoryOptions): SessionInfo[] {
list(options: ListHistoryOptions): SessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
let sessions = safeParseArray<SessionInfo>(content) ?? [];
let sessions = safeParseArray<SessionMetadata>(content) ?? [];
sessions = sessions.filter((session: any) => {
// Filter out old format
return typeof session.session_id !== "string";
@ -52,7 +52,7 @@ class HistoryManager {
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList =
safeParseArray<SessionInfo>(
safeParseArray<SessionMetadata>(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
@ -67,15 +67,13 @@ class HistoryManager {
);
}
load(sessionId: string): PersistedSessionInfo {
load(sessionId: string): Session {
try {
const sessionFile = getSessionFilePath(sessionId);
if (!fs.existsSync(sessionFile)) {
throw new Error(`Session file ${sessionFile} does not exist`);
}
const session: PersistedSessionInfo = JSON.parse(
fs.readFileSync(sessionFile, "utf8"),
);
const session: Session = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
session.sessionId = sessionId;
return session;
} catch (e) {
@ -89,11 +87,20 @@ class HistoryManager {
}
}
save(session: PersistedSessionInfo) {
save(session: Session) {
// Save the main session json file
// Explicitely rewriting here to influence the written key order in the file!
// e.g. id at the top, history next, etc.
const orderedSession: Session = {
sessionId: session.sessionId,
title: session.title,
workspaceDirectory: session.workspaceDirectory,
history: session.history,
checkpoints: session.checkpoints,
};
fs.writeFileSync(
getSessionFilePath(session.sessionId),
JSON.stringify(session, undefined, 2),
JSON.stringify(orderedSession, undefined, 2),
);
// Read and update the sessions list
@ -101,7 +108,7 @@ class HistoryManager {
try {
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
let sessionsList: SessionInfo[];
let sessionsList: SessionMetadata[];
try {
sessionsList = JSON.parse(rawSessionsList);
} catch (e) {
@ -114,23 +121,23 @@ class HistoryManager {
}
let found = false;
for (const sessionInfo of sessionsList) {
if (sessionInfo.sessionId === session.sessionId) {
sessionInfo.title = session.title;
sessionInfo.workspaceDirectory = session.workspaceDirectory;
for (const sessionMetadata of sessionsList) {
if (sessionMetadata.sessionId === session.sessionId) {
sessionMetadata.title = session.title;
sessionMetadata.workspaceDirectory = session.workspaceDirectory;
found = true;
break;
}
}
if (!found) {
const sessionInfo: SessionInfo = {
const sessionMetadata: SessionMetadata = {
sessionId: session.sessionId,
title: session.title,
dateCreated: String(Date.now()),
workspaceDirectory: session.workspaceDirectory,
};
sessionsList.push(sessionInfo);
sessionsList.push(sessionMetadata);
}
fs.writeFileSync(

View file

@ -1,107 +0,0 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.constants.getSessionFilePath
import com.github.continuedev.continueintellijextension.constants.getSessionsListPath
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.lang.reflect.Type
typealias PersistedSessionInfo = MutableMap<String, Any>
typealias SessionInfo = MutableMap<String, Any>
class HistoryManager {
private val gson = Gson()
fun list(): List<PersistedSessionInfo> {
val filePath = getSessionsListPath()
val file = File(filePath)
if (!file.exists()) {
return emptyList()
}
val reader = FileReader(file)
val type: Type = object : TypeToken<List<PersistedSessionInfo>>() {}.type
val sessions = gson.fromJson<List<PersistedSessionInfo>>(reader, type)
return sessions.filter { it["sessionId"] != null }
}
fun delete(sessionId: String) {
val sessionFile = getSessionFilePath(sessionId)
val file = File(sessionFile)
if (!file.exists()) {
throw Exception("Session file $sessionFile does not exist")
}
file.delete()
val sessionsListFile = getSessionsListPath()
val sessionsListRaw = FileReader(File(sessionsListFile))
val type: Type = object : TypeToken<List<SessionInfo>>() {}.type
var sessionsList = gson.fromJson<List<SessionInfo>>(sessionsListRaw, type)
sessionsList = sessionsList.filter { it["sessionId"] != sessionId }
val writer = FileWriter(sessionsListFile)
gson.toJson(sessionsList, writer)
writer.close()
}
fun load(sessionId: String): PersistedSessionInfo {
val sessionFile = getSessionFilePath(sessionId)
val file = File(sessionFile)
if (!file.exists()) {
throw Exception("Session file $sessionFile does not exist")
}
val reader = FileReader(file)
val text = reader.readText()
val type: Type = object : TypeToken<MutableMap<String, Any>>() {}.type
val session = gson.fromJson<MutableMap<String, Any>>(text, type)
session["sessionId"] = sessionId
return session
}
fun save(session: PersistedSessionInfo) {
val writer = FileWriter(getSessionFilePath(session["sessionId"] as String? ?: uuid()))
gson.toJson(session, writer)
writer.close()
val sessionsListFilePath = getSessionsListPath()
val rawSessionsList = FileReader(File(sessionsListFilePath))
val type: Type = object : TypeToken<List<SessionInfo>>() {}.type
val sessionsList = gson.fromJson<List<MutableMap<String, Any>>>(rawSessionsList, type).toMutableList()
var found = false
for (sessionInfo in sessionsList) {
if (sessionInfo["sessionId"] == session["sessionId"]) {
sessionInfo["title"] = session["title"] as Any
sessionInfo["workspaceDirectory"] = session["workspaceDirectory"] as Any
sessionInfo["dateCreated"] = System.currentTimeMillis().toString()
found = true
break
}
}
if (!found) {
val sessionInfo = mutableMapOf(
"sessionId" to session["sessionId"],
"title" to session["title"],
"dateCreated" to System.currentTimeMillis().toString(),
"workspaceDirectory" to session["workspaceDirectory"]
) as MutableMap<String, Any>
sessionsList.add(sessionInfo)
}
val writerList = FileWriter(sessionsListFilePath)
gson.toJson(sessionsList, writerList)
writerList.close()
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.232",
"version": "0.9.233",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.232",
"version": "0.9.233",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -109,7 +109,7 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",

8
gui/package-lock.json generated
View file

@ -56,7 +56,6 @@
"socket.io-client": "^4.7.2",
"styled-components": "^5.3.6",
"table": "^6.8.1",
"tailwind-scrollbar-hide": "^1.1.7",
"tippy.js": "^6.3.7",
"unist-util-visit": "^5.0.0",
"uuid": "^9.0.1",
@ -112,7 +111,7 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
@ -8984,11 +8983,6 @@
"node": ">=10.0.0"
}
},
"node_modules/tailwind-scrollbar-hide": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/tailwind-scrollbar-hide/-/tailwind-scrollbar-hide-1.1.7.tgz",
"integrity": "sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA=="
},
"node_modules/tailwindcss": {
"version": "3.4.12",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz",

View file

@ -1,5 +1,5 @@
import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline";
import { SessionInfo } from "core";
import { SessionMetadata } from "core";
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
@ -14,13 +14,15 @@ function lastPartOfPath(path: string): string {
}
export function HistoryTableRow({
session,
sessionMetadata,
date,
onDelete,
onEdit,
}: {
session: SessionInfo;
sessionMetadata: SessionMetadata;
date: Date;
onDelete: (sessionId: string) => void;
onEdit: (session: SessionMetadata) => void;
}) {
const dispatch = useDispatch();
const navigate = useNavigate();
@ -28,7 +30,7 @@ export function HistoryTableRow({
const [hovered, setHovered] = useState(false);
const [editing, setEditing] = useState(false);
const [sessionTitleEditValue, setSessionTitleEditValue] = useState(
session.title,
sessionMetadata.title,
);
const currentSessionId = useSelector(
(state: RootState) => state.state.sessionId,
@ -39,16 +41,19 @@ export function HistoryTableRow({
const handleKeyUp = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
if (sessionTitleEditValue !== session.title) {
session.title = sessionTitleEditValue;
const persistedSessionInfo = await getSession(session.sessionId);
persistedSessionInfo.title = sessionTitleEditValue;
await updateSession(persistedSessionInfo);
if (sessionTitleEditValue !== sessionMetadata.title) {
const sessionData = await getSession(sessionMetadata.sessionId);
sessionData.title = sessionTitleEditValue;
await updateSession(sessionData);
onEdit({
...sessionMetadata,
title: sessionTitleEditValue,
});
}
setEditing(false);
} else if (e.key === "Escape") {
setEditing(false);
setSessionTitleEditValue(session.title);
setSessionTitleEditValue(sessionMetadata.title);
}
};
@ -63,9 +68,9 @@ export function HistoryTableRow({
className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3"
onClick={async () => {
// Save current session
if (session.sessionId !== currentSessionId) {
if (sessionMetadata.sessionId !== currentSessionId) {
await saveSession();
await loadSession(session.sessionId);
await loadSession(sessionMetadata.sessionId);
}
navigate("/");
@ -86,12 +91,14 @@ export function HistoryTableRow({
</div>
) : (
<span className="text-md block max-w-80 truncate text-base font-semibold">
{JSON.stringify(session.title).slice(1, -1)}
{JSON.stringify(sessionMetadata.title).slice(1, -1)}
</span>
)}
<div className="flex" style={{ color: "#9ca3af" }}>
<span>{lastPartOfPath(session.workspaceDirectory || "")}</span>
<span>
{lastPartOfPath(sessionMetadata.workspaceDirectory || "")}
</span>
{/* Uncomment to show the date */}
{/* <span className="inline-block ml-auto">
{date.toLocaleString("en-US", {
@ -119,9 +126,10 @@ export function HistoryTableRow({
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Delete"
onClick={async () => {
await deleteSession(session.sessionId);
onDelete(session.sessionId);
onClick={async (e) => {
e.stopPropagation();
await deleteSession(sessionMetadata.sessionId);
onDelete(sessionMetadata.sessionId);
}}
>
<TrashIcon width="1.3em" height="1.3em" />

View file

@ -1,10 +1,10 @@
import { SessionInfo } from "core";
import { SessionMetadata } from "core";
import MiniSearch from "minisearch";
import React, { Fragment, useEffect, useMemo, useState } from "react";
import React, { Fragment, useEffect, useMemo, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import useHistory from "../../hooks/useHistory";
import { getFontSize } from "../../util";
import { getFontSize, getMetaKeyLabel } from "../../util";
import { HistoryTableRow } from "./HistoryTableRow";
import { XMarkIcon } from "@heroicons/react/24/solid";
@ -20,13 +20,7 @@ const HEADER_CLASS =
"flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6";
export function History() {
const [sessions, setSessions] = useState<SessionInfo[]>([]);
const deleteSessionInUI = async (sessionId: string) => {
setSessions((prev) =>
prev.filter((session) => session.sessionId !== sessionId),
);
};
const [sessions, setSessions] = useState<SessionMetadata[]>([]);
const searchInputRef = React.useRef<HTMLInputElement>(null);
@ -35,12 +29,12 @@ export function History() {
const [searchTerm, setSearchTerm] = useState("");
const minisearch = useMemo(() => {
return new MiniSearch({
const minisearch = useRef<MiniSearch>(
new MiniSearch({
fields: ["title"],
storeFields: ["title", "sessionId", "id"],
});
}, []);
}),
).current;
useEffect(() => {
const fetchSessions = async () => {
@ -64,7 +58,27 @@ export function History() {
fetchSessions();
}, [lastSessionId]);
const filteredAndSortedSessions: SessionInfo[] = useMemo(() => {
const deleteSessionInUI = async (sessionId: string) => {
setSessions((prev) =>
prev.filter((session) => session.sessionId !== sessionId),
);
minisearch.discard(sessionId);
};
const updateSessionInUI = async (session: SessionMetadata) => {
setSessions((prev) =>
prev.map((sess) =>
sess.sessionId === session.sessionId ? session : sess,
),
);
minisearch.replace({
title: session.title,
sessionId: session.sessionId,
id: session.sessionId,
});
};
const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => {
const sessionIds = minisearch
.search(searchTerm, {
fuzzy: 0.1,
@ -114,7 +128,9 @@ export function History() {
{filteredAndSortedSessions.length === 0 && (
<div className="m-4 text-center">
No past sessions found. To start a new session, either click the "+"
button or use the keyboard shortcut: <b>Option + Command + N</b>
button or use the keyboard shortcut: <code>{getMetaKeyLabel()}</code>
{` `}
<code>L</code>
</div>
)}
@ -152,10 +168,10 @@ export function History() {
)}
<HistoryTableRow
key={session.sessionId}
session={session}
sessionMetadata={session}
date={date}
onDelete={() => deleteSessionInUI(session.sessionId)}
onDelete={deleteSessionInUI}
onEdit={updateSessionInUI}
/>
</Fragment>
);

View file

@ -104,7 +104,7 @@ function ChatIndexingPeeks() {
return (
<div className="flex flex-col gap-1">
{mergedIndexingStates.map((state) => {
return <ChatIndexingPeek state={state} />;
return <ChatIndexingPeek key={state.type} state={state} />;
})}
</div>
);

View file

@ -1,7 +1,6 @@
import { Dispatch } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/react";
import {
ChatHistory,
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
@ -276,7 +275,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
editorState,
};
let newHistory: ChatHistory = [...history.slice(0, index), historyItem];
let newHistory: ChatHistoryItem[] = [
...history.slice(0, index),
historyItem,
];
const historyIndex = index || newHistory.length - 1;
dispatch(
setMessageAtIndex({

View file

@ -1,5 +1,5 @@
import { Dispatch } from "@reduxjs/toolkit";
import { PersistedSessionInfo, SessionInfo } from "core";
import { Session, SessionMetadata } from "core";
import { stripImages } from "core/llm/images";
import { useCallback, useContext } from "react";
@ -32,7 +32,7 @@ function useHistory(dispatch: Dispatch) {
async function getHistory(
offset?: number,
limit?: number,
): Promise<SessionInfo[]> {
): Promise<SessionMetadata[]> {
const result = await ideMessenger.request("history/list", {
offset,
limit,
@ -87,7 +87,7 @@ function useHistory(dispatch: Dispatch) {
? stateCopy.title
: (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page.
const sessionInfo: PersistedSessionInfo = {
const session: Session = {
history: stateCopy.history,
title: title,
sessionId: stateCopy.sessionId,
@ -95,10 +95,10 @@ function useHistory(dispatch: Dispatch) {
checkpoints: stateCopy.checkpoints,
};
return await ideMessenger.request("history/save", sessionInfo);
return await ideMessenger.request("history/save", session);
}
async function getSession(id: string): Promise<PersistedSessionInfo> {
async function getSession(id: string): Promise<Session> {
const result = await ideMessenger.request("history/load", { id });
if (result.status === "error") {
throw new Error(result.error);
@ -106,15 +106,15 @@ function useHistory(dispatch: Dispatch) {
return result.content;
}
async function updateSession(sessionInfo: PersistedSessionInfo) {
return await ideMessenger.request("history/save", sessionInfo);
async function updateSession(session: Session) {
return await ideMessenger.request("history/save", session);
}
async function deleteSession(id: string) {
return await ideMessenger.request("history/delete", { id });
}
async function loadSession(id: string): Promise<PersistedSessionInfo> {
async function loadSession(id: string): Promise<Session> {
updateLastSessionId(state.sessionId);
const result = await ideMessenger.request("history/load", { id });
if (result.status === "error") {
@ -126,7 +126,7 @@ function useHistory(dispatch: Dispatch) {
return sessionContent;
}
async function loadLastSession(): Promise<PersistedSessionInfo | undefined> {
async function loadLastSession(): Promise<Session | undefined> {
const lastSessionId = getLocalStorage("lastSessionId");
if (lastSessionId) {
return await loadSession(lastSessionId);

View file

@ -8,7 +8,7 @@ import {
ContextItemWithId,
FileSymbolMap,
IndexingStatus,
PersistedSessionInfo,
Session,
PromptLog,
} from "core";
import { BrowserSerializedContinueConfig } from "core/config/load";
@ -298,10 +298,7 @@ export const stateSlice = createSlice({
action.payload;
}
},
newSession: (
state,
{ payload }: PayloadAction<PersistedSessionInfo | undefined>,
) => {
newSession: (state, { payload }: PayloadAction<Session | undefined>) => {
state.streamAborter.abort();
state.streamAborter = new AbortController();