This commit is contained in:
litongjava 2025-02-02 15:13:27 -10:00
parent e023e5bc44
commit ee659d9e13
2 changed files with 85 additions and 16 deletions

View file

@ -1,17 +1,18 @@
'use client'; 'use client';
import { useEffect, useRef, useState } from 'react'; import {useEffect, useRef, useState} from 'react';
import { Document } from '@langchain/core/documents'; import {Document} from '@langchain/core/documents';
import Navbar from './Navbar'; import Navbar from './Navbar';
import Chat from './Chat'; import Chat from './Chat';
import EmptyChat from './EmptyChat'; import EmptyChat from './EmptyChat';
import crypto from 'crypto'; import crypto from 'crypto';
import { toast } from 'sonner'; import {toast} from 'sonner';
import { useSearchParams } from 'next/navigation'; import {useSearchParams} from 'next/navigation';
import { getSuggestions } from '@/lib/actions'; import {getSuggestions} from '@/lib/actions';
import { Settings } from 'lucide-react'; import {Settings} from 'lucide-react';
import SettingsDialog from './SettingsDialog'; import SettingsDialog from './SettingsDialog';
import NextError from 'next/error'; import NextError from 'next/error';
import {Mcid} from "@/lib/mcid";
export type Message = { export type Message = {
messageId: string; messageId: string;
@ -382,10 +383,10 @@ const loadMessages = async (
setIsMessagesLoaded(true); setIsMessagesLoaded(true);
}; };
const ChatWindow = ({ id }: { id?: string }) => { const ChatWindow = ({id}: { id?: string }) => {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const initialMessage = searchParams.get('q'); const initialMessage = searchParams.get('q');
const [userId, setUserId] = useState<string | undefined>();
const [chatId, setChatId] = useState<string | undefined>(id); const [chatId, setChatId] = useState<string | undefined>(id);
const [newChatCreated, setNewChatCreated] = useState(false); const [newChatCreated, setNewChatCreated] = useState(false);
@ -417,6 +418,36 @@ const ChatWindow = ({ id }: { id?: string }) => {
const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isSettingsOpen, setIsSettingsOpen] = useState(false);
useEffect(() => {
const initializeUserId = () => {
try {
// 从 localStorage 读取现有用户 ID
const storedUserId = localStorage.getItem('userId');
if (storedUserId) {
setUserId(storedUserId);
console.debug('Using existing user ID:', storedUserId);
} else {
// 生成新的 MCID
const newUserId = new Mcid().generate().toString(); // 转换为字符串
// 存储到 localStorage
localStorage.setItem('userId', newUserId);
setUserId(newUserId);
console.debug('Generated new user ID:', newUserId);
}
} catch (error) {
console.error('Error initializing user ID:', error);
// 生成随机 ID 作为 fallback
const fallbackId = crypto.randomBytes(20).toString('hex');
localStorage.setItem('userId', fallbackId);
setUserId(fallbackId);
}
};
initializeUserId();
}, []); // 空依赖数组确保只运行一次
useEffect(() => { useEffect(() => {
if ( if (
chatId && chatId &&
@ -465,7 +496,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
} else { } else {
setIsReady(false); setIsReady(false);
} }
}, [isMessagesLoaded, isWSReady]); }, [isMessagesLoaded, isWSReady, userId]);
const sendMessage = async (message: string, messageId?: string) => { const sendMessage = async (message: string, messageId?: string) => {
if (loading) return; if (loading) return;
@ -556,7 +587,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
setMessages((prev) => setMessages((prev) =>
prev.map((message) => { prev.map((message) => {
if (message.messageId === data.messageId) { if (message.messageId === data.messageId) {
return { ...message, content: message.content + data.data }; return {...message, content: message.content + data.data};
} }
return message; return message;
@ -589,7 +620,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
setMessages((prev) => setMessages((prev) =>
prev.map((msg) => { prev.map((msg) => {
if (msg.messageId === lastMsg.messageId) { if (msg.messageId === lastMsg.messageId) {
return { ...msg, suggestions: suggestions }; return {...msg, suggestions: suggestions};
} }
return msg; return msg;
}), }),
@ -639,19 +670,19 @@ const ChatWindow = ({ id }: { id?: string }) => {
Failed to connect to the server. Please try again later. Failed to connect to the server. Please try again later.
</p> </p>
</div> </div>
<SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} /> <SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen}/>
</div> </div>
); );
} }
return isReady ? ( return isReady ? (
notFound ? ( notFound ? (
<NextError statusCode={404} /> <NextError statusCode={404}/>
) : ( ) : (
<div> <div>
{messages.length > 0 ? ( {messages.length > 0 ? (
<> <>
<Navbar chatId={chatId!} messages={messages} /> <Navbar chatId={chatId!} messages={messages}/>
<Chat <Chat
loading={loading} loading={loading}
messages={messages} messages={messages}

38
ui/lib/mcid.ts Normal file
View file

@ -0,0 +1,38 @@
// utils/mcid.ts
export class Mcid {
private lastTimestamp = -1;
private sequence = 0;
constructor(private readonly machineId: number = 0) {
if (machineId < 0 || machineId > 255) {
throw new Error('Machine ID must be between 0 and 255');
}
}
generate(): number {
let now = Date.now();
if (now < this.lastTimestamp) {
throw new Error('Clock moved backwards');
}
if (now === this.lastTimestamp) {
this.sequence = (this.sequence + 1) & 0xf;
if (this.sequence === 0) {
while (now <= this.lastTimestamp) {
now = Date.now();
}
}
} else {
this.sequence = 0;
}
this.lastTimestamp = now;
return (
(now * 0x1000) + // 时间戳左移 12 位
(this.machineId * 16) + // 机器 ID 左移 4 位
this.sequence // 序列号
);
}
}