@myun/gimi-chat 0.9.77 → 0.9.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o =
8
8
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
9
9
  function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
10
10
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
11
- import React, { useEffect, useMemo, useState } from "react";
11
+ import React, { useEffect, useMemo, useRef, useState } from "react";
12
12
  import { MMarkdown } from '@myun/gimi-design';
13
13
  import IconFont from "../../../iconfont-com";
14
14
  import FileUpload from "../../../file-upload";
@@ -16,6 +16,8 @@ import styles from "./index.module.css";
16
16
  import classNames from "classnames";
17
17
  import { useTranslation } from "react-i18next";
18
18
  import { useAppSelector } from "../../../../store/hooks";
19
+ import useScroll from "../../../../hooks/useScroll";
20
+
19
21
  // 思考工具项组件
20
22
  var ThinkingToolItem = function ThinkingToolItem(_ref) {
21
23
  var item = _ref.item,
@@ -28,12 +30,22 @@ var ThinkingToolItem = function ThinkingToolItem(_ref) {
28
30
  _useState4 = _slicedToArray(_useState3, 2),
29
31
  manual = _useState4[0],
30
32
  setManual = _useState4[1]; // 用户是否手动操作过,手动后不再被状态覆盖
31
-
33
+ var contentRef = useRef(null);
34
+ var _useScroll = useScroll(contentRef),
35
+ _useScroll2 = _slicedToArray(_useScroll, 1),
36
+ throttledScrollToBottom = _useScroll2[0];
32
37
  useEffect(function () {
33
38
  if (!manual) {
34
39
  setShowContent(item.status !== "COMPLETED");
35
40
  }
36
41
  }, [item.status, manual]);
42
+
43
+ // 内容更新 / 展开时滚动到底部
44
+ useEffect(function () {
45
+ if (showContent) {
46
+ throttledScrollToBottom();
47
+ }
48
+ }, [item.content, showContent]);
37
49
  var handleToggle = function handleToggle() {
38
50
  setManual(true);
39
51
  setShowContent(function (v) {
@@ -60,7 +72,8 @@ var ThinkingToolItem = function ThinkingToolItem(_ref) {
60
72
  color: !showContent ? "var(--theme-neutral, #626262)" : "var(--theme-mediumNeutral, #B3B2B2)"
61
73
  }
62
74
  })), item.content && showContent && /*#__PURE__*/React.createElement("div", {
63
- className: styles.toolItemContent
75
+ className: styles.toolItemContent,
76
+ ref: contentRef
64
77
  }, /*#__PURE__*/React.createElement(MMarkdown, {
65
78
  content: item.content,
66
79
  customRender: customRender,
@@ -204,9 +204,9 @@ var AnswerItem = function AnswerItem(_ref) {
204
204
  return {
205
205
  id: "thinking-".concat(item.id),
206
206
  moduleType: 'thinking',
207
- toolName: getToolNameByStatus('thinking', item.reasoningStatus === 1 ? 'RUNNING' : item.reasoningStatus === 2 ? 'COMPLETED' : 'FAILED'),
207
+ toolName: getToolNameByStatus('thinking', item.reasoningStatus === 1 ? 'RUNNING' : item.reasoningStatus === 2 ? 'COMPLETED' : 'CANCELLED'),
208
208
  content: item.reasoningContent,
209
- status: item.reasoningStatus === 1 ? 'RUNNING' : item.reasoningStatus === 2 ? 'COMPLETED' : 'FAILED'
209
+ status: item.reasoningStatus === 1 ? 'RUNNING' : item.reasoningStatus === 2 ? 'COMPLETED' : 'CANCELLED'
210
210
  };
211
211
  }, [item.reasoningContent, item.reasoningStatus, item.vipLevel, item.id]);
212
212
 
@@ -44,6 +44,7 @@ import IconFontCom from "../iconfont-com";
44
44
  import VoiceBars from "../voice-bars";
45
45
  import classNames from 'classnames';
46
46
  import { maxInputLength } from "../../utils/tools";
47
+ import useDeepThinkConfig from "../../hooks/useDeepThinkConfig";
47
48
  var extractText = function extractText() {
48
49
  var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
49
50
  var skipSkill = arguments.length > 1 ? arguments[1] : undefined;
@@ -103,12 +104,6 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
103
104
  var inputRef = React.useRef(null);
104
105
  var isTruncatingRef = React.useRef(false);
105
106
  var uploadFileRef = React.useRef(null);
106
- // 缓存 getThinkingEffective 的结果,避免重复请求
107
- var thinkingCacheRef = React.useRef({
108
- agentId: null,
109
- promise: null,
110
- result: null
111
- });
112
107
  var conversationIdRef = React.useRef(conversationId);
113
108
  conversationIdRef.current = conversationId;
114
109
  var agentObjRef = React.useRef(agentObj);
@@ -144,21 +139,20 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
144
139
  _React$useState4 = _slicedToArray(_React$useState3, 2),
145
140
  hasContent = _React$useState4[0],
146
141
  setHasContent = _React$useState4[1];
147
- // thinking: 0 置灰禁用,1 可点击
148
- var _React$useState5 = React.useState(false),
149
- _React$useState6 = _slicedToArray(_React$useState5, 2),
150
- deepThinkDisabled = _React$useState6[0],
151
- setDeepThinkDisabled = _React$useState6[1];
152
- // thinkingEnable: 1 高亮(已开启),0 默认
153
- var _React$useState7 = React.useState(false),
154
- _React$useState8 = _slicedToArray(_React$useState7, 2),
155
- deepThinkActive = _React$useState8[0],
156
- setDeepThinkActive = _React$useState8[1];
157
142
  var _useContext = useContext(ChatContext),
158
143
  apiService = _useContext.apiService;
159
144
  var _ref = apiService,
160
145
  createRoomId = _ref.createRoomId;
161
146
 
147
+ // 深度思考开关:同一 agentId 只请求一次配置,内部已做跨重渲染/重挂载去重
148
+ var _useDeepThinkConfig = useDeepThinkConfig({
149
+ agentId: agentObj === null || agentObj === void 0 ? void 0 : agentObj.agentId,
150
+ hidden: props.hiddenDeepThink
151
+ }),
152
+ deepThinkDisabled = _useDeepThinkConfig.deepThinkDisabled,
153
+ deepThinkActive = _useDeepThinkConfig.deepThinkActive,
154
+ toggleDeepThink = _useDeepThinkConfig.toggleDeepThink;
155
+
162
156
  // skill 面板由 tiptap ReactRenderer 渲染、脱离 Context 树,注入 agentId 与 apiService 供其拉取接口
163
157
  useEffect(function () {
164
158
  setSkillContext({
@@ -178,78 +172,6 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
178
172
  }
179
173
  });
180
174
  }, [apiService]);
181
-
182
- // 获取深度思考配置
183
- useEffect(function () {
184
- var agentId = agentObj === null || agentObj === void 0 ? void 0 : agentObj.agentId;
185
- if (props.hiddenDeepThink || !agentId || !(apiService !== null && apiService !== void 0 && apiService.getThinkingEffective)) {
186
- setDeepThinkDisabled(false);
187
- setDeepThinkActive(false);
188
- return;
189
- }
190
-
191
- // 如果缓存中有相同 agentId 的结果,直接使用
192
- if (thinkingCacheRef.current.agentId === agentId && thinkingCacheRef.current.result) {
193
- var result = thinkingCacheRef.current.result;
194
- setDeepThinkDisabled(result.thinking !== 1);
195
- setDeepThinkActive(result.thinkingEnable === 1);
196
- return;
197
- }
198
-
199
- // 如果有正在进行的请求,复用该 Promise
200
- if (thinkingCacheRef.current.agentId === agentId && thinkingCacheRef.current.promise) {
201
- thinkingCacheRef.current.promise.then(function (result) {
202
- setDeepThinkDisabled(result.thinking !== 1);
203
- setDeepThinkActive(result.thinkingEnable === 1);
204
- }).catch(function (e) {
205
- console.error('[deepThink] getThinkingEffective error:', e);
206
- setDeepThinkDisabled(false);
207
- setDeepThinkActive(false);
208
- });
209
- return;
210
- }
211
-
212
- // 创建新请求并缓存
213
- var cancelled = false;
214
- var promise = apiService.getThinkingEffective(agentId).then(function (res) {
215
- if (cancelled) return null;
216
- var result = (res === null || res === void 0 ? void 0 : res.result) || {};
217
- // 缓存结果
218
- thinkingCacheRef.current = {
219
- agentId: agentId,
220
- promise: null,
221
- result: result
222
- };
223
- setDeepThinkDisabled(result.thinking !== 1);
224
- setDeepThinkActive(result.thinkingEnable === 1);
225
- return result;
226
- }).catch(function (e) {
227
- if (!cancelled) {
228
- console.error('[deepThink] getThinkingEffective error:', e);
229
- setDeepThinkDisabled(false);
230
- setDeepThinkActive(false);
231
- // 清除失败的缓存
232
- if (thinkingCacheRef.current.agentId === agentId) {
233
- thinkingCacheRef.current = {
234
- agentId: null,
235
- promise: null,
236
- result: null
237
- };
238
- }
239
- }
240
- throw e;
241
- });
242
-
243
- // 缓存正在进行的请求
244
- thinkingCacheRef.current = {
245
- agentId: agentId,
246
- promise: promise,
247
- result: null
248
- };
249
- return function () {
250
- cancelled = true;
251
- };
252
- }, [agentObj === null || agentObj === void 0 ? void 0 : agentObj.agentId, apiService, props.hiddenDeepThink]);
253
175
  React.useEffect(function () {
254
176
  if (!props.defaultPrompt) {
255
177
  setHasContent(false);
@@ -711,27 +633,6 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
711
633
  }
712
634
  (_props$onSend = props.onSend) === null || _props$onSend === void 0 || _props$onSend.call(props, text);
713
635
  }, [props, fileList, t]);
714
-
715
- // 点击切换深度思考开关
716
- var handleToggleDeepThink = React.useCallback(function () {
717
- var _agentObjRef$current4;
718
- if (deepThinkDisabled) return; // 置灰禁用时不可点击
719
- var agentId = (_agentObjRef$current4 = agentObjRef.current) === null || _agentObjRef$current4 === void 0 ? void 0 : _agentObjRef$current4.agentId;
720
- if (!agentId || !(apiService !== null && apiService !== void 0 && apiService.saveThinkingEnable)) return;
721
- var nextActive = !deepThinkActive;
722
- var thinkingEnable = nextActive ? 1 : 0;
723
- // 乐观更新 UI
724
- setDeepThinkActive(nextActive);
725
- apiService.saveThinkingEnable({
726
- agentId: agentId,
727
- thinkingEnable: thinkingEnable
728
- }).catch(function (e) {
729
- // 接口失败回滚
730
- console.error('[deepThink] saveThinkingEnable error:', e);
731
- setDeepThinkActive(!nextActive);
732
- Toast.error(t('action.failed'));
733
- });
734
- }, [apiService, deepThinkActive, deepThinkDisabled, t]);
735
636
  var renderConfigureArea = React.useCallback(function () {
736
637
  return /*#__PURE__*/React.createElement("div", {
737
638
  className: styles.configureArea
@@ -739,7 +640,7 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
739
640
  content: t('chatInput.deepThinkNotSupported')
740
641
  }, /*#__PURE__*/React.createElement("div", {
741
642
  className: classNames(styles.deepthink, _defineProperty(_defineProperty({}, styles.active, deepThinkActive), styles.disabled, deepThinkDisabled)),
742
- onClick: handleToggleDeepThink
643
+ onClick: toggleDeepThink
743
644
  }, /*#__PURE__*/React.createElement(IconFontCom, {
744
645
  type: "icon-moxing",
745
646
  size: 14
@@ -749,7 +650,7 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
749
650
  }
750
651
  }, t('chatInput.deepThinkModeAuto')))) : /*#__PURE__*/React.createElement("div", {
751
652
  className: classNames(styles.deepthink, _defineProperty(_defineProperty({}, styles.active, deepThinkActive), styles.disabled, deepThinkDisabled)),
752
- onClick: handleToggleDeepThink
653
+ onClick: toggleDeepThink
753
654
  }, /*#__PURE__*/React.createElement(IconFontCom, {
754
655
  type: "icon-moxing",
755
656
  size: 14
@@ -758,7 +659,7 @@ var ChatInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
758
659
  marginBottom: 2
759
660
  }
760
661
  }, t('chatInput.deepThinkModeAuto')))), AgentContainer);
761
- }, [UploadFileTool, props.hiddenDeepThink, deepThinkActive, deepThinkDisabled, handleToggleDeepThink, AgentContainer]);
662
+ }, [UploadFileTool, props.hiddenDeepThink, deepThinkActive, deepThinkDisabled, toggleDeepThink, AgentContainer]);
762
663
  var stopSSe = function stopSSe() {
763
664
  if (uploadFileRef.current) {
764
665
  var _uploadFileRef$curren2;
@@ -58,7 +58,8 @@ var NODE_STATUS_TEXTS = {
58
58
  'STARTED': '开始分析问题',
59
59
  'RUNNING': '正在分析问题',
60
60
  'COMPLETED': '已完成分析',
61
- 'FAILED': '分析问题失败'
61
+ 'FAILED': '分析问题失败',
62
+ 'CANCELLED': '分析问题已取消'
62
63
  },
63
64
  'knowledge': {
64
65
  'STARTED': '开始调用知识库检索',
@@ -298,13 +299,17 @@ export var useChatStream = function useChatStream(platform) {
298
299
  if (data.status === 0 && data.result && PROCESSABLE_MODULE_TYPES.includes(_dataObj.moduleType) && !_dataObj.ERROR) {
299
300
  console.log('dataObj-----', _dataObj);
300
301
  if (_dataObj.status === 'RUNNING' && _dataObj.moduleType === 'end') {
301
- if (_dataObj.content && !_dataObj.reasoningContent) {
302
- fullResponse += _dataObj.content;
303
- onDataReceived === null || onDataReceived === void 0 || onDataReceived(fullResponse, 'content');
304
- } else if (_dataObj.reasoningContent && !_dataObj.content) {
302
+ // reasoningContent content 可能出现在同一个事件里,
303
+ // 必须各自独立累加,互斥写法会把 reasoning 增量静默丢掉。
304
+ // reasoning content:content 到达意味着思考结束,reasoningStatus 最终落在 2。
305
+ if (_dataObj.reasoningContent) {
305
306
  reasoningResponse += _dataObj.reasoningContent;
306
307
  onDataReceived === null || onDataReceived === void 0 || onDataReceived(reasoningResponse, 'reasoningContent');
307
308
  }
309
+ if (_dataObj.content) {
310
+ fullResponse += _dataObj.content;
311
+ onDataReceived === null || onDataReceived === void 0 || onDataReceived(fullResponse, 'content');
312
+ }
308
313
  }
309
314
  if (_dataObj.moduleType === 'tool_call') {
310
315
  onMCPToolsStream === null || onMCPToolsStream === void 0 || onMCPToolsStream(_dataObj);
@@ -349,6 +349,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
349
349
  status: dataObj.status
350
350
  }
351
351
  })]);
352
+ messageListRef.current = newMessageList;
352
353
  dispatch(setMessageList({
353
354
  messageList: newMessageList
354
355
  }));
@@ -405,6 +406,10 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
405
406
  moduleType: dataObj.moduleType,
406
407
  toolList: _toConsumableArray(curToolList)
407
408
  })]);
