Add Vue user H5 client

This commit is contained in:
2026-07-06 17:34:37 +08:00
parent 17cba7cf61
commit e9f3db9ab2
20 changed files with 2433 additions and 0 deletions

View File

@@ -0,0 +1,182 @@
<script setup lang="ts">
import { nextTick, onMounted, ref } from "vue";
import ChatComposer from "./components/ChatComposer.vue";
import ChatMessage from "./components/ChatMessage.vue";
import LoginPanel from "./components/LoginPanel.vue";
import SessionDrawer from "./components/SessionDrawer.vue";
import { api, clearToken, getToken, streamChat } from "./services/api";
import type { ChatMessage as ApiMessage, ChatSession, UserProfile } from "./types/api";
interface UiMessage {
id: string;
role: "user" | "assistant";
content: string;
streaming?: boolean;
}
const user = ref<UserProfile | null>(null);
const sessions = ref<ChatSession[]>([]);
const activeSessionId = ref<number | null>(null);
const messages = ref<UiMessage[]>([]);
const drawerOpen = ref(false);
const loading = ref(false);
const booting = ref(true);
const statusText = ref("连接后端中");
const bottomRef = ref<HTMLElement | null>(null);
onMounted(async () => {
if (!getToken()) {
booting.value = false;
statusText.value = "请先登录";
return;
}
try {
user.value = await api.profile();
await loadSessions();
statusText.value = "已连接知识库服务";
} catch {
clearToken();
statusText.value = "登录已失效";
} finally {
booting.value = false;
}
});
async function onLoggedIn(profile: UserProfile) {
user.value = profile;
statusText.value = "已连接知识库服务";
await loadSessions();
}
async function loadSessions() {
sessions.value = await api.listSessions();
if (sessions.value.length === 0) {
await createSession();
return;
}
await selectSession(sessions.value[0].id);
}
async function createSession() {
const result = await api.createSession();
await refreshSessions(result.sessionId);
drawerOpen.value = false;
}
async function refreshSessions(selectId = activeSessionId.value) {
sessions.value = await api.listSessions();
if (selectId) await selectSession(selectId);
}
async function selectSession(sessionId: number) {
activeSessionId.value = sessionId;
const history = await api.history(sessionId);
messages.value = history.map(toUiMessage);
drawerOpen.value = false;
await scrollToBottom();
}
async function send(message: string) {
if (!activeSessionId.value || loading.value) return;
const userMessage: UiMessage = { id: `user-${Date.now()}`, role: "user", content: message };
const assistantMessage: UiMessage = { id: `assistant-${Date.now()}`, role: "assistant", content: "", streaming: true };
messages.value.push(userMessage, assistantMessage);
loading.value = true;
await scrollToBottom();
try {
await streamChat(activeSessionId.value, message, async (chunk) => {
assistantMessage.content += chunk;
await scrollToBottom();
});
assistantMessage.streaming = false;
await refreshSessions(activeSessionId.value);
} catch (error) {
assistantMessage.streaming = false;
assistantMessage.content = error instanceof Error ? error.message : "AI 回复失败";
} finally {
loading.value = false;
}
}
async function stop() {
if (!activeSessionId.value) return;
await api.stop(activeSessionId.value);
loading.value = false;
}
async function logout() {
try {
await api.logout();
} finally {
clearToken();
user.value = null;
sessions.value = [];
messages.value = [];
activeSessionId.value = null;
statusText.value = "请先登录";
}
}
function toUiMessage(message: ApiMessage): UiMessage {
return {
id: String(message.id),
role: message.role,
content: message.content,
streaming: message.message_status === "GENERATING",
};
}
async function scrollToBottom() {
await nextTick();
bottomRef.value?.scrollIntoView({ behavior: "smooth", block: "end" });
}
</script>
<template>
<main class="app-shell">
<section class="phone-frame">
<div v-if="booting" class="booting">正在启动...</div>
<LoginPanel v-else-if="!user" @logged-in="onLoggedIn" />
<template v-else>
<header class="topbar">
<button type="button" class="icon-btn" @click="drawerOpen = true"></button>
<div>
<h1>AI知识库助手</h1>
<p>{{ statusText }}</p>
</div>
<button type="button" class="plain-btn" @click="logout">退出</button>
</header>
<section class="quota-strip">
<span>{{ user.name }}</span>
<strong>{{ user.todayUsed }}/{{ user.dailyLimit }}</strong>
</section>
<section class="chat-area">
<div v-if="messages.length === 0" class="empty-state">
<strong>可以开始提问了</strong>
<p>当前阶段已接入后端 mock 聊天链路后续会替换为真实飞书知识库检索</p>
</div>
<ChatMessage
v-for="message in messages"
:key="message.id"
:role="message.role"
:content="message.content"
:streaming="message.streaming"
/>
<div ref="bottomRef"></div>
</section>
<ChatComposer :loading="loading" :disabled="!activeSessionId" @send="send" @stop="stop" />
<SessionDrawer
:open="drawerOpen"
:sessions="sessions"
:active-session-id="activeSessionId"
@close="drawerOpen = false"
@select="selectSession"
@create="createSession"
/>
</template>
</section>
</main>
</template>

