Elffuss BraidHub

kikocis/continue public

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