Skip to content

Commit f5c66ba

Browse files
author
linyuan.yang
committed
查看think
1 parent 324424c commit f5c66ba

11 files changed

Lines changed: 307 additions & 48 deletions

File tree

‎packages/chat-ui/src/components/MessageList.vue‎

Lines changed: 60 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script setup lang="ts">
2-
import { ref, computed } from 'vue'
2+
import { ref, computed, watch } from 'vue'
33
import { MessageRole, MessageKind } from '../types'
44
import type { StoredMessage, ToolCall, ChatLabels, DisplayContent } from '../types'
55
@@ -36,7 +36,7 @@ const props = withDefaults(defineProps<{
3636
queuedMessages?: DisplayContent[]
3737
labels?: ChatLabels
3838
fetchFn?: (url: string) => Promise<any>
39-
onThinkClick?: (thinkId: string, taskId?: string) => void
39+
onThinkClick?: (thinkId: string, taskId?: string, opts?: { live?: boolean }) => void
4040
}>(), {
4141
thinksUrlPrefix: null,
4242
tasksUrlPrefix: null,
@@ -110,15 +110,40 @@ const lightboxRef = ref<InstanceType<typeof ImageLightbox>>()
110110
const openLightbox = (src: string) => lightboxRef.value?.open(src)
111111
112112
const thinkDrawerRef = ref<InstanceType<typeof ThinkDrawer>>()
113-
function openThink(thinkId: string, taskId?: string) {
114-
if (props.onThinkClick) props.onThinkClick(thinkId, taskId)
115-
else thinkDrawerRef.value?.open(thinkId, taskId)
113+
function openThink(thinkId: string, taskId?: string, opts?: { live?: boolean }) {
114+
if (props.onThinkClick) props.onThinkClick(thinkId, taskId, opts)
115+
else thinkDrawerRef.value?.open(thinkId, taskId, opts)
116116
}
117117
118118
function findToolResult(toolCallId: string): StoredMessage | undefined {
119119
return toolResultMap.value.get(toolCallId)
120120
}
121121
122+
/**
123+
* 子任务进行中:开启 think 流时后端先落一条 `status: 'running'` 的占位工具消息
124+
* (带 thinkId/taskId,kind 为 command 不进 LLM 上下文),完成后被真实结果按
125+
* tool_call_id 覆盖 —— 故这里只看 toolResultMap 里的最终态。
126+
*/
127+
function isToolRunning(toolCallId: string): boolean {
128+
return findToolResult(toolCallId)?.message.status === 'running'
129+
}
130+
131+
/** 运行中的 thinkId 集合,用于在子任务结束时通知已打开的 Drawer 停止轮询。 */
132+
const runningThinkIds = computed(() => {
133+
const ids = new Set<string>()
134+
for (const msg of toolResultMap.value.values()) {
135+
if (msg.message.status === 'running' && msg.thinkId) ids.add(msg.thinkId)
136+
}
137+
return ids
138+
})
139+
140+
watch(runningThinkIds, (now, prev) => {
141+
if (!prev) return
142+
for (const id of prev) {
143+
if (!now.has(id)) thinkDrawerRef.value?.setLive(id, false)
144+
}
145+
})
146+
122147
/** True when the row should be skipped (tool results are rendered nested inside their AI parent). */
123148
function isEmbeddedTool(msg: StoredMessage): boolean {
124149
return msg.message.role === MessageRole.Tool && !!msg.message.tool_call_id
@@ -202,22 +227,32 @@ function contentCharLen(content?: DisplayContent): number {
202227
<span class="tool-call-name">{{ tc.name }}</span>
203228
<span class="tool-call-summary">
204229
<span v-if="inlineArgs(tc)" class="tool-call-inline-args" :title="inlineArgs(tc)">{{ inlineArgs(tc) }}</span>
205-
<span v-if="toolResultPreviewMap.get(tc.id)" class="tool-call-result-preview" :title="toolResultPreviewMap.get(tc.id)">↳ {{ toolResultPreviewMap.get(tc.id) }}</span>
230+
<!-- 子任务进行中:不必先展开 tool_call,直接从这里进思考过程 -->
231+
<span
232+
v-if="isToolRunning(tc.id) && findToolResult(tc.id)?.thinkId && thinksUrlPrefix"
233+
class="think-toggle think-toggle-running"
234+
@click.stop="openThink(findToolResult(tc.id)!.thinkId!, findToolResult(tc.id)!.taskId, { live: true })"
235+
>
236+
<span class="think-live-dot" /><span>{{ L.thinking }}</span>
237+
</span>
238+
<span v-else-if="toolResultPreviewMap.get(tc.id)" class="tool-call-result-preview" :title="toolResultPreviewMap.get(tc.id)">↳ {{ toolResultPreviewMap.get(tc.id) }}</span>
206239
</span>
207240
</button>
208241
<div class="tool-call-detail" :class="{ show: isToolCallExpanded(tc.id) }">
209242
<div class="tool-call-args">{{ JSON.stringify(tc.args, null, 2) }}</div>
210243
<template v-if="findToolResult(tc.id)">
211244
<div class="tool-call-result">
212245
<div class="tool-call-result-top">
213-
<div class="tool-call-result-label">{{ L.toolResult }}</div>
214-
<span class="msg-char-len" :title="`${contentCharLen(findToolResult(tc.id)!.message.content)} chars`">{{ contentCharLen(findToolResult(tc.id)!.message.content) }} chars</span>
246+
<div class="tool-call-result-label">{{ isToolRunning(tc.id) ? L.thinking : L.toolResult }}</div>
247+
<span v-if="!isToolRunning(tc.id)" class="msg-char-len" :title="`${contentCharLen(findToolResult(tc.id)!.message.content)} chars`">{{ contentCharLen(findToolResult(tc.id)!.message.content) }} chars</span>
215248
<div v-if="findToolResult(tc.id)?.thinkId && thinksUrlPrefix"
216-
class="think-toggle" @click="openThink(findToolResult(tc.id)!.thinkId!, findToolResult(tc.id)!.taskId)">
217-
<span>▸</span><span>{{ L.think }}</span>
249+
class="think-toggle" :class="{ 'think-toggle-running': isToolRunning(tc.id) }"
250+
@click="openThink(findToolResult(tc.id)!.thinkId!, findToolResult(tc.id)!.taskId, { live: isToolRunning(tc.id) })">
251+
<span v-if="isToolRunning(tc.id)" class="think-live-dot" /><span v-else>▸</span><span>{{ L.think }}</span>
218252
</div>
219253
</div>
220-
<ContentParts :content="findToolResult(tc.id)!.message.content"
254+
<!-- 进行中的占位没有 content,不渲染结果体 -->
255+
<ContentParts v-if="!isToolRunning(tc.id)" :content="findToolResult(tc.id)!.message.content"
221256
text-class="md-content tool-result-content"
222257
@open-image="openLightbox" />
223258
</div>
@@ -560,6 +595,20 @@ function contentCharLen(content?: DisplayContent): number {
560595
.think-toggle:hover {
561596
background: rgba(124, 58, 237, 0.18);
562597
}
598+
.think-toggle-running {
599+
font-weight: 500;
600+
}
601+
.think-live-dot {
602+
width: 6px;
603+
height: 6px;
604+
border-radius: 50%;
605+
background: currentColor;
606+
animation: think-live-pulse 1.2s ease-in-out infinite;
607+
}
608+
@keyframes think-live-pulse {
609+
0%, 100% { opacity: 0.3; }
610+
50% { opacity: 1; }
611+
}
563612
.think-toggle-human {
564613
background: rgba(255, 255, 255, 0.15);
565614
border-color: rgba(255, 255, 255, 0.3);

‎packages/chat-ui/src/components/ThinkDrawer.vue‎

Lines changed: 128 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script setup lang="ts">
2-
import { ref, computed, nextTick } from 'vue'
2+
import { ref, computed, nextTick, onUnmounted } from 'vue'
33
import type { StoredMessage, ChatLabels } from '../types'
44
import { resolveLabels } from '../labels'
55
import MessageList from './MessageList.vue'
@@ -25,20 +25,93 @@ interface ThinkLayer {
2525
taskMessages: StoredMessage[]
2626
taskLoading: boolean
2727
taskLoaded: boolean
28+
/** 子任务仍在执行:定时重拉 `/thinks/:id`,让思考过程实时增长 */
29+
live: boolean
30+
timer: ReturnType<typeof setInterval> | null
31+
/** 已轮询次数,达上限后自停,防止子任务异常未收尾时无限拉取 */
32+
polls: number
2833
}
2934
35+
/** 轮询间隔与上限(2.5s × 240 ≈ 10 分钟) */
36+
const POLL_INTERVAL_MS = 2500
37+
const POLL_MAX = 240
38+
3039
const visible = ref(false)
3140
const thinkStack = ref<ThinkLayer[]>([])
32-
const drawerEl = ref<HTMLElement | null>(null)
41+
const bodyEl = ref<HTMLElement | null>(null)
3342
3443
function doFetch(url: string): Promise<any> {
3544
if (props.fetchFn) return props.fetchFn(url)
3645
return fetch(url).then(r => r.json())
3746
}
3847
39-
async function open(thinkId: string, taskId?: string) {
48+
/** 距底部 40px 内视为“贴底”,此时新内容才自动滚动,避免打断向上翻阅 */
49+
function isAtBottom(): boolean {
50+
const el = bodyEl.value
51+
if (!el) return true
52+
return el.scrollHeight - el.scrollTop - el.clientHeight < 40
53+
}
54+
55+
async function scrollToBottom() {
56+
await nextTick()
57+
const el = bodyEl.value
58+
if (el) el.scrollTop = el.scrollHeight
59+
}
60+
61+
/** 拉取一层的 think 消息。`silent` 用于轮询:不打 loading 态,避免列表闪烁。 */
62+
async function loadThink(layer: ThinkLayer, silent = false) {
63+
if (!silent) layer.loading = true
64+
const stick = silent ? isAtBottom() : true
65+
try {
66+
const res = await doFetch(`${props.thinksUrlPrefix}/${encodeURIComponent(layer.id)}`)
67+
const payload = res.data
68+
layer.messages = Array.isArray(payload) ? payload : (payload?.messages || [])
69+
} catch {
70+
if (!silent) layer.messages = []
71+
} finally {
72+
layer.loading = false
73+
}
74+
if (stick) await scrollToBottom()
75+
}
76+
77+
function stopPolling(layer: ThinkLayer) {
78+
if (layer.timer) {
79+
clearInterval(layer.timer)
80+
layer.timer = null
81+
}
82+
layer.live = false
83+
}
84+
85+
function startPolling(layer: ThinkLayer) {
86+
if (layer.timer) return
87+
layer.live = true
88+
layer.polls = 0
89+
layer.timer = setInterval(() => {
90+
if (layer.polls >= POLL_MAX) { stopPolling(layer); return }
91+
layer.polls++
92+
// task 视图不参与轮询(子任务历史与 think 同源,切回时按需加载)
93+
if (layer.view === 'think') void loadThink(layer, true)
94+
}, POLL_INTERVAL_MS)
95+
}
96+
97+
/** 供外部(MessageList)在子任务结束/开始时切换轮询 */
98+
function setLive(thinkId: string, live: boolean) {
99+
const layer = thinkStack.value.find(s => s.id === thinkId)
100+
if (!layer) return
101+
if (live) startPolling(layer)
102+
else {
103+
stopPolling(layer)
104+
void loadThink(layer, true) // 停轮询前补最后一拉,确保收尾内容不丢
105+
}
106+
}
107+
108+
async function open(thinkId: string, taskId?: string, opts?: { live?: boolean }) {
40109
const existing = thinkStack.value.find(s => s.id === thinkId)
41-
if (existing) return
110+
if (existing) {
111+
// 该层已在栈中:仅在需要时补启轮询(例如结果未到、用户重新点入)
112+
if (opts?.live) startPolling(existing)
113+
return
114+
}
42115
43116
thinkStack.value.push({
44117
id: thinkId,
@@ -49,23 +122,16 @@ async function open(thinkId: string, taskId?: string) {
49122
taskMessages: [],
50123
taskLoading: false,
51124
taskLoaded: false,
125+
live: false,
126+
timer: null,
127+
polls: 0,
52128
})
53129
visible.value = true
54130
131+
// 必须从 ref 中取回响应式代理再改(直接改字面量对象不会触发更新)
55132
const layer = thinkStack.value[thinkStack.value.length - 1]
56-
try {
57-
const res = await doFetch(`${props.thinksUrlPrefix}/${encodeURIComponent(thinkId)}`)
58-
const payload = res.data
59-
layer.messages = Array.isArray(payload) ? payload : (payload?.messages || [])
60-
} catch {
61-
layer.messages = []
62-
} finally {
63-
layer.loading = false
64-
}
65-
await nextTick()
66-
if (drawerEl.value) {
67-
drawerEl.value.scrollTop = drawerEl.value.scrollHeight
68-
}
133+
await loadThink(layer)
134+
if (opts?.live) startPolling(layer)
69135
}
70136
71137
async function loadTask(layer: ThinkLayer) {
@@ -90,15 +156,19 @@ async function setView(layer: ThinkLayer, view: 'think' | 'task') {
90156
}
91157
92158
function popLayer() {
93-
thinkStack.value.pop()
159+
const layer = thinkStack.value.pop()
160+
if (layer) stopPolling(layer)
94161
if (thinkStack.value.length === 0) visible.value = false
95162
}
96163
97164
function close() {
98165
visible.value = false
166+
thinkStack.value.forEach(stopPolling)
99167
thinkStack.value = []
100168
}
101169
170+
onUnmounted(() => thinkStack.value.forEach(stopPolling))
171+
102172
const currentLayer = computed(() => thinkStack.value[thinkStack.value.length - 1])
103173
const currentMessages = computed(() => {
104174
const l = currentLayer.value
@@ -115,20 +185,35 @@ const showTabs = computed(() => {
115185
return !!(l && l.taskId && props.tasksUrlPrefix)
116186
})
117187
118-
defineExpose({ open })
188+
function refreshCurrent() {
189+
const l = currentLayer.value
190+
if (!l) return
191+
if (l.view === 'task') {
192+
l.taskLoaded = false
193+
void loadTask(l)
194+
} else {
195+
void loadThink(l, true)
196+
}
197+
}
198+
199+
defineExpose({ open, setLive })
119200
</script>
120201

121202
<template>
122203
<Teleport to="body">
123204
<Transition name="think-drawer">
124205
<div v-if="visible" class="think-drawer-backdrop" @click="close">
125-
<div class="think-drawer" ref="drawerEl" @click.stop>
206+
<div class="think-drawer" @click.stop>
126207
<div class="think-drawer-header">
127208
<button v-if="thinkStack.length > 1" class="think-drawer-back" @click="popLayer">←</button>
128209
<span class="think-drawer-title">
129210
{{ L.think }}
130211
<span v-if="thinkStack.length > 1" class="think-drawer-depth">({{ thinkStack.length }} layers)</span>
212+
<span v-if="currentLayer?.live" class="think-drawer-live">
213+
<span class="think-live-dot" />{{ L.thinking }}
214+
</span>
131215
</span>
216+
<button class="think-drawer-refresh" :title="L.refresh" @click="refreshCurrent">⟳</button>
132217
<button class="think-drawer-close" @click="close">×</button>
133218
</div>
134219

@@ -160,7 +245,7 @@ defineExpose({ open })
160245
</span>
161246
</div>
162247

163-
<div class="think-drawer-body">
248+
<div class="think-drawer-body" ref="bodyEl">
164249
<template v-if="currentLayer">
165250
<div v-if="currentLoading" class="think-drawer-loading">
166251
{{ L.loading }}
@@ -219,7 +304,28 @@ defineExpose({ open })
219304
color: var(--chatui-fg-secondary);
220305
margin-left: 4px;
221306
}
307+
.think-drawer-live {
308+
display: inline-flex;
309+
align-items: center;
310+
gap: 4px;
311+
margin-left: 8px;
312+
font-weight: 400;
313+
font-size: 12px;
314+
color: var(--chatui-fg-secondary);
315+
}
316+
.think-live-dot {
317+
width: 6px;
318+
height: 6px;
319+
border-radius: 50%;
320+
background: var(--chatui-accent, #3b82f6);
321+
animation: think-live-pulse 1.2s ease-in-out infinite;
322+
}
323+
@keyframes think-live-pulse {
324+
0%, 100% { opacity: 0.3; }
325+
50% { opacity: 1; }
326+
}
222327
.think-drawer-back,
328+
.think-drawer-refresh,
223329
.think-drawer-close {
224330
background: none;
225331
border: 1px solid var(--chatui-border);
@@ -235,6 +341,7 @@ defineExpose({ open })
235341
flex-shrink: 0;
236342
}
237343
.think-drawer-back:hover,
344+
.think-drawer-refresh:hover,
238345
.think-drawer-close:hover {
239346
background: var(--chatui-bg-hover);
240347
color: var(--chatui-fg-primary);

‎packages/chat-ui/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ export interface ChatMessage {
4949
tool_calls?: ToolCall[]
5050
tool_call_id?: string
5151
name?: string
52+
/** 工具消息的执行状态:`success` / `error` / `running`。`running` 是 think 进行中的占位,完成后被真结果按 `tool_call_id` 覆盖。 */
53+
status?: string
5254
}
5355

5456
/**

‎packages/sbot.commons/src/api.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ export interface ChatMessage {
7777
tool_calls?: ToolCall[]
7878
tool_call_id?: string
7979
name?: string
80+
/** 工具消息的执行状态:success / error / running(running 为 think 进行中的占位,完成后被真结果按 tool_call_id 覆盖) */
81+
status?: string
8082
}
8183

8284
export interface StoredMessage {

‎packages/scorpio.ai/src/Agents/AgentServiceBase.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ export enum ToolApproval {
3434
}
3535

3636

37+
/**
38+
* 工具声明「本次调用开启了 think 流」的回调。
39+
*
40+
* 框架在执行工具前生成 `thinkId` 并与本回调一起注入 `RunnableConfig.configurable`。
41+
* 会把子流程消息写入 `thinks[thinkId]` 的工具(如 `_dispatch_task`)在流程真正启动时调一次,
42+
* 框架据此把 `thinkId` 与本次 tool_call 的关联下发出去,使思考过程在执行中即可查看。
43+
* 不调用的工具,预留的 `thinkId` 直接丢弃。幂等:重复调用只生效一次。
44+
*
45+
* @param taskId 该 think 对应的子会话 id(若有),供前端在 think / task 视图间切换。
46+
*/
47+
export type OnCreateThinkFn = (taskId?: string) => Promise<void>;
48+
3749
/**
3850
* Agent 回调接口 - 统一管理消息、流式、工具确认和图片转换回调
3951
*/

0 commit comments

Comments
 (0)