Skip to content

Commit

Permalink
Merge pull request #9 from swuecho/clear_messages_should_keep_system_meg
Browse files Browse the repository at this point in the history
fix: clear chat messages
  • Loading branch information
swuecho committed Mar 20, 2023
2 parents f41e51e + 23f91b6 commit b0808a0
Show file tree
Hide file tree
Showing 13 changed files with 119 additions and 12 deletions.
3 changes: 2 additions & 1 deletion api/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
tmp/
api/chatgpt_backend
api/chatgpt_backend
env.sh
7 changes: 0 additions & 7 deletions api/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,6 @@ build: vet
go build
.PHONY: build


export OPENAI_API_KEY=sk-KltHM7dsS8x2oL0KGJ69XXX
export PG_HOST=192.168.0.1
export PG_DB=hwu
export PG_USER=hwu
export PG_PASS=123456
export PG_PORT=5432

serve:
@echo "Starting server..."
Expand Down
12 changes: 12 additions & 0 deletions api/chat_message_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func (h *ChatMessageHandler) Register(router *mux.Router) {
router.HandleFunc("/uuid/chat_messages/{uuid}", h.UpdateChatMessageByUUID).Methods(http.MethodPut)
router.HandleFunc("/uuid/chat_messages/{uuid}", h.DeleteChatMessageByUUID).Methods(http.MethodDelete)
router.HandleFunc("/uuid/chat_messages/chat_sessions/{uuid}", h.GetChatHistoryBySessionUUID).Methods(http.MethodGet)
router.HandleFunc("/uuid/chat_messages/chat_sessions/{uuid}", h.DeleteChatMessagesBySesionUUID).Methods(http.MethodDelete)

}

Expand Down Expand Up @@ -207,3 +208,14 @@ func (h *ChatMessageHandler) GetChatHistoryBySessionUUID(w http.ResponseWriter,
}
json.NewEncoder(w).Encode(simple_msgs)
}

// DeleteChatMessagesBySesionUUID delete chat messages by session uuid
func (h *ChatMessageHandler) DeleteChatMessagesBySesionUUID(w http.ResponseWriter, r *http.Request) {
uuidStr := mux.Vars(r)["uuid"]
err := h.service.DeleteChatMessagesBySesionUUID(r.Context(), uuidStr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
9 changes: 9 additions & 0 deletions api/chat_message_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,12 @@ func (s *ChatMessageService) GetLastNChatMessages(ctx context.Context, uuid stri
}
return message, nil
}

//DeleteChatMessagesBySesionUUID deletes chat messages by session uuid.
func (s *ChatMessageService) DeleteChatMessagesBySesionUUID(ctx context.Context, uuid string) error {
err := s.q.DeleteChatMessagesBySesionUUID(ctx, uuid)
if err != nil {
return errors.New("failed to delete message")
}
return nil
}
7 changes: 6 additions & 1 deletion api/sqlc/queries/chat_message.sql
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,9 @@ ORDER BY created_at;
-- name: UpdateChatMessageContent :exec
UPDATE chat_message
SET content = $2, updated_at = now()
WHERE uuid = $1 ;
WHERE uuid = $1 ;


-- name: DeleteChatMessagesBySesionUUID :exec
DELETE FROM chat_message
WHERE chat_session_uuid = $1;
10 changes: 10 additions & 0 deletions api/sqlc_queries/chat_message.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion e2e/tests/01_register.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,5 @@ test('test', async ({ page }) => {
await page.getByTestId('password').locator('input').click();
await page.getByTestId('password').locator('input').fill('@WuHao5');
await page.getByTestId('signup').click();

});

61 changes: 61 additions & 0 deletions e2e/tests/06_clear_messages.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { test, expect } from '@playwright/test';
import { Pool } from 'pg';
import { selectUserByEmail } from '../lib/db/user';
import { selectChatSessionByUserId as selectChatSessionsByUserId } from '../lib/db/chat_session';
import { selectChatPromptsBySessionUUID } from '../lib/db/chat_prompt';
import { selectChatMessagesBySessionUUID } from '../lib/db/chat_message';
import { randomEmail } from '../lib/sample';
import { db_config } from '../lib/db/config';

const pool = new Pool(db_config);

const test_email = randomEmail();

test('after clear conversation, only system message remains', async ({ page }) => {
await page.goto('/');
await page.getByTestId('email').click();
await page.getByTestId('email').locator('input').fill(test_email);
await page.getByTestId('password').locator('input').click();
await page.getByTestId('password').locator('input').fill('@WuHao5');
await page.getByTestId('signup').click();
// sleep 1 second
await page.waitForTimeout(1000);
let input_area = await page.$("#message_textarea textarea")
await input_area?.click();
await input_area?.fill('test_demo_bestqa');
await input_area?.press('Enter');
await page.waitForTimeout(1000);
await input_area?.fill('test_demo_bestqa');
await input_area?.press('Enter');
// get message counts in the conversation

await page.waitForTimeout(1000);

const message_counts = await page.$$eval('.message-text', (messages) => messages.length);
expect(message_counts).toBe(4);

const user = await selectUserByEmail(pool, test_email);
expect(user.email).toBe(test_email);
// expect(user.id).toBe(37);
const sessions = await selectChatSessionsByUserId(pool, user.id);
const session = sessions[0];

// clear
await page.getByRole('contentinfo').getByRole('button').first().click();
await page.getByRole('button', { name: '是' }).click();

// sleep 500 ms
await page.waitForTimeout(500);
// get message counts in the conversation
const message_count_after_clear = await page.$$eval('.message-text', (messages) => messages.length);
expect(message_count_after_clear).toBe(1);

const prompts = await selectChatPromptsBySessionUUID(pool, session.uuid)
expect(prompts.length).toBe(1);
expect(prompts[0].updated_by).toBe(user.id);
// sleep 5 seconds
await page.waitForTimeout(500);
const messages = await selectChatMessagesBySessionUUID(pool, session.uuid)
expect(messages.length).toBe(0);
});

12 changes: 12 additions & 0 deletions web/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,18 @@ export const renameChatSession = async (uuid: string, name: string) => {
}
}

