Elffuss BraidHub

kikocis/continue public

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