Elffuss BraidHub

kikocis/continue public

8eb3ae7b8d16 · 7.4 KiBRawPermalink
1import { SessionMetadata } from "core";
2import MiniSearch from "minisearch";
3import React, {
4 Fragment,
5 useContext,
6 useEffect,
7 useMemo,
8 useRef,
9 useState,
10} from "react";
11import Shortcut from "../gui/Shortcut";
12
13import { XMarkIcon } from "@heroicons/react/24/solid";
14import { useNavigate } from "react-router-dom";
15import { IdeMessengerContext } from "../../context/IdeMessenger";
16import { useAppDispatch, useAppSelector } from "../../redux/hooks";
17import {
18 newSession,
19 setAllSessionMetadata,
20} from "../../redux/slices/sessionSlice";
21import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
22import { refreshSessionMetadata } from "../../redux/thunks/session";
23import { getFontSize, getPlatform } from "../../util";
24import { ROUTES } from "../../util/navigation";
25import ConfirmationDialog from "../dialogs/ConfirmationDialog";
26import { Button } from "../ui";
27import { HistoryTableRow } from "./HistoryTableRow";
28import { groupSessionsByDate, parseDate } from "./util";
29
30export function History() {
31 const dispatch = useAppDispatch();
32 const navigate = useNavigate();
33 const searchInputRef = React.useRef<HTMLInputElement>(null);
34 const ideMessenger = useContext(IdeMessengerContext);
35
36 const [searchTerm, setSearchTerm] = useState("");
37
38 const minisearch = useRef<MiniSearch>(
39 new MiniSearch({
40 fields: ["title"],
41 storeFields: ["title", "sessionId", "id"],
42 }),
43 ).current;
44
45 const allSessionMetadata = useAppSelector(
46 (state) => state.session.allSessionMetadata,
47 );
48 const isSessionMetadataLoading = useAppSelector(
49 (state) => state.session.isSessionMetadataLoading,
50 );
51
52 useEffect(() => {
53 try {
54 minisearch.removeAll();
55 minisearch.addAll(
56 allSessionMetadata.map((session) => ({
57 title: session.title,
58 sessionId: session.sessionId,
59 id: session.sessionId,
60 })),
61 );
62 } catch (e) {
63 console.log("error adding sessions to minisearch", e);
64 }
65 }, [allSessionMetadata]);
66
67 const platform = useMemo(() => getPlatform(), []);
68
69 const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => {
70 // 1. Exact phrase matching
71 const exactResults = minisearch.search(searchTerm, {
72 fuzzy: false,
73 });
74
75 // 2. Fuzzy matching with higher tolerance
76 const fuzzyResults = minisearch.search(searchTerm, {
77 fuzzy: 0.3,
78 });
79
80 // 3. Prefix matching for partial words
81 const prefixResults = minisearch.search(searchTerm, {
82 prefix: true,
83 fuzzy: 0.2,
84 });
85
86 // Combine results, with exact matches having higher priority
87 const allResults = [
88 ...exactResults.map((r) => ({ ...r, priority: 3 })),
89 ...fuzzyResults.map((r) => ({ ...r, priority: 2 })),
90 ...prefixResults.map((r) => ({ ...r, priority: 1 })),
91 ];
92
93 // Remove duplicates while preserving highest priority
94 const uniqueResultsMap = new Map<string, any>();
95 allResults.forEach((result) => {
96 const existing = uniqueResultsMap.get(result.id);
97 if (!existing || existing.priority < result.priority) {
98 uniqueResultsMap.set(result.id, result);
99 }
100 });
101 const uniqueResults = Array.from(uniqueResultsMap.values());
102
103 const sessionIds = uniqueResults
104 .sort((a, b) => b.priority - a.priority || b.score - a.score)
105 .map((result) => result.id);
106
107 return allSessionMetadata
108 .filter((session) => {
109 return searchTerm === "" || sessionIds.includes(session.sessionId);
110 })
111 .sort(
112 (a, b) =>
113 parseDate(b.dateCreated).getTime() -
114 parseDate(a.dateCreated).getTime(),
115 );
116 }, [allSessionMetadata, searchTerm, minisearch]);
117
118 const sessionGroups = useMemo(() => {
119 return groupSessionsByDate(filteredAndSortedSessions);
120 }, [filteredAndSortedSessions]);
121
122 const showClearSessionsDialog = () => {
123 dispatch(
124 setDialogMessage(
125 <ConfirmationDialog
126 title={`Clear sessions`}
127 text={`Are you sure you want to permanently delete all chat sessions, including the current chat session?`}
128 onConfirm={async () => {
129 // optimistic update
130 dispatch(setAllSessionMetadata([]));
131
132 // actual update + refresh
133 await ideMessenger.request("history/clear", undefined);
134 void dispatch(refreshSessionMetadata({}));
135
136 // start a new session
137 dispatch(newSession());
138 navigate(ROUTES.HOME);
139 }}
140 />,
141 ),
142 );
143 dispatch(setShowDialog(true));
144 };
145
146 return (
147 <div
148 style={{ fontSize: getFontSize() }}
149 className="flex flex-1 flex-col overflow-auto px-1"
150 >
151 <div className="relative my-2 mt-4 flex justify-center space-x-2">
152 <input
153 className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-sm outline-none focus:outline-none"
154 ref={searchInputRef}
155 placeholder="Search past sessions"
156 type="text"
157 value={searchTerm}
158 onChange={(e) => setSearchTerm(e.target.value)}
159 />
160 {searchTerm && (
161 <XMarkIcon
162 className="text-vsc-foreground hover:bg-vsc-background duration-50 absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 transform cursor-pointer rounded-full p-0.5 transition-colors"
163 onClick={() => {
164 setSearchTerm("");
165 if (searchInputRef.current) {
166 searchInputRef.current.focus();
167 }
168 }}
169 />
170 )}
171 </div>
172
173 <div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto">
174 {filteredAndSortedSessions.length === 0 && (
175 <div className="m-3 text-center">
176 {isSessionMetadataLoading ? (
177 "Loading Sessions..."
178 ) : (
179 <>
180 No past sessions found. To start a new session, either click the
181 "+" button or use the keyboard shortcut:{" "}
182 <Shortcut>meta L</Shortcut>
183 </>
184 )}
185 </div>
186 )}
187
188 <table className="flex flex-1 flex-col">
189 <tbody className="">
190 {sessionGroups.map((group, groupIndex) => (
191 <Fragment key={group.label}>
192 <tr
193 className={`user-select-none sticky mb-3 ml-2 flex h-6 justify-start text-left text-base font-bold opacity-75 ${
194 groupIndex === 0 ? "mt-2" : "mt-8"
195 }`}
196 >
197 <td colSpan={3}>{group.label}</td>
198 </tr>
199 {group.sessions.map((session, sessionIndex) => (
200 <HistoryTableRow
201 key={session.sessionId}
202 sessionMetadata={session}
203 index={sessionIndex}
204 />
205 ))}
206 </Fragment>
207 ))}
208 </tbody>
209 </table>
210 </div>
211
212 <div className="border-border flex flex-col items-end justify-center border-0 border-t border-solid px-2 py-3 text-xs">
213 <Button variant="secondary" size="sm" onClick={showClearSessionsDialog}>
214 Clear chats
215 </Button>
216 <span
217 className="text-description text-2xs"
218 data-testid="history-sessions-note"
219 >
220 Chat history is saved to{" "}
221 <span className="italic">
222 {platform === "windows"
223 ? "%USERPROFILE%/.continue"
224 : "~/.continue/sessions"}
225 </span>
226 </span>
227 </div>
228 </div>
229 );
230}