1- import { useCallback , useEffect , useMemo , useState , useRef } from 'react' ;
1+ import { useCallback , useEffect , useMemo , useState } from 'react' ;
22import SandboxEditorModal from '@/pageComponents/chat/SandboxEditor/modal' ;
33import type { IconButtonProps } from '@chakra-ui/react' ;
44import { IconButton } from '@chakra-ui/react' ;
@@ -62,8 +62,8 @@ export const useSandboxEditor = ({
6262 * 职责:负责 checkSandboxExist 的网络同步及 SandboxEntryIcon 的显示控制。
6363 * 同步模式:
6464 * 1. 历史记录(ChatRecordContext):useMemo 派生,无副作用。
65- * 2. chatId 切换:渲染周期利用 useRef 确认 ID 变化并同步重置状态,防止 UI 闪烁 。
66- * 3. 网络请求:单一 useEffect,在参数变化时触发 1 次 。
65+ * 2. 网络请求:单一 useEffect,在参数变化时触发 1 次 。
66+ * 3. API 结果已返回时以 API 为准;未返回前才使用历史记录兜底 。
6767 */
6868export const useSandboxStatus = ( {
6969 appId,
@@ -75,13 +75,11 @@ export const useSandboxStatus = ({
7575 outLinkAuthData ?: OutLinkChatAuthProps ;
7676} ) => {
7777 const { t } = useTranslation ( ) ;
78- const [ apiSandboxExists , setApiSandboxExists ] = useState ( false ) ;
79- const lastChatIdRef = useRef ( chatId ) ;
80-
81- if ( lastChatIdRef . current !== chatId ) {
82- lastChatIdRef . current = chatId ;
83- setApiSandboxExists ( false ) ;
84- }
78+ const [ apiSandboxStatus , setApiSandboxStatus ] = useState ( {
79+ appId : '' ,
80+ chatId : '' ,
81+ exists : false
82+ } ) ;
8583
8684 const chatRecords = useContextSelector ( ChatRecordContext , ( v ) => {
8785 return v . chatRecords ;
@@ -97,22 +95,33 @@ export const useSandboxStatus = ({
9795 } , [ chatRecords , isChatRecordsLoaded ] ) ;
9896
9997 useEffect ( ( ) => {
100- if ( ! chatId ) return ;
98+ if ( ! appId || ! chatId ) return ;
10199 let cancelled = false ;
102100 checkSandboxExist ( { appId, chatId, outLinkAuthData } )
103101 . then ( ( result ) => {
104- if ( ! cancelled ) setApiSandboxExists ( result . exists ) ;
102+ if ( ! cancelled ) setApiSandboxStatus ( { appId , chatId , exists : result . exists } ) ;
105103 } )
106104 . catch ( ( error ) => {
107105 console . error ( 'Failed to check sandbox status:' , error ) ;
108106 } ) ;
109107 return ( ) => {
110108 cancelled = true ;
111109 } ;
112- } , [ appId , chatId ] ) ;
110+ } , [ appId , chatId , outLinkAuthData ] ) ;
113111
112+ const apiSandboxExists =
113+ apiSandboxStatus . appId === appId &&
114+ apiSandboxStatus . chatId === chatId &&
115+ apiSandboxStatus . exists ;
114116 const sandboxExists = hasSandboxInHistory || apiSandboxExists ;
115117
118+ const setSandboxExists = useCallback (
119+ ( exists : boolean ) => {
120+ setApiSandboxStatus ( { appId, chatId, exists } ) ;
121+ } ,
122+ [ appId , chatId ]
123+ ) ;
124+
116125 const SandboxEntryIcon = useCallback (
117126 ( {
118127 onOpen,
@@ -138,7 +147,7 @@ export const useSandboxStatus = ({
138147
139148 return {
140149 sandboxExists,
141- setSandboxExists : setApiSandboxExists ,
150+ setSandboxExists,
142151 SandboxEntryIcon
143152 } ;
144153} ;
0 commit comments