View File

@@ -0,0 +1,43 @@
<script setup lang="ts">
import { ref } from "vue";
defineProps<{
loading: boolean;
disabled: boolean;
}>();
const emit = defineEmits<{
send: [message: string];
stop: [];
}>();
const input = ref("");
function send() {
const text = input.value.trim();
if (!text) return;
emit("send", text);
input.value = "";
}
function onKeydown(event: KeyboardEvent) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
send();
}
}
</script>
<template>
<form class="composer" @submit.prevent="send">
<textarea
v-model="input"
rows="1"
placeholder="请输入你的问题"
:disabled="disabled"
@keydown="onKeydown"
/>
<button v-if="loading" type="button" class="stop-btn" @click="emit('stop')">停止</button>
<button v-else type="submit" class="send-btn" :disabled="disabled || !input.trim()">发送</button>
</form>
</template>

View File

@@ -0,0 +1,17 @@
<script setup lang="ts">
defineProps<{
role: "user" | "assistant";
content: string;
streaming?: boolean;
}>();
</script>
<template>
<article class="message" :class="role">
<div class="avatar">{{ role === "assistant" ? "AI" : "我" }}</div>
<div class="bubble">
<div class="content">{{ content }}</div>
<span v-if="streaming" class="typing">正在生成</span>
</div>
</article>
</template>

View File

@@ -0,0 +1,69 @@
<script setup lang="ts">
import { ref } from "vue";
import { api, saveToken } from "../services/api";
import type { UserProfile } from "../types/api";
const emit = defineEmits<{
loggedIn: [user: UserProfile];
}>();
const phone = ref("");
const code = ref("123456");
const loading = ref(false);
const message = ref("开发阶段验证码默认 123456");
async function sendCode() {
loading.value = true;
message.value = "";
try {
await api.sendSms(phone.value);
message.value = "验证码已发送,开发阶段默认 123456";
} catch (error) {
message.value = error instanceof Error ? error.message : "发送失败";
} finally {
loading.value = false;
}
}
async function login() {
loading.value = true;
message.value = "";
try {
const result = await api.login(phone.value, code.value);
saveToken(result.token);
emit("loggedIn", result.user);
} catch (error) {
message.value = error instanceof Error ? error.message : "登录失败";
} finally {
loading.value = false;
}
}
</script>
<template>
<section class="login-panel">
<div class="brand-mark">AI</div>
<h1>AI知识库助手</h1>
<p>企业知识统一问答入口</p>
<label>
手机号
<input v-model="phone" inputmode="numeric" maxlength="11" placeholder="请输入手机号" />
</label>
<label>
验证码
<div class="code-row">
<input v-model="code" inputmode="numeric" maxlength="8" placeholder="验证码" />
<button type="button" class="secondary" :disabled="loading || phone.length < 11" @click="sendCode">
发送
</button>
</div>
</label>
<button type="button" class="primary" :disabled="loading || phone.length < 11 || code.length < 4" @click="login">
{{ loading ? "处理中..." : "立即进入" }}
</button>
<div class="form-tip">{{ message }}</div>
</section>
</template>