409
+ // 同一网络分片内的多个 SSE 事件是在同一个同步调用栈里连续回调的,React 无法在中间完成 render。
410
+ // 这里若不同步 ref,后续事件仍基于上一次 render 的旧列表计算 ——
411
+ // 表现为:思考内容增量被覆盖丢失、节点终态被旧状态顶掉(一直停在 RUNNING)。
412
+ messageListRef.current = newMessageList;
408
413
  dispatch(setMessageList({
409
414
  messageList: newMessageList
410
415
  }));
@@ -545,6 +550,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
545
550
  reasoningLoading: false,
546
551
  stop: 0
547
552
  })]);
553
+ messageListRef.current = newMessageList;
548
554
  dispatch(setMessageList({
549
555
  messageList: newMessageList
550
556
  }));
@@ -566,6 +572,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
566
572
  });
567
573
  }
568
574
  var newMessageList = [].concat(_toConsumableArray(currentMessageList.slice(0, -1)), [_objectSpread(_objectSpread({}, currentMessageList[currentMessageList.length - 1]), {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, type, response || ''), "loading", again ? false : true), "msgLoading", false), "vipLevel", vipLevelRef.current), "reasoningLoading", type === 'content' ? false : again ? false : true), "reasoningStatus", type === 'content' ? 2 : 1), "moduleInfo", null), "moduleType", 'end'), "mcp", null), "toolList", lastToolList))]);
