比较提交
没有共同的提交。529357523c839a3ea2f35b048be40136a122380c 和 03b99efda83559f21124d34e24faaf64a48a08d6 的历史完全不同。
529357523c
...
03b99efda8
共有 3 个文件被更改,包括 9 次插入 和 185 次删除
|
|
@ -222,12 +222,6 @@ struct PendingMedia {
|
|||
media_type: String,
|
||||
}
|
||||
|
||||
/// Separates a message id from its reopen index.
|
||||
///
|
||||
/// Content that arrives after `complete` reuses the server's message id, so
|
||||
/// the reopened message needs a suffix the client will read as a new message.
|
||||
const REOPEN_SEPARATOR: &str = "#part-";
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AstrBotStreamMapper {
|
||||
server_instance_id: String,
|
||||
|
|
@ -239,17 +233,6 @@ pub struct AstrBotStreamMapper {
|
|||
sequence: u64,
|
||||
saw_assistant_delta: bool,
|
||||
pending_media: Option<PendingMedia>,
|
||||
/// True once the active message has been completed.
|
||||
///
|
||||
/// AstrBot can deliver content *after* the `complete` frame — an observed
|
||||
/// stream ended `complete(272 chars)` → `image` → `attachment_saved` →
|
||||
/// `end`, all under one message id. Re-accumulating that late content under
|
||||
/// the finished id made `end` emit a second completion whose body was the
|
||||
/// attachment marker alone, and the client overwrote the whole reply with
|
||||
/// it. Late content therefore has to open a message of its own.
|
||||
active_message_completed: bool,
|
||||
/// Distinguishes the ids of messages reopened after a completion.
|
||||
reopen_index: u32,
|
||||
}
|
||||
|
||||
impl AstrBotStreamMapper {
|
||||
|
|
@ -357,14 +340,14 @@ impl AstrBotStreamMapper {
|
|||
let mut events = Vec::new();
|
||||
if let Some(message_id) = frame.message_id {
|
||||
if self
|
||||
.active_base_id()
|
||||
.is_some_and(|current| current != message_id)
|
||||
.active_message_id
|
||||
.as_ref()
|
||||
.is_some_and(|current| current != &message_id)
|
||||
{
|
||||
events = self.complete_if_needed(FinishReason::Stop);
|
||||
self.accumulated.clear();
|
||||
self.delta_index = 0;
|
||||
self.saw_assistant_delta = false;
|
||||
self.active_message_completed = false;
|
||||
}
|
||||
self.active_message_id = Some(message_id);
|
||||
}
|
||||
|
|
@ -401,8 +384,9 @@ impl AstrBotStreamMapper {
|
|||
}
|
||||
if let Some(message_id) = frame.message_id.clone() {
|
||||
if self
|
||||
.active_base_id()
|
||||
.is_some_and(|current| current != message_id)
|
||||
.active_message_id
|
||||
.as_ref()
|
||||
.is_some_and(|current| current != &message_id)
|
||||
{
|
||||
// New assistant message id: complete the previous accumulation first.
|
||||
let mut events = self.complete_if_needed(FinishReason::Stop);
|
||||
|
|
@ -410,7 +394,6 @@ impl AstrBotStreamMapper {
|
|||
self.accumulated.clear();
|
||||
self.delta_index = 0;
|
||||
self.saw_assistant_delta = false;
|
||||
self.active_message_completed = false;
|
||||
events.extend(self.emit_delta(chunk));
|
||||
return events;
|
||||
}
|
||||
|
|
@ -422,15 +405,15 @@ impl AstrBotStreamMapper {
|
|||
fn map_complete(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
|
||||
if let Some(message_id) = frame.message_id.clone() {
|
||||
if self
|
||||
.active_base_id()
|
||||
.is_some_and(|current| current != message_id)
|
||||
.active_message_id
|
||||
.as_ref()
|
||||
.is_some_and(|current| current != &message_id)
|
||||
{
|
||||
let mut events = self.complete_if_needed(FinishReason::Stop);
|
||||
self.active_message_id = Some(message_id);
|
||||
self.accumulated.clear();
|
||||
self.delta_index = 0;
|
||||
self.saw_assistant_delta = false;
|
||||
self.active_message_completed = false;
|
||||
let final_text = text_from_value(&frame.data).unwrap_or_default();
|
||||
if !final_text.is_empty() {
|
||||
self.accumulated = final_text;
|
||||
|
|
@ -450,41 +433,10 @@ impl AstrBotStreamMapper {
|
|||
self.complete_if_needed(FinishReason::Stop)
|
||||
}
|
||||
|
||||
/// The active id without any reopen suffix, for comparing against a frame.
|
||||
fn active_base_id(&self) -> Option<&str> {
|
||||
self.active_message_id
|
||||
.as_deref()
|
||||
.map(|id| id.split_once(REOPEN_SEPARATOR).map_or(id, |(head, _)| head))
|
||||
}
|
||||
|
||||
/// Starts a new message after the active one has already been completed.
|
||||
///
|
||||
/// The server keeps the same message id for content that arrives after
|
||||
/// `complete`, so the id has to be made distinct here or the client merges
|
||||
/// the late content into the finished message and overwrites it.
|
||||
fn reopen_message(&mut self) {
|
||||
let base = self
|
||||
.active_base_id()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| self.stream_id.clone());
|
||||
self.reopen_index = self.reopen_index.saturating_add(1);
|
||||
self.active_message_id = Some(format!(
|
||||
"{base}{REOPEN_SEPARATOR}{index}",
|
||||
index = self.reopen_index
|
||||
));
|
||||
self.accumulated.clear();
|
||||
self.delta_index = 0;
|
||||
self.saw_assistant_delta = false;
|
||||
self.active_message_completed = false;
|
||||
}
|
||||
|
||||
fn emit_delta(&mut self, chunk: String) -> Vec<GatewayEvent> {
|
||||
if chunk.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
if self.active_message_completed {
|
||||
self.reopen_message();
|
||||
}
|
||||
self.accumulated.push_str(&chunk);
|
||||
self.saw_assistant_delta = true;
|
||||
let index = self.delta_index;
|
||||
|
|
@ -505,7 +457,6 @@ impl AstrBotStreamMapper {
|
|||
let content = std::mem::take(&mut self.accumulated);
|
||||
self.saw_assistant_delta = false;
|
||||
self.delta_index = 0;
|
||||
self.active_message_completed = true;
|
||||
let message_id = self.active_message_id.clone();
|
||||
vec");
|
||||
}
|
||||
|
||||
/// Replays the frame order of a captured stream that destroyed its own reply.
|
||||
///
|
||||
/// The server sent `complete` and then continued: `image`,
|
||||
/// `attachment_saved`, `end`, all under the same message id. The attachment
|
||||
/// marker re-accumulated onto the just-emptied buffer and `end` emitted a
|
||||
/// second completion for the finished message whose body was the marker
|
||||
/// alone, so the client replaced 272 characters of reply with an image tag.
|
||||
#[test]
|
||||
fn content_after_complete_does_not_overwrite_the_finished_message() {
|
||||
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a");
|
||||
let mut events = Vec::new();
|
||||
for line in [
|
||||
r#"data: {"type":"plain","data":"完整的回复正文","streaming":true,"message_id":"m1"}"#,
|
||||
r#"data: {"type":"complete","data":"完整的回复正文","message_id":"m1"}"#,
|
||||
r#"data: {"type":"image","data":"[IMAGE]sticker.png","message_id":"m1"}"#,
|
||||
r#"data: {"type":"attachment_saved","data":{"id":"att-9","type":"image"},"message_id":"m1"}"#,
|
||||
] {
|
||||
events.extend(mapper.push_line(line).expect("frame"));
|
||||
}
|
||||
events.extend(mapper.finish_stream());
|
||||
|
||||
let completions: Vec<(&str, &str)> = events
|
||||
.iter()
|
||||
.filter_map(|event| match &event.body {
|
||||
GatewayEventBody::MessageCompleted(payload) => Some((
|
||||
event.metadata.message_id.as_deref().unwrap_or("<none>"),
|
||||
payload.content.as_deref().unwrap_or(""),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(completions.len(), 2, "{completions:?}");
|
||||
assert_eq!(completions[0], ("m1", "完整的回复正文"));
|
||||
// The attachment lands in a message of its own, leaving the reply intact.
|
||||
assert_eq!(completions[1].1, "");
|
||||
assert_ne!(
|
||||
completions[1].0, "m1",
|
||||
"the attachment must not reuse the finished message id"
|
||||
);
|
||||
assert!(completions[1].0.starts_with("m1#part-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_streams_do_not_reuse_event_ids() {
|
||||
// Regression: a client keeps one deduplicator for its whole lifetime,
|
||||
|
|
|
|||
|
|
@ -136,44 +136,6 @@ it("releases every listener on unmount", async () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("follows the newest message, and stops once the reader scrolls up", async () => {
|
||||
// jsdom has no scrollTo, which is also why the component falls back to
|
||||
// scrollTop. Install a spy so the intent is observable either way.
|
||||
const scrollTo = vi.fn();
|
||||
Object.defineProperty(Element.prototype, "scrollTo", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: scrollTo,
|
||||
});
|
||||
|
||||
render(<ChatPanel fixedSlot="companion" />);
|
||||
await flushListen();
|
||||
scrollTo.mockClear();
|
||||
|
||||
emitTauriEvent("connection-runtime-event", deltaEvent("第一段"));
|
||||
await waitFor(() => expect(scrollTo).toHaveBeenCalled());
|
||||
|
||||
// Scrolling away from the bottom must stop the view from being yanked back.
|
||||
const list = document.querySelector(".chat-message-list") as HTMLElement;
|
||||
Object.defineProperty(list, "scrollHeight", {
|
||||
value: 1000,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(list, "clientHeight", {
|
||||
value: 200,
|
||||
configurable: true,
|
||||
});
|
||||
list.scrollTop = 0;
|
||||
fireEvent.scroll(list);
|
||||
|
||||
scrollTo.mockClear();
|
||||
emitTauriEvent("connection-runtime-event", deltaEvent("第二段"));
|
||||
await waitFor(() => expect(screen.getByText(/第二段/)).toBeInTheDocument());
|
||||
expect(scrollTo).not.toHaveBeenCalled();
|
||||
|
||||
delete (Element.prototype as unknown as Record<string, unknown>).scrollTo;
|
||||
});
|
||||
|
||||
it("keeps drafts on the slot they were typed in", async () => {
|
||||
await renderWithTabs();
|
||||
|
||||
|
|
|
|||
|
|
@ -102,13 +102,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
companion: false,
|
||||
operations: false,
|
||||
});
|
||||
const messageListRef = useRef<HTMLDivElement | null>(null);
|
||||
/// Whether the view should follow new content.
|
||||
///
|
||||
/// Starts true so opening a conversation lands on the newest message, and
|
||||
/// stays true until the reader scrolls up — following unconditionally would
|
||||
/// yank someone out of the history they were reading.
|
||||
const followTail = useRef(true);
|
||||
const speechRecognition = useRef<{
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
|
|
@ -171,38 +164,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
setSlotError((current) => ({ ...current, [slot]: message }));
|
||||
};
|
||||
|
||||
/// Distance from the bottom that still counts as "reading the newest".
|
||||
const TAIL_THRESHOLD_PX = 80;
|
||||
|
||||
const scrollToTail = useCallback((behavior: ScrollBehavior) => {
|
||||
const list = messageListRef.current;
|
||||
if (!list) return;
|
||||
// `scrollTo` carries the smooth behaviour, but it is not universally
|
||||
// available — jsdom has no implementation at all — so fall back to the
|
||||
// property, which every engine supports.
|
||||
if (typeof list.scrollTo === "function") {
|
||||
list.scrollTo({ top: list.scrollHeight, behavior });
|
||||
} else {
|
||||
list.scrollTop = list.scrollHeight;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Follow the tail whenever the rendered messages change: a sent message, a
|
||||
// streamed delta, or a freshly loaded history. The list had no scroll code at
|
||||
// all, so every send left the new message below the fold.
|
||||
useEffect(() => {
|
||||
if (!followTail.current) return;
|
||||
scrollToTail("smooth");
|
||||
}, [visibleMessages, scrollToTail]);
|
||||
|
||||
// Opening a conversation, or switching slot or session, starts at the newest
|
||||
// message rather than at the top.
|
||||
useEffect(() => {
|
||||
followTail.current = true;
|
||||
const frame = window.requestAnimationFrame(() => scrollToTail("auto"));
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [selectedSlot, historySessionId, scrollToTail]);
|
||||
|
||||
useEffect(() => {
|
||||
// `listen()` resolves after the effect may already have been cleaned up.
|
||||
// Assigning the unregister function unconditionally dropped it in that
|
||||
|
|
@ -800,13 +761,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
<div
|
||||
id={`chat-panel-${selectedSlot}`}
|
||||
className="chat-message-list"
|
||||
ref={messageListRef}
|
||||
onScroll={(event) => {
|
||||
const list = event.currentTarget;
|
||||
const distanceFromTail =
|
||||
list.scrollHeight - list.scrollTop - list.clientHeight;
|
||||
followTail.current = distanceFromTail <= TAIL_THRESHOLD_PX;
|
||||
}}
|
||||
role="tabpanel"
|
||||
aria-label={`${selectedSlot} messages`}
|
||||
aria-busy={sending[selectedSlot]}
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用