|
1 | 1 | import { clsx } from 'clsx' |
2 | | -import { useRef, useState } from 'react' |
| 2 | +import { useEffect, useRef, useState } from 'react' |
3 | 3 | import { Tooltip } from 'react-tooltip' |
4 | | -import { ApiMethod, xfetch } from 'x-fetch' |
| 4 | +import { |
| 5 | + ApiMethod, |
| 6 | + interceptors, |
| 7 | + ResponseError, |
| 8 | + xfetch, |
| 9 | + type ApiInterceptor, |
| 10 | +} from 'x-fetch' |
5 | 11 |
|
6 | 12 | import { type CloudAuth, useCloudAuth } from '../context.tsx' |
7 | 13 | import type { AuthInfo } from '../types.ts' |
@@ -54,6 +60,36 @@ export const AIAssistant = ({ open, onOpenChange }: AIAssistantProps) => { |
54 | 60 | onNewChat() |
55 | 61 | }) |
56 | 62 |
|
| 63 | + useEffect(() => { |
| 64 | + const interceptor: ApiInterceptor = async (req, next) => { |
| 65 | + if (!req.url.startsWith('/smart/')) { |
| 66 | + return next(req) |
| 67 | + } |
| 68 | + if (!req.headers.has('Authorization')) { |
| 69 | + req.headers.set('Authorization', `Bearer ${authInfo!.token}`) |
| 70 | + } |
| 71 | + if (!req.headers.has('CLOUD_AUTH_ORIGIN')) { |
| 72 | + req.headers.set('CLOUD_AUTH_ORIGIN', authInfo!.origin) |
| 73 | + } |
| 74 | + try { |
| 75 | + return await next(req) |
| 76 | + } catch (err) { |
| 77 | + if ( |
| 78 | + err instanceof ResponseError && |
| 79 | + // type-coverage:ignore-next-line -- no idea |
| 80 | + err.response.status === 401 |
| 81 | + ) { |
| 82 | + onLogout() |
| 83 | + } |
| 84 | + throw err |
| 85 | + } |
| 86 | + } |
| 87 | + interceptors.use(interceptor) |
| 88 | + return () => { |
| 89 | + interceptors.eject(interceptor) |
| 90 | + } |
| 91 | + }, [authInfo, onLogout]) |
| 92 | + |
57 | 93 | const onClose = useMemoizedFn(() => { |
58 | 94 | onOpenChange(false) |
59 | 95 | }) |
@@ -93,7 +129,6 @@ export const AIAssistant = ({ open, onOpenChange }: AIAssistantProps) => { |
93 | 129 | '/smart/api/new_session', |
94 | 130 | { |
95 | 131 | method: ApiMethod.POST, |
96 | | - headers: { username: authInfo!.detail!.user.name }, |
97 | 132 | }, |
98 | 133 | ) |
99 | 134 | sessionIdRef.current = session_id |
@@ -152,6 +187,9 @@ export const AIAssistant = ({ open, onOpenChange }: AIAssistantProps) => { |
152 | 187 | try { |
153 | 188 | await onSend_(content) |
154 | 189 | } catch { |
| 190 | + if (!sessionIdRef.current) { |
| 191 | + return |
| 192 | + } |
155 | 193 | flushMessages((messages) => { |
156 | 194 | const index = assistantMessageIndexRef.current |
157 | 195 | return [ |
|
0 commit comments