修复小壹流式正文显露和思考状态显示

This commit is contained in:
WuYongJie 2026-11-27 16:29:40 +08:00
parent c477ec7611
commit 5e5bef4a2e
3 changed files with 269 additions and 104 deletions

View File

@ -79,25 +79,13 @@ fn conversation_settled(workspace: &Workspace, production: bool) -> bool {
&& !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty()
}
fn thinking_usage(output: &Value, show_speed: bool) -> Option<String> {
let tokens = usage_count(&output["tokens"]).filter(|tokens| *tokens > 0)?;
let prefix = if output["estimated"] == true { "≈" } else { "" };
let mut stats = format!("{prefix}{tokens} tokens");
if show_speed && let Some(rate) = output["tokensPerSecond"].as_f64().filter(|rate| rate.is_finite() && *rate > 0.0) {
let speed = if rate < 10.0 { format!("{rate:.1}") } else { format!("{rate:.0}") };
stats.push_str(&format!(" · {prefix}{speed} tok/s"));
}
Some(stats)
}
fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) -> egui::Response {
let status = match (thinking["active"] == true, turn_running) {
(true, true) => timeline::ThinkingStatus::Active,
(true, false) => timeline::ThinkingStatus::Interrupted,
(false, _) => timeline::ThinkingStatus::Done,
};
let stats = thinking_usage(&thinking["output"], ui.available_width() >= 260.0);
timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, stats.as_deref(), reduced)
timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, None, reduced)
}
fn turn_reply_id(conversation_id: Id, user_index: Option<usize>) -> Id {
@ -5527,9 +5515,7 @@ mod tests {
let id = Id::unique("thinking-alone");
let (running, _) = handoff_frame(&ctx, w, 0.0, id);
assert!(running.iter().any(|(text,_,_,_)| text == "正在深度思考…"));
assert!(running.iter().any(|(text,_,_,_)| text == "≈128 tokens · ≈44 tok/s"));
assert_eq!(thinking_usage(&w.messages[1]["output"], true).as_deref(), Some("≈128 tokens · ≈44 tok/s"));
assert_eq!(thinking_usage(&w.messages[1]["output"], false).as_deref(), Some("≈128 tokens"));
assert!(!running.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s")));
assert!(!running.iter().any(|(text,_,_,_)| text == "独立思考原文"));
assert!(!running.iter().any(|(text,_,_,_)| text.starts_with("工具调用")));
w.busy = None;
@ -5537,11 +5523,14 @@ mod tests {
assert!(interrupted.iter().any(|(text,_,_,_)| text == "思考已中断"));
w.messages[1]["active"] = json!(false);
w.messages[1]["output"] = json!({"tokens":145,"tokensPerSecond":45.0,"estimated":false});
w.messages.push(json!({"role":"assistant","kind":"activity","event":{
"version":1,"type":"tool","run":"thinking-test","toolCallId":"read","toolName":"canvas_read",
"status":"completed","durationMs":12}}));
w.messages.push(json!({"role":"assistant","kind":"reply","text":"分析结论"}));
let (finished, _) = handoff_frame(&ctx, w, 0.3, id);
assert!(!finished.iter().any(|(text,_,_,_)| text == "独立思考原文"));
assert!(finished.iter().any(|(text,_,_,_)| text == "145 tokens · 45 tok/s"));
assert_eq!(thinking_usage(&w.messages[1]["output"], true), Some("145 tokens · 45 tok/s".to_owned()));
assert!(!finished.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s")));
assert!(finished.iter().any(|(text,_,_,_)| text == "12ms"));
let header = finished.iter().find(|(text,_,_,_)| text == "已深度思考").unwrap().1.center();
for pressed in [true, false] {
ctx.settle_ui(egui::RawInput { time:Some(0.5), events:vec![egui::Event::PointerMoved(header),
@ -5558,7 +5547,7 @@ mod tests {
}
#[test]
fn a_final_receipt_and_lingering_stream_paint_one_response_without_replaying_glow() {
fn a_final_receipt_and_lingering_stream_keep_one_response_and_finish_its_glow() {
let ctx = egui::Context::default();
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
let (mut app, requests) = dock_fixture();
@ -5579,7 +5568,9 @@ mod tests {
assert_eq!(response.len(),1);
assert_eq!(response[0].1.top(),top);
assert!(after.iter().any(|(text,_,_,_)| text=="输出未完成"), "handoff retains the real incomplete-output warning");
assert!(meshes.is_empty(), "history never paints a send pulse");
assert!(!meshes.is_empty(), "the live reply carries its remaining glow across handoff");
let (_, rested) = handoff_frame(&ctx, w, 3.2, id);
assert!(rested.is_empty(), "the lasting receipt never replays the finished glow");
assert!(requests.try_recv().is_err());
}
@ -5648,25 +5639,23 @@ mod tests {
w.messages.push(json!({"role":"assistant","kind":"reply","text":final_text}));
w.stream_reply.clear();w.busy = None;
let (first, _) = handoff_frame(&ctx,w,0.80,id);
let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==final_text)
let visible = if appending { "已完成矩" } else { final_text };
let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==visible)
.expect("the already visible reply cannot disappear for its final message entrance");
assert_eq!(rect.top(),top,"finishing the same turn cannot replay its five-point arrival offset");
assert_eq!(*alpha,255,"the already displayed prefix stays fully opaque");
if appending {
assert!(sections.first()==Some(&255) && sections.last()==Some(&0), "the old prefix remains opaque: {sections:?}");
let (during, meshes) = handoff_frame(&ctx,w,0.90,id);
let (_,rect,alpha,sections) = during.iter().find(|(text,_,_,_)| text==final_text).unwrap();
let (during, _) = handoff_frame(&ctx,w,0.90,id);
let (_,_,alpha,sections) = during.iter().find(|(text,_,_,_)| text==final_text).unwrap();
assert_eq!(*alpha,255);
assert!(sections.first()==Some(&255) && sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255));
let samples: Vec<_> = meshes.iter().filter(|vertices| vertices.iter().any(|(pos, alpha)| *alpha > 0 && *alpha < 255 && pos.y >= rect.top() - 6.0 && pos.y <= rect.bottom() + 6.0 && pos.x > rect.left() + 20.0)).collect();
assert!(samples.is_empty(), "the suffix lives in the one shaped glyph layer, without shadow meshes");
assert_eq!(during.iter().filter(|(text,_,_,_)| text==final_text).count(), 1);
let reveal = super::super::typing_text::ENTER + 2.0 * super::super::typing_text::STEP;
let (settled, meshes) = handoff_frame(&ctx,w,0.80 + reveal + 0.05,id);
let (settled, _) = handoff_frame(&ctx,w,0.80 + reveal + 0.05,id);
let (_,_,alpha,sections) = settled.iter().find(|(text,_,_,_)| text==final_text).unwrap();
assert_eq!(*alpha,255);
assert!(sections.iter().all(|alpha| *alpha == 255), "the final suffix settles after its glyphs arrive");
assert!(meshes.iter().all(|vertices| !vertices.iter().any(|(pos, alpha)| *alpha > 0 && *alpha < 255 && pos.y >= rect.top() - 6.0 && pos.y <= rect.bottom() + 6.0 && pos.x > rect.left() + 20.0)));
}
assert!(requests.try_recv().is_err());
}
@ -5729,17 +5718,16 @@ mod tests {
handoff_frame(&ctx,w,0.3,id);
w.stream_reply = "已完成矩形".into();
let (during, _) = handoff_frame(&ctx,w,0.4,id);
let top = during.iter().find(|(text,_,_,_)|text=="已完成矩形").unwrap().1.top();
let top = during.iter().find(|(text,_,_,_)|text=="已完成矩").unwrap().1.top();
w.messages.push(json!({"role":"assistant","kind":"reply","text":"已完成矩形"}));
w.stream_reply.clear();
w.messages.push(json!({"role":"assistant","kind":"activity","event":{
"version":1,"type":"tool","run":"trace","toolCallId":"call_trace|fc_trace","toolName":"canvas_read","status":"started"}}));
let (after, meshes) = handoff_frame(&ctx,w,0.5,id);
let (after, _) = handoff_frame(&ctx,w,0.5,id);
let (_,rect,alpha,sections) = after.iter().find(|(text,_,_,_)|text=="已完成矩形").unwrap();
assert_eq!(rect.top(), top);
assert_eq!(*alpha, 255);
assert!(sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255));
assert_eq!(meshes.iter().filter(|mesh| mesh.iter().any(|(pos, alpha)| *alpha > 0 && *alpha < 255 && pos.y >= rect.top() - 6.0 && pos.y <= rect.bottom() + 6.0 && pos.x > rect.left() + 20.0)).count(), 0);
assert!(requests.try_recv().is_err());
}
@ -7605,6 +7593,57 @@ mod tests {
assert!(requests.try_recv().is_err());
}
#[test]
#[ignore = "offscreen GPU visual evidence for the reply reveal frontier"]
fn typing_frontier_visual_evidence() {
let _gpu = photocraft_testkit::gpu_lock();
let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap());
let reply = "已核对主图构图和原片,结果一致。继续检查每屏卖点和商品规格。\n```text\n主图:保留商品结构\n详情:核对材质和尺寸\n收尾:复查文字与图位\n```\n检查完成后即可保存。";
for width in [270.0, 520.0] {
let (mut app, requests) = dock_fixture();
let w = app.jiansun.as_mut().unwrap();
w.reduce_motion = false;
w.busy = Some("pi-agent".into());
w.messages = vec![
json!({"role":"user","text":"核对主图和详情页。"}),
json!({"role":"assistant","kind":"thinking","active":true,
"output":{"tokens":84,"tokensPerSecond":17}}),
json!({"role":"assistant","kind":"activity","event":{
"version":1,"type":"tool","run":"reveal-visual","toolCallId":"read",
"toolName":"canvas_read","status":"completed","durationMs":12}}),
];
let mut h = egui_kittest::Harness::builder()
.with_size(vec2(width, 360.0)).with_step_dt(1.0 / 120.0).wgpu()
.build_ui_state(|ui, app: &mut PhotocraftApp| {
if !super::super::stitch_ui::ui_fonts_ready(ui) { return; }
Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| {
let w = app.jiansun.as_ref().unwrap();
w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique("typing-frontier-visual"), w.messages.len(), true);
});
}, app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium);
let save = |h: &mut egui_kittest::Harness<PhotocraftApp>, frame| {
h.render().unwrap().save(out.join(format!("typing-{width}-{frame}.png"))).unwrap();
};
h.run_steps(40);
save(&mut h, "thinking");
let w = h.state_mut().jiansun.as_mut().unwrap();
w.messages[1]["active"] = json!(false);
w.stream_reply = reply.into();
h.run_steps(28);
save(&mut h, "streaming");
let w = h.state_mut().jiansun.as_mut().unwrap();
w.messages.push(json!({"role":"assistant","kind":"reply","text":reply}));
w.stream_reply.clear();
w.busy = None;
h.run_steps(67);
save(&mut h, "draining");
h.run_steps(360);
save(&mut h, "settled");
assert!(requests.try_recv().is_err());
}
}
#[test]
#[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"]
fn response_refinement_visual_acceptance() {

View File

@ -486,8 +486,7 @@ impl ResponseArrival {
}
}
/// 流式回复每个字符的到达时间。历史消息第一次出现就是定稿;纯追加的新字按每字 15ms 铺开,
/// 积压过多时整体压回跨度上限,吐字不会越拖越远。
/// 历史消息首次显示即定稿。流式新字按到达时间入队,相邻字素至少隔 15ms。
fn response_arrivals(state: &mut ResponseArrival, rendered: &str, now: f64, is_streaming: bool) {
if state.rendered == rendered { return; }
let live = is_streaming || !state.rendered.is_empty();
@ -592,8 +591,7 @@ pub(super) struct RevealPaint {
}
/// 逐字扩散:输入框、用户气泡与 Agent 正文共用的字形入场与柔光,节奏见 `typing_text`。
/// 只改已经排好版的 galley 里的字形顶点,原生几何与文本不变;标点与空白不入场,
/// 保持它们已排好的位置。
/// 字形到达前完全透明;标点和空白到达后保持原排版位置。
pub(super) fn animate_galley(
galley: &mut std::sync::Arc<egui::Galley>,
arrivals: &[f64],
@ -619,6 +617,9 @@ pub(super) fn animate_galley(
continue;
}
let Some(arrival) = arrivals.get(index) else { break 'collect };
if *arrival > now {
continue;
}
let top = placed.pos.y + glyph.pos.y - glyph.font_ascent;
tokens.push(TrailToken {
row: row_index,
@ -638,7 +639,7 @@ pub(super) fn animate_galley(
}
reveal::light_trail(&mut tokens, now);
}
// 入场:单字 460ms cubic-out,自下方 4pt 升起并从 1.035 倍收拢;尚未轮到的字以极淡的光雾占位;
// 入场:单字 460ms cubic-out,自下方 4pt 升起并从 1.035 倍收拢;
// 尾韵里的字被柔光微微托起并染上光的颜色。
let lit = ink.glow().lerp_to_gamma(Color32::WHITE, 0.5);
let first_trail_row = tokens.last().map_or(usize::MAX, |token| token.row);
@ -648,7 +649,7 @@ pub(super) fn animate_galley(
let row_chars = placed.glyphs.len() + usize::from(placed.ends_with_newline);
let range = index..index + row_chars;
index += row_chars;
if range.end > arrivals.len() || !arrivals[range.clone()].iter().any(|at| *at > now || now - *at < reveal::ENTER) {
if range.end > arrivals.len() || (row_index < first_trail_row && !arrivals[range.clone()].iter().any(|at| now - *at < reveal::ENTER)) {
continue;
}
let row = std::sync::Arc::make_mut(&mut placed.row);
@ -687,7 +688,7 @@ pub(super) fn animate_galley(
if glow >= reveal::GLOW_LIMIT {
vertex.color = vertex.color.lerp_to_gamma(lit, 0.38 * glow);
}
let opacity = if mist && show_glow { reveal::MIST } else { progress };
let opacity = if mist { reveal::MIST } else { progress };
vertex.color = vertex.color.gamma_multiply(opacity);
}
}
@ -701,8 +702,8 @@ pub(super) fn animate_galley(
paint
}
fn response_caret_rect(galley: &egui::Galley, pos: egui::Pos2) -> egui::Rect {
let layout_cursor = galley.layout_from_cursor(galley.end());
fn response_caret_rect(galley: &egui::Galley, pos: egui::Pos2, visible: usize) -> egui::Rect {
let layout_cursor = galley.layout_from_cursor(egui::text::CCursor::new(visible));
let cursor = galley.pos_from_layout_cursor(&layout_cursor).translate(pos.to_vec2());
let glyph = galley.rows.get(layout_cursor.row).and_then(|row| {
row.glyphs.get(..layout_cursor.column.0.min(row.glyphs.len()))
@ -803,6 +804,54 @@ pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streamin
reply_with_arrival(ui, id, text, is_streaming, false, reduced)
}
/// 保留缓存中的换行与已显露行。只重新排版被切开的末行,让行内代码底色、
/// 字形和可选文本一起结束在前沿。
fn visible_reply_galley(ui: &Ui, mut galley: std::sync::Arc<egui::Galley>, visible: usize) -> std::sync::Arc<egui::Galley> {
let Some((end, _)) = galley.text().char_indices().nth(visible) else { return galley };
let cursor = galley.layout_from_cursor(egui::text::CCursor::new(visible));
let frame = std::sync::Arc::make_mut(&mut galley);
frame.rows.truncate(cursor.row + 1);
if let Some(last) = frame.rows.last_mut() {
if cursor.column.0 < last.glyphs.len() {
let start = frame.job.text.char_indices().nth(visible - cursor.column.0).map_or(end, |(byte, _)| byte);
let mut job = egui::text::LayoutJob {
first_row_min_height: last.size.y,
direction: frame.job.direction,
..Default::default()
};
for section in &frame.job.sections {
let left = start.max(section.byte_range.start.0);
let right = end.min(section.byte_range.end.0);
if left < right {
job.append(&frame.job.text[left..right], 0.0, section.format.clone());
}
}
if let Some(prefix) = ui.fonts_mut(|fonts| fonts.layout_job(job)).rows.first() {
last.row = prefix.row.clone();
}
}
last.ends_with_newline = false;
}
let job = std::sync::Arc::make_mut(&mut frame.job);
job.text.truncate(end);
let end = egui::text::ByteIndex(end);
job.sections.retain_mut(|section| {
section.byte_range.end = section.byte_range.end.min(end);
section.byte_range.start < end
});
frame.rect = egui::Rect::ZERO;
frame.mesh_bounds = egui::Rect::NOTHING;
frame.num_vertices = 0;
frame.num_indices = 0;
for row in &frame.rows {
frame.rect = frame.rect.union(row.rect());
frame.mesh_bounds = frame.mesh_bounds.union(row.visuals.mesh_bounds.translate(row.pos.to_vec2()));
frame.num_vertices += row.visuals.mesh.vertices.len();
frame.num_indices += row.visuals.mesh.indices.len();
}
galley
}
pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_streaming: bool, animate_final: bool, reduced: bool) -> Response {
let now = ui.input(|input| input.time);
let t = Tokens::get(ui.ctx()).agent();
@ -818,6 +867,11 @@ pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_strea
state.reveal_final = animate_final && !reduced;
}
response_arrivals(state, &layout.rendered, now, (is_streaming || state.reveal_final) && !reduced);
if reduced && now < state.rest_at {
// 减少动态已显示全文,重新开启动效时从后续新字继续。
state.arrivals.fill(now - reveal::SETTLED_AGE);
state.rest_at = reveal::rest_at(&state.arrivals);
}
if is_streaming {
state.caret_exit = None;
} else if state.was_streaming && !reduced {
@ -826,20 +880,24 @@ pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_strea
state.was_streaming = is_streaming;
state.clone()
});
let mut galley = layout.galley.clone();
// 还在逐字扩散时才改写已排好版的 galley:每个可见字形有自己的顶点区间,
// 标点、选区几何与代码块背景都留在原位。定稿的回复一个顶点都不碰。
let visible = if reduced { state.arrivals.len() } else { state.arrivals.partition_point(|at| *at <= now) };
let mut galley = if visible < state.arrivals.len() {
visible_reply_galley(ui, layout.galley.clone(), visible)
} else {
layout.galley.clone()
};
let mut frame = RevealPaint::default();
if now < state.rest_at {
frame = animate_galley(&mut galley, &state.arrivals, now, reduced, is_streaming || state.reveal_final, reveal::RevealInk::agent(t));
let revealing = !reduced && now < state.rest_at;
if revealing {
frame = animate_galley(&mut galley, &state.arrivals[..visible], now, false, true, reveal::RevealInk::agent());
}
let response = ui.add(egui::Label::new(galley.clone()).selectable(true));
let pos = response.rect.min;
let mut backgrounds = Vec::new();
for (index, block) in blocks.iter().enumerate() {
for (index, block) in blocks.iter().enumerate().take_while(|(_, block)| block.start < visible) {
let start = galley.pos_from_cursor(egui::text::CCursor::new(block.start)).translate(pos.to_vec2());
let end_index = if block.contents.ends_with('\n') { block.end.saturating_sub(1) } else { block.end };
let end = galley.pos_from_cursor(egui::text::CCursor::new(end_index)).translate(pos.to_vec2());
let end = galley.pos_from_cursor(egui::text::CCursor::new(end_index.min(visible))).translate(pos.to_vec2());
let rect = egui::Rect::from_min_max(egui::pos2(pos.x, start.top()), egui::pos2(pos.x + width, end.bottom().max(start.bottom())));
backgrounds.push(egui::Shape::rect_filled(rect, radius::CHIP, t.canvas));
backgrounds.push(egui::Shape::rect_stroke(rect.shrink(0.5), radius::CHIP, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside));
@ -847,11 +905,13 @@ pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_strea
let label_clip = egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - 32.0).max(rect.left()), (rect.top() + REPLY_CODE_HEADER_HEIGHT).min(rect.bottom())));
ui.painter().with_clip_rect(ui.clip_rect().intersect(label_clip)).text(rect.min + vec2(10.0, 7.0), egui::Align2::LEFT_TOP, &block.language, Type::Caption.font_id(), t.text.gamma_multiply(0.7));
}
let button_rect = egui::Rect::from_min_size(egui::pos2(rect.right() - 30.0, rect.top() + 1.0), vec2(control::STANDARD, control::STANDARD));
let mut child = ui.new_child(egui::UiBuilder::new().id_salt((id, "copy-code", index)).max_rect(button_rect));
child.set_clip_rect(ui.clip_rect().intersect(rect));
if crate::icons::agent_icon_button(&mut child, "copy", control::STANDARD, false, "复制代码").clicked() {
ui.ctx().copy_text(block.contents.clone());
if block.end <= visible {
let button_rect = egui::Rect::from_min_size(egui::pos2(rect.right() - 30.0, rect.top() + 1.0), vec2(control::STANDARD, control::STANDARD));
let mut child = ui.new_child(egui::UiBuilder::new().id_salt((id, "copy-code", index)).max_rect(button_rect));
child.set_clip_rect(ui.clip_rect().intersect(rect));
if crate::icons::agent_icon_button(&mut child, "copy", control::STANDARD, false, "复制代码").clicked() {
ui.ctx().copy_text(block.contents.clone());
}
}
}
// 流头柔光与尾韵光带垫在字形下面、代码块背景上面。
@ -864,14 +924,12 @@ pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_strea
state.caret_exit.map_or(0.0, |(start, initial)| initial * (1.0 - response_ease(((now - start) / timing::CARET_EXIT).clamp(0.0, 1.0) as f32)))
};
if caret_alpha > 0.001 {
let caret = response_caret_rect(&galley, pos);
let caret = response_caret_rect(&galley, pos, visible);
ui.painter().rect_filled(caret, caret.width() * 0.5, t.text.gamma_multiply(caret_alpha));
}
// 逐字入场、流式输出与光标按满帧;只剩尾韵在收时交给待机档;定稿且不可见时一帧都不申请。
if !reduced && (frame.entering || frame.glowing || is_streaming || caret_alpha > 0.001) {
// 模型结束后,继续按满帧排空队列并收完柔光。
if !reduced && (revealing || is_streaming || caret_alpha > 0.001) {
schedule(ui, response.rect, Pace::Full);
} else if frame.fading {
schedule(ui, response.rect, Pace::Idle);
}
response
}
@ -2716,8 +2774,7 @@ mod tests {
response_arrivals(&mut long, &"乙".repeat(65_000), 1.0, true);
assert_eq!(long.arrivals.len(), 65_000);
assert!(long.arrivals.iter().all(|time| *time >= 1.0));
assert!(long.arrivals.windows(2).all(|pair| pair[0] < pair[1]), "a rewritten tail still spreads out in order");
assert!(long.arrivals[64_999] - 1.0 <= reveal::MAX_SPAN + 1e-9, "and never lags more than the span cap");
assert!(long.arrivals.windows(2).all(|pair| (pair[1] - pair[0] - step).abs() < 1e-9), "a rewritten tail keeps the fixed minimum interval");
let mut history = ResponseArrival::default();
response_arrivals(&mut history, "历史回复", 5.0, false);
assert!(history.arrivals.iter().all(|time| *time <= 5.0 - reveal::SETTLED_AGE + 1e-9));
@ -3277,6 +3334,90 @@ mod tests {
assert!(!response_static_character('中') && !response_static_character('🪵'));
}
#[test]
fn future_punctuation_is_transparent_and_cannot_take_the_glow_head() {
let ctx = Context::default();
crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
ctx.settle_ui(egui::RawInput::default(), |ui| {
let layout = |text| ui.fonts_mut(|fonts| fonts.layout_job(reply_job(text, 260.0, Color32::WHITE, Color32::BLACK)));
let mut prefix = layout("ABC");
let mut full = layout("ABC! X");
let arrivals = [0.0, 0.015, 0.030, 1.0, 1.015, 1.030, 1.045, 1.060, 1.075, 1.090];
let ink = reveal::RevealInk::agent();
let expected = animate_galley(&mut prefix, &arrivals[..3], 0.15, false, true, ink);
assert!(!expected.glow.is_empty());
let frame = animate_galley(&mut full, &arrivals, 0.15, false, true, ink);
assert_eq!(frame.glow, expected.glow);
assert!(frame.entering);
let row = &full.rows[0];
for glyph in &row.glyphs[3..] {
if !glyph.uv_rect.is_nothing() {
let start = glyph.first_vertex as usize;
assert!(row.visuals.mesh.vertices[start..start + 4].iter().all(|vertex| vertex.color == Color32::TRANSPARENT));
}
}
for shape in frame.glow {
let egui::Shape::Mesh(mesh) = shape else { panic!("the text glow is a mesh") };
assert!(mesh.vertices.iter().all(|v| v.color.r() == v.color.g() && v.color.g() == v.color.b()));
}
}).drop_without_applying_deltas();
}
#[test]
fn reply_crops_buffered_rows_and_drains_at_full_pace_after_stream_end() {
let ctx = Context::default();
crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
settle_test_cjk_font(&ctx);
let id = egui::Id::unique("buffered-reply");
let text = format!("Visible!\n```txt\n{}\n```\nFinal line.", "buffered code line\n".repeat(6));
let render = |time, streaming, reduced, resize: &mut egui::Rect| {
ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| {
ui.set_width(220.0);
*resize = streaming_reply(ui, id, &text, streaming, reduced).rect;
})
};
let mut rect = egui::Rect::NOTHING;
render(0.0, true, false, &mut rect).drop_without_applying_deltas();
let early = render(7.5 * reveal::STEP, true, false, &mut rect);
let early_height = rect.height();
let drawn = reply_text_shapes(&early, "Visible!");
assert_eq!(drawn.len(), 1);
assert_eq!(drawn[0].galley.rows.len(), 1);
assert!(reply_text_shapes(&early, "txt").is_empty(), "the future code header is absent");
let caret = response_caret_rect(&drawn[0].galley, drawn[0].pos, 8);
assert!(early.shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == caret)));
early.drop_without_applying_deltas();
let finished = render(0.2, false, false, &mut rect);
assert_eq!(requested_delay(&finished), Some(timing::FRAME_FULL));
assert!(!reply_text_shapes(&finished, "txt").is_empty(), "the code header appears at the front");
assert!(rect.height() > early_height);
let partial_height = rect.height();
finished.drop_without_applying_deltas();
let state = ctx.data(|data| data.get_temp::<ResponseArrival>(id)).unwrap();
let draining = render(0.7, false, false, &mut rect);
assert_eq!(requested_delay(&draining), Some(timing::FRAME_FULL), "keeps moving after the caret fades");
assert!(rect.height() > partial_height);
draining.drop_without_applying_deltas();
let tail = render(state.rest_at - 0.01, false, false, &mut rect);
assert_eq!(requested_delay(&tail), Some(timing::FRAME_FULL));
tail.drop_without_applying_deltas();
let full_height = rect.height();
let rested = render(state.rest_at, false, false, &mut rect);
assert_eq!(requested_delay(&rested), None);
assert_eq!(glow_mesh_count(&rested), 0);
assert_eq!(rect.height(), full_height);
rested.drop_without_applying_deltas();
ctx.data_mut(|data| data.remove::<ResponseArrival>(id));
render(5.0, true, false, &mut rect).drop_without_applying_deltas();
assert!(rect.height() < full_height);
render(5.1, true, true, &mut rect).drop_without_applying_deltas();
assert_eq!(rect.height(), full_height);
render(5.2, true, false, &mut rect).drop_without_applying_deltas();
assert_eq!(rect.height(), full_height, "re-enabling motion keeps already displayed text");
}
#[test]
fn glow_send_envelope_retriggers_only_on_another_accepted_send() {
let ctx=Context::default();let id=egui::Id::unique("glow-test");
@ -3635,7 +3776,7 @@ mod tests {
let galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
let cursor = galley.layout_from_cursor(galley.end());
let cursor_rect = galley.pos_from_layout_cursor(&cursor);
let caret = response_caret_rect(&galley, egui::Pos2::ZERO);
let caret = response_caret_rect(&galley, egui::Pos2::ZERO, text.chars().count());
assert!((caret.left() - cursor_rect.left() - 1.0).abs() < 0.01, "{text:?}");
assert!(caret.center().y >= cursor_rect.top() && caret.center().y <= cursor_rect.bottom(), "{text:?}: {caret:?} {cursor_rect:?}");
let row = &galley.rows[cursor.row];
@ -4311,7 +4452,8 @@ mod tests {
assert!((reveal::ENTER - 0.460).abs() < 1e-9, "单字入场 460ms cubic-out");
assert!((reveal::STEP - 0.015).abs() < 1e-9, "每字步进 15ms");
assert_eq!(reveal::TAIL, 13);
assert_eq!(reveal::MIST, 0.12);
assert_eq!(reveal::MIST, 0.0);
assert_eq!(reveal::RevealInk::agent().glow(), Color32::WHITE);
assert!((timing::STOP_SETTLE - 0.190).abs() < 1e-9, "停止减速定格收敛在 180–200ms");
assert_eq!(timing::FRAME_FULL, std::time::Duration::from_millis(16), "发送脉冲、运行、交互满帧");
assert_eq!(timing::FRAME_IDLE, std::time::Duration::from_millis(32), "纯待机降到半帧");

View File

@ -2,7 +2,7 @@
//!
//! 节奏由用户定稿:单字 460ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光,
//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 13 字宽的尾韵,流头另有一团柔光。
//! 尚未轮到的字先以极淡的光雾占位,光标不会跑到文字前面。
//! 尚未轮到的字保持透明,柔光跟随已经显露的字。
//!
//! 这里只管到达时间、柔光数学与柔光网格;字形网格的改写在 `stitch_ui::animate_galley`。
use crate::theme::agent_scale::motion as timing;
@ -18,8 +18,6 @@ use super::agent_motion::{Pace, schedule};
pub(super) const ENTER: f64 = timing::REVEAL_ENTER;
/// 相邻两字的到达步进:15ms。
pub(super) const STEP: f64 = timing::REVEAL_STEP;
/// 一批同时到达的字铺开后的总跨度上限,超出就压缩步进,吐字不会越拖越远。
pub(super) const MAX_SPAN: f64 = timing::REVEAL_MAX_SPAN;
/// 尾韵宽度:流头向回约 11 个字。
pub(super) const TAIL: usize = timing::REVEAL_TAIL;
/// 光波向回传播:每个字 22ms。
@ -31,8 +29,8 @@ const FADE_MS: f64 = timing::REVEAL_FADE * 1000.0;
const SPREAD: f32 = timing::REVEAL_SPREAD;
/// 每个字最多叠加最近 7 次到达的柔光。
const SOURCES: usize = 7;
/// 还没轮到的字先以极淡的光雾占位。
pub(super) const MIST: f32 = 0.12;
/// 尚未轮到的字完全透明。
pub(super) const MIST: f32 = 0.0;
/// 入场时从下方 4pt 升起。
pub(super) const RISE_POINTS: f32 = 4.0;
/// 入场时从 1.035 倍收拢到原大。
@ -101,9 +99,9 @@ pub(super) fn light_trail(tokens: &mut [TrailToken], now: f64) {
}
}
/// `count` 个字逐字铺开时每个字的步进:每字 STEP,超长时压缩,总跨度恰好不超过 MAX_SPAN。
pub(super) fn batch_step(count: usize) -> f64 {
if count <= 1 { 0.0 } else { STEP.min(MAX_SPAN / count.saturating_sub(1) as f64) }
/// 用户已发送的气泡有固定的入场跨度上限。
fn batch_step(count: usize) -> f64 {
if count <= 1 { 0.0 } else { STEP.min(timing::REVEAL_MAX_SPAN / (count - 1) as f64) }
}
/// 一段 `count` 个字的文字从开始到完全定稿需要的时长。
@ -126,9 +124,8 @@ pub(super) fn rest_at(arrivals: &[f64]) -> f64 {
}
/// 把刚到达的一批字(`added`,初值都是它们的 `now`)按每字 STEP 逐字铺开。
/// 前一个字还没轮到时,这批字接在它后面,先后顺序不乱;
/// 积压超过 MAX_SPAN 时,把这一串还没轮到的字整体压回 MAX_SPAN,吐字不会越拖越远。
pub(super) fn spread(arrivals: &mut [f64], added: Range<usize>, now: f64) {
/// 每批新字跟随实际到达时间,相邻字素至少隔 STEP。
fn spread(arrivals: &mut [f64], added: Range<usize>, now: f64) {
spread_by(arrivals, added, &[], now);
}
@ -148,45 +145,28 @@ fn spread_by(arrivals: &mut [f64], added: Range<usize>, sizes: &[usize], now: f6
}
let clustered = sizes.iter().sum::<usize>() == added.len();
let before = if added.start == 0 { None } else { Some(arrivals[added.start - 1]) };
let queued = before.is_some_and(|at| at > now);
let step = batch_step(if clustered { sizes.len() } else { added.len() } + usize::from(queued));
let base = before.map_or(now, |at| now.max(at + step));
let base = before.map_or(now, |at| now.max(at + STEP));
let (mut index, mut unit) = (added.start, 0_usize);
while index < added.end {
let size = if clustered { sizes.get(unit).copied().unwrap_or(1).max(1) } else { 1 };
let arrival = base + step * unit as f64;
let arrival = base + STEP * unit as f64;
for slot in &mut arrivals[index..(index + size).min(added.end)] {
*slot = arrival;
}
index += size;
unit += 1;
}
if arrivals[added.end - 1] - now <= MAX_SPAN {
return;
}
let mut start = added.start;
while start > 0 && arrivals[start - 1] > now {
start -= 1;
}
let mut end = added.end;
while end < arrivals.len() && arrivals[end] > now {
end += 1;
}
let count = (end - start) as f64;
for (offset, arrival) in arrivals[start..end].iter_mut().enumerate() {
*arrival = now + MAX_SPAN * (offset + 1) as f64 / count;
}
}
/// 逐字柔光的用色:Agent 正文用冷月青,用户输入与用户气泡用琥珀。
/// 逐字柔光的用色:Agent 正文用白色,用户输入与用户气泡用琥珀。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RevealInk { glow: Color32 }
impl RevealInk {
pub(super) fn glow(self) -> Color32 { self.glow }
pub(super) fn agent(t: Tokens) -> Self {
Self { glow: t.agent_semantic().glow_agent }
pub(super) fn agent() -> Self {
Self { glow: Color32::WHITE }
}
pub(super) fn user(t: Tokens) -> Self {
@ -374,7 +354,7 @@ mod tests {
assert_eq!(batch_step(0), 0.0);
assert_eq!(batch_step(1), 0.0);
assert_eq!(batch_step(40), STEP);
assert!((batch_step(200) * 199.0 - MAX_SPAN).abs() < 1e-9, "a long paste still spreads out within the span cap");
assert!((batch_step(200) * 199.0 - timing::REVEAL_MAX_SPAN).abs() < 1e-9, "a long sent bubble has a bounded entrance");
assert_eq!(ease_out(0.0), 0.0);
assert_eq!(ease_out(1.0), 1.0);
assert!((ease_out(0.5) - 0.875).abs() < 1e-6, "cubic-out: half of the time covers seven eighths of the way");
@ -446,7 +426,7 @@ mod tests {
}
#[test]
fn spread_keeps_order_and_never_lags_more_than_the_span_cap() {
fn spread_tracks_slow_arrivals_and_never_compresses_a_burst() {
let mut arrivals = vec![0.0, 0.0, 1.0, 1.0, 1.0];
spread(&mut arrivals, 2..5, 1.0);
assert_eq!(arrivals, vec![0.0, 0.0, 1.0, 1.0 + STEP, 1.0 + 2.0 * STEP]);
@ -458,17 +438,21 @@ mod tests {
let mut middle = vec![-5.0, -5.0, -5.0, -5.0];
spread(&mut middle, 1..2, 3.0);
assert_eq!(middle, vec![-5.0, 3.0, -5.0, -5.0]);
// 每帧涌进一大段:步进被压缩,总跨度不超过 MAX_SPAN,先后顺序不乱。
let mut slow = vec![1.0, 1.04, 1.10];
spread(&mut slow, 1..2, 1.04);
spread(&mut slow, 2..3, 1.10);
assert_eq!(slow, vec![1.0, 1.04, 1.10]);
let mut fast = vec![1.0, 1.005, 1.010];
spread(&mut fast, 1..2, 1.005);
spread(&mut fast, 2..3, 1.010);
assert_eq!(fast, vec![1.0, 1.0 + STEP, 1.0 + STEP + STEP]);
let mut burst = vec![1.0; 400];
spread(&mut burst, 0..400, 1.0);
assert!(burst.windows(2).all(|pair| pair[0] < pair[1]));
assert!(burst[399] - 1.0 <= MAX_SPAN + 1e-9);
// 积压太多:这一串还没轮到的字被整体压回 MAX_SPAN,吐字不会越拖越远。
let mut backlog = vec![1.600; 100];
backlog.extend(vec![1.0; 100]);
spread(&mut backlog, 100..200, 1.0);
assert!(backlog.windows(2).all(|pair| pair[0] < pair[1]));
assert!(backlog[199] - 1.0 <= MAX_SPAN + 1e-9, "the backlog is compressed into the span cap");
let original = burst.clone();
burst.extend(vec![1.010; 100]);
spread(&mut burst, 400..500, 1.010);
assert_eq!(&burst[..400], &original);
assert!(burst.windows(2).all(|pair| (pair[1] - pair[0] - STEP).abs() < 1e-9));
let mut trailing = vec![1.0, 1.0, 1.0];
spread(&mut trailing, 3..3, 1.0);
assert_eq!(trailing, vec![1.0, 1.0, 1.0], "an empty batch changes nothing");