export const clearSessionChatMessages = async (sessionUuid: string) => {
try {
const response = await request.delete(`/uuid/chat_messages/chat_sessions/${sessionUuid}`)
return response.data
}
catch (error) {
console.error(error)
throw error
}
}


export const deleteChatMessage = async (uuid: string) => {
try {
const response = await request.delete(`/uuid/chat_messages/${uuid}`)
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh-CN.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export default {
common: {
help: '第一条是主题(prompt), 上下午包括10条信息',
edit: '编辑',
delete: '删除',
save: '保存',
Expand Down
5 changes: 4 additions & 1 deletion web/src/store/modules/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { v4 as uuidv4 } from 'uuid'
import { getLocalState, setLocalState } from './helper'
import { router } from '@/router'
import {
clearSessionChatMessages,
createChatSession,
createOrUpdateUserActiveChatSession,
deleteChatData,
Expand Down Expand Up @@ -237,6 +238,7 @@ export const useChatStore = defineStore('chat-store', {
},

clearChatByUuid(uuid: string) {
// does this every happen?
if (!uuid) {
if (this.chat.length) {
this.chat[0].data = []
Expand All @@ -247,7 +249,8 @@ export const useChatStore = defineStore('chat-store', {

const index = this.chat.findIndex(item => item.uuid === uuid)
if (index !== -1) {
this.chat[index].data = []
this.chat[index].data = this.chat[index].data.slice(0, 1)
clearSessionChatMessages(uuid)
this.recordState()
}
},
Expand Down
1 change: 1 addition & 0 deletions web/src/views/chat/components/Message/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ function handleRegenerate() {
>
<TextComponent
ref="textRef"
class="message-text"
:inversion="inversion"
:error="error"
:text="text"
Expand Down
2 changes: 1 addition & 1 deletion web/src/views/chat/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ onUnmounted(() => {
<template v-if="!dataSources.length">
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl" />
<span>Aha~</span>
<span>{{ $t('common.help') }}</span>
</div>
</template>
<template v-else>
Expand Down

0 comments on commit b0808a0

Please sign in to comment.