575
+ messageListRef.current = newMessageList;
569
576
  dispatch(setMessageList({
570
577
  messageList: newMessageList
571
578
  }));
@@ -616,6 +623,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
616
623
  return v.moduleType !== "agent" && v.moduleType !== 'end';
617
624
  }))))]);
618
625
  }
626
+ messageListRef.current = newMessageList;
619
627
  dispatch(setMessageList({
620
628
  messageList: newMessageList
621
629
  }));
@@ -626,13 +634,13 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
626
634
  // 获取最新的agent详情,防止redux异步更新
627
635
  agentDetail = agentInfo || agentObjRef.current; // 获取推荐追问
628
636
  if (!((agentDetail === null || agentDetail === void 0 ? void 0 : agentDetail.isEnableRelated) === 1 && (type === 'end' || type === 'COMPLETED'))) {
629
- _context5.next = 12;
637
+ _context5.next = 13;
630
638
  break;
631
639
  }
632
640
  setMsgLoading(true);
633
- _context5.next = 12;
641
+ _context5.next = 13;
634
642
  return getRecommendList(newMessageList, lastId, statusRef.current);
635
- case 12:
643
+ case 13:
636
644
  // 获取相关课程
637
645
  userInput = newMessageList[newMessageList.length - 2].content;
638
646
  getRelatedCourses(userInput || '');
