Browse Source

Merge pull request #346 from AprilNEA/reset

The Clear Data button on the Settings page is only clear for all dialog data.
Yifei Zhang 2 years ago
parent
commit
d226090926

+ 1 - 1
app/api/openai/route.ts

@@ -5,7 +5,7 @@ async function makeRequest(req: NextRequest) {
   try {
     const api = await requestOpenai(req);
     const res = new NextResponse(api.body);
-    res.headers.set('Content-Type', 'application/json');
+    res.headers.set("Content-Type", "application/json");
     return res;
   } catch (e) {
     console.error("[OpenAI] ", req.body, e);

+ 8 - 8
app/components/home.tsx

@@ -108,7 +108,7 @@ export function ChatList() {
       state.currentSessionIndex,
       state.selectSession,
       state.removeSession,
-    ]
+    ],
   );
 
   return (
@@ -134,7 +134,7 @@ function useSubmitHandler() {
 
   const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
     if (e.key !== "Enter") return false;
-    if(e.key==='Enter' && e.nativeEvent.isComposing) return false
+    if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
     return (
       (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
       (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
@@ -202,7 +202,7 @@ export function Chat(props: {
       setPromptHints(promptStore.search(text));
     },
     100,
-    { leading: true, trailing: true }
+    { leading: true, trailing: true },
   );
 
   const onPromptSelect = (prompt: Prompt) => {
@@ -216,7 +216,7 @@ export function Chat(props: {
     if (!dom) return;
     const paddingBottomNum: number = parseInt(
       window.getComputedStyle(dom).paddingBottom,
-      10
+      10,
     );
     dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
   };
@@ -304,7 +304,7 @@ export function Chat(props: {
               preview: true,
             },
           ]
-        : []
+        : [],
     )
     .concat(
       userInput.length > 0
@@ -316,7 +316,7 @@ export function Chat(props: {
               preview: true,
             },
           ]
-        : []
+        : [],
     );
 
   // auto scroll
@@ -354,7 +354,7 @@ export function Chat(props: {
               const newTopic = prompt(Locale.Chat.Rename, session.topic);
               if (newTopic && newTopic !== session.topic) {
                 chatStore.updateCurrentSession(
-                  (session) => (session.topic = newTopic!)
+                  (session) => (session.topic = newTopic!),
                 );
               }
             }}
@@ -603,7 +603,7 @@ export function Home() {
       state.newSession,
       state.currentSessionIndex,
       state.removeSession,
-    ]
+    ],
   );
   const loading = !useHasHydrated();
   const [showSideBar, setShowSideBar] = useState(true);

+ 5 - 5
app/components/settings.tsx

@@ -49,14 +49,14 @@ function SettingItem(props: {
 
 export function Settings(props: { closeSettings: () => void }) {
   const [showEmojiPicker, setShowEmojiPicker] = useState(false);
-  const [config, updateConfig, resetConfig, clearAllData] = useChatStore(
-    (state) => [
+  const [config, updateConfig, resetConfig, clearAllData, clearSessions] =
+    useChatStore((state) => [
       state.config,
       state.updateConfig,
       state.resetConfig,
       state.clearAllData,
-    ],
-  );
+      state.clearSessions,
+    ]);
 
   const updateStore = useUpdateStore();
   const [checkingUpdate, setCheckingUpdate] = useState(false);
@@ -120,7 +120,7 @@ export function Settings(props: { closeSettings: () => void }) {
           <div className={styles["window-action-button"]}>
             <IconButton
               icon={<ClearIcon />}
-              onClick={clearAllData}
+              onClick={clearSessions}
               bordered
               title={Locale.Settings.Actions.ClearAll}
             />

+ 5 - 3
app/locales/es.ts

@@ -143,12 +143,14 @@ const es: LocaleType = {
       Summarize:
         "Resuma nuestra discusión brevemente en 50 caracteres o menos para usarlo como un recordatorio para futuros contextos.",
     },
-    ConfirmClearAll: "¿Confirmar para borrar todos los datos de chat y configuración?",
+    ConfirmClearAll:
+      "¿Confirmar para borrar todos los datos de chat y configuración?",
   },
   Copy: {
     Success: "Copiado al portapapeles",
-    Failed: "La copia falló, por favor concede permiso para acceder al portapapeles",
+    Failed:
+      "La copia falló, por favor concede permiso para acceder al portapapeles",
   },
 };
 
-export default es;
+export default es;

+ 1 - 1
app/locales/index.ts

@@ -57,4 +57,4 @@ export function changeLang(lang: Lang) {
   location.reload();
 }
 
-export default { en: EN, cn: CN, tw: TW, es: ES }[getLang()];
+export default { en: EN, cn: CN, tw: TW, es: ES }[getLang()];

+ 5 - 5
app/requests.ts

@@ -3,7 +3,7 @@ import { filterConfig, Message, ModelConfig, useAccessStore } from "./store";
 import Locale from "./locales";
 
 if (!Array.prototype.at) {
-  require('array.prototype.at/auto');
+  require("array.prototype.at/auto");
 }
 
 const TIME_OUT_MS = 30000;
@@ -13,7 +13,7 @@ const makeRequestParam = (
   options?: {
     filterBot?: boolean;
     stream?: boolean;
-  }
+  },
 ): ChatRequest => {
   let sendMessages = messages.map((v) => ({
     role: v.role,
@@ -74,7 +74,7 @@ export async function requestChat(messages: Message[]) {
 
 export async function requestUsage() {
   const res = await requestOpenaiClient(
-    "dashboard/billing/credit_grants?_vercel_no_cache=1"
+    "dashboard/billing/credit_grants?_vercel_no_cache=1",
   )(null, "GET");
 
   try {
@@ -97,7 +97,7 @@ export async function requestChatStream(
     onMessage: (message: string, done: boolean) => void;
     onError: (error: Error) => void;
     onController?: (controller: AbortController) => void;
-  }
+  },
 ) {
   const req = makeRequestParam(messages, {
     stream: true,
@@ -192,7 +192,7 @@ export const ControllerPool = {
   addController(
     sessionIndex: number,
     messageIndex: number,
-    controller: AbortController
+    controller: AbortController,
   ) {
     const key = this.key(sessionIndex, messageIndex);
     this.controllers[key] = controller;

+ 9 - 1
app/store/app.ts

@@ -12,7 +12,7 @@ import { trimTopic } from "../utils";
 import Locale from "../locales";
 
 if (!Array.prototype.at) {
-  require('array.prototype.at/auto');
+  require("array.prototype.at/auto");
 }
 
 export type Message = ChatCompletionResponseMessage & {
@@ -189,6 +189,7 @@ interface ChatStore {
   config: ChatConfig;
   sessions: ChatSession[];
   currentSessionIndex: number;
+  clearSessions: () => void;
   removeSession: (index: number) => void;
   selectSession: (index: number) => void;
   newSession: () => void;
@@ -227,6 +228,13 @@ export const useChatStore = create<ChatStore>()(
         ...DEFAULT_CONFIG,
       },
 
+      clearSessions() {
+        set(() => ({
+          sessions: [createEmptySession()],
+          currentSessionIndex: 0,
+        }));
+      },
+
       resetConfig() {
         set(() => ({ config: { ...DEFAULT_CONFIG } }));
       },

+ 4 - 4
app/store/prompt.ts

@@ -99,19 +99,19 @@ export const usePromptStore = create<PromptStore>()(
                     ({
                       title,
                       content,
-                    } as Prompt)
+                    } as Prompt),
                 );
               })
               .concat([...(state?.prompts?.values() ?? [])]);
 
             const allPromptsForSearch = builtinPrompts.reduce(
               (pre, cur) => pre.concat(cur),
-              []
+              [],
             );
             SearchService.count.builtin = res.en.length + res.cn.length;
             SearchService.init(allPromptsForSearch);
           });
       },
-    }
-  )
+    },
+  ),
 );