View File

@@ -0,0 +1,40 @@
<script setup lang="ts">
import type { ChatSession } from "../types/api";
defineProps<{
open: boolean;
sessions: ChatSession[];
activeSessionId: number | null;
}>();
const emit = defineEmits<{
close: [];
select: [sessionId: number];
create: [];
delete: [sessionId: number];
}>();
</script>
<template>
<div class="drawer-mask" :class="{ show: open }" @click="emit('close')"></div>
<aside class="session-drawer" :class="{ open }">
<div class="drawer-head">
<strong>历史会话</strong>
<button type="button" class="icon-btn" @click="emit('close')">×</button>
</div>
<button type="button" class="new-session-btn" @click="emit('create')"> 新聊天</button>
<div class="session-list">
<button
v-for="session in sessions"
:key="session.id"
type="button"
class="session-item"
:class="{ active: session.id === activeSessionId }"
@click="emit('select', session.id)"
>
<span>{{ session.title }}</span>
<small>{{ session.messageCount }} 条消息</small>
</button>
</div>
</aside>
</template>

View File

@@ -0,0 +1,5 @@
import { createApp } from "vue";
import App from "./App.vue";
import "./styles.css";
createApp(App).mount("#app");

View File

@@ -0,0 +1,79 @@
import type { ApiResponse, ChatMessage, ChatSession, LoginResult, UserProfile } from "../types/api";
const API_BASE = import.meta.env.VITE_API_BASE_URL ?? "http://127.0.0.1:8100/api";
const TOKEN_KEY = "ai-kb-user-token";
export function getToken() {
return window.localStorage.getItem(TOKEN_KEY);
}
export function saveToken(token: string) {
window.localStorage.setItem(TOKEN_KEY, token);
}
export function clearToken() {
window.localStorage.removeItem(TOKEN_KEY);
}
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set("Content-Type", "application/json");
const token = getToken();
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
const response = await fetch(`${API_BASE}${path}`, { ...init, headers });
const body = (await response.json()) as ApiResponse<T>;
if (!response.ok || body.code !== 0) {
throw new Error(body.message || `${response.status} ${response.statusText}`);
}
return body.data;
}
export const api = {
sendSms: (phone: string) => request<null>("/auth/sms/send", { method: "POST", body: JSON.stringify({ phone }) }),
login: (phone: string, code: string) =>
request<LoginResult>("/auth/login", { method: "POST", body: JSON.stringify({ phone, code }) }),
logout: () => request<null>("/auth/logout", { method: "POST", body: JSON.stringify({}) }),
profile: () => request<UserProfile>("/user/profile"),
createSession: () => request<{ sessionId: number }>("/chat/session", { method: "POST", body: JSON.stringify({}) }),
listSessions: () => request<ChatSession[]>("/chat/session/list"),
history: (sessionId: number) => request<ChatMessage[]>(`/chat/history?sessionId=${sessionId}`),
renameSession: (sessionId: number, title: string) =>
request<ChatSession>("/chat/session/title", { method: "PUT", body: JSON.stringify({ sessionId, title }) }),
deleteSession: (sessionId: number) => request<null>(`/chat/session/${sessionId}`, { method: "DELETE" }),
stop: (sessionId: number) => request<null>("/chat/stop", { method: "POST", body: JSON.stringify({ sessionId }) }),
};
export async function streamChat(sessionId: number, message: string, onChunk: (chunk: string) => void) {
const token = getToken();
const response = await fetch(`${API_BASE}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify({ sessionId, message }),
});
if (!response.ok || !response.body) {
throw new Error("AI 回复连接失败");
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop() ?? "";
for (const part of parts) {
const line = part.trim();
if (!line.startsWith("data:")) continue;
const payload = line.slice(5).trim();
if (payload === "[DONE]") return;
const parsed = JSON.parse(payload) as { content?: string };
if (parsed.content) onChunk(parsed.content);
}
}
}

View File

@@ -0,0 +1,429 @@
:root {
font-family: Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
color: #17211d;
background: #e9efed;
font-synthesis: none;
text-rendering: optimizeLegibility;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
}
button,
input,
textarea {
font: inherit;
}
button {
cursor: pointer;
}
.app-shell {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
}
.phone-frame {
position: relative;
width: min(100%, 430px);
height: min(860px, calc(100vh - 48px));
min-height: 640px;
overflow: hidden;
background: #f8fbfa;
border: 1px solid rgba(117, 135, 128, 0.22);
border-radius: 28px;
box-shadow: 0 28px 80px rgba(15, 31, 26, 0.18);
}
.booting {
height: 100%;
display: grid;
place-items: center;
color: #557066;
}
.login-panel {
height: 100%;
padding: 72px 24px 24px;
display: flex;
flex-direction: column;
gap: 18px;
background: linear-gradient(180deg, #ffffff 0%, #f3faf7 100%);
}
.brand-mark {
width: 56px;
height: 56px;
display: grid;
place-items: center;
border-radius: 16px;
background: #0f8b6f;
color: #ffffff;
font-weight: 800;
letter-spacing: 0;
}
.login-panel h1 {
margin: 10px 0 0;
font-size: 28px;
line-height: 1.2;
}
.login-panel p {
margin: 0 0 18px;
color: #5f746c;
}
.login-panel label {
display: grid;
gap: 8px;
color: #40524b;
font-size: 14px;
}
.login-panel input,
.composer textarea {
width: 100%;
border: 1px solid #cad8d2;
border-radius: 14px;
background: #ffffff;
color: #17211d;
outline: none;
}
.login-panel input {
height: 48px;
padding: 0 14px;
}
.login-panel input:focus,
.composer textarea:focus {
border-color: #0f8b6f;
box-shadow: 0 0 0 3px rgba(15, 139, 111, 0.12);
}
.code-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 92px;
gap: 10px;
}
.primary,
.secondary,
.send-btn,
.stop-btn,
.new-session-btn {
border: 0;
border-radius: 14px;
font-weight: 700;
}
.primary {
height: 50px;
margin-top: 8px;
background: #0f8b6f;
color: #ffffff;
}
.secondary {
background: #e5f3ef;
color: #0f735d;
}
button:disabled {
cursor: not-allowed;
opacity: 0.52;
}
.form-tip {
min-height: 20px;
color: #657970;
font-size: 13px;
}
.topbar {
height: 72px;
display: grid;
grid-template-columns: 42px minmax(0, 1fr) 54px;
align-items: center;
gap: 10px;
padding: 12px 16px 10px;
border-bottom: 1px solid #e0ebe7;
background: rgba(255, 255, 255, 0.94);
}
.topbar h1 {
margin: 0;
font-size: 18px;
line-height: 1.2;
}
.topbar p {
margin: 4px 0 0;
color: #6a7d75;
font-size: 12px;
}
.icon-btn,
.plain-btn {
height: 38px;
border: 0;
border-radius: 12px;
background: #edf5f2;
color: #285247;
}
.icon-btn {
width: 38px;
font-size: 20px;
}
.plain-btn {
font-size: 13px;
}
.quota-strip {
display: flex;
justify-content: space-between;
align-items: center;
margin: 12px 16px 0;
padding: 10px 12px;
border-radius: 14px;
background: #eaf5f1;
color: #315d52;
font-size: 13px;
}
.quota-strip strong {
color: #0f735d;
}
.chat-area {
height: calc(100% - 72px - 54px - 82px);
overflow-y: auto;
padding: 16px;
}
.empty-state {
margin: 72px auto 0;
max-width: 280px;
text-align: center;
color: #60756d;
}
.empty-state strong {
display: block;
margin-bottom: 8px;
color: #20332c;
font-size: 18px;
}
.empty-state p {
margin: 0;
font-size: 14px;
line-height: 1.7;
}
.message {
display: grid;
grid-template-columns: 32px minmax(0, 1fr);
gap: 10px;
margin-bottom: 16px;
}
.message.user {
grid-template-columns: minmax(0, 1fr) 32px;
}
.message.user .avatar {
grid-column: 2;
background: #163d34;
}
.message.user .bubble {
grid-column: 1;
grid-row: 1;
justify-self: end;
background: #0f8b6f;
color: #ffffff;
border-color: #0f8b6f;
}
.avatar {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 10px;
background: #dcebe6;
color: #285247;
font-size: 12px;
font-weight: 800;
}
.bubble {
max-width: 100%;
width: fit-content;
padding: 12px 13px;
border: 1px solid #dbe7e3;
border-radius: 16px;
background: #ffffff;
box-shadow: 0 8px 22px rgba(31, 57, 49, 0.06);
}
.content {
white-space: pre-wrap;
word-break: break-word;
line-height: 1.65;
font-size: 15px;
}
.typing {
display: inline-block;
margin-top: 8px;
color: #0f8b6f;
font-size: 12px;
}
.composer {
position: absolute;
left: 0;
right: 0;
bottom: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 64px;
gap: 10px;
padding: 12px 14px max(12px, env(safe-area-inset-bottom));
border-top: 1px solid #e0ebe7;
background: #ffffff;
}
.composer textarea {
min-height: 48px;
max-height: 96px;
resize: none;
padding: 13px 14px;
line-height: 1.45;
}
.send-btn,
.stop-btn {
min-height: 48px;
}
.send-btn {
background: #0f8b6f;
color: #ffffff;
}
.stop-btn {
background: #ffe9e5;
color: #bb3b2f;
}
.drawer-mask {
position: absolute;
inset: 0;
z-index: 20;
pointer-events: none;
background: rgba(15, 33, 29, 0);
transition: background 0.2s ease;
}
.drawer-mask.show {
pointer-events: auto;
background: rgba(15, 33, 29, 0.28);
}
.session-drawer {
position: absolute;
inset: 0 auto 0 0;
z-index: 30;
width: 82%;
max-width: 340px;
display: flex;
flex-direction: column;
padding: 18px;
background: #ffffff;
transform: translateX(-102%);
transition: transform 0.22s ease;
box-shadow: 18px 0 50px rgba(20, 37, 32, 0.16);
}
.session-drawer.open {
transform: translateX(0);
}
.drawer-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.new-session-btn {
height: 44px;
margin-bottom: 14px;
background: #0f8b6f;
color: #ffffff;
}
.session-list {
overflow-y: auto;
display: grid;
gap: 8px;
}
.session-item {
display: grid;
gap: 5px;
width: 100%;
padding: 12px;
border: 1px solid #e0ebe7;
border-radius: 14px;
background: #f8fbfa;
color: #253b34;
text-align: left;
}
.session-item.active {
border-color: #0f8b6f;
background: #eaf5f1;
}
.session-item span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 700;
}
.session-item small {
color: #6f817a;
}
@media (max-width: 520px) {
.app-shell {
display: block;
min-height: 100vh;
padding: 0;
}
.phone-frame {
width: 100%;
height: 100vh;
min-height: 100vh;
border: 0;
border-radius: 0;
box-shadow: none;
}
}

View File

@@ -0,0 +1,36 @@
export interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
export interface UserProfile {
id: number;
phone: string;
name: string;
nickname?: string | null;
dailyLimit: number;
todayUsed: number;
status: number;
}
export interface LoginResult {
token: string;
expiredAt: string;
user: UserProfile;
}
export interface ChatSession {
id: number;
title: string;
messageCount: number;
updatedAt: string;
}
export interface ChatMessage {
id: number;
role: "user" | "assistant";
content: string;
message_status: string;
created_at: string;
}

View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />