fix(chat): preserve steering continuity and composer focus

main
wizardchen 2026-09-09 20:05:47 +08:00 committed by lyingbug
parent 3ab6d3940d
commit 5cf093706e
45 changed files with 1224 additions and 353 deletions

View File

@ -0,0 +1,44 @@
# Steering an active conversation
While an agent is running, you can queue a follow-up or guide the current task.
| Action | Behavior |
| --- | --- |
| Enter or the send button | Queue the draft to send after the current answer finishes. |
| Command+Enter or Alt/Option+Enter | Send the draft as guidance for the active task. With an empty draft, promote the first eligible queued message. |
| Up arrow on a queued message | Send that message as guidance immediately. |
| Remove on a queued message | Remove the queued message. |
| Stop button | Stop generation. This replaces the send button while the agent is running and the draft is empty. |
| Shift+Enter or Ctrl+Enter | Insert a newline. |
Outside an active agent run, Enter sends a normal message. Input methods can
confirm composed text without accidentally sending it. Modes without steering
support keep the stop action during generation.
Queued messages appear in a compact strip immediately above the input's focus
border. Guidance moves into the conversation immediately; delivery failures can
be retried or removed. Earlier work remains visible, and guidance does not mark
the ongoing task as complete. Sending and entering a newly created session keep
the composer ready for further input.
Guidance applies to the task in progress. The agent retains unfinished goals and
constraints unless the user explicitly changes or cancels them. A short tagged
reminder accompanies each guidance message; existing context and tool results
are reused without an additional model call to classify the message. Message IDs
and execution boundaries preserve ordering across live updates and history reloads.
The conversation outline includes both user and assistant messages and highlights
all messages intersecting the visible conversation area.
## Component previews
These previews use sample messages and isolated production components; they do
not contain real conversation data or invoke a model.
Running with an empty draft:
![Queued guidance, visible outline entries, and Stop](images/chat-steer-preview.png)
Running with a draft:
![The same primary control becomes Send](images/chat-steer-send-preview.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -9,16 +9,17 @@ export type SteerQueueItem = {
mentioned_items?: unknown[]
promoting?: boolean
awaitingIdleSend?: boolean
// True while POST /steer is in flight. The overlay uses a client-side
// id until the server replies with the durable one; promote/remove are
// disabled in that window so they cannot hit /steer/{client_id}.
// True while POST /steer is in flight. The stable client UUID is also the
// durable server ID; disable actions until its queue entry exists.
pending?: boolean
failed?: boolean
expected_assistant_message_id?: string
client_id?: string
}
/**
* Append a message to a running agent turn.
* Returns { success, status: 'queued' | 'new_run', steer_id?, delivery?, assistant_message_id? }.
* Returns { success, status: 'queued' | 'already_injected' | 'new_run', steer_id?, delivery?, assistant_message_id? }.
* - delivery 'after' (default): waits until the current run exits, then starts a follow-up turn.
* - delivery 'inject': the running engine injects it at the next round boundary.
* - 'new_run': no run is live; the caller should fall back to a normal send.
@ -30,9 +31,13 @@ export async function steerSession(
query: string,
mentionedItems: any[] = [],
delivery: SteerDelivery = 'after',
expectedAssistantMessageId?: string,
steerId?: string,
) {
return post(`/api/v1/sessions/${session_id}/steer`, {
query,
expected_assistant_message_id: expectedAssistantMessageId,
steer_id: steerId,
mentioned_items: mentionedItems,
channel: 'web',
delivery,

View File

@ -1,10 +1,41 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
import { computed, reactive, ref } from 'vue'
import { chatSubmitShortcut } from '../utils/chatSubmitShortcut.ts'
const inputField = readFileSync(new URL('./Input-field.vue', import.meta.url), 'utf8')
const settingsStore = readFileSync(new URL('../stores/settings.ts', import.meta.url), 'utf8')
test('composer shortcuts queue Enter, inject drafts, and promote the first queued message when empty', () => {
const code = inputField.slice(inputField.indexOf('const steerShortcutLabel ='), inputField.indexOf('const onPaste ='))
const sends = [], promotes = []
const query = ref('draft')
const composing = ref(false)
const props = reactive({ isReplying: true, canSteer: true, queuedSteers: [
{ steer_id: 'pending', delivery: 'after', pending: true },
{ steer_id: 'first', delivery: 'after' }, { steer_id: 'second', delivery: 'after' },
] })
const { onKeydown } = vm.runInNewContext(ts.transpile(`${code}\n({ onKeydown })`), {
navigator: { platform: 'MacIntel' }, computed, props, query, chatSubmitShortcut,
isComposing: composing, showMention: ref(false),
createSession: (...args) => sends.push(args), emit: (...args) => promotes.push(args),
})
const enter = { key: 'Enter', keyCode: 13, preventDefault() {}, shiftKey: false, ctrlKey: false, altKey: false }
onKeydown(query.value, { e: enter })
onKeydown(query.value, { e: { ...enter, altKey: true } })
onKeydown(query.value, { e: { ...enter, metaKey: true } })
assert.deepEqual(sends, [['draft', 'after'], ['draft', 'inject'], ['draft', 'inject']])
query.value = ''
onKeydown('', { e: { ...enter, metaKey: true } })
assert.deepEqual(promotes, [['promote-steer', 'first']])
composing.value = true
onKeydown('', { e: { ...enter, altKey: true } })
assert.equal(promotes.length, 1, 'IME confirmation must not promote a message')
})
test('selecting an agent leaves web search off until the user enables it', () => {
const selectAgentStart = settingsStore.indexOf('selectAgent(agentId: string')
const getSelectedAgentStart = settingsStore.indexOf('getSelectedAgentId()', selectAgentStart)
@ -36,17 +67,18 @@ test('shared-agent web search button waits for source readiness metadata', () =>
assert.match(showWebSearchButton, /selectedSharedAgent\.value\?\.web_search_ready/)
})
test('replying keeps stop visible; typed text also shows send', () => {
test('one composer action switches between stop and send', () => {
const controlsStart = inputField.indexOf('class="control-right"')
const controls = inputField.slice(controlsStart, controlsStart + 1200)
const controls = inputField.slice(controlsStart, controlsStart + 2200)
assert.notEqual(controlsStart, -1)
assert.doesNotMatch(inputField, /steer-delivery-toggle/)
assert.doesNotMatch(inputField, /setSteerDelivery/)
assert.match(inputField, /emit\('steer-msg', val\.trim\(\), steerMentions, 'after'\)/)
assert.match(controls, /v-if="isReplying"/)
assert.match(inputField, /emit\('steer-msg', val\.trim\(\), steerMentions, delivery\)/)
assert.match(controls, /v-if="isReplying && \(!canSteer \|\| !query\.trim\(\)\)"/)
assert.match(controls, /handleStop/)
assert.match(controls, /v-if="!isReplying \|\| query\.trim\(\)"[\s\S]*createSession\(query\)[\s\S]*send-btn/)
assert.doesNotMatch(controls, /v-if="isReplying && \(!canSteer \|\| !query\.trim\(\)\)"/)
assert.match(controls, /v-else[\s\S]*createSession\(query\)[\s\S]*send-btn/)
assert.match(controls, /<t-icon name="arrow-up"/)
assert.doesNotMatch(controls, /steer-inject-btn|<t-icon[^>]*'time'/)
})
// Only agent turns have a round boundary to take a mid-run message at, and a
@ -74,7 +106,7 @@ test('queued follow-ups sit in one block with send-now and remove', () => {
assert.match(inputField, /queuedSteers/)
assert.match(inputField, /emit\('promote-steer', item\.steer_id\)/)
assert.match(inputField, /emit\('remove-steer', item\.steer_id\)/)
assert.match(inputField, /class="steer-queue-remove"/)
assert.match(inputField, /class="steer-queue-action steer-queue-remove"/)
assert.match(inputField, /\$t\('input\.steerQueueSendNow'\)/)
assert.match(inputField, /:disabled="item\.promoting \|\| item\.pending"/)
assert.match(inputField, /\.steer-queue-item \+ \.steer-queue-item/)

View File

@ -0,0 +1,81 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
const source = readFileSync(new URL('./Input-field.vue', import.meta.url), 'utf8')
const focusCode = source.slice(source.indexOf('const focusInput ='), source.indexOf('const onInput ='))
const sendCode = source.slice(source.indexOf('const createSession ='), source.indexOf('const updateAgentModeDropdownPosition ='))
for (const mode of ['normal', 'embedded', 'after', 'inject']) {
test(`${mode} send clears the draft and restores focus after the DOM update`, async () => {
const effects = [], ticks = []
const textarea = {
isConnected: true,
focus: options => effects.push(['focus', options.preventScroll]),
blur: () => { throw new Error('sending must not blur the textarea') },
}
const context = {
props: { isReplying: ['after', 'inject'].includes(mode), canSteer: true, embeddedMode: mode === 'embedded' },
uploadedAttachments: { value: [] }, uploadedImages: { value: [] },
allSelectedItems: { value: [] }, selectedModelId: { value: 'model' },
selectedAgent: { value: { config: {} } },
settingsStore: {}, chatResources: { isFresh: () => true },
collectAgentNotReadyReasons: () => ({ keys: [], labels: [] }),
attachmentUploadRef: { value: null },
emit: name => effects.push([name]),
clearvalue: () => effects.push(['clear']),
getTextareaEl: () => textarea,
nextTick: () => new Promise(resolve => ticks.push(resolve)),
}
const send = vm.runInNewContext(ts.transpile(`${focusCode}\n${sendCode}\ncreateSession`), context)
await send('hello', mode === 'inject' ? 'inject' : 'after')
assert.deepEqual(effects, [[context.props.isReplying ? 'steer-msg' : 'send-msg'], ['clear']])
for (const resolve of ticks) resolve()
await new Promise(setImmediate)
assert.deepEqual(effects.at(-1), ['focus', true])
})
}
test('a queued focus does not focus a textarea removed during navigation', async () => {
let resolveTick, connected = true, focused = false
const focus = vm.runInNewContext(`${focusCode}\nfocusInput`, {
nextTick: () => new Promise(resolve => { resolveTick = resolve }),
getTextareaEl: () => ({ isConnected: connected, focus: () => { focused = true } }),
})
const pending = focus()
connected = false
resolveTick()
await pending
assert.equal(focused, false)
})
test('teardown blurs the active textarea before it is detached', () => {
const code = source.slice(source.indexOf('onBeforeUnmount(() =>'), source.indexOf('onUnmounted(() =>'))
let teardown, blurred = false
const textarea = { isConnected: true, blur: () => { blurred = true } }
vm.runInNewContext(code, {
onBeforeUnmount: fn => { teardown = fn }, getTextareaEl: () => textarea,
document: { activeElement: textarea },
})
teardown()
assert.equal(blurred, true)
})
test('new-session focus survives consumption of the first query and runs on child mount', () => {
const page = readFileSync(new URL('../views/chat/index.vue', import.meta.url), 'utf8')
const snapshot = page.match(/const focusComposerOnMount = [^;]+;/)[0]
const firstQuery = { value: 'initial question' }
const autoFocus = vm.runInNewContext(`${snapshot}\nfirstQuery.value = ''; focusComposerOnMount`, { firstQuery })
assert.equal(autoFocus, true)
assert.match(page, /:auto-focus="focusComposerOnMount"/)
const mountStart = source.slice(source.indexOf('onMounted(() => {'), source.indexOf('// Embed 渠道'))
let mounted, focused = false
vm.runInNewContext(`${mountStart}\n});`, {
props: { autoFocus }, onMounted: fn => { mounted = fn }, focusInput: () => { focused = true },
})
assert.equal(focused, false)
mounted()
assert.equal(focused, true)
})

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch, nextTick, h, type PropType } from "vue";
import { ref, onMounted, onBeforeUnmount, onUnmounted, computed, watch, nextTick, h, type PropType } from "vue";
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { onBeforeRouteUpdate } from 'vue-router';
@ -11,6 +11,7 @@ import { listKnowledgeBases, searchKnowledge, batchQueryKnowledge, listKnowledge
import { listMCPServices, type MCPService } from '@/api/mcp-service';
import { stopSession } from '@/api/chat';
import type { SteerQueueItem } from '@/api/chat/steer';
import { chatSubmitShortcut } from '@/utils/chatSubmitShortcut';
import { useOrganizationStore } from '@/stores/organization';
import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue';
import MentionSelector from './MentionSelector.vue';
@ -502,6 +503,10 @@ const sharedAgentOrgName = computed(() => {
});
const props = defineProps({
autoFocus: {
type: Boolean,
default: false
},
isReplying: {
type: Boolean,
required: false
@ -1507,6 +1512,12 @@ const getTextareaEl = () => {
return el.querySelector('textarea');
};
const focusInput = async () => {
await nextTick();
const textarea = getTextareaEl();
if (textarea?.isConnected) textarea.focus({ preventScroll: true });
};
const onInput = (val: string | InputEvent) => {
// 如果正在输入法组合中,不处理搜索逻辑,等待 compositionend
if (isComposing.value) return;
@ -1794,6 +1805,7 @@ let resizeHandler: (() => void) | null = null;
let scrollHandler: (() => void) | null = null;
onMounted(() => {
if (props.autoFocus) void focusInput();
// Embed 渠道由宿主注入 agent/KB,勿拉取需 JWT 的平台资源
if (props.embeddedMode) return;
@ -1861,6 +1873,12 @@ onMounted(() => {
window.addEventListener('scroll', scrollHandler, { passive: true, capture: true });
});
onBeforeUnmount(() => {
// Let TDesign handle blur while its textarea is still attached to the DOM.
const textarea = getTextareaEl();
if (textarea?.isConnected && document.activeElement === textarea) textarea.blur();
});
onUnmounted(() => {
window.removeEventListener(CHAT_FILE_DROP_EVENT, handleChatFileDrop as EventListener);
document.removeEventListener('click', closeAgentModeSelector);
@ -1906,14 +1924,15 @@ const emit = defineEmits<{
(e: 'stop-generation'): void;
(e: 'stop-confirmed'): void;
(e: 'stop-failed'): void;
// Mid-run send queues until the current run exits (delivery=after).
// Running input defaults to after; the explicit shortcut/action steers.
// Empty input while replying shows Stop; typed text also shows Send.
(e: 'steer-msg', query: string, mentionedItems: MentionRequestItem[], delivery: 'inject' | 'after'): void;
(e: 'promote-steer', steerId: string): void;
(e: 'remove-steer', steerId: string): void;
(e: 'retry-steer', steerId: string): void;
}>();
const createSession = async (val: string) => {
const createSession = async (val: string, delivery: 'inject' | 'after' = 'after') => {
if (!val.trim()) {
MessagePlugin.info(t('input.messages.enterContent'));
return;
@ -1926,7 +1945,7 @@ const createSession = async (val: string) => {
MessagePlugin.info(t('input.messages.replying'));
return;
}
// Mid-run steering: queue until the current run exits (delivery=after).
// Queue the selected delivery mode until its next safe boundary.
// Attachments are intentionally not allowed on the steer path — the
// running turn already resolved its own scope.
if (uploadedAttachments.value.some(item => item.status === 'uploading')) {
@ -1947,8 +1966,9 @@ const createSession = async (val: string) => {
service_id: item.serviceId,
skill_name: item.skillName,
}));
emit('steer-msg', val.trim(), steerMentions, 'after');
emit('steer-msg', val.trim(), steerMentions, delivery);
clearvalue();
void focusInput();
return;
}
// Only block while the file is still uploading (no document ID yet). Once
@ -1969,10 +1989,9 @@ const createSession = async (val: string) => {
// Embed 渠道由后端绑定 agent/KB,勿走平台侧 agent 列表与就绪校验
if (props.embeddedMode) {
const textarea = getTextareaEl();
if (textarea) textarea.blur();
emit('send-msg', val, selectedModelId.value || '', [], [], []);
clearvalue();
void focusInput();
return;
}
@ -2033,11 +2052,6 @@ const createSession = async (val: string) => {
const imageFiles = uploadedImages.value.map(img => img.file);
const attachmentFiles = uploadedAttachments.value;
// Blur the textarea BEFORE emitting, so that when the parent navigates away
// and Vue unmounts this component, TDesign's blur handler won't fire on a
// detached DOM element (which causes getComputedStyle to throw).
const textarea = getTextareaEl();
if (textarea) textarea.blur();
emit('send-msg', val, selectedModelId.value, mentionedItems, imageFiles, attachmentFiles);
// Clean up image previews
@ -2049,6 +2063,7 @@ const createSession = async (val: string) => {
uploadedAttachments.value = [];
clearvalue();
void focusInput();
}
const updateAgentModeDropdownPosition = () => {
@ -2272,7 +2287,17 @@ const clearPendingUploads = () => {
uploadedAttachments.value = [];
}
const onKeydown = (val: string, event: { e: { preventDefault(): unknown; keyCode: number; shiftKey: any; ctrlKey: any; }; }) => {
const steerShortcutLabel = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘ Enter' : 'Alt+Enter';
const firstQueuedSteer = computed(() => props.queuedSteers.find(item =>
item.delivery === 'after' && !item.pending && !item.promoting && !item.failed));
const injectCurrentInput = () => {
if (!props.isReplying || !props.canSteer) return;
if (query.value.trim()) void createSession(query.value, 'inject');
else if (firstQueuedSteer.value) emit('promote-steer', firstQueuedSteer.value.steer_id);
};
const onKeydown = (val: string, event: { e: KeyboardEvent }) => {
if (isComposing.value || event.e.isComposing || event.e.keyCode === 229) return;
if (showMention.value) {
if (event.e.keyCode === 38) { // Up
event.e.preventDefault();
@ -2312,12 +2337,11 @@ const onKeydown = (val: string, event: { e: { preventDefault(): unknown; keyCode
}
}
if ((event.e.keyCode == 13 && event.e.shiftKey) || (event.e.keyCode == 13 && event.e.ctrlKey)) {
return;
}
if (event.e.keyCode == 13) {
const delivery = chatSubmitShortcut(event.e, props.isReplying && props.canSteer);
if (delivery) {
event.e.preventDefault();
createSession(val)
if (delivery === 'inject' && props.isReplying && props.canSteer) injectCurrentInput();
else void createSession(val, delivery);
}
}
@ -2557,6 +2581,7 @@ onBeforeRouteUpdate((to, from, next) => {
})
defineExpose({
focusInput,
triggerSend(text: string) {
if (!text.trim()) return;
query.value = text;
@ -2570,29 +2595,31 @@ defineExpose({
<!-- Hidden file input for image upload -->
<input ref="imageInputRef" type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple
style="display:none" @change="handleImageSelect" />
<!-- 队列紧贴输入框上方,不参与输入区的焦点高亮 -->
<div v-if="queuedSteers.length" class="steer-queue" role="list" :aria-label="$t('input.steerQueueWaiting')">
<div v-for="item in queuedSteers" :key="item.steer_id" class="steer-queue-item" role="listitem">
<span class="steer-queue-text">{{ item.content }}</span>
<t-tooltip :content="$t('input.steerAfter')">
<t-icon name="time" class="steer-queue-icon" :aria-label="$t('input.steerAfter')" />
</t-tooltip>
<span class="steer-queue-text" :title="item.content">{{ item.content }}</span>
<div class="steer-queue-actions">
<button
v-if="item.delivery !== 'inject'"
type="button"
class="steer-queue-send-now"
:disabled="item.promoting || item.pending"
@click="emit('promote-steer', item.steer_id)"
>{{ $t('input.steerQueueSendNow') }}</button>
<span v-else class="steer-queue-hint">{{ $t('input.steerQueueInjecting') }}</span>
<button
type="button"
class="steer-queue-remove"
:aria-label="$t('common.remove')"
:disabled="item.promoting || item.pending"
@click="emit('remove-steer', item.steer_id)"
>×</button>
<t-tooltip v-if="item.failed" :content="$t('input.steerRetry')">
<button type="button" class="steer-queue-action" :aria-label="$t('input.steerRetry')" @click="emit('retry-steer', item.steer_id)"><t-icon name="refresh" /></button>
</t-tooltip>
<t-icon v-else-if="item.pending" name="loading" class="steer-sending" :aria-label="$t('common.loading')" />
<t-tooltip v-else :content="`${$t('input.steerQueueSendNow')}${item.steer_id === firstQueuedSteer?.steer_id ? ` · ${steerShortcutLabel}` : ''}`">
<button type="button" class="steer-queue-action"
:aria-label="$t('input.steerQueueSendNow')" :disabled="item.promoting || item.pending"
@click="emit('promote-steer', item.steer_id)"><t-icon name="arrow-up" /></button>
</t-tooltip>
<t-tooltip :content="$t('common.remove')">
<button type="button" class="steer-queue-action steer-queue-remove"
:aria-label="$t('common.remove')" :disabled="item.promoting || item.pending"
@click="emit('remove-steer', item.steer_id)"><t-icon name="close" /></button>
</t-tooltip>
</div>
</div>
</div>
<!-- 富文本输入框容器 -->
<div class="rich-input-container" data-guide="chat-input">
<!-- 图片预览区域 -->
<div v-if="uploadedImages.length > 0" class="image-preview-bar">
@ -2635,7 +2662,7 @@ defineExpose({
@keydown="onKeydown" @input="onInput" @compositionstart="onCompositionStart" @compositionend="onCompositionEnd"
@paste="onPaste" />
<!-- 控制栏(放在 rich-input-container 内,相对输入框边框定位) -->
<!-- 控制栏按文档流排列,换行时自动撑开容器 -->
<div class="control-bar" :class="{ 'is-embedded': embeddedMode }">
<!-- 左侧控制按钮 -->
<div class="control-left" v-if="!embeddedMode">
@ -2815,19 +2842,18 @@ defineExpose({
<!-- 右侧控制:回复中且输入为空是停止,一旦输入新内容同一位置变成发送 -->
<div class="control-right">
<t-tooltip v-if="isReplying" :content="$t('input.stopGeneration')"
placement="top">
<div @click="handleStop" class="control-btn stop-btn">
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<rect x="5" y="5" width="6" height="6" rx="1" />
</svg>
</div>
<t-tooltip v-if="isReplying && (!canSteer || !query.trim())" :content="$t('input.stopGeneration')" placement="top">
<button type="button" @click="handleStop" class="control-btn stop-btn" :aria-label="$t('input.stopGeneration')">
<t-icon name="stop" />
</button>
</t-tooltip>
<t-tooltip v-else :content="`${isReplying && canSteer ? $t('input.steerAfter') : $t('input.send')} · Enter`">
<button type="button" @click="createSession(query)" class="control-btn send-btn" data-guide="chat-send"
:disabled="!query.trim()" :class="{ 'disabled': !query.trim() }"
:aria-label="isReplying && canSteer ? $t('input.steerAfter') : $t('input.send')">
<t-icon name="arrow-up" />
</button>
</t-tooltip>
<div v-if="!isReplying || query.trim()" @click="createSession(query)" class="control-btn send-btn" data-guide="chat-send"
:class="{ 'disabled': !query.length }">
<img src="../assets/img/sending-aircraft.svg" :alt="$t('input.send')" />
</div>
</div>
</div>
</div>
@ -2879,21 +2905,22 @@ const getImgSrc = (url: string) => {
}
.steer-queue {
width: 100%;
max-width: 960px;
margin-bottom: 8px;
background: var(--td-bg-color-container, #fff);
width: calc(100% - 24px);
max-width: 936px;
box-sizing: border-box;
max-height: 140px;
overflow-y: auto;
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
border: 1px solid var(--td-component-stroke, #dcdcdc);
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
overflow: hidden;
border-bottom: 0;
border-radius: 10px 10px 0 0;
}
.steer-queue-item {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px 12px;
align-items: center;
gap: 8px;
padding: 4px 12px;
}
.steer-queue-item + .steer-queue-item {
@ -2906,8 +2933,9 @@ const getImgSrc = (url: string) => {
font-size: 13px;
line-height: 1.5;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.steer-queue-actions {
@ -2915,60 +2943,35 @@ const getImgSrc = (url: string) => {
align-items: center;
flex-shrink: 0;
gap: 4px;
padding-top: 1px;
}
.steer-queue-send-now {
.steer-queue-icon {
flex-shrink: 0;
margin: 0;
padding: 0 4px;
border: 0;
background: transparent;
color: var(--td-brand-color, #07C05F);
font-size: 12px;
line-height: 22px;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
.steer-queue-hint {
flex-shrink: 0;
font-size: 12px;
line-height: 22px;
font-size: 14px;
color: var(--td-text-color-secondary);
}
.steer-queue-remove {
.steer-queue-action {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
margin: 0;
width: 26px;
height: 26px;
padding: 0;
border: 0;
border-radius: 50%;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-placeholder, #999);
color: var(--td-text-color-secondary);
font-size: 16px;
line-height: 1;
cursor: pointer;
&:hover:not(:disabled) {
background: var(--td-bg-color-secondarycontainer, #f3f3f3);
color: var(--td-text-color-primary);
}
&:disabled {
opacity: 0.4;
cursor: default;
}
&:hover:not(:disabled) { background: var(--td-bg-color-secondarycontainer); color: var(--td-text-color-primary); }
&:disabled { opacity: 0.4; cursor: default; }
}
.steer-sending { animation: steer-spin 1s linear infinite; }
@keyframes steer-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .steer-sending { animation: none; } }
/* 富文本输入框容器 */
.rich-input-container {
position: relative;
@ -3145,15 +3148,15 @@ const getImgSrc = (url: string) => {
:deep(.t-textarea__inner) {
width: 100%;
max-height: 200px !important;
min-height: 120px !important;
max-height: 152px !important;
min-height: 72px !important;
resize: none;
color: var(--td-text-color-primary, #000000e6);
font-size: 16px;
font-weight: 400;
line-height: 24px;
font-family: var(--app-font-family);
padding: 12px 16px 56px 16px;
padding: 12px 16px;
border-radius: 0 0 12px 12px;
border: none;
box-sizing: border-box;
@ -3182,18 +3185,14 @@ const getImgSrc = (url: string) => {
/* 控制栏 */
.control-bar {
position: absolute;
bottom: 12px;
left: 16px;
right: 16px;
position: relative;
margin: 0 16px 12px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
max-height: 56px;
z-index: 10;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, var(--td-bg-color-container, #fff) 40%, var(--td-bg-color-container, #fff) 100%);
pointer-events: auto;
padding-top: 8px;
@ -3212,6 +3211,8 @@ const getImgSrc = (url: string) => {
}
.control-btn {
border: 0;
font: inherit;
display: flex;
align-items: center;
justify-content: center;
@ -3558,61 +3559,23 @@ const getImgSrc = (url: string) => {
gap: 8px;
}
.stop-btn {
.stop-btn, .send-btn {
width: 28px;
height: 28px;
padding: 0;
background: rgba(16, 185, 129, 0.08);
color: var(--td-brand-color);
border: 1.5px solid rgba(16, 185, 129, 0.2);
position: relative;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
font-size: 16px;
line-height: 1;
&:hover {
background: rgba(16, 185, 129, 0.12);
border-color: var(--td-brand-color);
}
&:active {
background: rgba(16, 185, 129, 0.15);
}
svg {
display: none;
}
&::before {
content: '';
width: 12px;
height: 12px;
background: var(--td-brand-color);
border-radius: 50%;
display: block;
animation: stopBtnPulse 1.5s ease-in-out infinite;
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
}
@keyframes stopBtnPulse {
0%,
100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(0.75);
opacity: 0.6;
}
}
.send-btn {
width: 28px;
height: 28px;
padding: 0;
.stop-btn, .send-btn {
background-color: var(--td-brand-color);
color: #fff;
&:hover:not(.disabled) {
background-color: var(--td-brand-color-active);

View File

@ -76,9 +76,11 @@ test('does not paint the first question green on hover-open', () => {
assert.doesNotMatch(component, /question-minimap__row:hover,\s*\.question-minimap__row--active/)
})
test('highlights the matching tick for the peaked question', () => {
test('highlights visible messages without losing them when previewing another tick', () => {
assert.match(component, /peakId/)
assert.match(component, /tick\.id === peakId/)
assert.match(component, /highlightedIds\.has\(tick\.id\)/)
assert.match(component, /new Set\(visibleIds\.value\)/)
assert.match(composable, /visibleMessageIds\(measured, el\.scrollTop, el\.clientHeight\)/)
})
test('keeps the preview card at 13px instead of inheriting the chat 20px type', () => {

View File

@ -23,10 +23,10 @@
v-for="tick in ticks"
:key="tick.id"
class="question-minimap__tick"
:class="{ 'question-minimap__tick--active': tick.id === peakId }"
:class="{ 'question-minimap__tick--active': highlightedIds.has(tick.id) }"
:style="{
top: `${tick.yPx}px`,
transform: `translateY(-50%) scaleX(${tickDisplayScale(tick.yPx, mountainPointerY, tick.id === peakId)})`,
transform: `translateY(-50%) scaleX(${tickDisplayScale(tick.yPx, mountainPointerY, highlightedIds.has(tick.id))})`,
}"
/>
</button>
@ -65,7 +65,7 @@ import {
questionDisplayText,
tickDisplayScale,
type ChatMessageLike,
type UserQuestion,
type OutlineMessage,
} from '@/utils/chatQuestionMinimap'
const CLOSE_DELAY_MS = 150
@ -94,6 +94,7 @@ const {
questions,
ticks,
activeId,
visibleIds,
anchoredIds,
trackHeight,
} = useChatQuestionMinimap({
@ -114,6 +115,11 @@ const peakId = computed(() => {
const peakTurn = computed(() => (
questions.value.find((question) => question.id === peakId.value) ?? null
))
const highlightedIds = computed(() => {
const ids = new Set(visibleIds.value)
if ((hoveredId.value || keyboardIndex.value >= 0) && peakId.value) ids.add(peakId.value)
return ids
})
const peakYPx = computed(() => {
const tick = ticks.value.find((item) => item.id === peakId.value)
return tick?.yPx ?? 0
@ -125,11 +131,13 @@ const mountainPointerY = computed(() => {
let closeTimer: number | null = null
const questionText = (question: UserQuestion) => (
questionDisplayText(question.content, t('chat.questionMinimapAttachmentPlaceholder'))
const questionText = (question: OutlineMessage) => (
question.role === 'assistant'
? answerPreviewText(question.content) || t('chat.thinking')
: questionDisplayText(question.content, t('chat.questionMinimapAttachmentPlaceholder'))
)
const answerText = (question: UserQuestion) => (
const answerText = (question: OutlineMessage) => (
answerPreviewText(question.answerContent)
)

View File

@ -10,16 +10,17 @@ import {
} from 'vue'
import {
activeQuestionId,
collectUserQuestions,
collectOutlineMessages,
isChatOverflowing,
mapQuestionTicks,
offsetFromScrollContent,
questionMinimapTrackHeight,
shouldShowQuestionMinimap,
viewportBand,
visibleMessageIds,
type ChatMessageLike,
type QuestionTick,
type UserQuestion,
type OutlineMessage,
type ViewportBand,
} from '@/utils/chatQuestionMinimap'
@ -28,19 +29,21 @@ export function useChatQuestionMinimap(options: {
messages: ChatMessageLike[] | Ref<ChatMessageLike[]>
}): {
visible: ComputedRef<boolean>
questions: ComputedRef<UserQuestion[]>
questions: ComputedRef<OutlineMessage[]>
ticks: Ref<QuestionTick[]>
viewport: Ref<ViewportBand>
activeId: Ref<string | null>
visibleIds: Ref<Set<string>>
anchoredIds: Ref<Set<string>>
scrollbarGutterPx: Ref<number>
trackHeight: Ref<number>
} {
const questions = computed(() => collectUserQuestions(toValue(options.messages)))
const questions = computed(() => collectOutlineMessages(toValue(options.messages)))
const overflowing = ref(false)
const ticks = ref<QuestionTick[]>([])
const viewport = ref<ViewportBand>({ topPx: 0, heightPx: 0 })
const activeId = ref<string | null>(null)
const visibleIds = ref<Set<string>>(new Set())
const anchoredIds = ref<Set<string>>(new Set())
const scrollbarGutterPx = ref(0)
const trackHeight = ref(0)
@ -59,6 +62,7 @@ export function useChatQuestionMinimap(options: {
ticks.value = []
viewport.value = { topPx: 0, heightPx: 0 }
activeId.value = null
visibleIds.value = new Set()
anchoredIds.value = new Set()
scrollbarGutterPx.value = 0
trackHeight.value = 0
@ -90,14 +94,17 @@ export function useChatQuestionMinimap(options: {
const measured = questions.value.flatMap((question) => {
const anchor = anchorByMessageId.get(question.id)
if (!anchor) return []
const rect = anchor.getBoundingClientRect()
if (rect.height <= 0) return []
return [{
id: question.id,
offsetTop: offsetFromScrollContent(
anchor.getBoundingClientRect().top,
rect.top,
containerTop,
el.scrollTop,
),
offsetBottom: offsetFromScrollContent(rect.bottom, containerTop, el.scrollTop),
}]
})
@ -105,6 +112,7 @@ export function useChatQuestionMinimap(options: {
ticks.value = mapQuestionTicks(measured, trackHeight.value)
viewport.value = viewportBand(el.scrollTop, el.clientHeight, el.scrollHeight, trackHeight.value)
activeId.value = activeQuestionId(measured, el.scrollTop)
visibleIds.value = visibleMessageIds(measured, el.scrollTop, el.clientHeight)
anchoredIds.value = new Set(measured.map((item) => item.id))
}
@ -179,6 +187,7 @@ export function useChatQuestionMinimap(options: {
ticks,
viewport,
activeId,
visibleIds,
anchoredIds,
scrollbarGutterPx,
trackHeight,

View File

@ -1,9 +1,33 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
import { resetSteerTurnForReplay } from '../utils/steerStreamFork.ts'
const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')
test('replaying agent_query binds the first segment and preserves distinct row IDs', () => {
const messagesList = [
{ id: 'a', role: 'assistant', request_id: 'r', steerForked: true, is_completed: true },
{ id: 'u', role: 'user', request_id: 'r' },
{ id: 'a:steer:1', assistant_message_id: 'a', role: 'assistant', request_id: 'r', is_completed: false },
]
const start = source.indexOf("if (data.response_type === 'agent_query')")
const block = source.slice(start, source.indexOf('const isAgentOnlyResponse', start))
const replaySegments = new Map()
const process = vm.runInNewContext(ts.transpile(`(data) => { ${block} }`), {
messagesList, replaySegments, resetSteerTurnForReplay,
currentAssistantMessageId: { value: 'a' },
getTrailingIncompleteAssistant: () => [...messagesList].reverse().find(m => m.role === 'assistant' && !m.is_completed),
findLastMessage: fn => [...messagesList].reverse().find(fn),
log() {}, ensureAgentMessageShell() {}, bindServerTurnTimestamps() {}, onAgentQuery() {},
})
process({ response_type: 'agent_query', id: 'r', assistant_message_id: 'a' })
assert.deepEqual(messagesList.map(m => m.id), ['a', 'u', 'a:steer:1'])
assert.equal(replaySegments.get('r'), messagesList[0])
})
test('failed tool results keep stdout/output instead of replacing it with the short error', () => {
assert.match(source, /toolCallEvent\.output = dataPayload\.output \|\| data\.content/)
assert.doesNotMatch(

View File

@ -3,7 +3,7 @@ import { markRaw, nextTick, type Ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ensureRagPipelineHistoryStream } from '@/utils/rag-pipeline-history'
import { applyMessageCreatedAt, bindServerTurnTimestamps, ensureMessageCreatedAt } from '@/utils/messageTimestamp'
import { expandSteerForksInHistory, forkAfterInjectedUser } from '@/utils/steerStreamFork'
import { expandSteerForksInHistory, forkAfterInjectedUser, steerStepEvents, resetSteerTurnForReplay } from '@/utils/steerStreamFork'
export type ChatMessage = Record<string, unknown>
@ -163,6 +163,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
return Array.isArray(refs) ? refs : []
}
const replaySegments = new Map<string, ChatMessage>()
/** Match the in-flight assistant row by request id or assistant message id. */
const resolveActiveAssistantMessage = (data: ChatMessage) => {
const dataId = data.id as string | undefined
@ -171,6 +173,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
currentAssistantMessageId.value ||
undefined
if (dataId && replaySegments.has(dataId)) return replaySegments.get(dataId)
const matched = findLastMessage((item) => {
if (item.role !== 'assistant') return false
if (dataId && (item.request_id === dataId || item.id === dataId)) return true
@ -326,6 +330,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
if (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) {
agentSteps.forEach((rawStep) => {
const step = rawStep as ChatMessage
events.push(...steerStepEvents(step))
const stepTimestamp = step.timestamp ? new Date(String(step.timestamp)).getTime() : 0
const toolCalls = step.tool_calls
const hasToolCalls = toolCalls && Array.isArray(toolCalls) && toolCalls.length > 0
@ -346,6 +351,10 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
})
}
const preambleText = step.thought && String(step.thought).trim() ? String(step.thought) : ''
if (preambleText && step.intermediate_answer) {
events.push({ type: 'answer', event_id: `step-${step.iteration}-answer`,
content: preambleText, done: true, intermediate_answer: true, timestamp: stepTimestamp || undefined })
}
if (preambleText && hasToolCalls) {
events.push({
type: 'answer',
@ -941,8 +950,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
)
alreadyInList = Boolean(injectedUser)
if (!injectedUser) {
// Queued messages live in the composer overlay, never as chat
// rows, so the first delivery builds the bubble here.
// A restored event or promoted follow-up may arrive before its preview.
injectedUser = {
id: injectedId || steerId,
role: 'user',
@ -953,6 +961,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
}
if (data.created_at) applyMessageCreatedAt(injectedUser, data.created_at)
}
if (injectedId) injectedUser.id = injectedId
if (data.created_at) applyMessageCreatedAt(injectedUser, data.created_at)
}
if (injectedUser) {
if (dataId && !injectedUser.request_id) injectedUser.request_id = dataId
@ -962,6 +972,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
injectedUser,
steerId,
)
if (dataId && replaySegments.has(dataId)) replaySegments.set(dataId, continuation)
if (!alreadyInList) emitMessageCreated(injectedUser)
if (continuation !== message) {
emitMessageCreated(continuation)
@ -972,6 +983,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
break
}
case 'complete': {
if (dataId) replaySegments.delete(dataId)
log('[Agent] Complete event received')
applyFinalArtifactContent(message, (dataPayload as any)?.final_content)
loading.value = false
@ -1040,6 +1052,9 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
})
if (data.response_type === 'agent_query') {
if (data.id) replaySegments.delete(String(data.id))
const replay = resetSteerTurnForReplay(messagesList, String(data.id || ''))
if (replay) replaySegments.set(String(data.id), replay)
if (data.id) {
const earlyMsg = getTrailingIncompleteAssistant()
if (earlyMsg) earlyMsg.request_id = data.id
@ -1055,7 +1070,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
request_id: (data.data as ChatMessage | undefined)?.request_id,
})
let existingMessage = findLastMessage(
let existingMessage = replay || findLastMessage(
(item) =>
item.role === 'assistant' &&
(item.id === data.id || item.request_id === data.id),
@ -1144,6 +1159,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
log('[Stop Event] Generation stopped')
const stoppedMessage = resolveActiveAssistantMessage(data)
if (stoppedMessage) markAssistantStopped(stoppedMessage)
if (data.id) replaySegments.delete(String(data.id))
loading.value = false
isReplying.value = false
currentAssistantMessageId.value = ''

View File

@ -2445,9 +2445,13 @@ export default {
noModel: 'No available models',
stopGeneration: 'Stop Generation',
send: 'Send',
steerQueueSendNow: 'Send now',
steerCurrent: 'Supplement current task',
steerAfter: 'Send after completion',
steerAccepted: 'Added during this task',
steerRetry: 'Retry sending',
steerQueueSendNow: 'Supplement current task',
steerQueueWaiting: 'Will send after the current answer finishes',
steerQueueInjecting: 'Waiting for the next thinking round',
steerQueueInjecting: 'Waiting to apply update',
messages: {
enterContent: 'Please enter content first!',
replying: 'Currently replying, please try again later!',

View File

@ -2445,9 +2445,13 @@ export default {
noModel: '利用可能なモデルがありません',
stopGeneration: '生成を停止',
send: '送信',
steerQueueSendNow: '今すぐ送信',
steerCurrent: '現在のタスクに追加',
steerAfter: '完了後に送信',
steerAccepted: 'このタスクへの追加',
steerRetry: '再送信',
steerQueueSendNow: '現在のタスクに追加',
steerQueueWaiting: '現在の回答が終わってから送信されます',
steerQueueInjecting: '次の思考ラウンドを待っています',
steerQueueInjecting: '追加内容の適用待ち',
messages: {
enterContent: '先に内容を入力してください。',
replying: '回答中です。しばらくしてから再試行してください。',

View File

@ -4511,9 +4511,13 @@ export default {
noModel: '사용 가능한 모델 없음',
stopGeneration: '생성 중지',
send: '전송',
steerQueueSendNow: '지금 보내기',
steerCurrent: '현재 작업에 추가',
steerAfter: '완료 후 보내기',
steerAccepted: '현재 작업에 추가됨',
steerRetry: '다시 보내기',
steerQueueSendNow: '현재 작업에 추가',
steerQueueWaiting: '현재 답변이 끝난 뒤에 전송됩니다',
steerQueueInjecting: '다음 사고 라운드를 기다리는 중',
steerQueueInjecting: '추가 내용 반영 대기 중',
webSearchDisabledByAgent: '현재 에이전트에 대해서는 네트워크 검색이 비활성화되어 있습니다.',
kbLockedByAgent: '현재 에이전트가 지식베이스 구성을 잠갔습니다.',
kbDisabledByAgent: '현재 에이전트가 지식베이스 기능을 비활성화했습니다.',

View File

@ -4511,9 +4511,13 @@ export default {
noModel: 'Нет доступных моделей',
stopGeneration: 'Остановить генерацию',
send: 'Отправить',
steerQueueSendNow: 'Отправить сейчас',
steerCurrent: 'Дополнить текущую задачу',
steerAfter: 'Отправить после завершения',
steerAccepted: 'Дополнение к текущей задаче',
steerRetry: 'Повторить отправку',
steerQueueSendNow: 'Дополнить текущую задачу',
steerQueueWaiting: 'Отправится после завершения текущего ответа',
steerQueueInjecting: 'Ожидание следующего раунда рассуждения',
steerQueueInjecting: 'Ожидание применения дополнения',
webSearchDisabledByAgent: 'Web search is disabled by the current agent',
kbLockedByAgent: 'Knowledge base configuration is locked by the current agent',
kbDisabledByAgent: 'Knowledge base is disabled by the current agent',

View File

@ -4513,9 +4513,13 @@ export default {
noModel: '暂无可用模型',
stopGeneration: '停止生成',
send: '发送',
steerQueueSendNow: '立即发送',
steerCurrent: '补充当前任务',
steerAfter: '完成后发送',
steerAccepted: '本轮补充',
steerRetry: '重试发送',
steerQueueSendNow: '补充当前任务',
steerQueueWaiting: '当前回答结束后发送',
steerQueueInjecting: '等待下一轮思考',
steerQueueInjecting: '等待接收补充',
webSearchDisabledByAgent: '当前智能体已禁用网络搜索',
kbLockedByAgent: '当前智能体已锁定知识库配置',
kbDisabledByAgent: '当前智能体已禁用知识库功能',

View File

@ -10,7 +10,7 @@ import {
CURRENT_TICK_SCALE,
activeQuestionId,
answerPreviewText,
collectUserQuestions,
collectOutlineMessages,
isChatOverflowing,
mapQuestionTicks,
nearestTickId,
@ -21,6 +21,7 @@ import {
tickDisplayScale,
tickMountainScale,
viewportBand,
visibleMessageIds,
} from './chatQuestionMinimap.ts'
test('isChatOverflowing is false when content fits or matches the viewport', () => {
@ -48,8 +49,8 @@ test('shouldShowQuestionMinimap requires overflow and at least two questions', (
assert.equal(shouldShowQuestionMinimap(false, 4), false)
})
test('collectUserQuestions keeps loaded user turns with ids, in list order', () => {
const questions = collectUserQuestions([
test('collectOutlineMessages includes both user and assistant messages in order', () => {
const questions = collectOutlineMessages([
{ role: 'assistant', id: 'a1', content: 'hi' },
{ role: 'user', content: 'no id yet' },
{ role: 'user', id: 'u1', content: 'first', images: [{}] },
@ -59,10 +60,29 @@ test('collectUserQuestions keeps loaded user turns with ids, in list order', ()
assert.deepEqual(
questions.map((q) => ({ id: q.id, hasAttachments: q.hasAttachments, answerContent: q.answerContent })),
[
{ id: 'a1', hasAttachments: false, answerContent: '' },
{ id: 'u1', hasAttachments: true, answerContent: 'answer one' },
{ id: 'a2', hasAttachments: false, answerContent: '' },
{ id: 'u2', hasAttachments: true, answerContent: '' },
],
)
assert.deepEqual(questions.map(q => q.role), ['assistant', 'user', 'assistant', 'user'])
})
test('all messages intersecting the viewport are highlighted, including partial and long answers', () => {
const items = [
{ id: 'above', offsetTop: 0, offsetBottom: 100 },
{ id: 'user', offsetTop: 90, offsetBottom: 125 },
{ id: 'assistant', offsetTop: 140, offsetBottom: 280 },
{ id: 'next-user', offsetTop: 290, offsetBottom: 330 },
{ id: 'below', offsetTop: 300, offsetBottom: 400 },
{ id: 'hidden', offsetTop: 150, offsetBottom: 150 },
]
assert.deepEqual([...visibleMessageIds(items, 100, 200)], ['user', 'assistant', 'next-user'])
assert.deepEqual([...visibleMessageIds([
{ id: 'long-answer', offsetTop: 0, offsetBottom: 2000 },
], 500, 200)], ['long-answer'])
assert.equal(visibleMessageIds(items, 100, 0).size, 0)
})
test('answerPreviewText strips markdown and stays empty when there is no answer yet', () => {

View File

@ -30,8 +30,9 @@ export type ChatMessageLike = {
attachments?: unknown[]
}
export type UserQuestion = {
export type OutlineMessage = {
id: string
role: 'user' | 'assistant'
content: string
hasAttachments: boolean
answerContent: string
@ -56,15 +57,15 @@ export function shouldShowQuestionMinimap(overflowing: boolean, questionCount: n
return overflowing && questionCount >= 2
}
export function collectUserQuestions(messages: ChatMessageLike[]): UserQuestion[] {
const questions: UserQuestion[] = []
export function collectOutlineMessages(messages: ChatMessageLike[]): OutlineMessage[] {
const questions: OutlineMessage[] = []
for (let index = 0; index < messages.length; index++) {
const message = messages[index]
if (message.role !== 'user' || !message.id) continue
if ((message.role !== 'user' && message.role !== 'assistant') || !message.id) continue
let answerContent = ''
for (let next = index + 1; next < messages.length; next++) {
for (let next = index + 1; message.role === 'user' && next < messages.length; next++) {
const following = messages[next]
if (following.role === 'user') break
if (following.role === 'assistant') {
@ -75,6 +76,7 @@ export function collectUserQuestions(messages: ChatMessageLike[]): UserQuestion[
questions.push({
id: message.id,
role: message.role,
content: message.content ?? '',
hasAttachments:
(message.images?.length ?? 0) > 0 || (message.attachments?.length ?? 0) > 0,
@ -85,6 +87,19 @@ export function collectUserQuestions(messages: ChatMessageLike[]): UserQuestion[
return questions
}
/** Include partially visible messages and long answers spanning the viewport. */
export function visibleMessageIds(
items: Array<{ id: string; offsetTop: number; offsetBottom: number }>,
scrollTop: number,
clientHeight: number,
): Set<string> {
if (clientHeight <= 0) return new Set()
const bottom = scrollTop + clientHeight
return new Set(items.filter(item => (
item.offsetBottom > item.offsetTop && item.offsetBottom > scrollTop && item.offsetTop < bottom
)).map(item => item.id))
}
export function questionDisplayText(
content: string | undefined,
attachmentPlaceholder: string,

View File

@ -0,0 +1,25 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { chatSubmitShortcut } from './chatSubmitShortcut'
const enter = { key: 'Enter', keyCode: 13, isComposing: false, shiftKey: false, ctrlKey: false, altKey: false, metaKey: false }
test('Enter queues during a run and Alt+Enter injects only while steering is available', () => {
assert.equal(chatSubmitShortcut(enter, true), 'after')
assert.equal(chatSubmitShortcut(enter, false), 'inject')
assert.equal(chatSubmitShortcut({ ...enter, altKey: true }, true), 'inject')
assert.equal(chatSubmitShortcut({ ...enter, altKey: true }, false), undefined)
})
test('Cmd+Enter injects during a run and sends normally when idle', () => {
const cmdEnter = { ...enter, metaKey: true }
assert.equal(chatSubmitShortcut(cmdEnter, true), 'inject')
assert.equal(chatSubmitShortcut(cmdEnter, false), 'inject')
for (const modifiers of [{ shiftKey: true }, { ctrlKey: true }, { isComposing: true }, { keyCode: 229 }]) {
assert.equal(chatSubmitShortcut({ ...cmdEnter, ...modifiers }, true), undefined)
}
})
test('newlines and IME confirmation never submit', () => {
for (const modifiers of [{ shiftKey: true }, { ctrlKey: true }, { isComposing: true }, { keyCode: 229 }]) {
assert.equal(chatSubmitShortcut({ ...enter, ...modifiers }, true), undefined)
}
assert.equal(chatSubmitShortcut({ ...enter, key: 'a', keyCode: 65 }, true), undefined)
})

View File

@ -0,0 +1,11 @@
/** Enter queues during a run; Cmd/Alt+Enter steers. Preserve newline and IME behavior. */
export function chatSubmitShortcut(
event: Pick<KeyboardEvent, 'key' | 'keyCode' | 'isComposing' | 'shiftKey' | 'ctrlKey' | 'altKey' | 'metaKey'>,
canSteer: boolean,
): 'inject' | 'after' | undefined {
if (event.isComposing || event.keyCode === 229 || (event.key !== 'Enter' && event.keyCode !== 13)) return
if (event.shiftKey || event.ctrlKey) return
if (event.metaKey) return 'inject'
if (event.altKey) return canSteer ? 'inject' : undefined
return canSteer ? 'after' : 'inject'
}

View File

@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { expandSteerForksInHistory, forkAfterInjectedUser } from './steerStreamFork.ts'
import { expandSteerForksInHistory, forkAfterInjectedUser, resetSteerTurnForReplay, steerStepEvents, isAssistantTurnComplete, previewSteerMessage, discardSteerPreview } from './steerStreamFork.ts'
test('inject forks later events onto a new assistant below the user bubble', () => {
const assistant = {
@ -219,3 +219,92 @@ test('expanding an already split transcript is a no-op', () => {
assert.equal(twice[3].assistant_message_id, 'a0')
assert.equal(twice[3].id, once[3].id)
})
test('explicit boundaries preserve drafts, repeated inputs and delivery order despite equal timestamps', () => {
const users = ['u2', 'u1'].map(id => ({ id, role: 'user', request_id: 'r', content: 'revise', created_at: '1970-01-01T00:00:00Z' }))
const assistant = { id: 'a', role: 'assistant', request_id: 'r', content: 'final', is_completed: true,
used_memories: [{ id: 'memory' }], agentEventStream: [
{ type: 'answer', content: 'first draft', done: true, intermediate_answer: true },
{ type: 'user_message_injected', user_message_id: 'u1' },
{ type: 'answer', content: 'second draft', done: true, intermediate_answer: true },
{ type: 'user_message_injected', user_message_id: 'u2' },
{ type: 'answer', content: 'final', done: true },
] }
const out = expandSteerForksInHistory([assistant, ...users])
assert.deepEqual(out.map(m => m.content), ['first draft', 'revise', 'second draft', 'revise', 'final'])
assert.equal(out[1].id, 'u1')
assert.equal(out[3].id, 'u2')
assert.equal(out[1].isSteer, true)
assert.equal(out.filter(m => m.used_memories?.length).length, 1)
})
test('sealing a draft finishes its text stream without discarding the draft', () => {
const source = { id: 'a', role: 'assistant', request_id: 'r', content: 'draft', agentEventStream: [{ type: 'answer', content: 'draft', done: false }] }
const list = [source]
forkAfterInjectedUser(list, source, { id: 'u1', role: 'user', request_id: 'r', content: 'revise' }, 's1')
assert.equal(source.content, 'draft')
assert.equal(source.agentEventStream[0].done, true)
})
test('replay walks successive existing segments rather than duplicating earlier events on the tail', () => {
const a = { id: 'a', role: 'assistant', request_id: 'r', steerForked: true, content: 'draft', agentEventStream: [{ type: 'answer', content: 'draft' }] }
const u1 = { id: 'u1', role: 'user', request_id: 'r', content: 'one' }
const middle = { id: 'a:1', role: 'assistant', request_id: 'r', steerForked: true, agentEventStream: [] }
const u2 = { id: 'u2', role: 'user', request_id: 'r', content: 'two' }
const tail = { id: 'a:2', role: 'assistant', request_id: 'r', is_completed: false, agentEventStream: [] }
const list = [a, u1, middle, u2, tail]
let cursor = resetSteerTurnForReplay(list, 'r')
assert.equal(cursor, a)
cursor.agentEventStream.push({ type: 'answer', content: 'draft' })
cursor = forkAfterInjectedUser(list, cursor, u1, 's1')
assert.equal(cursor, middle)
cursor.agentEventStream.push({ type: 'thinking', content: 'work' })
cursor = forkAfterInjectedUser(list, cursor, u2, 's2')
assert.equal(cursor, tail)
assert.equal(list.length, 5)
assert.equal(a.agentEventStream.length, 1)
assert.equal(middle.agentEventStream.length, 1)
assert.equal(tail.agentEventStream.length, 0)
assert.equal(a.is_completed, true)
assert.equal(middle.is_completed, true)
assert.equal(tail.is_completed, false)
})
test('step boundary events retain the server delivery order', () => {
assert.deepEqual(steerStepEvents({ user_messages_before: ['u2', 'u1'] }).map(e => e.user_message_id), ['u2', 'u1'])
})
test('only run completion ends the task; draft completion and sealed prefixes do not', () => {
assert.equal(isAssistantTurnComplete({ is_completed: false, agentEventStream: [{ type: 'answer', done: true }] }), false)
assert.equal(isAssistantTurnComplete({ is_completed: true, steerForked: true }), false)
assert.equal(isAssistantTurnComplete({ agentEventStream: [{ type: 'agent_complete' }] }), true)
assert.equal(isAssistantTurnComplete({ agentEventStream: [{ type: 'stop' }] }), true)
assert.equal(isAssistantTurnComplete({ is_completed: true }), true)
})
test('inject appears immediately and the delivery receipt reuses its bubble', () => {
const assistant = { id: 'a', role: 'assistant', request_id: 'r', is_completed: false, agentEventStream: [{ type: 'thinking', done: false }] }
const list = [assistant]
const preview = previewSteerMessage(list, { steer_id: 's', content: '补充' })
assert.equal(list[1], preview)
assert.equal(assistant.is_completed, false)
assert.equal(assistant.agentEventStream[0].done, false)
assert.equal(previewSteerMessage(list, { steer_id: 's', content: '补充' }), preview)
assert.equal(list.length, 2)
forkAfterInjectedUser(list, assistant, preview, 's')
assert.equal(list.length, 3)
assert.equal(list[1], preview)
assert.equal(preview._steerPending, undefined)
discardSteerPreview(list, 's')
assert.equal(list.length, 3, 'removal must never discard a consumed message')
})
test('failed promotion can restore its queue without leaving a duplicate bubble', () => {
const list = []
previewSteerMessage(list, { steer_id: 's', content: '补充' })
discardSteerPreview(list, 's')
assert.equal(list.length, 0)
previewSteerMessage(list, { steer_id: 's', content: '补充' })
assert.equal(list.length, 1)
})

View File

@ -2,6 +2,24 @@ import { markRaw } from 'vue'
export type ChatMessage = Record<string, unknown>
/** Display a steer immediately; the receipt, not this preview, splits execution. */
export function previewSteerMessage(list: ChatMessage[], item: { steer_id: string; content: string; mentioned_items?: unknown[] }): ChatMessage {
const existing = list.find(m => m.role === 'user' && m.steer_id === item.steer_id)
if (existing) return existing
const message: ChatMessage = {
id: `steer-user-${item.steer_id}`, steer_id: item.steer_id,
role: 'user', content: item.content, mentioned_items: item.mentioned_items || [],
isSteer: true, is_completed: true, _steerPending: true,
}
list.push(message)
return message
}
export function discardSteerPreview(list: ChatMessage[], steerId: string): void {
const index = list.findIndex(m => m.steer_id === steerId && m._steerPending)
if (index >= 0) list.splice(index, 1)
}
/**
* The row id the server knows this assistant message by.
*
@ -28,7 +46,7 @@ export function sealAssistantSegment(message: ChatMessage): void {
for (const raw of stream) {
if (!raw || typeof raw !== 'object') continue
const event = raw as ChatMessage
if (event.type === 'thinking') {
if (event.type === 'thinking' || event.type === 'answer') {
event.done = true
event.thinking = false
}
@ -48,6 +66,9 @@ export function forkAfterInjectedUser(
// "Already split" means the bubble sits *between* two segments of this turn.
// A bubble merely sitting above the live assistant is the opposite case —
// it still has to be moved underneath it.
userMessage.isSteer = true
delete userMessage._steerPending
delete userMessage._steerFailed
const existingIdx = list.indexOf(userMessage)
if (existingIdx > 0) {
const before = list[existingIdx - 1]
@ -56,9 +77,14 @@ export function forkAfterInjectedUser(
before?.role === 'assistant' &&
before.request_id === sourceAssistant.request_id &&
after?.role === 'assistant' &&
!after.is_completed &&
after.request_id === sourceAssistant.request_id
) {
sealAssistantSegment(before)
if (after._steerReplayPending) {
delete after._steerReplayPending
after.is_completed = false
after.steerForked = false
}
return after
}
}
@ -122,7 +148,7 @@ function eventTime(event: ChatMessage): number {
function isTrailingTurnEvent(event: ChatMessage): boolean {
if (event.type === 'agent_complete' || event.type === 'stop') return true
return event.type === 'answer' && event.done === true && !event.superseded
return event.type === 'answer' && event.done === true && !event.superseded && !event.intermediate_answer
}
export function expandSteerForksInHistory(messages: ChatMessage[]): ChatMessage[] {
@ -159,20 +185,34 @@ export function expandSteerForksInHistory(messages: ChatMessage[]): ChatMessage[
}
const stream = Array.isArray(item.agentEventStream) ? (item.agentEventStream as ChatMessage[]) : []
const boundaryIDs = stream.filter(e => e.type === 'user_message_injected').map(e => e.user_message_id)
const hasBoundaries = boundaryIDs.length > 0
if (hasBoundaries) {
forks.sort((a, b) => {
const ai = boundaryIDs.indexOf(a.id), bi = boundaryIDs.indexOf(b.id)
return (ai < 0 ? Infinity : ai) - (bi < 0 ? Infinity : bi)
})
}
const cuts = forks.map((user) => {
const parsed = Date.parse(String(user.created_at || ''))
return Number.isNaN(parsed) ? 0 : parsed
})
const buckets: ChatMessage[][] = Array.from({ length: forks.length + 1 }, () => [])
const trailing: ChatMessage[] = []
let segmentIndex = 0
for (const event of stream) {
if (event.type === 'user_message_injected') {
const index = forks.findIndex(user => user.id === event.user_message_id)
if (index >= 0) segmentIndex = index + 1
continue
}
if (isTrailingTurnEvent(event)) {
trailing.push(event)
continue
}
const t = eventTime(event)
let idx = 0
while (idx < cuts.length && t >= cuts[idx]) idx += 1
let idx = hasBoundaries ? segmentIndex : 0
while (!hasBoundaries && idx < cuts.length && t >= cuts[idx]) idx += 1
buckets[idx].push(event)
}
buckets[buckets.length - 1].push(...trailing)
@ -197,6 +237,7 @@ export function expandSteerForksInHistory(messages: ChatMessage[]): ChatMessage[
assistant_message_id: persistedId,
}
segment.agentEventStream = markRaw(buckets[s])
if (s > 0) segment.used_memories = undefined
if (isLast) {
segment.content = original.content
segment.artifacts = original.artifacts
@ -207,15 +248,54 @@ export function expandSteerForksInHistory(messages: ChatMessage[]): ChatMessage[
} else {
segment.steerForked = true
segment.is_completed = true
segment.content = ''
segment.content = buckets[s].filter(e => e.type === 'answer' && !e.superseded).map(e => e.content || '').join('')
segment.artifacts = undefined
segment.usage = undefined
segment.knowledge_references = []
}
out.push(segment)
if (s < forks.length) out.push(forks[s])
if (s < forks.length) {
forks[s].isSteer = true
out.push(forks[s])
}
}
i = j - 1
}
return out
}
export function steerStepEvents(step: ChatMessage): ChatMessage[] {
const events: ChatMessage[] = []
if (Array.isArray(step.user_messages_before)) {
for (const id of step.user_messages_before) {
events.push({ type: 'user_message_injected', user_message_id: id })
}
}
return events
}
/** A continue-stream replays from offset zero. Keep row identities, but rebuild
* every segment from that log rather than appending old events onto the tail. */
export function resetSteerTurnForReplay(list: ChatMessage[], requestId: string): ChatMessage | undefined {
const segments = list.filter(m => m.role === 'assistant' && m.request_id === requestId)
if (!segments.some(m => m.steerForked)) return undefined
for (const segment of segments) {
segment.content = ''
segment.agentEventStream = []
segment._eventMap = new Map()
segment._pendingToolCalls = new Map()
segment.is_completed = true
segment._steerReplayPending = true
}
segments[0].is_completed = false
segments[0].steerForked = false
delete segments[0]._steerReplayPending
return segments[0]
}
/** Individual answer.done events close a message, not the running task. */
export function isAssistantTurnComplete(message: ChatMessage | undefined): boolean {
if (!message || message.steerForked) return false
return Boolean(message.is_completed) || (Array.isArray(message.agentEventStream) &&
message.agentEventStream.some(e => e.type === 'agent_complete' || e.type === 'stop'))
}

View File

@ -3,10 +3,32 @@ import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import vm from 'node:vm'
import { computed, reactive } from 'vue'
import { isAssistantTurnComplete } from '../../../utils/steerStreamFork.ts'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'AgentStreamDisplay.vue'), 'utf8')
test('streamed responses do not mount a hidden Wiki drawer that steals composer focus', () => {
assert.match(source, /<t-drawer v-if="wikiDrawerVisible" v-model:visible="wikiDrawerVisible"/)
})
test('steer seals animation while keeping the preceding timeline open without completion', () => {
const stateBlock = source.slice(source.indexOf('const isConversationDone ='), source.indexOf('const streamingMermaidSvgCache ='))
const collapseBlock = source.slice(source.indexOf('const shouldShowCollapsedSteps ='), source.indexOf('// Once the steps collapse'))
const props = reactive({ ragMode: false, session: { steerForked: true, is_completed: true } })
const state = vm.runInNewContext(`${stateBlock}\n${collapseBlock}\n({ isConversationDone, isSegmentDone, shouldShowCollapsedSteps })`, {
props, computed, isAssistantTurnComplete, intermediateStepsCount: { value: 2 },
})
assert.equal(state.isSegmentDone.value, true)
assert.equal(state.isConversationDone.value, false)
assert.equal(state.shouldShowCollapsedSteps.value, false)
props.session.steerForked = false
assert.equal(state.isConversationDone.value, true)
assert.equal(state.shouldShowCollapsedSteps.value, true)
})
test('agent steps use compact muted timeline styling', () => {
assert.match(source, /--agent-step-text-size:\s*14px/)
assert.match(source, /--agent-step-summary-size:\s*13px/)
@ -50,7 +72,7 @@ test('streaming tool log uses the same timeline structure', () => {
test('final done row uses an existing common translation key', () => {
assert.match(source, /t\('common\.finish'\)/)
assert.doesNotMatch(source, /\$t\('common\.done'\)/)
assert.match(source, /'tree-child-last': !isConversationDone && index === visibleIntermediateEvents\.length - 1/)
assert.match(source, /'tree-child-last': !isSegmentDone && index === visibleIntermediateEvents\.length - 1/)
})
test('tool rows use line icon names instead of legacy asset masks', () => {
@ -71,7 +93,7 @@ test('tool rows use line icon names instead of legacy asset masks', () => {
test('rag mode delegates pre-answer loading to pipeline and adds no row after answer starts', () => {
assert.match(source, /if \(props\.ragMode \|\| hasAnswerStarted\.value\) return false/)
assert.match(source, /v-if="!ragMode \|\| displayEvents\.length > 0 \|\| showAgentActivityIndicator"/)
assert.match(source, /v-if="displayEvents\.length > 0 \|\| showMemoryRow \|\| showAgentActivityIndicator"/)
assert.doesNotMatch(source, /ChatActivityIndicator/)
})
@ -119,7 +141,7 @@ test('pending tool rows do not render an extra axis dot', () => {
})
test('agent mode shows a native placeholder before answer whenever nothing is pending', () => {
assert.match(source, /if \(isConversationDone\.value\) return false/)
assert.match(source, /if \(isSegmentDone\.value\) return false/)
assert.match(source, /return !hasPendingStreamingActivity\.value/)
assert.match(source, /const hasPendingStreamingActivity = computed/)
assert.match(source, /event\.thinking === true \|\| isThinkingActive\(event\.event_id\)/)

View File

@ -1,5 +1,5 @@
<template>
<div ref="rootElement" class="agent-stream-display" :class="{ 'is-embedded': embeddedMode, 'is-rag-mode': ragMode }">
<div ref="rootElement" class="agent-stream-display" :class="{ 'is-embedded': embeddedMode, 'is-rag-mode': ragMode, 'is-steer-prefix': session?.steerForked }">
<!-- Collapsed intermediate steps (tree root) -->
<div v-if="shouldShowCollapsedSteps" class="tree-container">
@ -28,7 +28,7 @@
/>
<template v-for="(event, index) in visibleIntermediateEvents" :key="getEventKey(event, index)">
<div v-if="event && event.type" class="tree-child"
:class="{ 'tree-child-last': !isConversationDone && index === visibleIntermediateEvents.length - 1 }">
:class="{ 'tree-child-last': !isSegmentDone && index === visibleIntermediateEvents.length - 1 }">
<div class="tree-branch"></div>
<div class="tree-child-content">
<!-- Plan Task Change Event -->
@ -246,9 +246,9 @@
</div>
<!-- Event Stream (non-tree mode: before answer starts, or answer events) -->
<div v-if="!ragMode || displayEvents.length > 0 || showAgentActivityIndicator" ref="streamingStepsContainer"
<div v-if="displayEvents.length > 0 || showMemoryRow || showAgentActivityIndicator" ref="streamingStepsContainer"
class="streaming-steps-container" :class="{
'streaming-steps-constrained': !answerEverStarted && !isConversationDone,
'streaming-steps-constrained': !answerEverStarted && !isSegmentDone,
'is-streaming-timeline': showStreamingTimeline
}">
<!-- Recalled memory leads the timeline: it is what the turn knew before it
@ -546,7 +546,8 @@
<picturePreview :reviewImg="imagePreviewVisible" :reviewUrl="imagePreviewUrl" @closePreImg="closeImagePreview" />
<!-- Wiki Page Detail Drawer -->
<t-drawer v-model:visible="wikiDrawerVisible" :header="wikiDrawerPage?.title || ''" size="480px" :footer="false"
<!-- Mount on demand: a hidden TDesign drawer steals focus when each response mounts. -->
<t-drawer v-if="wikiDrawerVisible" v-model:visible="wikiDrawerVisible" :header="wikiDrawerPage?.title || ''" size="480px" :footer="false"
placement="right" attach="body" :show-overlay="true" :close-btn="true" :close-on-overlay-click="true"
class="wiki-graph-drawer">
<template v-if="wikiDrawerPage">
@ -587,6 +588,7 @@
</template>
<script setup lang="ts">
import { isAssistantTurnComplete } from '@/utils/steerStreamFork';
import { ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { marked } from 'marked';
@ -1547,36 +1549,9 @@ watch(eventStream, (stream) => {
}, { deep: true, immediate: true });
// Check if conversation is done (based on answer event with done=true or stop event)
const isConversationDone = computed(() => {
if (props.session?.steerForked) return true
const stream = eventStream.value;
if (!stream || stream.length === 0) {
console.log('[Collapse] No stream or empty stream');
return false;
}
// Check for stop event (user cancelled)
const stopEvent = stream.find((e: any) => e.type === 'stop');
if (stopEvent) {
console.log('[Collapse] Found stop event, conversation done');
return true;
}
const completeEvent = stream.find((e: any) => e.type === 'agent_complete');
if (completeEvent) {
console.log('[Collapse] Found complete event, conversation done');
return true;
}
// Check for answer event with done=true. Exclude superseded preambles: a
// retracted tool-round preamble is also closed with done=true, but the agent
// keeps running, so it must not mark the whole conversation as finished.
const answerEvents = stream.filter((e: any) => e.type === 'answer' && !e.superseded);
const doneAnswer = answerEvents.find((e: any) => e.done === true);
return !!doneAnswer;
});
// A steer boundary stops local animation without completing or folding the task.
const isConversationDone = computed(() => isAssistantTurnComplete(props.session));
const isSegmentDone = computed(() => Boolean(props.session?.steerForked) || isConversationDone.value);
const streamingMermaidSvgCache = ref<string[]>([]);
let streamingMermaidRenderTask: Promise<void> | null = null;
@ -1603,7 +1578,7 @@ const activeAnswerEventRef = computed(() => {
// full instead of replaying.
const { displayed: typedAnswer } = useTypewriter(
() => activeAnswerMarkdown.value,
() => isConversationDone.value,
() => isSegmentDone.value,
);
const cacheStreamingMermaidSvg = async () => {
@ -1629,7 +1604,7 @@ const cacheStreamingMermaidSvg = async () => {
}
};
watch(isConversationDone, (done) => {
watch(isSegmentDone, (done) => {
if (!done) {
streamingMermaidSvgCache.value = [];
streamingMermaidRenderTask = null;
@ -1656,7 +1631,7 @@ watch(activeAnswerMarkdown, () => {
const answerFullyRendered = computed(
() =>
!props.session?.steerForked &&
isConversationDone.value &&
isSegmentDone.value &&
typedAnswer.value.length >= activeAnswerMarkdown.value.length,
);
watch(answerFullyRendered, (ready) => {
@ -1696,7 +1671,7 @@ const hasPendingStreamingActivity = computed(() => {
// feedback-less timeline. Once a real pending step exists it carries its own
// shimmer, and once answer text starts the stream itself is enough feedback.
const showAgentActivityIndicator = computed(() => {
if (isConversationDone.value) return false;
if (isSegmentDone.value) return false;
if (props.ragMode || hasAnswerStarted.value) return false;
return !hasPendingStreamingActivity.value;
});
@ -1734,7 +1709,7 @@ const finalContent = computed(() => {
return null;
}
if (!isConversationDone.value) {
if (!isSegmentDone.value) {
return null;
}
@ -1779,7 +1754,7 @@ const finalContent = computed(() => {
// Count intermediate steps (after merging consecutive thinking events, matching what user sees in tree)
const intermediateStepsCount = computed(() => {
if (!hasAnswerStarted.value && !isConversationDone.value) return 0;
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
// Count only thinking and tool_call events (exclude plan_task_change, etc.)
return intermediateEvents.value.filter(
(e: any) => e.type === 'thinking' || e.type === 'tool_call'
@ -1791,12 +1766,12 @@ const intermediateStepsCount = computed(() => {
// over-counts what the user perceives as agent loops (a single loop emits one
// thinking card plus its tool calls).
const reasoningRoundsCount = computed(() => {
if (!hasAnswerStarted.value && !isConversationDone.value) return 0;
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
return intermediateEvents.value.filter((e: any) => e.type === 'thinking').length;
});
const toolCallsCount = computed(() => {
if (!hasAnswerStarted.value && !isConversationDone.value) return 0;
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
return intermediateEvents.value.filter((e: any) => e.type === 'tool_call').length;
});
@ -2545,7 +2520,7 @@ agentRenderer.image = function agentImageRenderer(token) {
artifacts: artifactList.value,
labels: artifactRefLabels.value,
context: artifactRefContext.value,
streaming: !isConversationDone.value,
streaming: !isSegmentDone.value,
});
if (artifactHtml !== null) return artifactHtml;
return defaultImageRenderer.call(this, token);
@ -2561,7 +2536,7 @@ const prepareAgentMarkdown = (markdown: string, cachedSvgHtml?: CachedMermaidSvg
const cache = cachedSvgHtml ?? streamingMermaidSvgCache.value;
// Keep masking after the turn ends when SVG is already cached so v-html /
// v-stable-html cannot replace a painted diagram with mermaid source.
const mermaidSafe = !isConversationDone.value || hasCachedMermaidSvg(cache)
const mermaidSafe = !isSegmentDone.value || hasCachedMermaidSvg(cache)
? prepareStreamingMermaidMarkdown(markdown, cache)
: replaceIncompleteMermaidWithPlaceholder(markdown);
return mermaidSafe.replace(/<(?:kb|web)\b[^>]*$/i, '');
@ -2578,7 +2553,7 @@ const renderAgentMarkdown = (
renderer: agentRenderer,
escapeMarkdown,
sanitizeHtml: sanitizeMarkdownHTML,
streaming: !isConversationDone.value,
streaming: !isSegmentDone.value,
knowledgeReferences: getReferencesForDrawer(),
cachedMermaidSvgHtml: streamingMermaidSvgCache.value,
prepareMarkdown: prepareAgentMarkdown,
@ -3157,6 +3132,11 @@ const handleAddToKnowledge = (answerEvent: any) => {
--stream-brand-15: color-mix(in srgb, var(--td-brand-color) 15%, transparent);
--stream-brand-20: color-mix(in srgb, var(--td-brand-color) 20%, transparent);
&.is-steer-prefix {
margin-bottom: 0;
.tree-container { margin-bottom: 0; }
}
&.is-rag-mode {
margin-top: 0;
}

View File

@ -43,6 +43,11 @@
<div class="user_msg">
{{ content }}
</div>
<div v-if="steerFailed" class="steer-failure" role="status">
<span>{{ t('input.messages.steerFailed') }}</span>
<t-tooltip :content="t('input.steerRetry')"><button type="button" :aria-label="t('input.steerRetry')" @click="emit('retry-steer')"><t-icon name="refresh" /></button></t-tooltip>
<t-tooltip :content="t('common.remove')"><button type="button" :aria-label="t('common.remove')" @click="emit('remove-steer')"><t-icon name="close" /></button></t-tooltip>
</div>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg" />
</div>
</template>
@ -54,6 +59,7 @@ import { useI18n } from 'vue-i18n';
import { useChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';
import { isPreviewableAttachment, resolveAttachmentFileType } from '@/utils/attachmentPreview';
import { SKILL_ICON } from '@/types/mention';
const emit = defineEmits(['retry-steer', 'remove-steer']);
const { t } = useI18n();
@ -70,6 +76,7 @@ const mentionTagIcon = (item) => {
};
const props = defineProps({
steerFailed: { type: Boolean, default: false },
content: {
type: String,
required: false
@ -357,3 +364,10 @@ html[theme-mode="dark"] {
}
}
</style>
<style scoped>
.steer-failure { display: flex; align-items: center; justify-content: flex-end; gap: 4px; font-size: 12px; color: var(--td-text-color-secondary); margin-bottom: 4px; }
.steer-failure { margin-top: 6px; color: var(--td-error-color); }
.steer-failure button { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border: 0; border-radius: 6px; background: transparent; color: inherit; cursor: pointer; }
.steer-failure button:hover { background: var(--td-bg-color-secondarycontainer); }
</style>

View File

@ -98,7 +98,8 @@
仅对极少数尚未拿到 id 的本地占位消息 fallback 到 role+created_at+index。
-->
<div v-for="(session, index) in messagesList"
:key="session.id || `${session.role}-${session.created_at}-${index}`" class="msg-item-wrapper">
:key="session.id || `${session.role}-${session.created_at}-${index}`" class="msg-item-wrapper"
:class="{ 'is-steer-prefix': session.steerForked, 'is-empty-segment': session.role === 'assistant' && !shouldRenderAssistantMessage(session) }">
<MessageTimestamp v-if="shouldShowConversationTimestamp(messagesList, index)"
:value="session.created_at" />
@ -107,7 +108,10 @@
:class="{ 'is-minimap-target': session.id && session.id === minimapTargetId }">
<usermsg :content="session.content" :mentioned_items="session.mentioned_items"
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"
:session-id="session_id">
:session-id="session_id"
:steer-failed="Boolean(session._steerFailed)"
@retry-steer="handleRetrySteer(session.steer_id)"
@remove-steer="handleRemoveSteer(session.steer_id)">
</usermsg>
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"
@ -143,16 +147,17 @@
</div>
</transition>
<div class="input-container" :class="{ 'is-embedded': embeddedMode }">
<InputField ref="inputFieldRef"
<InputField ref="inputFieldRef" :auto-focus="focusComposerOnMount"
@send-msg="(query, modelId, mentionedItems, imageFiles, attachmentFiles) => sendMsg(query, modelId, mentionedItems, imageFiles, attachmentFiles)"
@steer-msg="(query, mentionedItems, delivery) => handleSteerMsg(query, mentionedItems, delivery)"
@promote-steer="handlePromoteSteer"
@remove-steer="handleRemoveSteer"
@retry-steer="handleRetrySteer"
@stop-generation="handleStopGeneration"
@stop-confirmed="handleStopConfirmed"
@stop-failed="handleStopFailed" :isReplying="isReplying" :sessionId="session_id"
:assistantMessageId="currentAssistantMessageId" :embeddedMode="embeddedMode"
:queuedSteers="steerQueue" :canSteer="isAgentStreamSession()"></InputField>
:queuedSteers="steerQueue.filter(item => item.delivery === 'after')" :canSteer="isAgentStreamSession()"></InputField>
</div>
</div>
<KnowledgeBaseEditorModal :visible="uiStore.showKBEditorModal" :mode="uiStore.kbEditorMode"
@ -178,7 +183,7 @@ import { getSuggestedQuestions } from "@/api/agent/index";
import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments';
import { useStream } from '../../api/chat/streame'
import { listSteerSession, promoteSteerSession, removeSteerSession, steerSession } from '@/api/chat/steer';
import { persistedAssistantId } from '@/utils/steerStreamFork';
import { persistedAssistantId, previewSteerMessage, discardSteerPreview } from '@/utils/steerStreamFork';
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
import { MessagePlugin } from 'tdesign-vue-next';
@ -239,6 +244,8 @@ const uiStore = useUIStore();
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
const { t } = useI18n();
const { firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles } = storeToRefs(usemenuStore);
// Capture before the initial send consumes firstQuery; the child focuses after mounting.
const focusComposerOnMount = Boolean(firstQuery.value);
const { onChunk, error, isStreaming, startStream, stopStream, lastStreamRequest } = useStream();
/** Snapshot of the in-flight HTTP request for attaching to the next assistant message. */
const pendingStreamDebug = ref(null);
@ -639,7 +646,11 @@ const hydrateSteerQueue = async ({ onlyWhenLive = false } = {}) => {
content: item.content || '',
delivery: item.delivery === 'inject' ? 'inject' : 'after',
mentioned_items: item.mentioned_items || [],
}));
expected_assistant_message_id: res.assistant_message_id,
})).concat(steerQueue.value.filter(item => item.failed && !items.some(remote => remote.steer_id === item.steer_id)));
for (const item of steerQueue.value) {
if (item.delivery === 'inject') previewSteerMessage(messagesList, item);
}
} catch (e) {
console.warn('[Steer] Failed to restore queue:', e);
}
@ -738,6 +749,7 @@ const {
dropSteerQueueItem(steerId);
},
onGenerationStopped: () => {
for (const item of steerQueue.value) discardSteerPreview(messagesList, item.steer_id);
steerQueue.value = [];
},
onTurnComplete: (message) => {
@ -803,6 +815,7 @@ const handleStopGeneration = () => {
};
const handleStopConfirmed = () => {
for (const item of steerQueue.value) discardSteerPreview(messagesList, item.steer_id);
steerQueue.value = [];
};
@ -820,97 +833,135 @@ const dropSteerQueueItem = (steerId) => {
const findSteerQueueItem = (steerId) =>
steerQueue.value.find((item) => item.steer_id === steerId);
const makeSteerClientId = () =>
`steer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const makeSteerClientId = () => {
// getRandomValues also works on HTTP deployments without randomUUID.
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 15) | 64;
bytes[8] = (bytes[8] & 63) | 128;
const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
};
// 追加消息到正在运行的 agent turn。默认 delivery=after,排队显示在输入框上方;
// 点「立即发送」再 promote 为 inject。注入后的时间线分叉复用 forkAfterInjectedUser。
const handleSteerMsg = async (value, mentionedItems = [], delivery = 'after') => {
// Enter queues a follow-up; an explicit inject appears in the transcript immediately.
const handleSteerMsg = async (value, mentionedItems = [], delivery = 'after', retryId = '') => {
if (!session_id.value || !value?.trim()) return;
if (!isReplying.value) {
if (!isReplying.value && !retryId) {
// 空闲时没有运行中的 turn 可排队:直接走正常发送,而不是把
// steering(服务端为 handleSteer/指定事务)当隐形 sendMsg 用。
await sendMsg(value, '', mentionedItems);
return;
}
const clientId = makeSteerClientId();
steerQueue.value.push({
const requestSessionId = session_id.value;
const clientId = retryId || makeSteerClientId();
const retryItem = retryId ? findSteerQueueItem(retryId) : null;
const expectedId = retryItem?.expected_assistant_message_id || currentAssistantMessageId.value;
if (retryItem) { retryItem.pending = true; retryItem.failed = false; }
else steerQueue.value.push({
steer_id: clientId,
client_id: clientId,
expected_assistant_message_id: expectedId,
content: value,
delivery,
mentioned_items: mentionedItems,
pending: true,
});
if (delivery === 'inject') {
const preview = previewSteerMessage(messagesList, findSteerQueueItem(clientId));
delete preview._steerFailed;
scrollToBottom(true);
}
try {
const res = await steerSession(session_id.value, value, mentionedItems, delivery);
const res = await steerSession(requestSessionId, value, mentionedItems, delivery, expectedId, clientId);
if (session_id.value !== requestSessionId) return;
if (res?.status === 'already_injected') {
dropSteerQueueItem(clientId);
const preview = messagesList.find(m => m.steer_id === clientId);
if (preview) delete preview._steerPending;
MessagePlugin.info(t('input.messages.steerAlreadyInjected'));
return;
}
if (res?.status === 'new_run') {
const item = findSteerQueueItem(clientId);
// Still attached to a stream: aborting it to POST AgentQA races the
// finishing turn and can start a second engine. Keep the chip and
// finishing turn and can start a second engine. Keep the message and
// send once the current SSE completes.
if (isReplying.value || isStreaming.value) {
if (item) {
item.pending = false;
item.awaitingIdleSend = true;
item.delivery = 'after';
}
return;
}
dropSteerQueueItem(clientId);
discardSteerPreview(messagesList, clientId);
await sendMsg(value, '', mentionedItems);
return;
}
const item = findSteerQueueItem(clientId);
if (item) {
// The server id is the durable one — promote/remove and the
// injected-event correlation all go through it. client_id stays
// so handlePromoteSteer can still find the row while the swap
// is rendering.
// The server echoes the stable client UUID used by SSE receipts.
if (res?.steer_id) item.steer_id = res.steer_id;
item.pending = false;
}
} catch (e) {
console.error('[Steer] Failed to queue message:', e);
dropSteerQueueItem(clientId);
if (session_id.value !== requestSessionId) return;
const item = findSteerQueueItem(clientId);
if (!item) return; // The delivery receipt may have already consumed it.
item.pending = false;
item.failed = true;
const preview = messagesList.find(m => m.steer_id === clientId && m._steerPending);
if (preview) preview._steerFailed = true;
if (e?.status === 409) item.expected_assistant_message_id = currentAssistantMessageId.value;
MessagePlugin.error(e?.message || t('input.messages.steerFailed'));
}
};
const handleRetrySteer = async (steerId) => {
const item = findSteerQueueItem(steerId);
if (!item || item.pending) return;
await handleSteerMsg(item.content, item.mentioned_items || [], item.delivery, steerId);
};
const handlePromoteSteer = async (steerId) => {
if (!session_id.value || !steerId) return;
const item = findSteerQueueItem(steerId) || steerQueue.value.find((entry) => entry.client_id === steerId);
if (!item || item.delivery === 'inject') return;
if (item.pending || item.promoting || item.failed) return;
const requestSessionId = session_id.value;
item.promoting = true;
item.delivery = 'inject';
previewSteerMessage(messagesList, item);
scrollToBottom(true);
try {
// Promote needs the durable server id; a pending item only has the
// client-side one. isPending doesn't disable the button yet, so guard
// here to keep the queue handlers total.
if (item.pending) {
MessagePlugin.info(t('input.messages.steerPromoteFailed'));
return;
}
const res = await promoteSteerSession(session_id.value, item.steer_id);
const res = await promoteSteerSession(requestSessionId, item.steer_id);
if (session_id.value !== requestSessionId) return;
if (res?.status === 'already_injected') {
dropSteerQueueItem(item.steer_id);
const preview = messagesList.find(m => m.steer_id === item.steer_id);
if (preview) delete preview._steerPending;
MessagePlugin.info(t('input.messages.steerAlreadyInjected'));
return;
}
if (res?.status === 'new_run') {
if (isReplying.value || isStreaming.value) {
item.awaitingIdleSend = true;
item.delivery = 'after';
return;
}
const content = item.content;
const mentions = item.mentioned_items || [];
dropSteerQueueItem(steerId);
discardSteerPreview(messagesList, steerId);
await sendMsg(content, '', mentions);
return;
}
item.delivery = 'inject';
} catch (e) {
console.error('[Steer] Failed to promote queued message:', e);
if (session_id.value !== requestSessionId) return;
if (!findSteerQueueItem(steerId)) return;
item.delivery = 'after';
discardSteerPreview(messagesList, steerId);
MessagePlugin.error(e?.message || t('input.messages.steerPromoteFailed'));
} finally {
item.promoting = false;
@ -932,14 +983,16 @@ const handleRemoveSteer = async (steerId) => {
return;
}
if (res?.status === 'gone') {
discardSteerPreview(messagesList, steerId);
dropSteerQueueItem(steerId);
return;
}
if (res && res.removed === false) {
if (res && res.removed === false && !item.failed) {
MessagePlugin.error(t('input.messages.steerRemoveFailed'));
return;
}
}
discardSteerPreview(messagesList, steerId);
dropSteerQueueItem(steerId);
} catch (e) {
console.error('[Steer] Failed to remove queued message:', e);
@ -955,6 +1008,7 @@ const flushSteerAfterTurn = async (completedAssistantId) => {
const awaiting = steerQueue.value.filter((item) => item.awaitingIdleSend);
if (awaiting.length) {
const batch = awaiting.slice();
for (const item of batch) discardSteerPreview(messagesList, item.steer_id);
steerQueue.value = steerQueue.value.filter((item) => !item.awaitingIdleSend);
const first = batch[0];
await sendMsg(first.content, '', first.mentioned_items || []);
@ -967,7 +1021,7 @@ const flushSteerAfterTurn = async (completedAssistantId) => {
};
const attachSteerFollowUp = async (completedAssistantId) => {
const queued = steerQueue.value.slice();
const queued = steerQueue.value.filter(item => !item.failed);
if (!queued.length || attachingSteerFollowUp || !session_id.value) return;
const sessionId = session_id.value;
attachingSteerFollowUp = true;
@ -999,12 +1053,19 @@ const attachSteerFollowUp = async (completedAssistantId) => {
(q) => q.content === persisted.content && !claimed.has(q.steer_id)
);
if (queuedMatch) claimed.add(queuedMatch.steer_id);
messagesList.push({
const userRow = {
...persisted,
mentioned_items: queuedMatch?.mentioned_items?.length
? queuedMatch.mentioned_items
: persisted.mentioned_items,
});
};
const preview = queuedMatch && messagesList.find(m => m.steer_id === queuedMatch.steer_id && m._steerPending);
if (preview) {
delete preview._steerPending;
delete preview._steerFailed;
delete preview.isSteer;
Object.assign(preview, userRow);
} else messagesList.push(userRow);
}
// Rows that made it into the transcript are no longer queued.
for (const steerId of claimed) dropSteerQueueItem(steerId);
@ -1038,7 +1099,7 @@ const attachSteerFollowUp = async (completedAssistantId) => {
loading.value = false;
isReplying.value = false;
MessagePlugin.error(t('input.messages.steerFollowUpTimeout'));
} else if (steerQueue.value.length) {
} else if (steerQueue.value.some(item => !item.failed)) {
// startStream awaits the whole SSE. The follow-up's onTurnComplete
// therefore runs while attachingSteerFollowUp is still true and
// no-ops. Chain remaining after-items once that guard drops.
@ -1521,7 +1582,7 @@ onBeforeRouteUpdate((to, from, next) => {
&.is-embedded :deep(.answers-input) .t-textarea__inner {
width: 100% !important;
min-height: 48px !important;
padding: 10px 14px 48px 14px;
padding: 10px 14px;
}
}
@ -1721,6 +1782,8 @@ onBeforeRouteUpdate((to, from, next) => {
*/
.msg-item-wrapper {
contain: layout style;
&.is-empty-segment { display: none; }
&.is-steer-prefix { margin-bottom: -4px; }
}
.message-row {

View File

@ -84,7 +84,7 @@ test('follow-up attaches persisted users by request_id', () => {
// an explicit new_run (no live turn) starts a normal AgentQA.
test('steer lookup failure does not start a second turn', () => {
const start = source.indexOf('const handleSteerMsg = async')
const end = source.indexOf('const handlePromoteSteer = async', start)
const end = source.indexOf('const handleRetrySteer = async', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
const fn = source.slice(start, end)
@ -102,7 +102,7 @@ test('steer lookup failure does not start a second turn', () => {
test('new_run while a stream is live does not abort it', () => {
const start = source.indexOf('const handleSteerMsg = async')
const end = source.indexOf('const handlePromoteSteer = async', start)
const end = source.indexOf('const handleRetrySteer = async', start)
const fn = source.slice(start, end)
const newRun = fn.indexOf("if (res?.status === 'new_run')")
const catchIdx = fn.indexOf('} catch (e) {')
@ -130,7 +130,7 @@ test('remaining overlay after-items chain after a follow-up stream ends', () =>
// startStream awaits the whole SSE. The follow-up's onTurnComplete therefore
// runs while attachingSteerFollowUp is still true and would no-op. Remaining
// after-items have to be retried once that guard drops.
assert.match(finallyBlock, /steerQueue\.value\.length/)
assert.match(finallyBlock, /steerQueue\.value\.some\(item => !item\.failed\)/)
assert.match(finallyBlock, /void attachSteerFollowUp\(/)
})

View File

@ -0,0 +1,93 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { webcrypto } from 'node:crypto'
import vm from 'node:vm'
import test from 'node:test'
import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser } from '../../utils/steerStreamFork.ts'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const handlers = source.slice(source.indexOf('const dropSteerQueueItem ='), source.indexOf('let attachingSteerFollowUp ='))
const deferred = () => {
let resolve, reject
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
function harness(overrides = {}) {
const state = {
session_id: { value: 'session' }, currentAssistantMessageId: { value: 'assistant' },
isReplying: { value: true }, isStreaming: { value: true },
steerQueue: { value: [] }, messagesList: [], crypto: webcrypto,
previewSteerMessage, discardSteerPreview,
scrollToBottom() {}, sendMsg() { throw new Error('must not start a second run') },
MessagePlugin: { info() {}, error() {} }, t: key => key,
console: { error() {} }, ...overrides,
}
const actions = vm.runInNewContext(`${handlers}\n({ handleSteerMsg, handlePromoteSteer, handleRetrySteer, handleRemoveSteer })`, state)
return { ...actions, state }
}
test('default after stays below; promotion immediately moves it into the transcript', async () => {
const request = deferred(), promote = deferred()
const h = harness({ steerSession: () => request.promise, promoteSteerSession: () => promote.promise })
const sending = h.handleSteerMsg('queued')
const item = h.state.steerQueue.value[0]
assert.equal(item.delivery, 'after')
assert.equal(h.state.messagesList.length, 0)
request.resolve({ status: 'queued', steer_id: item.steer_id })
await sending
const promoting = h.handlePromoteSteer(item.steer_id)
assert.equal(item.delivery, 'inject')
assert.equal(h.state.steerQueue.value.filter(q => q.delivery === 'after').length, 0)
assert.equal(h.state.messagesList[0].content, 'queued')
promote.resolve({ status: 'queued' })
await promoting
})
test('direct inject shows immediately and an early SSE receipt does not duplicate it', async () => {
const request = deferred()
const h = harness({ steerSession: () => request.promise })
const assistant = { id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false }
h.state.messagesList.push(assistant)
const sending = h.handleSteerMsg('补充', [], 'inject')
const item = h.state.steerQueue.value[0]
assert.equal(h.state.messagesList[1].content, '补充')
forkAfterInjectedUser(h.state.messagesList, assistant, h.state.messagesList[1], item.steer_id)
h.state.steerQueue.value.splice(0, 1) // onUserMessageInjected receipt
request.resolve({ status: 'queued', steer_id: item.steer_id })
await sending
assert.equal(h.state.messagesList.filter(m => m.role === 'user').length, 1)
assert.equal(h.state.steerQueue.value.length, 0)
})
test('failed inject retries with the same ID and bubble', async () => {
const ids = []
const h = harness({ steerSession: async (...args) => {
ids.push(args[5])
if (ids.length === 1) throw new Error('network')
return { status: 'queued', steer_id: args[5] }
} })
await h.handleSteerMsg('补充', [], 'inject')
assert.equal(h.state.messagesList[0]._steerFailed, true)
await h.handleRetrySteer(ids[0])
assert.deepEqual(ids, [ids[0], ids[0]])
assert.equal(h.state.messagesList.length, 1)
assert.equal(h.state.messagesList[0]._steerFailed, undefined)
})
test('a lost HTTP response after a delivery receipt does not report a failed send', async () => {
const request = deferred(), errors = []
const h = harness({ steerSession: () => request.promise, MessagePlugin: { info() {}, error: message => errors.push(message) } })
const sending = h.handleSteerMsg('补充', [], 'inject')
h.state.steerQueue.value.splice(0, 1) // receipt already removed the item
request.reject(new Error('response lost'))
await sending
assert.equal(errors.length, 0)
})
test('failed promotion restores the after queue and removes only its optimistic row', async () => {
const h = harness({ promoteSteerSession: async () => { throw new Error('network') } })
h.state.steerQueue.value.push({ steer_id: 'queued', content: '补充', delivery: 'after' })
await h.handlePromoteSteer('queued')
assert.equal(h.state.steerQueue.value[0].delivery, 'after')
assert.equal(h.state.messagesList.length, 0)
})

View File

@ -731,12 +731,14 @@ func (e *AgentEngine) runReActIteration(
// Create agent step
step := types.AgentStep{
Iteration: state.CurrentRound,
Thought: response.Content,
ReasoningContent: response.ReasoningContent,
ToolCalls: make([]types.ToolCall, 0),
Timestamp: time.Now(),
UserMessagesBefore: state.PendingSteerMessages,
Iteration: state.CurrentRound,
Thought: response.Content,
ReasoningContent: response.ReasoningContent,
ToolCalls: make([]types.ToolCall, 0),
Timestamp: time.Now(),
}
state.PendingSteerMessages = nil
// If the request was cancelled while the LLM was streaming (e.g. the
// user pressed "stop"), the stream driver still returns a usable
@ -751,7 +753,7 @@ func (e *AgentEngine) runReActIteration(
if ctx.Err() != nil {
logger.Warnf(ctx, "[Agent][Round-%d] Context cancelled during LLM call; preserving partial step",
round)
if step.Thought != "" || len(step.ToolCalls) > 0 {
if step.Thought != "" || len(step.ToolCalls) > 0 || len(step.UserMessagesBefore) > 0 {
state.RoundSteps = append(state.RoundSteps, step)
}
return iterOutcomeBreak, nil
@ -766,6 +768,7 @@ func (e *AgentEngine) runReActIteration(
if verdict.emptyContent {
*emptyRetries++
if *emptyRetries <= maxEmptyResponseRetries {
state.PendingSteerMessages = step.UserMessagesBefore
logger.Warnf(ctx, "[Agent][Round-%d] Empty content with stop - retrying (%d/%d)",
round, *emptyRetries, maxEmptyResponseRetries)
*messagesPtr = append(*messagesPtr, chat.Message{
@ -799,6 +802,7 @@ func (e *AgentEngine) runReActIteration(
})
injected := e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
if injected > 0 {
verdict.step.IntermediateAnswer = true
state.RoundSteps = append(state.RoundSteps, verdict.step)
if !e.withinIterationBudget(nextRound) {
e.steerOverruns++

View File

@ -192,6 +192,14 @@ func (e *AgentEngine) handleMaxIterations(
func (e *AgentEngine) emitCompletionEvent(
ctx context.Context, state *types.AgentState, sessionID, messageID string, startTime time.Time,
) {
steps := state.RoundSteps
if len(state.PendingSteerMessages) > 0 {
// A stop or model failure can arrive after delivery but before the next
// response exists. Preserve that boundary without inventing an answer.
steps = append(append([]types.AgentStep(nil), steps...), types.AgentStep{
Iteration: state.CurrentRound, UserMessagesBefore: state.PendingSteerMessages,
})
}
// Convert knowledge refs to interface{} slice for event data
knowledgeRefsInterface := make([]interface{}, 0, len(state.KnowledgeRefs))
for _, ref := range state.KnowledgeRefs {
@ -205,7 +213,7 @@ func (e *AgentEngine) emitCompletionEvent(
Data: event.AgentCompleteData{
FinalAnswer: state.FinalAnswer,
KnowledgeRefs: knowledgeRefsInterface,
AgentSteps: state.RoundSteps, // Include detailed execution steps for message storage
AgentSteps: steps,
Usage: turnUsage(state),
TotalSteps: len(state.RoundSteps),
TotalDurationMs: time.Since(startTime).Milliseconds(),

View File

@ -390,6 +390,7 @@ func BuildSystemPromptWithOptions(
language = options.Language
}
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime, language)
basePrompt += "\n\n" + steerGuidance
if options != nil {
basePrompt += formatGroundingGuidance(options.SelectedTools)
@ -406,6 +407,14 @@ func BuildSystemPromptWithOptions(
return basePrompt
}
// Apply to custom prompts too: mid-run delivery is a harness capability.
const steerGuidance = "<steering_guidance>\n" +
"Messages in <steer_message> guide the task in progress. Apply them in context; " +
"respond briefly when appropriate, then continue unfinished work. Preserve unfinished objectives, " +
"accepted constraints and useful tool results unless explicitly changed. " +
"Acknowledging guidance alone does not complete the task. Follow explicit cancellation or replacement requests. " +
"Hide delivery tags. Untagged subsequent requests are ordinary user messages.\n</steering_guidance>"
// GetPureAgentSystemPrompt returns the Pure Agent system prompt from config templates.
// The template must be defined in config/prompt_templates/agent_system_prompt.yaml
// with mode "pure". Returns empty string if config is nil or template not found.

View File

@ -66,7 +66,8 @@ func (e *AgentEngine) drainSteerMessages(
logger.Warnf(ctx, "[Agent] Steer persist failed for %s, leaving event pending", steerID)
continue
}
*messagesPtr = append(*messagesPtr, chat.Message{Role: "user", Content: content})
*messagesPtr = append(*messagesPtr, chat.Message{Role: "user", Content: types.SteerMessageContent(content)})
state.PendingSteerMessages = append(state.PendingSteerMessages, userMessageID)
_ = e.eventBus.Emit(ctx, event.Event{
ID: generateEventID("injected"),
Type: event.EventUserMessageInjected,

View File

@ -98,9 +98,10 @@ func TestDrainSteerMessagesInjectsIntoTail(t *testing.T) {
require.Len(t, messages, 5)
assert.Equal(t, "user", messages[4].Role)
assert.Equal(t, "再补充一点:也对比一下成本", messages[4].Content)
assert.Equal(t, types.SteerMessageContent("再补充一点:也对比一下成本"), messages[4].Content)
// Tool result pairing is untouched — the tool message stays where it was.
assert.Equal(t, "tool", messages[3].Role)
assert.Equal(t, []string{"user-row-for-再补充一点:也对比一下成本"}, state.PendingSteerMessages)
require.Len(t, sink.persisted, 1)
assert.Equal(t, "再补充一点:也对比一下成本", sink.persisted[0])
@ -136,8 +137,8 @@ func TestDrainSteerMessagesEmptyAndOffset(t *testing.T) {
}
engine.drainSteerMessages(context.Background(), state, &messages, "sess", "msg")
assert.Len(t, messages, 3)
assert.Equal(t, "first", messages[1].Content)
assert.Equal(t, "second", messages[2].Content)
assert.Equal(t, types.SteerMessageContent("first"), messages[1].Content)
assert.Equal(t, types.SteerMessageContent("second"), messages[2].Content)
require.Len(t, sink.persisted, 2)
engine.drainSteerMessages(context.Background(), state, &messages, "sess", "msg")
@ -178,7 +179,7 @@ func TestDrainSteerMessagesBlankContentSkipped(t *testing.T) {
engine.drainSteerMessages(context.Background(), state, &messages, "sess", "msg")
require.Len(t, messages, 2)
assert.Equal(t, "real instruction", messages[1].Content)
assert.Equal(t, types.SteerMessageContent("real instruction"), messages[1].Content)
require.Len(t, sink.persisted, 1)
}
@ -206,14 +207,15 @@ func TestExecuteLoopInjectsBeforeNextLLMCall(t *testing.T) {
engine := newTestEngine(t, model)
engine.eventBus = event.NewEventBus()
sink := &fakeSteerSink{}
engine.SetSteerSink(sink)
// Simulate the user queueing a message while round 1 runs: it is in the
// queue before the loop's second drain point executes.
sink.queued = []map[string]interface{}{
steerEntry("s1", "focus on the cost angle"),
// Deliver only after round 1 so this exercises continuation with existing
// tool results, rather than adding guidance before any work has started.
sink := &delayedSteerSink{
fakeSteerSink: fakeSteerSink{
queued: []map[string]interface{}{steerEntry("s1", "focus on the cost angle")},
},
hideUntil: 2,
}
engine.SetSteerSink(sink)
engine.toolRegistry = agentRegistryForTest(t, "counting_tool")
@ -230,20 +232,28 @@ func TestExecuteLoopInjectsBeforeNextLLMCall(t *testing.T) {
require.NoError(t, err)
require.Len(t, model.calls, 2)
// Round 2's call must contain the injected steer text. SanitizeMessages
// merges consecutive same-role messages, so the injected user message
// may be concatenated onto the original "start" user turn — that is the
// desired end state (the model reads it as the user adding instructions
// mid-task).
for _, msg := range model.calls[0] {
assert.NotContains(t, msg.Content, "focus on the cost angle")
}
// Continue with the original task and tool result exactly once; steering
// needs neither a restarted run nor an extra model call to interpret it.
second := model.calls[1]
found := false
steerCount, taskCount, toolCount := 0, 0, 0
for _, msg := range second {
if msg.Role == "user" && msg.Content == "start" {
taskCount++
}
if msg.Role == "tool" && msg.ToolCallID == "tc1" {
toolCount++
}
if msg.Role == "user" && strings.Contains(msg.Content, "focus on the cost angle") {
found = true
break
steerCount++
assert.Contains(t, msg.Content, "<continue_task>")
}
}
assert.True(t, found, "injected steer text missing from round 2 LLM call: %+v", second)
assert.Equal(t, 1, taskCount)
assert.Equal(t, 1, toolCount)
assert.Equal(t, 1, steerCount)
require.Len(t, sink.persisted, 1)
}
@ -486,3 +496,10 @@ func agentRegistryForTest(t *testing.T, name string) *agenttools.ToolRegistry {
registry.RegisterTool(tool)
return registry
}
func TestSteerGuidanceAppliesToCustomAgentPrompt(t *testing.T) {
prompt := BuildSystemPromptWithOptions(nil, false, nil, "Custom agent instructions.")
assert.Contains(t, prompt, "Custom agent instructions.")
assert.Contains(t, prompt, steerGuidance)
assert.Contains(t, prompt, "Preserve unfinished objectives")
}

View File

@ -18,10 +18,11 @@ import (
const mcpDiscoveryDescription = "" +
"Discover authorized MCP tools without loading every schema. If a server_id is " +
"already listed in this tool's source summaries, call list_tools or describe " +
"already listed in this tool's source summaries, call list_tools or search " +
"directly; do not call list_servers first. Use list_servers only when this " +
"description says further services are available, or to paginate. After you " +
"have a server_id, list_tools (or search), then describe an exact tool. " +
"description says further services are available, or to paginate. Describe tools, " +
"not servers; use describe directly only with an exact tool name already returned " +
"by this directory. Never infer tool names from server summaries. " +
"Server IDs and tool names must come from this directory. Only describe returns " +
"a callable tool_ref. Call call_mcp_tool with that tool_ref and arguments " +
"matching input_schema. Wait for each discovery result before issuing dependent calls. " +

View File

@ -137,22 +137,39 @@ func buildTurnBodyMessages(assistant *types.Message, midRunUsers []*types.Messag
}
out := make([]chat.Message, 0, len(assistant.AgentSteps)*2+len(midRunUsers)+1)
usersByID := make(map[string]*types.Message, len(midRunUsers))
for _, user := range midRunUsers {
usersByID[user.ID] = user
}
hasBoundaries := false
for _, step := range assistant.AgentSteps {
hasBoundaries = hasBoundaries || len(step.UserMessagesBefore) > 0
}
appendUser := func(user *types.Message) {
msg := buildUserHistoryMessage(user)
msg.Content = types.SteerMessageContent(msg.Content)
out = append(out, msg)
delete(usersByID, user.ID)
}
next := 0
for _, step := range assistant.AgentSteps {
stepMsgs := buildAgentStepMessages(step)
if len(stepMsgs) == 0 {
continue
for _, id := range step.UserMessagesBefore {
if user := usersByID[id]; user != nil {
appendUser(user)
}
}
for next < len(midRunUsers) &&
for !hasBoundaries && next < len(midRunUsers) &&
!step.Timestamp.IsZero() &&
midRunUsers[next].CreatedAt.Before(step.Timestamp) {
out = append(out, buildUserHistoryMessage(midRunUsers[next]))
appendUser(midRunUsers[next])
next++
}
out = append(out, stepMsgs...)
out = append(out, buildAgentStepMessages(step)...)
}
for ; next < len(midRunUsers); next++ {
out = append(out, buildUserHistoryMessage(midRunUsers[next]))
for _, user := range midRunUsers {
if usersByID[user.ID] != nil {
appendUser(user)
}
}
if final := finalAnswerHistoryMessage(assistant); final != nil {
@ -203,6 +220,9 @@ func buildAssistantHistoryMessages(m *types.Message) []chat.Message {
func buildAgentStepMessages(step types.AgentStep) []chat.Message {
nonTerminalCalls := filterNonTerminalToolCalls(step.ToolCalls)
if len(nonTerminalCalls) == 0 {
if step.IntermediateAnswer && strings.TrimSpace(step.Thought) != "" {
return []chat.Message{{Role: "assistant", Content: step.Thought, ReasoningContent: step.ReasoningContent}}
}
return nil
}
assistantMsg := chat.Message{

View File

@ -356,7 +356,7 @@ func TestBuildTurnBodyMessages_KeepsMidRunUsersInPlace(t *testing.T) {
// The injected message belongs between the round it interrupted and the
// round it caused, not bolted onto either end.
assert.Equal(t, chat.Message{Role: "user", Content: "also check B"}, got[2])
assert.Equal(t, chat.Message{Role: "user", Content: types.SteerMessageContent("also check B")}, got[2])
assert.Equal(t, "assistant", got[3].Role)
assert.Equal(t, "tool", got[4].Role)
@ -390,7 +390,7 @@ func TestBuildTurnBodyMessages_LateMidRunUserPrecedesAnswer(t *testing.T) {
got := buildTurnBodyMessages(assistant, midRun)
require.Len(t, got, 4)
assert.Equal(t, chat.Message{Role: "user", Content: "and keep it short"}, got[2])
assert.Equal(t, chat.Message{Role: "user", Content: types.SteerMessageContent("and keep it short")}, got[2])
assert.Equal(t, chat.Message{Role: "assistant", Content: "Here you go."}, got[3])
}
@ -474,3 +474,27 @@ func TestMCPProxyHistoryRetainsProtocolCallAndTarget(t *testing.T) {
require.Contains(t, history[0].ToolCalls[0].Function.Arguments, "tool_ref")
require.Equal(t, "proxy-id", history[1].ToolCallID)
}
func TestBuildTurnBodyMessages_ReplaysExplicitBoundariesAndIntermediateAnswers(t *testing.T) {
// Identical (and deliberately misleading) timestamps must not move updates
// ahead of work the model already did. IDs, not text, distinguish repeats.
now := time.Now()
users := []*types.Message{
{ID: "u2", Content: "revise", CreatedAt: now},
{ID: "u1", Content: "revise", CreatedAt: now},
}
assistant := &types.Message{Content: "final", AgentSteps: types.AgentSteps{
{Thought: "first draft", IntermediateAnswer: true, Timestamp: now.Add(time.Second)},
{Thought: "second draft", IntermediateAnswer: true, UserMessagesBefore: []string{"u1"}},
{Thought: "final", UserMessagesBefore: []string{"u2"}},
}}
got := buildTurnBodyMessages(assistant, users)
require.Len(t, got, 5)
assert.Equal(t, []chat.Message{
{Role: "assistant", Content: "first draft"},
{Role: "user", Content: types.SteerMessageContent("revise")},
{Role: "assistant", Content: "second draft"},
{Role: "user", Content: types.SteerMessageContent("revise")},
{Role: "assistant", Content: "final"},
}, got)
}

View File

@ -39,9 +39,13 @@ const steerDataUserMessageID = "user_message_id"
// SteerMessageRequest is the payload of POST /sessions/:session_id/steer.
type SteerMessageRequest struct {
Query string `json:"query" binding:"required"`
MentionedItems []MentionedItemRequest `json:"mentioned_items,omitempty"`
Channel string `json:"channel,omitempty"`
// Optional for older clients. New clients pin delivery to the run they see
// and supply a stable ID so a consume event may precede the HTTP response.
ExpectedAssistantMessageID string `json:"expected_assistant_message_id,omitempty"`
SteerID string `json:"steer_id,omitempty"`
Query string `json:"query" binding:"required"`
MentionedItems []MentionedItemRequest `json:"mentioned_items,omitempty"`
Channel string `json:"channel,omitempty"`
// Delivery is "after" (default) or "inject". See the constants above.
Delivery string `json:"delivery,omitempty"`
}
@ -495,6 +499,27 @@ func (h *Handler) SteerMessage(c *gin.Context) {
if !ok {
return
}
if req.SteerID != "" && req.ExpectedAssistantMessageID != "" {
previous, _, err := h.streamManager.GetSteerEvents(ctx, sessionID, req.ExpectedAssistantMessageID, 0)
if err != nil {
_ = c.Error(errors.NewServiceUnavailableError("Failed to look up previous delivery"))
return
}
for _, delivered := range previous {
if delivered.ID == req.SteerID && steerEventConsumed(delivered) {
if delivered.Content != query {
_ = c.Error(errors.NewConflictError("steer_id already belongs to another message"))
return
}
c.JSON(200, gin.H{"success": true, "status": "already_injected", "steer_id": req.SteerID})
return
}
}
}
if req.ExpectedAssistantMessageID != "" && assistantID != "" && req.ExpectedAssistantMessageID != assistantID {
_ = c.Error(errors.NewConflictError("The active turn changed; retry the message"))
return
}
if assistantID == "" {
// No run is live: the message starts a brand-new run via the normal
// AgentQA path. The request returns immediately and the SSE stream
@ -513,13 +538,33 @@ func (h *Handler) SteerMessage(c *gin.Context) {
_ = c.Error(errors.NewInternalServerError("Failed to check steer queue"))
return
}
steerID := req.SteerID
if steerID == "" {
steerID = uuid.New().String()
} else if _, err := uuid.Parse(steerID); err != nil {
_ = c.Error(errors.NewBadRequestError("invalid steer_id"))
return
}
for _, existingEvent := range existing {
if existingEvent.ID == steerID {
if existingEvent.Content != query {
_ = c.Error(errors.NewConflictError("steer_id already belongs to another message"))
return
}
c.JSON(200, gin.H{
"success": true, "status": "queued", "steer_id": steerID,
"assistant_message_id": assistantID, "delivery": steerDeliveryOfEvent(existingEvent),
})
return
}
}
pending := len(selectSteerBacklog(existing, nil))
if pending >= maxSteerQueueDepth {
_ = c.Error(errors.NewBadRequestError("too many queued messages for the running turn"))
return
}
steerID := uuid.New().String()
evt := steerEvent(steerID, query, convertMentionedItems(req.MentionedItems), req.Channel)
evt.Data["delivery"] = delivery
if err := h.streamManager.AppendSteerEvents(ctx, sessionID, assistantID,

View File

@ -460,3 +460,31 @@ func TestRebindSteerKeepsEventWhenAppendFails(t *testing.T) {
require.Len(t, old, 1)
assert.Equal(t, "late-1", old[0].ID)
}
func TestSteerMessageRejectsDifferentExpectedRun(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{msg: &types.Message{ID: "new-run", IsCompleted: false}},
streamManager: &steerLiveRunLookupStub{assistantID: "new-run"},
}
w := postSteer(t, newSteerLiveRunRouter(h),
`{"query":"keep going","delivery":"inject","expected_assistant_message_id":"old-run"}`)
assert.Equal(t, http.StatusConflict, w.Code)
}
func TestSteerRetryFindsConsumedReceiptAfterRunCompleted(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
id := "7c2f7062-c80a-480e-ac21-c509b6210936"
evt := steerEventWithDelivery(id, "more", steerDeliveryInject)
evt.Data[steerDataConsumed] = true
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess-1", "old-run", []interfaces.StreamEvent{evt}))
h := &Handler{
sessionService: &steerOwnedSessionStub{}, messageService: &steerMessageLookupStub{}, streamManager: mgr,
}
w := postSteer(t, newSteerLiveRunRouter(h),
`{"query":"more","delivery":"inject","expected_assistant_message_id":"old-run","steer_id":"`+id+`"}`)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "already_injected")
assert.NotContains(t, w.Body.String(), "new_run")
}

View File

@ -137,7 +137,15 @@ func (m *MemoryStreamManager) AppendSteerEvents(
stream.mu.Lock()
defer stream.mu.Unlock()
seen := make(map[string]bool, len(stream.steerEvents))
for _, event := range stream.steerEvents {
seen[event.ID] = true
}
for i := range events {
if events[i].ID != "" && seen[events[i].ID] {
continue
}
seen[events[i].ID] = true
if events[i].Timestamp.IsZero() {
events[i].Timestamp = time.Now()
}

View File

@ -150,3 +150,35 @@ func TestMemorySetLiveRunRejectsADifferentAssistant(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "assist-2", id)
}
func TestAppendSteerEventsDeduplicatesClientIDs(t *testing.T) {
redisManager, _ := newTestRedisStreamManager(t, time.Hour)
for name, manager := range map[string]interfaces.StreamManager{
"memory": NewMemoryStreamManager(), "redis": redisManager,
} {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
evt := interfaces.StreamEvent{
ID: "same-client-id", Content: "do this next", Data: map[string]interface{}{"delivery": "after"},
}
errs := make(chan error, 8)
for i := 0; i < 8; i++ {
go func() { errs <- manager.AppendSteerEvents(ctx, "session", "run", []interfaces.StreamEvent{evt}) }()
}
for i := 0; i < 8; i++ {
require.NoError(t, <-errs)
}
events, _, err := manager.GetSteerEvents(ctx, "session", "run", 0)
require.NoError(t, err)
require.Len(t, events, 1)
_, err = manager.UpdateSteerEventData(ctx, "session", "run", evt.ID,
map[string]interface{}{"consumed": true})
require.NoError(t, err)
require.NoError(t, manager.AppendSteerEvents(ctx, "session", "run", []interfaces.StreamEvent{evt}))
events, _, err = manager.GetSteerEvents(ctx, "session", "run", 0)
require.NoError(t, err)
require.Len(t, events, 1)
require.Equal(t, true, events[0].Data["consumed"])
})
}
}

View File

@ -170,16 +170,33 @@ func (r *RedisStreamManager) AppendSteerEvents(
payloads = append(payloads, eventJSON)
}
pipe := r.client.Pipeline()
pipe.RPush(ctx, key, payloads...)
pipe.Expire(ctx, key, r.ttl)
pipe.Expire(ctx, r.buildLiveRunKey(sessionID), r.ttl)
if _, err := pipe.Exec(ctx); err != nil {
// Deduplication is atomic with append: a timed-out POST can be retried
// while another replica is still accepting the same client ID.
args := append([]interface{}{int64(r.ttl / time.Second)}, payloads...)
if err := steerAppendUnique.Run(ctx, r.client, []string{key}, args...).Err(); err != nil {
return fmt.Errorf("failed to append steer events to Redis: %w", err)
}
_ = r.client.Expire(ctx, r.buildLiveRunKey(sessionID), r.ttl).Err()
return nil
}
var steerAppendUnique = redis.NewScript(`
local seen = {}
for _, raw in ipairs(redis.call('LRANGE', KEYS[1], 0, -1)) do
local ok, event = pcall(cjson.decode, raw)
if ok and event.id then seen[event.id] = true end
end
for i = 2, #ARGV do
local event = cjson.decode(ARGV[i])
if not event.id or event.id == '' or not seen[event.id] then
redis.call('RPUSH', KEYS[1], ARGV[i])
if event.id then seen[event.id] = true end
end
end
redis.call('EXPIRE', KEYS[1], ARGV[1])
return 1
`)
// GetSteerEvents drains the steer sub-list starting fromOffset.
func (r *RedisStreamManager) GetSteerEvents(
ctx context.Context,

View File

@ -413,6 +413,12 @@ func IsPipelineToolCallID(id string) bool {
type AgentStep struct {
Iteration int `json:"iteration"` // Iteration number (0-indexed)
Thought string `json:"thought"` // LLM's reasoning/thinking (Think phase)
// UserMessagesBefore records consumed steer rows in delivery order, before
// this model response. Unlike timestamps, this remains unambiguous on replay.
UserMessagesBefore []string `json:"user_messages_before,omitempty"`
// IntermediateAnswer preserves a plain answer followed by a loop-end steer.
// The canonical final answer is still stored in Message.Content.
IntermediateAnswer bool `json:"intermediate_answer,omitempty"`
// ReasoningContent stores the OpenAI-protocol reasoning_content emitted by the
// model in this round. Persisted on AgentStep so cross-turn replay can put it
// back on the assistant message — required by MiMo / DeepSeek V3.2+ thinking
@ -439,12 +445,13 @@ func (s *AgentStep) GetObservations() []string {
// AgentState tracks the execution state of an agent across iterations
type AgentState struct {
CurrentRound int `json:"current_round"` // Current round number
RoundSteps []AgentStep `json:"round_steps"` // All steps taken so far in the current round
IsComplete bool `json:"is_complete"` // Whether agent has finished
FinalAnswer string `json:"final_answer"` // The final answer to the query
KnowledgeRefs []*SearchResult `json:"knowledge_refs"` // Collected knowledge references
TurnUsage TokenUsage `json:"turn_usage"` // LLM token usage accumulated across every round of this turn
PendingSteerMessages []string `json:"-"`
CurrentRound int `json:"current_round"` // Current round number
RoundSteps []AgentStep `json:"round_steps"` // All steps taken so far in the current round
IsComplete bool `json:"is_complete"` // Whether agent has finished
FinalAnswer string `json:"final_answer"` // The final answer to the query
KnowledgeRefs []*SearchResult `json:"knowledge_refs"` // Collected knowledge references
TurnUsage TokenUsage `json:"turn_usage"` // LLM usage accumulated across this turn
}
// FunctionDefinition represents a function definition for LLM function calling

View File

@ -4,6 +4,14 @@ import (
"context"
)
// SteerMessageContent adds delivery context only to model input. The persisted
// user message and the UI always retain the user's original text.
func SteerMessageContent(content string) string {
return "<steer_message>\n" + content + "\n</steer_message>\n<continue_task>\n" +
"This is guidance for the task in progress. Apply it and continue unfinished work " +
"unless the user explicitly changes or cancels the task.\n</continue_task>"
}
// SteerSink abstracts the handler-side back half of mid-run message
// injection: draining the queued steer events and persisting accepted
// messages. Declared in types (not agent/interfaces) because both packages

View File

@ -0,0 +1,26 @@
package types
import (
"strings"
"testing"
)
func TestSteerMessageContentKeepsContinuationHintSmall(t *testing.T) {
content := strings.Repeat("补充说明\n", 1000)
wrapped := SteerMessageContent(content)
if strings.Count(wrapped, content) != 1 {
t.Fatal("user update must appear exactly once")
}
if len(wrapped)-len(content) > 210 {
t.Fatal("steering delivery overhead exceeded 210 bytes")
}
if !strings.Contains(wrapped, "guidance for the task in progress") ||
!strings.Contains(wrapped, "explicitly changes or cancels") {
t.Fatal("steering must preserve the task while respecting explicit redirection")
}
for _, marker := range []string{"<steer_message>", "</steer_message>", "<continue_task>", "</continue_task>"} {
if strings.Count(wrapped, marker) != 1 {
t.Fatalf("expected a single %s", marker)
}
}
}