Elffuss BraidHub

kikocis/continue public

5aed8ce6ba7e · 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 { HistoryTableRow } from "./HistoryTableRow";
27
28const parseDate = (date: string): Date => {
29 let dateObj = new Date(date);
30 if (isNaN(dateObj.getTime())) {
31 dateObj = new Date(parseInt(date));
32 }
33 return dateObj;
34};
35
36const HEADER_CLASS =
37 "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6";
38
39export function History() {
40 const dispatch = useAppDispatch();
41 const navigate = useNavigate();
42 const searchInputRef = React.useRef<HTMLInputElement>(null);
43 const ideMessenger = useContext(IdeMessengerContext);
44
45 const [searchTerm, setSearchTerm] = useState("");
46
47 const minisearch = useRef<MiniSearch>(
48 new MiniSearch({
49 fields: ["title"],
50 storeFields: ["title", "sessionId", "id"],
51 }),
52 ).current;
53
54 const allSessionMetadata = useAppSelector(
55 (state) => state.session.allSessionMetadata,
56 );
57 const isSessionMetadataLoading = useAppSelector(
58 (state) => state.session.isSessionMetadataLoading,
59 );
60
61 useEffect(() => {
62 try {
63 minisearch.removeAll();
64 minisearch.addAll(
65 allSessionMetadata.map((session) => ({
66 title: session.title,
67 sessionId: session.sessionId,
68 id: session.sessionId,
69 })),
70 );
71 } catch (e) {
72 console.log("error adding sessions to minisearch", e);
73 }
74 }, [allSessionMetadata]);
75
76 const platform = useMemo(() => getPlatform(), []);
77
78 const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => {
79 const sessionIds = minisearch
80 .search(searchTerm, {
81 fuzzy: 0.1,
82 })
83 .map((result) => result.id);
84
85 return allSessionMetadata
86 .filter((session) => {
87 return searchTerm === "" || sessionIds.includes(session.sessionId);
88 })
89 .sort(
90 (a, b) =>
91 parseDate(b.dateCreated).getTime() -
92 parseDate(a.dateCreated).getTime(),
93 );
94 }, [allSessionMetadata, searchTerm, minisearch]);
95
96 const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
97 const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);
98 const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30);
99 const earlier = new Date(0);
100
101 const showClearSessionsDialog = () => {
102 dispatch(
103 setDialogMessage(
104 <ConfirmationDialog
105 title={`Clear sessions`}
106 text={`Are you sure you want to permanently delete all chat sessions, including the current chat session?`}
107 onConfirm={async () => {
108 // optimistic update
109 dispatch(setAllSessionMetadata([]));
110
111 // actual update + refresh
112 await ideMessenger.request("history/clear", undefined);
113 void dispatch(refreshSessionMetadata({}));
114
115 // start a new session
116 dispatch(newSession());
117 navigate(ROUTES.HOME);
118 }}
119 />,
120 ),
121 );
122 dispatch(setShowDialog(true));
123 };
124
125 return (
126 <div
127 style={{ fontSize: getFontSize() }}
128 className="flex flex-1 flex-col overflow-auto px-1"
129 >
130 <div className="relative my-2 flex justify-center space-x-2">
131 <input
132 className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-base outline-none focus:outline-none"
133 ref={searchInputRef}
134 placeholder="Search past sessions"
135 type="text"
136 value={searchTerm}
137 onChange={(e) => setSearchTerm(e.target.value)}
138 />
139 {searchTerm && (
140 <XMarkIcon
141 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"
142 onClick={() => {
143 setSearchTerm("");
144 if (searchInputRef.current) {
145 searchInputRef.current.focus();
146 }
147 }}
148 />
149 )}
150 </div>
151 <div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto pr-4">
152 {filteredAndSortedSessions.length === 0 && (
153 <div className="m-3 text-center">
154 {isSessionMetadataLoading ? (
155 "Loading Sessions..."
156 ) : (
157 <>
158 No past sessions found. To start a new session, either click the
159 "+" button or use the keyboard shortcut:{" "}
160 <Shortcut>meta L</Shortcut>
161 </>
162 )}
163 </div>
164 )}
165
166 <table className="flex flex-1 flex-col">
167 <tbody className="">
168 {filteredAndSortedSessions.map((session, index) => {
169 const prevDate =
170 index > 0
171 ? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
172 : earlier;
173 const date = parseDate(session.dateCreated);
174 return (
175 <Fragment key={index}>
176 {index === 0 && date > yesterday && (
177 <tr className={HEADER_CLASS}>
178 <td colSpan={3}>Today</td>
179 </tr>
180 )}
181 {date < yesterday &&
182 date > lastWeek &&
183 prevDate > yesterday && (
184 <div className={HEADER_CLASS}>
185 <td colSpan={3}>This Week</td>
186 </div>
187 )}
188 {date < lastWeek &&
189 date > lastMonth &&
190 prevDate > lastWeek && (
191 <div className={HEADER_CLASS}>
192 <td colSpan={3}>This Month</td>
193 </div>
194 )}
195 {date < lastMonth && prevDate > lastMonth && (
196 <div className={HEADER_CLASS}>
197 <td colSpan={3}>Older</td>
198 </div>
199 )}
200
201 <HistoryTableRow
202 sessionMetadata={session}
203 date={date}
204 index={index}
205 />
206 </Fragment>
207 );
208 })}
209 </tbody>
210 </table>
211 </div>
212 <div className="flex flex-col items-end justify-center border-0 border-t border-solid border-gray-400 px-2 py-1.5 text-sm">
213 <i
214 className=""
215 data-testid="history-sessions-note"
216 >{`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`}</i>
217 <span
218 className="cursor-pointer text-xs text-gray-400 hover:underline"
219 onClick={showClearSessionsDialog}
220 >
221 Clear session history
222 </span>
223 </div>
224 </div>
225 );
226}