Elffuss BraidHub

kikocis/continue public

9d8db5fc402e · 6.0 KiBRawPermalink
1import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2import { ChatMessage, Session, SessionMetadata } from "core";
3import { NEW_SESSION_TITLE } from "core/util/constants";
4import { renderChatMessage } from "core/util/messageContent";
5import { IIdeMessenger } from "../../context/IdeMessenger";
6import { selectSelectedChatModel } from "../slices/configSlice";
7import {
8 deleteSessionMetadata,
9 newSession,
10 setAllSessionMetadata,
11 updateSessionMetadata,
12} from "../slices/sessionSlice";
13import { ThunkApiType } from "../store";
14
15const MAX_TITLE_LENGTH = 100;
16
17// Async session functions live in thunks (because of IDE messaging mostly)
18// see sessionSlice for sync redux session functions
19
20export async function getSession(
21 ideMessenger: IIdeMessenger,
22 id: string,
23): Promise<Session> {
24 const result = await ideMessenger.request("history/load", { id });
25 if (result.status === "error") {
26 throw new Error(result.error);
27 }
28 return result.content;
29}
30
31export const refreshSessionMetadata = createAsyncThunk<
32 SessionMetadata[],
33 {
34 offset?: number;
35 limit?: number;
36 },
37 ThunkApiType
38>("session/refreshMetadata", async ({ offset, limit }, { dispatch, extra }) => {
39 const result = await extra.ideMessenger.request("history/list", {
40 limit,
41 offset,
42 });
43 if (result.status === "error") {
44 throw new Error(result.error);
45 }
46 dispatch(setAllSessionMetadata(result.content));
47 return result.content;
48});
49
50export const deleteSession = createAsyncThunk<void, string, ThunkApiType>(
51 "session/delete",
52 async (id, { getState, dispatch, extra }) => {
53 dispatch(deleteSessionMetadata(id)); // optimistic
54 const state = getState();
55 if (id === state.session.id) {
56 await dispatch(
57 loadLastSession({
58 saveCurrentSession: false,
59 }),
60 );
61 }
62 const result = await extra.ideMessenger.request("history/delete", { id });
63 if (result.status === "error") {
64 throw new Error(result.error);
65 }
66 dispatch(refreshSessionMetadata({}));
67 },
68);
69
70export const updateSession = createAsyncThunk<void, Session, ThunkApiType>(
71 "session/update",
72 async (session, { extra, dispatch }) => {
73 dispatch(
74 updateSessionMetadata({
75 sessionId: session.sessionId,
76 title: session.title,
77 }),
78 ); // optimistic session metadata update
79 await extra.ideMessenger.request("history/save", session);
80 await dispatch(refreshSessionMetadata({}));
81 },
82);
83
84/*
85 this is only used for the custom focusContinueSessionId command at the moment
86*/
87export const loadSession = createAsyncThunk<
88 void,
89 {
90 sessionId: string;
91 saveCurrentSession: boolean;
92 },
93 ThunkApiType
94>(
95 "session/load",
96 async ({ sessionId, saveCurrentSession: save }, { extra, dispatch }) => {
97 if (save) {
98 const result = await dispatch(
99 saveCurrentSession({
100 openNewSession: false,
101 generateTitle: true,
102 }),
103 );
104 unwrapResult(result);
105 }
106 const session = await getSession(extra.ideMessenger, sessionId);
107 dispatch(newSession(session));
108 },
109);
110
111export const loadLastSession = createAsyncThunk<
112 void,
113 {
114 saveCurrentSession: boolean;
115 },
116 ThunkApiType
117>(
118 "session/loadLast",
119 async ({ saveCurrentSession }, { extra, dispatch, getState }) => {
120 const state = getState();
121
122 if (state.session.id && saveCurrentSession) {
123 }
124 const lastSessionId = getState().session.lastSessionId;
125
126 if (!lastSessionId) {
127 dispatch(newSession());
128 return;
129 }
130
131 const session = await getSession(extra.ideMessenger, lastSessionId);
132 dispatch(newSession(session));
133 },
134);
135
136function getChatTitleFromMessage(message: ChatMessage) {
137 const text =
138 renderChatMessage(message)
139 .split("\n")
140 .filter((l) => l.trim() !== "")
141 .slice(-1)[0] || "";
142
143 // Truncate
144 if (text.length > MAX_TITLE_LENGTH) {
145 return text.slice(0, MAX_TITLE_LENGTH - 3) + "...";
146 }
147 return text;
148}
149
150export const saveCurrentSession = createAsyncThunk<
151 void,
152 { openNewSession: boolean; generateTitle: boolean },
153 ThunkApiType
154>(
155 "session/saveCurrent",
156 async ({ openNewSession, generateTitle }, { dispatch, extra, getState }) => {
157 const state = getState();
158 if (state.session.history.length === 0) {
159 return;
160 }
161
162 if (openNewSession) {
163 dispatch(newSession());
164 }
165
166 // New session has already been dispatched
167 // Now save previous session and update chat title if relevant
168 let title = state.session.title;
169 if (title === NEW_SESSION_TITLE) {
170 const selectedChatModel = selectSelectedChatModel(state);
171
172 if (!state.config.config?.disableSessionTitles && selectedChatModel) {
173 let assistantResponse = state.session.history
174 ?.filter((h) => h.message.role === "assistant")[0]
175 ?.message?.content?.toString();
176
177 if (assistantResponse && generateTitle) {
178 try {
179 const result = await extra.ideMessenger.request(
180 "chatDescriber/describe",
181 {
182 text: assistantResponse,
183 },
184 );
185 if (result.status === "success" && result.content) {
186 title = result.content;
187 }
188 } catch (e) {
189 console.error("Error generating chat title", e);
190 }
191 }
192 }
193 // Fallbacks if above doesn't work out or session titles disabled
194 if (title === NEW_SESSION_TITLE) {
195 title = getChatTitleFromMessage(state.session.history[0].message);
196 }
197 }
198 // More fallbacks in case of no title
199 if (!title.length) {
200 const metadata = getState().session.allSessionMetadata.find(
201 (m) => m.sessionId === state.session.id,
202 );
203 if (metadata?.title) {
204 title = metadata.title;
205 }
206 }
207 if (!title.length) {
208 title = NEW_SESSION_TITLE;
209 }
210
211 const session: Session = {
212 sessionId: state.session.id,
213 title,
214 workspaceDirectory: window.workspacePaths?.[0] || "",
215 history: state.session.history,
216 };
217
218 const result = await dispatch(updateSession(session));
219 unwrapResult(result);
220 },
221);