Skip to content

Commit 6be0304

Browse files
committed
feat(DocsAssistant): implement hashTransportConfig for secure chat runtime ID generation
1 parent d922295 commit 6be0304

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

app/components/DocsAssistant.tsx

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,18 @@ interface DocsAssistantProps {
2828
pageContext: PageContext;
2929
}
3030

31+
function hashTransportConfig(value: string): string {
32+
// 使用FNV-1a(32位)算法,避免在客户端聊天ID中嵌入原始API密钥。
33+
let hash = 0x811c9dc5;
34+
35+
for (let i = 0; i < value.length; i += 1) {
36+
hash ^= value.charCodeAt(i);
37+
hash = Math.imul(hash, 0x01000193);
38+
}
39+
40+
return (hash >>> 0).toString(36);
41+
}
42+
3143
export function DocsAssistant({ pageContext }: DocsAssistantProps) {
3244
return (
3345
<AssistantSettingsProvider>
@@ -50,6 +62,10 @@ function DocsAssistantInner({ pageContext }: DocsAssistantProps) {
5062
const [chatId] = useState(
5163
() => `chat-${Date.now()}-${Math.random().toString(36).slice(2)}`,
5264
);
65+
const chatRuntimeId = useMemo(
66+
() => `${chatId}:${provider}:${hashTransportConfig(apiKey)}`,
67+
[chatId, provider, apiKey],
68+
);
5369

5470
const transport = useMemo(
5571
() =>
@@ -110,9 +126,10 @@ function DocsAssistantInner({ pageContext }: DocsAssistantProps) {
110126
}, [logAnalyticsEvent]);
111127

112128
const chat = useChat({
113-
id: chatId,
114-
// 当 Provider 或 Key 更改时强制重置聊天 (但保持 chatId 不变会不会有问题?可能需要重新生成)
115-
// 这里我们暂时保留 chatId 不变,视为同一会话切换了模型
129+
// ai-sdk/react 的 useChat 只在 id 改变时重建内部 Chat 实例;
130+
// transport/body 变化不会自动生效。这里用 runtime id 触发重建,
131+
// 同时保留 body.chatId 作为后端持久化会话 id。
132+
id: chatRuntimeId,
116133
transport,
117134
onFinish: () => {
118135
// 聊天流式传输完成后(onFinish),记录一次查询行为
@@ -277,7 +294,7 @@ function DocsAssistantInner({ pageContext }: DocsAssistantProps) {
277294
// 当 Provider 更改时清除之前的错误
278295
useEffect(() => {
279296
clearChatError();
280-
}, [provider, clearChatError]);
297+
}, [provider, apiKey, clearChatError]);
281298

282299
// 当对话状态重置时也清除错误
283300
useEffect(() => {

0 commit comments

Comments
 (0)