@@ -643,7 +651,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
643
651
  }
644
652
  setMsgLoading(false);
645
653
  onSendEnd === null || onSendEnd === void 0 || onSendEnd(newMessageList[newMessageList.length - 1]);
646
- case 17:
654
+ case 18:
647
655
  case "end":
648
656
  return _context5.stop();
649
657
  }
@@ -673,6 +681,7 @@ var useCommonChatAPI = function useCommonChatAPI(props) {
673
681
  return v.moduleType !== "agent" && v.moduleType !== 'end';
674
682
  }))
675
683
  })]);
684
+ messageListRef.current = newMessageList;
676
685
  dispatch(setMessageList({
677
686
  messageList: newMessageList
678
687
  }));
@@ -0,0 +1,23 @@
1
+ /** 深度思考配置(服务端按 agentId 维度返回) */
2
+ export interface IThinkingConfig {
3
+ /** 1: 该智能体支持深度思考,其它值置灰禁用 */
4
+ thinking?: number;
5
+ /** 1: 深度思考已开启(高亮) */
6
+ thinkingEnable?: number;
7
+ [key: string]: any;
8
+ }
9
+ /**
10
+ * 深度思考开关(读取配置 + 切换开关)
11
+ *
12
+ * 同一 agentId 全局只请求一次 getThinkingEffective:
13
+ * 重渲染、卸载重挂载、多实例共用同一份缓存。
14
+ */
15
+ declare const useDeepThinkConfig: ({ agentId, hidden }: {
16
+ agentId?: number | undefined;
17
+ hidden?: boolean | undefined;
18
+ }) => {
19
+ deepThinkDisabled: boolean;
20
+ deepThinkActive: boolean;
21
+ toggleDeepThink: () => void;
22
+ };
23
+ export default useDeepThinkConfig;
@@ -0,0 +1,138 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
5
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
6
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
7
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
8
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
9
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
10
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
11
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
12
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
13
+ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
14
+ import { useTranslation } from 'react-i18next';
15
+ import { Toast } from '@douyinfe/semi-ui';
16
+ import ChatContext from "../components/templates/chatContext";
17
+
18
+ /** 深度思考配置(服务端按 agentId 维度返回) */
19
+
20
+ /**
21
+ * 深度思考配置缓存,key 为 agentId。
22
+ *
23
+ * 放在模块作用域(而不是组件内 ref)是为了覆盖三种「同一个 agentId 被多次请求」:
24
+ * 1. 组件重渲染:`useApi` 每次渲染都返回新对象,apiService 一变 effect 就会重跑;
25
+ * 2. 组件卸载后重新挂载:ChatInput 由 CommonChat 条件渲染,收起/展开、切 tab 都会重建;
26
+ * 3. 同一页面存在多个实例:每个实例各自的 ref 会各请求一份。
27
+ */
28
+ var thinkingCache = new Map();
29
+
30
+ /** 按 agentId 取配置:已有(含进行中)的请求直接复用,不重复发起 */
31
+ var loadThinkingConfig = function loadThinkingConfig(apiService, agentId) {
32
+ var cached = thinkingCache.get(agentId);
33
+ if (cached) return cached.promise;
34
+ var entry = {
35
+ promise: null,
36
+ result: null
37
+ };
38
+ entry.promise = apiService.getThinkingEffective(agentId).then(function (res) {
39
+ entry.result = (res === null || res === void 0 ? void 0 : res.result) || {};
40
+ return entry.result;
41
+ }).catch(function (e) {
42
+ // 失败的请求不入缓存,下次挂载可重试
43
+ thinkingCache.delete(agentId);
44
+ throw e;
45
+ });
46
+ thinkingCache.set(agentId, entry);
47
+ return entry.promise;
48
+ };
49
+
50
+ /** 开关保存成功后同步缓存,避免下次挂载又拉到旧值 */
51
+ var patchThinkingConfig = function patchThinkingConfig(agentId, patch) {
52
+ var entry = thinkingCache.get(agentId);
53
+ if (entry !== null && entry !== void 0 && entry.result) {
54
+ entry.result = _objectSpread(_objectSpread({}, entry.result), patch);
55
+ }
56
+ };
57
+
58
+ /**
59
+ * 深度思考开关(读取配置 + 切换开关)
60
+ *
61
+ * 同一 agentId 全局只请求一次 getThinkingEffective:
62
+ * 重渲染、卸载重挂载、多实例共用同一份缓存。
63
+ */
64
+ var useDeepThinkConfig = function useDeepThinkConfig(_ref) {
65
+ var agentId = _ref.agentId,
66
+ hidden = _ref.hidden;
67
+ var _useTranslation = useTranslation(),
68
+ t = _useTranslation.t;
69
+ var _useContext = useContext(ChatContext),
70
+ apiService = _useContext.apiService;
71
+
72
+ // apiService 每次渲染都是新对象,用 ref 读取并把它移出 effect deps,避免 effect 无意义地反复执行
73
+ var apiServiceRef = useRef(null);
74
+ apiServiceRef.current = apiService;
75
+
76
+ // true: 置灰禁用(该智能体不支持深度思考)
77
+ var _useState = useState(false),
78
+ _useState2 = _slicedToArray(_useState, 2),
79
+ deepThinkDisabled = _useState2[0],
80
+ setDeepThinkDisabled = _useState2[1];
81
+ // true: 已开启(高亮)
82
+ var _useState3 = useState(false),
83
+ _useState4 = _slicedToArray(_useState3, 2),
84
+ deepThinkActive = _useState4[0],
85
+ setDeepThinkActive = _useState4[1];
86
+ useEffect(function () {
87
+ var id = Number(agentId);
88
+ var api = apiServiceRef.current;
89
+ if (hidden || !agentId || !(api !== null && api !== void 0 && api.getThinkingEffective)) {
90
+ setDeepThinkDisabled(false);
91
+ setDeepThinkActive(false);
92
+ return;
93
+ }
94
+ var alive = true;
95
+ loadThinkingConfig(api, id).then(function (result) {
96
+ if (!alive) return;
97
+ setDeepThinkDisabled(result.thinking !== 1);
98
+ setDeepThinkActive(result.thinkingEnable === 1);
99
+ }).catch(function (e) {
100
+ if (!alive) return;
101
+ console.error('[deepThink] getThinkingEffective error:', e);
102
+ setDeepThinkDisabled(false);
103
+ setDeepThinkActive(false);
104
+ });
105
+ return function () {
106
+ alive = false;
107
+ };
108
+ }, [agentId, hidden]);
109
+
110
+ // 点击切换深度思考开关
111
+ var toggleDeepThink = useCallback(function () {
112
+ if (deepThinkDisabled) return; // 置灰禁用时不可点击
113
+ var id = Number(agentId);
114
+ var api = apiServiceRef.current;
115
+ if (!agentId || !(api !== null && api !== void 0 && api.saveThinkingEnable)) return;
116
+ var nextActive = !deepThinkActive;
117
+ var thinkingEnable = nextActive ? 1 : 0;
118
+ setDeepThinkActive(nextActive); // 乐观更新
119
+ api.saveThinkingEnable({
120
+ agentId: id,
121
+ thinkingEnable: thinkingEnable
122
+ }).then(function () {
123
+ return patchThinkingConfig(id, {
124
+ thinkingEnable: thinkingEnable
125
+ });
126
+ }).catch(function (e) {
127
+ console.error('[deepThink] saveThinkingEnable error:', e);
128
+ setDeepThinkActive(!nextActive); // 接口失败回滚
129
+ Toast.error(t('action.failed'));
130
+ });
131
+ }, [agentId, deepThinkActive, deepThinkDisabled, t]);
132
+ return {
133
+ deepThinkDisabled: deepThinkDisabled,
134
+ deepThinkActive: deepThinkActive,
135
+ toggleDeepThink: toggleDeepThink
136
+ };
137
+ };
138
+ export default useDeepThinkConfig;