diff --git a/apps/detail-photocraft/DESIGN.md b/apps/detail-photocraft/DESIGN.md index 683862cb..d06bf575 100644 --- a/apps/detail-photocraft/DESIGN.md +++ b/apps/detail-photocraft/DESIGN.md @@ -419,11 +419,11 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 **事件行。** 高 24 逻辑点:24 点的图标列内放 14 点图标,随后是 12 点文字,再后是弱化的补充信息,可展开的行末尾带箭头。只有可点击的行回应悬停。行本身不做动画,一轮对话里唯一的等待动画属于状态行。字号只用三档:12 用于行和补充信息,13 用于标题与控件,14 用于回复正文。 -- 思考:只有一行状态,原文不展示;token 数和速度放在悬停说明里,不占行。 +- 思考:运行时图标轻微呼吸,完成后收成一行静态状态。用量和速度有数据才显示在同一行右侧。 - 通知:按类型取图标;等待中用亮色,核查类用告警色,失败用危险色。同一句状态反复记入时,时间线只显示最新一条,更早的相同记录留在对话数据里不再占一行。 -- 工具调用:标题是“工具调用”加已完成数,展开后是一张任务卡,逐行列出图标、名称、状态徽章和真实耗时。进行中的工具组自动展开,成功完成后停留 1.2 秒再收起。失败组保持展开,手动开合优先于自动行为。历史成功组默认收起。耗时按人读的粗细写:1 秒以内写毫秒,10 秒以内保留一位小数,一分钟以内写整秒,再长写几分几秒,统一由 `duration_text` 生成。 +- 工具调用:运行时标题标出当前实际工具,完成时显示结果摘要,失败时标出失败数。展开区用 26 点缩进的无框列表,每行状态图标、工具名、右对齐等宽耗时。进行中自动展开,成功完成后停留 1.2 秒再收起。失败组保持展开,手动开合优先。秒以下用毫秒,如 320ms。连续的思考、工具、通知和图片标题由 1 像素细线相连,图标与正文处断开。 - 回复:正文按到达顺序直接显示。新回复逐字入场,流式转为记录时延续当前字形动画,历史正文直接显示。复制按钮只在鼠标指向这条回复或按钮持有焦点时出现。 -- 图片结果:标题是“生成图片”或“图片来源”加数量;图片按自身比例排列,说明文字统一为左下角白字衬底。 +- 图片结果:标题是“生成图片”或“图片来源”加数量;图片按自身比例排列,说明文字统一为左下角单行白字。真实候选审阅状态在左上角显示语义色圆点和短标签。 - 空对话:还没有任何消息时,时间线顶部用几行说明小壹在这里能做哪三件事、从输入框或一条建议开始;没有打开项目时另给“我的项目”入口。第一条消息出现后即消失,不发送任何请求。 **顶部状态头。** 整套制作期间,状态头固定在对话滚动区上方,向上翻看历史时不动。收起时依次是:标题行(等待指示或时钟、当前步骤、展开钮、停止钮)、图片与文案各有一组独立圆角进度格,子代理字母与阶段按网格排列。进度格保持 5–7 点,空间不足时在对应统计标签右侧换行。展开后追加每个子代理的图位与步骤汇总。标题行在窄栏把位置让给步骤名:侧栏不超过 260 点时不放等待指示和时钟,九个字的步骤名完整显示,等待状态由标题的告警色表达。子代理只有一个写法:汇总行和展开列表用同一个字母,展开列表里的胶囊同宽,等待中没有动画点的胶囊也占同样的宽度,图位名从同一列开始。状态头只有一套进度色:还没有图位格子时用同比例的进度条,已填未验同为琥珀。进度数字显示已上画布的数量,含已显示的首图预览和已写入的文案初稿。蓝格显示已核验,悬停可查看可定位的图片图位。 @@ -466,7 +466,7 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 **品牌动效的定稿参数。** -- 逐字扩散(输入框、用户气泡、回复正文共用 `typing_text.rs`):单字 300ms cubic-out 入场,自下方 4 点升起并从 1.035 倍收拢到原大;相邻两字步进 15ms,同一批到达的字按字素簇铺开,积压时整体压回 650ms。一次到达激起一道柔光,以每字 22ms 向回传、按 exp(−距离/9) 衰减,在流头身后留下约 11 字宽的尾韵;流头另有一团柔光。尚未轮到的字以 12% 的光雾占位,光标不会跑到文字前面。回复里柔光垫在字形下面;输入浮层的文字经光涌透镜绘制,柔光由 `typing_text::paint_glow` 画在玻璃上面、文字光标下面。 +- 逐字扩散(输入框、用户气泡、回复正文共用 `typing_text.rs`):单字 460ms cubic-out 入场,自下方 4 点升起并从 1.035 倍收拢到原大;相邻两字步进 15ms,同一批到达的字按字素簇铺开,积压时整体压回 650ms。一次到达激起一道柔光,以每字 22ms 向回传、按 exp(−距离/9) 衰减,在流头身后留下约 13 字宽的尾韵;流头另有一团柔光。尚未轮到的字以 12% 的光雾占位,光标不会跑到文字前面。回复里柔光垫在字形下面;输入浮层的文字经光涌透镜绘制,柔光由 `typing_text::paint_glow` 画在玻璃上面、文字光标下面。 - 停止:流光、内雾与占位、光球的减速定格统一收敛在 190ms;光球停下时略微变暗。 - 光球档位:待机极柔慢呼吸、输入轻柔响应、运行平稳流动、等待结果慢一档巡视、暂停减速变暗定格。 - 光涌:玻璃光场、流光与 640ms 发送脉冲原样不动,只改了“什么时候申请下一帧”。 diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index bf8c3038..b81c1281 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -79,30 +79,25 @@ fn conversation_settled(workspace: &Workspace, production: bool) -> bool { && !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty() } -/// Token counts and speed serve the person debugging a run, not someone -/// reading the timeline, so they ride on the row's hover text. -fn thinking_usage(output: &Value) -> (Option, &'static str) { - let mut note = "本次输出用量由模型回传。速度从首段输出开始计算。"; - let Some(tokens) = usage_count(&output["tokens"]).filter(|tokens| *tokens > 0) else { return (None, note) }; +fn thinking_usage(output: &Value, show_speed: bool) -> Option { + 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 let Some(rate) = output["tokensPerSecond"].as_f64().filter(|rate| rate.is_finite() && *rate > 0.0) { + 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")); } - if output["estimated"] == true { note = "输出用量暂为估算,模型回传后校准。速度从首段输出开始计算。"; } - (Some(stats), note) + Some(stats) } -fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) { +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, note) = thinking_usage(&thinking["output"]); - let hint = stats.map(|stats| format!("{stats}。{note}")); - timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, hint.as_deref(), reduced); + 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) } fn turn_reply_id(conversation_id: Id, user_index: Option) -> Id { @@ -1330,7 +1325,7 @@ impl Workspace { if turn_count == 0 && production { let jobs = self.projected_worker_jobs(); if !jobs.is_empty() { - self.timeline_images(ui, conversation_id.with("worker-jobs"), &jobs.iter().collect::>()); + self.timeline_images(ui, conversation_id.with("worker-jobs"), &jobs.iter().collect::>(), &mut Default::default()); } } self.workflow_card_ui(app, ui); @@ -1734,6 +1729,7 @@ impl Workspace { let merged_images = matches!(turn.items.last(), Some(TurnItem::Images(..))); let last_position = turn.items.len().saturating_sub(1); let mut locate = None; + let mut flow = super::agent_stream::Flow::default(); if let Some(text) = turn.user { let enter = agent_motion::message_enter(ui, conversation_id, turn.user_index.unwrap_or(usize::MAX), count, self.reduce_motion); let reveal_id = self.user_reveal_id(turn.user_index); @@ -1783,14 +1779,16 @@ impl Workspace { for (position, item) in turn.items.into_iter().enumerate() { match item { TurnItem::Thinking(thinking) => { - thinking_ui(ui, thinking, turn_running, self.reduce_motion); + let row = thinking_ui(ui, thinking, turn_running, self.reduce_motion); + flow.connect(ui, row.rect); } TurnItem::Notice(text) => { let text = activity_history_label(text); let display = product.then(|| production_reply_text(text, false)); - timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { + let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { kind: notice_kind(text), text: display.as_deref().unwrap_or(text), hint: None, }, self.reduce_motion); + flow.connect(ui, row.rect); } TurnItem::Tools(tasks) => { let Some((_, first)) = tasks.first() else { continue }; @@ -1806,15 +1804,17 @@ impl Workspace { status: if status == ToolStatus::Started && !turn_running { ToolStatus::Unknown } else { status }, elapsed: elapsed.as_deref() } }).collect(); - timeline::tool_group(ui, id, timeline::ToolGroupHead { + let row = timeline::tool_group(ui, id, timeline::ToolGroupHead { total: rows.len(), completed: rows.iter().filter(|row| row.status == ToolStatus::Completed).count(), failed: rows.iter().filter(|row| row.status == ToolStatus::Failed).count(), active: turn_running && rows.iter().any(|row| row.status.running()), }, &rows, self.reduce_motion); + flow.connect(ui, row.rect); ui.add_space(8.0); } TurnItem::Reply(text, index) => { + flow.break_run(); let is_last_reply = tail_reply.is_some_and(|(_, last)| index == last); if is_last_reply && stream_extends_receipt && let Some(text) = stream { paint_stream(ui, text); @@ -1858,11 +1858,12 @@ impl Workspace { } TurnItem::Images(first, images) => { let images = images.into_iter().chain(projected.iter().filter(|_| position == last_position)).collect::>(); - if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images) { + if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images, &mut flow) { locate = Some(target); } } TurnItem::Choice(index) => { + flow.break_run(); let action = match self.messages.get(index).and_then(|message| message["kind"].as_str()) { Some("pi-ui-request") => self.pi_ui_render(ui, index), kind => timeline::interaction_card(ui, timeline::InteractionCard { title: None, note: None }, |ui| { @@ -1876,6 +1877,7 @@ impl Workspace { } } if let Some(text) = stream.filter(|_| !stream_is_persisted && !stream_extends_receipt) { + flow.break_run(); paint_stream(ui, text); } if stream.is_some() && self.unknown && !batch_progress { @@ -1884,18 +1886,20 @@ impl Workspace { } if !projected.is_empty() && !merged_images { let images: Vec<_> = projected.iter().collect(); - self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images); + self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images, &mut flow); } locate } - fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value]) -> Option { + fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value], flow: &mut super::agent_stream::Flow) -> Option { let heading = if images.iter().any(|image| image["kind"] == "template-image") { "图片来源" } else { "生成图片" }; let count = images.len().to_string(); ui.add_space(2.0); - timeline::image_set(ui, id, timeline::ImageSet::conversation(heading, Some(&count), images.len()), - self.reduce_motion, |ui, index, width| self.image_result(ui, images[index], width)) - .1.into_iter().flatten().last() + let (row, results) = timeline::image_set(ui, id, timeline::ImageSet::conversation(heading, Some(&count), images.len()), + self.reduce_motion, |ui, index, width| self.image_result(ui, images[index], width)); + flow.connect(ui, row.rect); + flow.break_run(); + results.into_iter().flatten().last() } fn image_result(&self, ui: &mut Ui, value: &Value, cell_width: f32) -> Option { @@ -1939,7 +1943,7 @@ impl Workspace { let step = value["step"].as_str().unwrap_or("正在生成图片…"); let (rect, response) = ui.allocate_ui_with_layout( vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), - |ui| ui.allocate_exact_size(size, Sense::hover()), + |ui| ui.allocate_exact_size(size, Sense::empty()), ).inner; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text} · {step}"))); if ui.is_rect_visible(rect) { @@ -1986,22 +1990,24 @@ impl Workspace { } let caption = if page_label.is_empty() { short_label.clone() } else { format!("{page_label} · {short_label}") }; paint_image_caption(&ui.painter_at(rect), rect, &caption); - paint_worker_badge(ui, response.id, rect, value, self.reduce_motion); let review = &self.workflow.production_progress()["candidateReviews"][id]; - if let Some(label) = match review["status"].as_str() { - Some("adopted") => Some("已采纳"), - Some("passed") => Some("验图通过"), - Some("not_selected") => Some("未选用"), - Some("rejected") => Some("已退回"), - Some("pending") => Some("待核查"), + if let Some((status, color)) = match review["status"].as_str() { + Some("adopted") => Some(("已采纳", t.agent_semantic().success)), + Some("passed") => Some(("验图通过", t.agent_semantic().success)), + Some("not_selected") => Some(("未选用", t.text_faint)), + Some("rejected") => Some(("已退回", t.danger)), + Some("pending") => Some(("待核查", t.warning)), _ => None, - } && rect.width() >= 118.0 && rect.height() >= 70.0 { - let badge = Rect::from_min_size(rect.left_top() + vec2(8.0, 36.0), vec2(66.0, 22.0)); - let kind = match review["status"].as_str() { - Some("rejected" | "pending") => super::stitch_ui::BadgeKind::Warning, - _ => super::stitch_ui::BadgeKind::Neutral, - }; - super::stitch_ui::paint_badge(ui, response.id.with("image-review"), badge, kind, label, self.reduce_motion); + } && rect.width() >= 112.0 && rect.height() >= 52.0 { + let painter = ui.painter_at(rect); + let font = crate::theme::agent_scale::Type::Meta.font_id(); + let text = painter.layout_no_wrap(status.to_owned(), font, Color32::WHITE); + let tag = Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(text.size().x + 21.0, 22.0)); + painter.rect_filled(tag, 6.0, Color32::from_black_alpha(188)); + painter.circle_filled(egui::pos2(tag.left() + 8.0, tag.center().y), 3.0, color); + painter.galley(egui::pos2(tag.left() + 15.0, tag.center().y - text.size().y * 0.5), text, Color32::WHITE); + } else { + paint_worker_badge(ui, response.id, rect, value, self.reduce_motion); } let expand = (rect.width() >= 42.0 && rect.height() >= 42.0).then(|| image_preview_button(ui, rect, id)); let response = response.on_hover_text(if original { label.clone() } else { format!("定位 {label} · 右键查看候选大图") }); @@ -4212,6 +4218,9 @@ mod tests { let target = image_location(message, task); let (_, _, label) = image_result_labels(&target, &w.template_workflow, &w.creation_brief); w.agent_images.insert(task.into(), texture); + let mut progress = w.workflow.production_progress().clone(); + progress["candidateReviews"][task]["status"] = json!("adopted"); + w.workflow.set_production_progress(&progress); harness.run_steps(8); let received = harness.get_by_label(format!("定位 {label}").as_str()).rect(); assert_eq!(waiting, received); @@ -5235,22 +5244,22 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let initial = frame(&ctx,w,0.0,vec![]); let reply_top = initial.iter().find(|(text,_)|text==&w.stream_reply).unwrap_or_else(|| panic!("reply shape missing: {initial:?}")).1.top(); - let summary_top = initial.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.top(); + let summary_top = initial.iter().find(|(text,_)|text == "正在组合画布操作…").unwrap().1.top(); assert!(summary_top < reply_top, "the processing summary precedes the live reply"); w.messages[1]["event"]["status"] = json!("completed"); frame(&ctx,w,0.1,vec![]); let gap = frame(&ctx,w,6.2,vec![]); assert!(!gap.iter().any(|(text,_)|text=="组合画布操作"), "completed tools fold during a provider wait"); - assert!(gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.center(); + assert!(gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); + let header = gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.center(); click(&ctx,w,6.3,header); click(&ctx,w,6.6,header); w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:执行原生操作","event":{ "version":1,"type":"tool","run":"trace-run","toolCallId":"two","toolName":"native_call","status":"started"}})); let closed = frame(&ctx,w,12.5,vec![]); assert!(!closed.iter().any(|(text,_)|text=="组合画布操作" || text=="执行原生操作"), "new tools must respect the reader's collapsed state"); - assert!(closed.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.top() < closed.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = closed.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.center(); + assert!(closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.top() < closed.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); + let header = closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.center(); click(&ctx,w,12.6,header); w.busy = None; let held = frame(&ctx,w,20.0,vec![]); @@ -5311,8 +5320,8 @@ mod tests { let mut labels = Vec::new(); for shape in &output.shapes { texts(&shape.shape, &mut labels); } let top = |label: &str| labels.iter().find(|(text, _)| text.starts_with(label)).unwrap_or_else(|| panic!("missing {label}: {labels:?}")).1.top(); - assert!(top("用户请求") < top("正在深度思考…") && top("正在深度思考…") < top("工具调用")); - assert!(top("工具调用") < top("正式回复")); + assert!(top("用户请求") < top("正在深度思考…") && top("正在深度思考…") < top("已完成 1 项 · 正在执行原生操作…")); + assert!(top("已完成 1 项 · 正在执行原生操作…") < top("正式回复")); assert!(!labels.iter().any(|(text, _)| text == "内部思考内容")); let mut dots = Vec::new(); for shape in &output.shapes { circles(&shape.shape, &mut dots); } @@ -5369,7 +5378,7 @@ mod tests { for _ in 0..2 { frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); } let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); assert!(!shows(&labels, "过程说明")); - let order = ["我先核对原图。", "模板已就绪。", "工具调用", "正在安排图位。", "已深度思考", "全部图位已完成。"]; + let order = ["我先核对原图。", "模板已就绪。", "已完成 · 读取画布", "正在安排图位。", "已深度思考", "全部图位已完成。"]; let positions: Vec<_> = order.iter().map(|prefix| rows_of(&labels, prefix)[0]).collect(); assert!(positions.windows(2).all(|rows| rows[0] < rows[1]), "{labels:?}"); assert!(requests.try_recv().is_err()); @@ -5423,9 +5432,9 @@ 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.contains("tokens")), "token counts stay off the timeline"); - assert_eq!(thinking_usage(&w.messages[1]["output"]).0.as_deref(), Some("≈128 tokens · ≈44 tok/s")); - assert_eq!(thinking_usage(&w.messages[1]["output"]).1, "输出用量暂为估算,模型回传后校准。速度从首段输出开始计算。"); + 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 == "独立思考原文")); assert!(!running.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); w.busy = None; @@ -5436,8 +5445,8 @@ mod tests { 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.contains("tokens")), "a finished turn keeps its usage on hover"); - assert_eq!(thinking_usage(&w.messages[1]["output"]), (Some("145 tokens · 45 tok/s".to_owned()), "本次输出用量由模型回传。速度从首段输出开始计算。")); + 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())); 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), @@ -5539,28 +5548,29 @@ mod tests { w.stream_reply = stream.into(); let id = Id::unique("completed-stream-trace"); handoff_frame(&ctx,w,0.0,id); - let (before, _) = handoff_frame(&ctx,w,0.3,id); + let (before, _) = handoff_frame(&ctx,w,0.70,id); let top = before.iter().find(|(text,_,_,_)|text==stream).unwrap().1.top(); 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.4,id); + let (first, _) = handoff_frame(&ctx,w,0.80,id); let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==final_text) .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.5,id); + let (during, meshes) = handoff_frame(&ctx,w,0.90,id); let (_,rect,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 (settled, meshes) = handoff_frame(&ctx,w,0.7,id); + 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 (_,_,alpha,sections) = settled.iter().find(|(text,_,_,_)| text==final_text).unwrap(); assert_eq!(*alpha,255); - assert!(sections.iter().all(|alpha| *alpha == 255), "suffix settles after 220ms"); + 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()); @@ -5597,13 +5607,13 @@ mod tests { found }; frame(&mut app,0.0); - let before = frame(&mut app,0.3); + let before = frame(&mut app,0.65); assert_eq!(before.len(), 1); let w = app.jiansun.as_mut().unwrap(); w.messages.push(json!({"role":"assistant","kind":"reply","text":"无用户行的流式回复"})); w.stream_reply.clear(); w.busy = None; - let after = frame(&mut app,0.4); + let after = frame(&mut app,0.75); assert_eq!(after.len(), 1, "the final receipt must paint exactly once"); assert_eq!(after[0].1, 255, "visible text must not restart its opacity entrance"); assert_eq!(after[0].0.top(), before[0].0.top(), "the reply keeps its vertical anchor"); @@ -5716,9 +5726,9 @@ mod tests { let foreign = json!({"version":1,"type":"tool","status":"started","toolName":"secret tool"}); assert_eq!(tool_activity_label(&foreign).unwrap().0, "进行中 · 工具"); let timed = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":1250}); - assert_eq!(tool_activity_label(&timed).unwrap().0, "已完成 · 读取画布 · 耗时 1.3 秒"); + assert_eq!(tool_activity_label(&timed).unwrap().0, "已完成 · 读取画布 · 1.3s"); assert_eq!((duration_text(25), duration_text(9_999), duration_text(27_400), duration_text(61_200)), - ("耗时 25 毫秒".to_owned(), "耗时 10.0 秒".to_owned(), "耗时 27 秒".to_owned(), "耗时 1 分 01 秒".to_owned())); + ("25ms".to_owned(), "10.0s".to_owned(), "27s".to_owned(), "1m01s".to_owned())); let running = json!({"version":1,"type":"tool","status":"started","toolName":"canvas_read","durationMs":1250}); assert_eq!(tool_activity_label(&running).unwrap().0, "进行中 · 读取画布", "never invent an elapsed time from a nonterminal event"); let invalid = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":-1}); @@ -7380,7 +7390,7 @@ mod tests { h.render().unwrap().save(path).unwrap(); }; save(&mut h, "collapsed"); - let button = h.get_by_label("工具调用").rect().center(); + let button = h.get_by_label("已完成 2 项操作").rect().center(); h.hover_at(button); h.run_steps(2); for pressed in [true, false] { @@ -7408,8 +7418,10 @@ mod tests { w.messages = vec![ json!({"role":"user","text":"核对当前画布后继续制作。"}), json!({"role":"assistant","kind":"reply","text":"先看首屏卖点和原片是否一致。"}), + json!({"role":"assistant","kind":"thinking","active":false,"output":{"tokens":293}}), json!({"role":"assistant","kind":"activity","event":{"version":1,"type":"tool","run":"visual", "toolCallId":"call_4fca7b5|fc_0c72ae9","toolName":"canvas_read","status":"started"}}), + json!({"role":"assistant","kind":"activity","text":"模板已就绪。"}), ]; let mut h = egui_kittest::Harness::builder() .with_size(vec2(360.0, 520.0)).with_step_dt(1.0 / 120.0).wgpu() @@ -7428,16 +7440,16 @@ mod tests { h.run_steps(48); save(&mut h, "tool-running"); let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages[2]["event"]["status"] = json!("completed"); - w.messages[2]["event"]["durationMs"] = json!(320); + w.messages[3]["event"]["status"] = json!("completed"); + w.messages[3]["event"]["durationMs"] = json!(320); w.messages.push(json!({"role":"assistant","kind":"reply","text":"首屏原片与文案一致,接下来核对主图的构图和规格。"})); h.run_steps(19); save(&mut h, "inline-reveal"); h.run_steps(89); save(&mut h, "tool-completion-hold"); - h.run_steps(38); + h.run_steps(44); save(&mut h, "tool-collapsing"); - h.run_steps(60); + h.run_steps(160); save(&mut h, "tool-folded"); assert!(requests.try_recv().is_err()); } @@ -7773,7 +7785,7 @@ mod tests { }); let mut labels = Vec::new(); for shape in &output.shapes { collect(&shape.shape, &mut labels); } - let heads: Vec<_> = labels.iter().filter(|(s, _)| s=="工具调用").map(|(_, y)| *y).collect(); + let heads: Vec<_> = labels.iter().filter(|(s, _)| s=="已完成 2 项操作" || s.starts_with("已完成 · ")).map(|(_, y)| *y).collect(); let y = |name: &str| labels.iter().find(|(s, _)| s==name).unwrap().1; assert_eq!(heads.len(), 2, "visible timeline labels at {width}: {labels:?}"); assert!(y("先核对商品原片") < heads[0] && heads[0] < y("原片核对完成,接着制作")); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs index 6baf1a11..04b2ad73 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs @@ -1,6 +1,6 @@ //! Working-state vocabulary for the 小壹 timeline. Every event in the -//! conversation reads as the same quiet row, production progress is a single -//! row of cells, and suggestions are borderless chips. Materials and motion +//! conversation reads as the same quiet row, production progress uses individual +//! cells, and suggestions are borderless chips. Materials and motion //! stay with `stitch_ui` and `agent_motion`; this module fixes only geometry //! and typography so the rows cannot drift apart. Sizes and colours come from //! `theme::agent_scale` and the semantic tokens; nothing here reads copy to decide a state. @@ -29,14 +29,47 @@ pub(super) fn cell_verified(t: &Tokens) -> Color32 { t.agent_semantic().verified /// is about 49pt wide (three dots, a letter, the padding); a waiting one owns /// no dots. The list gives both the same width so their labels share a column. pub(super) const WORKER_BADGE_WIDTH: f32 = 50.0; -/// How much of a folded narration's first line its hover preview carries. +const EVENT_ICON_X: f32 = 12.0; +const EVENT_ICON_CLEARANCE: f32 = 9.0; +const EVENT_LABEL_X: f32 = 26.0; +const EVENT_END_GAP: f32 = 5.0; +const EVENT_CHEVRON_SPACE: f32 = 18.0; +pub(super) const DISCLOSURE_LABEL_SPACE: f32 = EVENT_LABEL_X + EVENT_END_GAP + EVENT_CHEVRON_SPACE; -/// A row's colour only. Rows never animate: the one waiting mark of a turn -/// belongs to the status row, so `Active` just brightens the text. +/// Process rows in the same uninterrupted part of a turn share a quiet rail. +#[derive(Default)] +pub(super) struct Flow(Option); + +impl Flow { + pub(super) fn connect(&mut self, ui: &Ui, current: Rect) { + if let Some(previous) = self.0.replace(current) + && let Some(segment) = flow_segment(previous, current, ui.ctx().pixels_per_point()) + { + let color = Tokens::get(ui.ctx()).agent().card_border; + ui.painter().line_segment(segment, Stroke::new(1.0 / ui.ctx().pixels_per_point(), color)); + } + } + + pub(super) fn break_run(&mut self) { + self.0 = None; + } +} + +fn flow_segment(previous: Rect, current: Rect, scale: f32) -> Option<[egui::Pos2; 2]> { + let x = (((current.left() + EVENT_ICON_X) * scale).floor() + 0.5) / scale; + let top = previous.center().y + EVENT_ICON_CLEARANCE; + let bottom = current.center().y - EVENT_ICON_CLEARANCE; + (bottom > top).then(|| [egui::pos2(x, top), egui::pos2(x, bottom)]) +} + +/// A row's semantic text and icon treatment. #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum EventTone { Quiet, Active, + Working, + Thinking, + Success, Warning, Failure, } @@ -93,21 +126,38 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - } let tint = match row.tone { EventTone::Quiet => t.text_dim, - EventTone::Active => t.text, + EventTone::Active | EventTone::Working | EventTone::Thinking => t.text, + EventTone::Success => t.text_dim, EventTone::Warning => t.warning, EventTone::Failure => t.danger, }; if ui.is_rect_visible(rect) { let painter = ui.painter_at(rect.intersect(ui.clip_rect())); let middle = rect.center().y; - crate::icons::paint(ui, Rect::from_center_size(egui::pos2(rect.left() + 12.0, middle), Vec2::splat(14.0)), - row.glyph, 14.0, tint); - let mut end = rect.right() - 5.0; + let center = egui::pos2(rect.left() + EVENT_ICON_X, middle); + let icon_rect = Rect::from_center_size(center, Vec2::splat(14.0)); + match row.tone { + EventTone::Working => working_ring(ui, icon_rect, t.text_dim, reduced), + EventTone::Thinking => { + if !reduced { + let time = ui.input(|input| input.time); + let breath = (0.5 + 0.5 * (time * std::f64::consts::TAU / 2.4).sin()) as f32; + painter.circle_filled(center, 9.0, t.text_dim.gamma_multiply(0.035 + 0.075 * breath)); + super::agent_motion::schedule(ui, icon_rect, super::agent_motion::Pace::Idle); + } + crate::icons::paint(ui, icon_rect, row.glyph, 14.0, tint); + } + _ => { + let icon_color = if row.tone == EventTone::Success { t.agent_semantic().success } else { tint }; + crate::icons::paint(ui, icon_rect, row.glyph, 14.0, icon_color); + } + } + let mut end = rect.right() - EVENT_END_GAP; if let RowAction::Expand(open) = row.action { let chevron = if open { "chevron-down" } else { "chevron-right" }; crate::icons::paint(ui, Rect::from_center_size(egui::pos2(end - 6.5, middle), Vec2::splat(13.0)), chevron, 13.0, t.text_dim); - end -= 18.0; + end -= EVENT_CHEVRON_SPACE; } if let Some(meta) = row.meta.filter(|meta| !meta.is_empty()) { let galley = painter.layout_no_wrap(meta.to_owned(), Type::Meta.font_id(), t.text_faint); @@ -116,7 +166,7 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - painter.galley(egui::pos2(end, top), galley, t.text_faint); end -= 8.0; } - let start = rect.left() + 26.0; + let start = rect.left() + EVENT_LABEL_X; let mut job = egui::text::LayoutJob::simple_singleline(row.text.to_owned(), Type::Meta.font_id(), tint); job.wrap.max_width = (end - start).max(1.0); job.wrap.max_rows = 1; @@ -134,6 +184,20 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - if interactive { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } } +pub(super) fn working_ring(ui: &Ui, rect: Rect, tint: Color32, reduced: bool) { + if !ui.is_rect_visible(rect) { return; } + let time = if reduced { 0.0 } else { ui.input(|input| input.time) }; + let phase = (time / 2.4).fract() as f32 * std::f32::consts::TAU; + let painter = ui.painter(); + painter.circle_stroke(rect.center(), 5.0, Stroke::new(1.2, tint.gamma_multiply(0.25))); + let points = (0..=10).map(|step| { + let angle = phase + step as f32 * 0.20; + rect.center() + vec2(angle.cos(), angle.sin()) * 5.0 + }).collect(); + painter.add(egui::Shape::line(points, Stroke::new(1.3, tint))); + if !reduced { super::agent_motion::schedule(ui, rect, super::agent_motion::Pace::Idle); } +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Cell { Empty, @@ -302,6 +366,31 @@ pub(super) fn worker_stage(step: &str, review: bool, from_image: bool) -> &'stat #[cfg(test)] mod tests { use super::*; + use crate::jiansun::test_support::SettleUi; + + #[test] + fn timeline_rail_joins_process_rows_and_clears_the_icon_centers() { + let row = |y| Rect::from_min_size(egui::pos2(8.0, y), vec2(200.0, 30.0)); + for scale in [1.0, 1.25, 1.5] { + let [start, end] = flow_segment(row(0.0), row(30.0), scale).unwrap(); + assert_eq!((start.x * scale).fract(), 0.5); + assert_eq!(start.x, end.x); + assert_eq!((start.y, end.y), (24.0, 36.0)); + } + let ctx = egui::Context::default(); + let frame = ctx.settle_ui(egui::RawInput::default(), |ui| { + let mut flow = Flow::default(); + flow.connect(ui, row(0.0)); + flow.connect(ui, row(30.0)); + flow.break_run(); + flow.connect(ui, row(90.0)); + }); + let segments: Vec<_> = frame.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::LineSegment { points, stroke } => Some((points, stroke.width)), + _ => None, + }).collect(); + assert_eq!(segments, vec![(&[egui::pos2(20.5, 24.0), egui::pos2(20.5, 36.0)], 1.0)]); + } #[test] fn event_rows_preserve_active_warning_and_failure_tones() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs index b2128772..4e91ef17 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -471,14 +471,17 @@ pub(super) fn tool_glyph(tool: &str) -> &'static str { /// 人读耗时读个大概:一秒以内给毫秒,十秒以内给一位小数,一分钟以内给整秒,再往上给分秒。 pub(super) fn duration_text(ms: u64) -> String { match ms { - 0..=999 => format!("耗时 {ms} 毫秒"), - 1000..=9_999 => format!("耗时 {}.{} 秒", (ms + 50) / 100 / 10, (ms + 50) / 100 % 10), + 0..=999 => format!("{ms}ms"), + 1000..=9_999 => { + let tenths = (ms + 50) / 100; + format!("{}.{}s", tenths / 10, tenths % 10) + } _ => { - let seconds = (ms + 500) / 1000; + let seconds = ms / 1000 + u64::from(ms % 1000 >= 500); if seconds < 60 { - format!("耗时 {seconds} 秒") + format!("{seconds}s") } else { - format!("耗时 {} 分 {:02} 秒", seconds / 60, seconds % 60) + format!("{}m{:02}s", seconds / 60, seconds % 60) } } } @@ -650,9 +653,9 @@ mod tests { assert_eq!(tool_glyph("memory_set"), "type"); assert_eq!(tool_glyph("workflow_propose"), "folder-open"); assert_eq!(tool_glyph("anything-else"), "settings"); - assert_eq!(duration_text(27), "耗时 27 毫秒"); - assert_eq!(duration_text(1300), "耗时 1.3 秒"); - assert_eq!(duration_text(27_400), "耗时 27 秒"); - assert_eq!(duration_text(61_600), "耗时 1 分 02 秒"); + assert_eq!(duration_text(27), "27ms"); + assert_eq!(duration_text(1300), "1.3s"); + assert_eq!(duration_text(27_400), "27s"); + assert_eq!(duration_text(61_600), "1m02s"); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs index 9c244272..ed572613 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -37,14 +37,13 @@ impl ThinkingStatus { } } - fn tone(self) -> Tone { - match self { Self::Active => Tone::Active, Self::Interrupted | Self::Done => Tone::Quiet } - } } -pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, usage_hint: Option<&str>, reduced: bool) -> Response { +pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, usage: Option<&str>, reduced: bool) -> Response { agent_stream::event_row(ui, id, EventRow { - glyph: "sparkles", text: status.label(), meta: None, tone: status.tone().into(), hint: usage_hint, action: RowAction::None, + glyph: "sparkles", text: status.label(), meta: usage, + tone: if status == ThinkingStatus::Active { EventTone::Thinking } else { EventTone::Quiet }, + hint: None, action: RowAction::None, }, reduced) } @@ -54,12 +53,45 @@ pub(super) use kit::ToolGroupHead; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct ToolRow<'a> { pub tool: &'a str, pub name: &'a str, pub status: ToolStatus, pub elapsed: Option<&'a str> } -pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) { - kit::tool_group_head(ui, id, "工具调用", Some(&head.count()), head, reduced, |ui| { +fn tool_group_summary(ui: &Ui, head: ToolGroupHead, rows: &[ToolRow<'_>]) -> (String, Option) { + if head.failed > 0 { + return (format!("{} 项操作失败", head.failed), Some(format!("{}/{} 已完成", head.completed, head.total))); + } + if head.active { + let activity = if let Some(row) = rows.iter().rev().find(|row| row.status == ToolStatus::Started) { + format!("正在{}…", row.name) + } else if let Some(row) = rows.iter().find(|row| row.status == ToolStatus::Pending) { + format!("等待 · {}", row.name) + } else { + "正在处理…".to_owned() + }; + if head.completed > 0 { + let summary = format!("已完成 {} 项 · {activity}", head.completed); + let width = ui.painter().layout_no_wrap(summary.clone(), Type::Meta.font_id(), Color32::PLACEHOLDER).size().x; + if width + agent_stream::DISCLOSURE_LABEL_SPACE <= ui.available_width() { + return (summary, None); + } + } + return (activity, None); + } + if head.completed == head.total { + return if let [row] = rows { + (format!("已完成 · {}", row.name), row.elapsed.map(str::to_owned)) + } else { + (format!("已完成 {} 项操作", head.completed), Some(format!("{}/{}", head.completed, head.total))) + }; + } + let stopped = rows.iter().any(|row| row.status == ToolStatus::Stopped); + (if stopped { "工具调用已停止" } else { "工具调用待核查" }.to_owned(), Some(format!("{}/{} 已完成", head.completed, head.total))) +} + +pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) -> Response { + let (label, meta) = tool_group_summary(ui, head, rows); + kit::tool_group_head(ui, id, &label, meta.as_deref(), head, reduced, |ui| { for (index, row) in rows.iter().enumerate() { kit::task_status_row(ui, id.with(("tool", index)), tool_glyph(row.tool), row.name, row.status, row.elapsed, reduced); } - }); + }) } /// 6. 通知:图标与色调取自 `NoticeKind`,失败、待核查、未执行不再共用一个图标。 @@ -736,7 +768,7 @@ mod tests { // 这一组含失败项,默认折叠;测试里先展开,好核对各行。 ui.data_mut(|data| data.insert_temp(id.with("tools").with("open"), true)); tool_group(ui, id.with("tools"), ToolGroupHead { total: 3, completed: 2, failed: 1, active: false }, &[ - ToolRow { tool: "canvas_read", name: "读取画布", status: ToolStatus::Completed, elapsed: Some("耗时 0.4 秒") }, + ToolRow { tool: "canvas_read", name: "读取画布", status: ToolStatus::Completed, elapsed: Some("400ms") }, ToolRow { tool: "generate_slot_image", name: "生成候选图片", status: ToolStatus::Failed, elapsed: None }, ToolRow { tool: "check_image_slots", name: "发起验图", status: ToolStatus::Started, elapsed: None }, ], true); @@ -769,7 +801,7 @@ mod tests { assert_eq!(interaction, 2); assert_eq!(suggestions.len(), 2); let drawn = texts(&output); - for expected in ["给这款边几做一整套详情页", "边几 · 胡桃木", "已深度思考", "工具调用", "2/3 已完成 · 1 项失败", "读取画布", "失败", + for expected in ["给这款边几做一整套详情页", "边几 · 胡桃木", "已深度思考", "1 项操作失败", "2/3 已完成", "读取画布", "主图 4 · 细节特写没生成出来", "有一条对话未确认结果", "整套已经推进到主图这一步。", "生成图片", "添加待审核建议", "执行创作操作", "先不用", "选一个卖点方向", "继续做剩下的 SKU 图"] { assert!(drawn.iter().any(|text| text == expected), "{expected} is drawn: {drawn:?}"); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 54af2e74..100e8331 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -307,26 +307,11 @@ pub(super) fn ai_loader(ui: &mut Ui, id: egui::Id, running: bool, reduced: bool) /// Only public, allowlisted activity is passed in by the business layer. /// Each group keeps its own disclosure choice as tool states change. The -/// heading is the same quiet row as every other timeline event; only an open -/// group spends a card on its rows. +/// heading is the same quiet row as every other timeline event. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) struct ToolGroupHead { pub total: usize, pub completed: usize, pub failed: usize, pub active: bool } -impl ToolGroupHead { - pub(super) fn tone(self) -> Tone { - if self.failed > 0 { Tone::Failure } else if self.active { Tone::Active } else { Tone::Quiet } - } - - pub(super) fn count(self) -> String { - let mut count = format!("{}/{} 已完成", self.completed, self.total); - if self.failed > 0 { - count.push_str(&format!(" · {} 项失败", self.failed)); - } - count - } -} - -/// 工具调用组的外壳:标题行与可折叠的卡片。计数与成败由调用方结构化给出,不从标题文案里拆。 +/// 工具调用组的展开选择与完成后的停留时钟。 #[derive(Clone, Copy, Default)] struct ToolDisclosure { open: bool, @@ -350,14 +335,18 @@ impl ToolDisclosure { } } -pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count: Option<&str>, head: ToolGroupHead, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { +pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, meta: Option<&str>, head: ToolGroupHead, reduced: bool, body: impl FnOnce(&mut Ui) -> R) -> Response { use super::agent_stream::{EventRow, EventTone, RowAction}; let key = id.with("disclosure"); let now = ui.input(|input| input.time); let mut state = ui.data(|data| data.get_temp::(key)).unwrap_or_default(); state.update(now, head.active, head.failed > 0); + let (glyph, tone) = if head.failed > 0 { ("triangle-alert", EventTone::Failure) } + else if head.active { ("circle-dashed", EventTone::Working) } + else if head.completed == head.total { ("check", EventTone::Success) } + else { ("info", EventTone::Warning) }; let header = super::agent_stream::event_row(ui, id.with("header"), EventRow { - glyph: "settings", text: heading, meta: count, tone: EventTone::from(head.tone()), + glyph, text: heading, meta, tone, hint: None, action: RowAction::Expand(state.open), }, reduced); if header.clicked() { @@ -370,17 +359,13 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((finished + ToolDisclosure::HOLD_SECONDS - now).max(0.0))); } morph_surface(ui, id.with("tool-body"), state.open, reduced, |ui| { - ui.horizontal(|ui| { - ui.add_space(space::MD); - surface(ui, SurfaceRole::Task, |ui| { - ui.vertical(|ui| { - ui.set_width(ui.available_width().max(1.0)); - body(ui); - }); - }); + egui::Frame::NONE.inner_margin(egui::Margin { left: 26, top: 2, right: 5, bottom: 4 }).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + body(ui) }); }); ui.data_mut(|data| data.insert_temp(key, state)); + header } /// 旧签名垫片:标题形如"工具调用 · 3/5 已完成 · 1 项失败",成败仍从文案里读。 @@ -389,7 +374,7 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { let (heading, count) = title.split_once(" · ").map_or((title, None), |(heading, count)| (heading, Some(count))); let head = ToolGroupHead { active, failed: usize::from(title.contains("失败")), total: 0, completed: 0 }; - tool_group_head(ui, id, heading, count, head, reduced, body) + tool_group_head(ui, id, heading, count, head, reduced, body); } /// A static capacity ring; missing measurements show only the neutral track. @@ -420,51 +405,48 @@ pub(super) fn task_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, stat /// 一行工具调用:图标、状态徽标与可选的真实耗时。文案、色调与图标都取自 `ToolStatus`。 pub(super) fn task_status_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, status: ToolStatus, elapsed: Option<&str>, reduced: bool) { let t = Tokens::get(ui.ctx()).agent(); - let state = status.label(); let running = status == ToolStatus::Started; - let text_color = status.tone().color(&t); - let status_galley = ui.painter().layout_no_wrap(state.to_owned(), Type::Meta.font_id(), text_color); - let name_galley = ui.painter().layout_no_wrap(name.to_owned(), Type::Meta.font_id(), t.text); - let timer_height = elapsed.map_or(0.0, |text| ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), t.text_dim).size().y.max(12.0)); - let badge_height = status_galley.size().y.max(12.0) + space::SM; - let row_height = badge_height.max(name_galley.size().y).max(timer_height).max(icon::MD); - let row = ui.allocate_ui_with_layout(vec2(ui.available_width(), row_height), egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| { - ui.add(crate::icons::image(glyph, icon::MD, t.text_dim)); - ui.label(RichText::new(name).size(Type::Meta.size()).color(t.text)); - let size = vec2(space::SM + icon::SM + space::XS + status_galley.size().x + space::SM, badge_height); - let (rect, response) = ui.allocate_exact_size(size, egui::Sense::empty()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, state)); - ui.painter().rect_filled(rect, radius::CONTROL, t.field); - let color = match status { - ToolStatus::Completed => t.agent_semantic().success, - ToolStatus::Failed => t.danger, - ToolStatus::Stopped => t.warning, - _ => t.text_dim, + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), egui::Sense::empty()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{name} · {}", status.label()))); + if !ui.is_rect_visible(rect) { return; } + let painter = ui.painter_at(rect); + let mid = rect.center().y; + let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + 7.0, mid), vec2(14.0, 14.0)); + if running { + super::agent_stream::working_ring(ui, icon, t.text_dim, reduced); + } else { + let (glyph, tint) = match status { + ToolStatus::Completed => ("check", t.agent_semantic().success), + ToolStatus::Failed => ("triangle-alert", t.danger), + ToolStatus::Stopped => ("triangle-alert", t.warning), + _ => (glyph, t.text_faint), }; - let alpha = if running && !reduced { 0.55 + 0.45 * ((ui.input(|i| i.time) as f32 * std::f32::consts::TAU).sin() * 0.5 + 0.5) } else { 1.0 }; - let image = crate::icons::image(status.glyph(), icon::SM, color.gamma_multiply(alpha)); - let image = if running && !reduced { - image.rotate((ui.input(|i| i.time).rem_euclid(timing::LOADER_PERIOD) / timing::LOADER_PERIOD * std::f64::consts::TAU) as f32, vec2(0.5, 0.5)) - } else { image }; - image.paint_at(ui, egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), vec2(icon::SM, icon::SM))); - let text_pos = egui::pos2(rect.left() + 24.0, rect.center().y - status_galley.size().y * 0.5); - ui.painter().galley(text_pos, status_galley.clone(), text_color); - if let Some(elapsed) = elapsed { timer(ui, elapsed); } - }); - if running && !reduced { schedule(ui, row.response.rect, Pace::Full); } -} - -/// A compact, non-interactive timer sourced entirely from the caller's actual -/// upstream duration. Reserving the measured group keeps it on one line. -pub(super) fn timer(ui: &mut Ui, elapsed: &str) { - let t = Tokens::get(ui.ctx()).agent(); - let galley = ui.painter().layout_no_wrap(elapsed.to_owned(), Type::Meta.font_id(), t.text_dim); - let width = galley.size().x + 16.0; - ui.allocate_ui_with_layout(vec2(width, galley.size().y.max(12.0)), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.add(crate::icons::image("clock", 12.0, t.text_dim)); - ui.add(egui::Label::new(RichText::new(elapsed).size(Type::Meta.size()).color(t.text_dim)).extend()); - }); + crate::icons::paint(ui, icon, glyph, 14.0, tint); + } + let mut end = rect.right(); + if let Some(elapsed) = elapsed { + let digits = painter.layout_no_wrap(elapsed.to_owned(), crate::theme::mono(Type::Meta.size()), t.text_faint); + end -= digits.size().x; + painter.galley(egui::pos2(end, mid - digits.size().y * 0.5), digits, t.text_faint); + end -= 8.0; + } + let color = if running || status == ToolStatus::Failed { t.text } else { t.text_dim }; + let start = rect.left() + 22.0; + let mut job = egui::text::LayoutJob::default(); + let font_id = Type::Meta.font_id(); + job.append(name, 0.0, egui::TextFormat::simple(font_id.clone(), color)); + if let Some(label) = match status { + ToolStatus::Failed | ToolStatus::Stopped => Some(status.label()), + ToolStatus::Unknown => Some("待核查"), + _ => None, + } { + job.append(" · ", 0.0, egui::TextFormat::simple(font_id.clone(), t.text_faint)); + job.append(label, 0.0, egui::TextFormat::simple(font_id, t.text_faint)); + } + job.wrap.max_width = (end - start).max(1.0); + job.wrap.max_rows = 1; + let line = painter.layout_job(job); + painter.galley(egui::pos2(start, mid - line.size().y * 0.5), line, color); } pub(super) fn disclosure(ui: &mut Ui, id: egui::Id, title: &str, default_open: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) -> Response { @@ -656,7 +638,7 @@ pub(super) fn animate_galley( } reveal::light_trail(&mut tokens, now); } - // 入场:单字 300ms 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); @@ -2455,7 +2437,6 @@ pub(super) fn ui_fonts_ready(ui: &Ui) -> bool { mod tests { use super::*; use crate::jiansun::test_support::SettleUi; - use super::super::stitch_state::tool_glyph; use super::ToolGroupHead; /// Exercise the real lazy system-font loader until both the actual CJK @@ -2816,60 +2797,58 @@ mod tests { fn tool_task_row_renders_real_status_and_only_supplied_duration() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for (status, elapsed, expected) in [("started", None, "进行中"), ("completed", Some("耗时 1.3 秒"), "已完成"), ("failed", None, "失败"), ("unknown", None, "状态未知")] { + for (status, elapsed, name) in [ + ("started", None, "读取项目规则"), + ("completed", Some("1.3s"), "读取项目规则"), + ("failed", None, "读取项目规则 · 失败"), + ("unknown", None, "读取项目规则 · 待核查"), + ] { let output = ctx.settle_ui(egui::RawInput::default(), |ui| task_row(ui, egui::Id::unique("task"), "settings", "读取项目规则", status, elapsed, true)); let texts: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Text(text) => Some(text.galley.text()), _ => None }).collect(); - assert!(texts.contains(&"读取项目规则") && texts.contains(&expected)); - assert_eq!(texts.iter().any(|text| text.contains("耗时")), elapsed.is_some()); + assert!(texts.contains(&name), "{texts:?}"); + assert_eq!(texts.contains(&"1.3s"), elapsed.is_some()); + assert!(!texts.iter().any(|text| text.contains("耗时") || *text == "已完成")); } } #[test] - fn task_status_badges_are_compact_without_changing_parent_interaction_height() { + fn tool_group_body_and_task_rows_have_no_frames() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let t = Tokens::get(&ctx).agent(); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() }, |ui| { - scope_with_motion(ui, false, |ui| { - let interaction_height = ui.spacing().interact_size.y; - task_row(ui, egui::Id::unique("compact-badge"), "check", "读取画布", "completed", Some("耗时 1.3 秒"), false); - assert_eq!(ui.spacing().interact_size.y, interaction_height); + scope_with_motion(ui, true, |ui| { + let head = ToolGroupHead { total: 2, completed: 1, failed: 0, active: true }; + tool_group_head(ui, egui::Id::unique("plain-body"), "正在更新图层…", None, head, true, |ui| { + let top = ui.next_widget_position().y; + task_row(ui, egui::Id::unique("plain-row"), "check", "读取画布", "completed", Some("1.3s"), true); + assert!((ui.min_rect().bottom() - top - 26.0).abs() < 0.5); + }); }); }); - let badges: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) if rect.fill == t.field => Some(rect.rect), - _ => None, - }).collect(); - assert_eq!(badges.len(), 1); - assert!((20.0..=26.0).contains(&badges[0].height()), "actual status badge: {:?}", badges[0]); + assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) + if rect.fill == t.field || rect.stroke.color == t.card_border))); } #[test] - fn task_status_glyph_centers_match_name_at_multiple_scales_and_widths() { + fn task_name_and_monospace_duration_use_the_same_line_at_all_scales() { for ppp in [1.25, 1.5] { for width in [250.0, 400.0] { let ctx = Context::default(); ctx.set_pixels_per_point(ppp); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 200.0))), ..Default::default() }, |ui| { - task_row(ui, egui::Id::unique("baseline-check"), "search", "读取画布", "completed", Some("耗时 27 毫秒"), true); + task_row(ui, egui::Id::unique("three-columns"), "search", "读取画布", "completed", Some("27ms"), true); }); let find = |wanted| output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == wanted => { - let row = text.galley.rows.first()?; - let glyph = row.glyphs.first()?; - let baseline = text.pos.y + row.pos.y + glyph.pos.y; - Some((baseline, text.galley.mesh_bounds.translate(text.pos.to_vec2()))) - } + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text), _ => None, }).expect("painted task text"); - let (name_baseline, name) = find("读取画布"); - let (status_baseline, status) = find("已完成"); - assert!((name_baseline - status_baseline).abs() <= 1.0 / ppp, "ppp={ppp} width={width}: name baseline={name_baseline}, status baseline={status_baseline}; {name:?} / {status:?}"); - let (elapsed_baseline, elapsed) = find("耗时 27 毫秒"); - if (elapsed_baseline - name_baseline).abs() < 5.0 { - assert!((elapsed_baseline - name_baseline).abs() <= 1.0 / ppp, "ppp={ppp} width={width}: name baseline={name_baseline}, timer baseline={elapsed_baseline}; {name:?} / {elapsed:?}"); - } else { assert!(elapsed.top() >= name.bottom(), "wrapped timer must begin below the first row: {name:?} / {elapsed:?}"); } + let name = find("读取画布"); + let elapsed = find("27ms"); + assert!((elapsed.pos.y + elapsed.galley.size().y / 2.0 - name.pos.y - name.galley.size().y / 2.0).abs() <= 1.0 / ppp); + assert!(elapsed.pos.x > name.pos.x + name.galley.size().x); + assert_eq!(elapsed.galley.job.sections[0].format.font_id, crate::theme::mono(Type::Meta.size())); } } } @@ -2880,10 +2859,10 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 200.0))), ..Default::default() }, |ui| { ui.set_width(250.0); - task_row(ui, egui::Id::unique("narrow-duration"), "search", "读取项目规则", "completed", Some("耗时 27 毫秒"), true); + task_row(ui, egui::Id::unique("narrow-duration"), "search", "读取项目规则", "completed", Some("27ms"), true); }); let (clip, text) = output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "耗时 27 毫秒" => Some((shape.clip_rect, text)), + egui::Shape::Text(text) if text.galley.text() == "27ms" => Some((shape.clip_rect, text)), _ => None, }).expect("actual elapsed label is painted"); assert_eq!(text.galley.rows.len(), 1, "duration must never split between lines"); @@ -3386,7 +3365,7 @@ mod tests { if !ui_fonts_ready(ui) { return; } let t = Tokens::get(ui.ctx()).agent(); ui.painter().rect_filled(ui.max_rect(), 0.0, t.dock); - task_row(ui, egui::Id::unique("task-alignment"), "layers", "读取画布", "completed", Some("耗时 25 毫秒"), true); + task_row(ui, egui::Id::unique("task-alignment"), "layers", "读取画布", "completed", Some("25ms"), true); }); crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); h.run_steps(8); @@ -3595,8 +3574,8 @@ mod tests { file_drop_zone(ui, egui::Id::unique("visual-drop-active"), field_width, Some(pointer), true, reduced); tool_group(ui, egui::Id::unique("visual-task"), "工具调用 · 1/3 已完成", true, reduced, |ui| { task_row(ui, egui::Id::unique("visual-running"), "search", "读取项目规则", "started", None, reduced); - task_row(ui, egui::Id::unique("visual-complete"), "check", "读取画布", "completed", Some("耗时 1.3 秒"), reduced); - task_row(ui, egui::Id::unique("visual-failed"), "triangle-alert", "更新图层", "failed", Some("耗时 400 毫秒"), reduced); + task_row(ui, egui::Id::unique("visual-complete"), "check", "读取画布", "completed", Some("1.3s"), reduced); + task_row(ui, egui::Id::unique("visual-failed"), "triangle-alert", "更新图层", "failed", Some("400ms"), reduced); }); ai_loader(ui, egui::Id::unique("visual-loader"), true, reduced); let (pill, _) = ui.allocate_exact_size(vec2(ui.available_width(), 54.0), egui::Sense::hover()); @@ -4329,13 +4308,10 @@ mod tests { /// 品牌动效的定稿参数都落在 Token 上:改这里就是改观感,别处不许再写字面量。 #[test] fn typing_reveal_and_motion_tokens_hold_the_locked_brand_parameters() { - assert!((reveal::ENTER - 0.300).abs() < 1e-9, "单字入场 300ms cubic-out"); + assert!((reveal::ENTER - 0.460).abs() < 1e-9, "单字入场 460ms cubic-out"); assert!((reveal::STEP - 0.015).abs() < 1e-9, "每字步进 15ms"); - assert!((10..=12).contains(&reveal::TAIL), "尾韵约 10–12 字"); - assert!( - (reveal::ENTER + reveal::STEP * reveal::TAIL as f64) < 0.5, - "原型 460ms 的单字节奏已明显加快:一个字入场、整段尾韵铺完都不到半秒" - ); + assert_eq!(reveal::TAIL, 13); + assert_eq!(reveal::MIST, 0.12); 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), "纯待机降到半帧"); @@ -4352,7 +4328,7 @@ mod tests { assert_eq!(timing::DEEP_AFTER, 15.0); } - /// 回复正文逐字入场时带着柔光:流头一团、身后一条约 11 字的光带;定稿后什么都不画、不申请重绘。 + /// 回复正文逐字入场时带着柔光:流头一团、身后一条约 13 字的光带;定稿后什么都不画、不申请重绘。 #[test] fn streaming_reply_carries_a_head_halo_and_a_tail_band_then_goes_completely_still() { let ctx = Context::default(); @@ -4512,61 +4488,4 @@ mod tests { } } - /// 旧的字符串入参行与新的类型化行读出来完全一样:状态文案、颜色与图标只有一份定义。 - #[test] - fn typed_and_legacy_tool_rows_read_the_same_status() { - let ctx = Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - settle_test_cjk_font(&ctx); - let t = Tokens::get(&ctx).agent(); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 120.0))); - let status_color = |output: &egui::FullOutput, label: &str| { - output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == label => Some(text.galley.job.sections.first().map(|section| section.format.color)), - _ => None, - }).flatten().next() - }; - let mut labels = Vec::new(); - for (legacy, typed) in [ - ("pending", ToolStatus::Pending), ("started", ToolStatus::Started), ("completed", ToolStatus::Completed), - ("failed", ToolStatus::Failed), ("stopped", ToolStatus::Stopped), ("nonsense", ToolStatus::Unknown), - ] { - let legacy_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| task_row(ui, egui::Id::unique("legacy"), "search", "读取画布", legacy, Some("耗时 27 毫秒"), true)).inner - }); - let typed_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| task_status_row(ui, egui::Id::unique("typed"), tool_glyph("canvas_read"), "读取画布", typed, Some("耗时 27 毫秒"), true)).inner - }); - assert_eq!(status_color(&legacy_row, typed.label()), Some(typed.tone().color(&t)), "legacy {legacy}"); - assert_eq!(status_color(&typed_row, typed.label()), Some(typed.tone().color(&t)), "typed {legacy}"); - assert!(reply_text_shapes(&typed_row, "读取画布").len() == 1 && reply_text_shapes(&typed_row, "耗时 27 毫秒").len() == 1); - labels.push(typed.label()); - } - assert_eq!(labels, ["等待", "进行中", "已完成", "失败", "已停止", "状态未知"]); - } - - /// 旧的工具组标题垫片与新的类型化标题读出同一行字:计数与失败数只有一处拼法。 - #[test] - fn legacy_tool_group_title_and_typed_head_agree() { - let head = ToolGroupHead { total: 5, completed: 3, failed: 1, active: true }; - assert_eq!(head.count(), "3/5 已完成 · 1 项失败"); - assert_eq!(head.tone(), Tone::Failure, "a failure outranks running for the row's colour"); - assert_eq!(ToolGroupHead { total: 5, completed: 3, failed: 0, active: true }.tone(), Tone::Active); - assert_eq!(ToolGroupHead { total: 5, completed: 5, failed: 0, active: false }.tone(), Tone::Quiet); - let ctx = Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - settle_test_cjk_font(&ctx); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 160.0))); - let texts = |title: &str| { - let output = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| tool_group(ui, egui::Id::unique(("title", title)), title, true, true, |_| ())); - }); - output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) => Some(text.galley.text().to_owned()), - _ => None, - }).collect::>() - }; - let legacy = texts(&format!("工具调用 · {}", head.count())); - assert!(legacy.iter().any(|text| text == "工具调用") && legacy.iter().any(|text| text == "3/5 已完成 · 1 项失败"), "{legacy:?}"); - } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs index 50dde227..808f7621 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs @@ -1,7 +1,7 @@ //! 逐字扩散:输入框、用户气泡与 Agent 正文共用的一套入场与柔光算法。 //! -//! 节奏由用户定稿:单字 300ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光, -//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 11 字宽的尾韵,流头另有一团柔光。 +//! 节奏由用户定稿:单字 460ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光, +//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 13 字宽的尾韵,流头另有一团柔光。 //! 尚未轮到的字先以极淡的光雾占位,光标不会跑到文字前面。 //! //! 这里只管到达时间、柔光数学与柔光网格;字形网格的改写在 `stitch_ui::animate_galley`。 @@ -14,7 +14,7 @@ use unicode_segmentation::UnicodeSegmentation; use super::agent_motion::{Pace, schedule}; -/// 单字入场时长:300ms cubic-out。 +/// 单字入场时长:460ms cubic-out。 pub(super) const ENTER: f64 = timing::REVEAL_ENTER; /// 相邻两字的到达步进:15ms。 pub(super) const STEP: f64 = timing::REVEAL_STEP; @@ -79,9 +79,9 @@ pub(super) struct TrailToken { pub glow: f32, } -/// 尾韵窗口:流头向回第 6 个字以内全亮,到第 13 个字减到零,约 11 字宽。 +/// 尾韵窗口:流头向回第 6 个字以内全亮,到第 15 个字减到零,约 13 字宽。 fn window(distance: usize) -> f32 { - let t = ((distance as f32 - 6.0) / 7.0).clamp(0.0, 1.0); + let t = ((distance as f32 - 6.0) / 9.0).clamp(0.0, 1.0); 1.0 - t * t * (3.0 - 2.0 * t) } @@ -369,8 +369,8 @@ mod tests { } #[test] - fn each_character_enters_in_300ms_with_a_15ms_step_and_bounded_span() { - assert!((ENTER - 0.300).abs() < 1e-9 && (STEP - 0.015).abs() < 1e-9 && TAIL == 11); + fn each_character_enters_in_460ms_with_a_15ms_step_and_bounded_span() { + assert!((ENTER - 0.460).abs() < 1e-9 && (STEP - 0.015).abs() < 1e-9 && TAIL == 13); assert_eq!(batch_step(0), 0.0); assert_eq!(batch_step(1), 0.0); assert_eq!(batch_step(40), STEP); @@ -405,15 +405,15 @@ mod tests { } #[test] - fn trail_is_brightest_at_the_head_and_fades_over_about_eleven_characters() { - // 一批字同时到达:流头自己还在升起,身后几个字叠加到最亮,再向回在约 11 字内收束。 + fn trail_is_brightest_at_the_head_and_fades_over_about_thirteen_characters() { + // 一批字同时到达:流头自己还在升起,身后几个字叠加到最亮,再向回在约 13 字内收束。 let mut tokens: Vec<_> = (0..20).map(|index| token(0, 14.0 * index as f32, 0.0)).collect(); light_trail(&mut tokens, 0.138); assert!(tokens[0].glow > 0.5, "the head is lit"); assert!(tokens[1].glow > 0.99); assert!(tokens[1..].windows(2).all(|pair| pair[0].glow >= pair[1].glow), "light fades away from the head"); - assert!(tokens[11].glow > 0.0 && tokens[11].glow < 0.5 * tokens[1].glow, "the tail is still present but half gone at eleven characters"); - assert_eq!(tokens[13].glow, 0.0, "nothing glows beyond the tail window"); + assert!(tokens[13].glow > 0.0 && tokens[13].glow < 0.5 * tokens[1].glow, "the glow tapers at thirteen characters"); + assert_eq!(tokens[15].glow, 0.0, "nothing glows beyond the tail window"); // 逐字到达:最新的字始终是流头,光带跟着它走。`light_trail` 按由新到旧取字,和 `animate_galley` 的收集顺序一致。 let mut typed: Vec<_> = (0..14).map(|index| token(0, 14.0 * index as f32, (13 - index) as f64 * STEP)).collect(); light_trail(&mut typed, 0.138 + 13.0 * STEP); diff --git a/apps/detail-photocraft/crates/ui-egui/src/theme.rs b/apps/detail-photocraft/crates/ui-egui/src/theme.rs index abaa61d8..5930fce3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/theme.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/theme.rs @@ -1648,7 +1648,7 @@ pub(crate) mod agent_scale { pub(crate) const LG: f32 = 16.0; } - /// 动效时长(秒)。用户定稿的三条:逐字 300ms + 15ms 步进、停止 190ms 收敛、满帧 16ms。 + /// 动效时长(秒)。用户定稿的三条:逐字 460ms + 15ms 步进、停止 190ms 收敛、满帧 16ms。 pub(crate) mod motion { use core::time::Duration; @@ -1682,11 +1682,11 @@ pub(crate) mod agent_scale { /// 光球:一圈 20 秒,呼吸 5.5 秒。 pub(crate) const ORB_LOOP: f64 = 20.0; pub(crate) const ORB_BREATH: f64 = 5.5; - /// 逐字扩散:单字入场 300ms cubic-out,每字步进 15ms,尾韵约 11 字。 - pub(crate) const REVEAL_ENTER: f64 = 0.300; + /// 逐字扩散:单字入场 460ms cubic-out,每字步进 15ms,尾韵约 13 字。 + pub(crate) const REVEAL_ENTER: f64 = 0.460; pub(crate) const REVEAL_STEP: f64 = 0.015; pub(crate) const REVEAL_MAX_SPAN: f64 = 0.650; - pub(crate) const REVEAL_TAIL: usize = 11; + pub(crate) const REVEAL_TAIL: usize = 13; pub(crate) const REVEAL_WAVE: f64 = 0.022; pub(crate) const REVEAL_RISE: f64 = 0.070; pub(crate) const REVEAL_FADE: f64 = 0.430; @@ -1796,7 +1796,7 @@ mod agent_token_tests { } /// 动效时长:对话框与浮层的进退场、表面弹簧、流光周期都保持此前的取值; - /// 用户定稿的三条(逐字 300ms + 15ms、停止 190ms、满帧 16ms)单独钉一遍。 + /// 用户定稿的三条(逐字 460ms + 15ms、停止 190ms、满帧 16ms)单独钉一遍。 #[test] fn agent_motion_tokens_keep_the_dialog_motion_and_pin_the_locked_brand_values() { assert_eq!(motion::NATIVE, 0.22); @@ -1808,9 +1808,8 @@ mod agent_token_tests { assert_eq!((motion::HALO_PERIOD, motion::LOADER_PERIOD), (1.8, 1.2)); assert_eq!((motion::GLOW_SEND, motion::GLOW_SEND_PEAK, motion::GLOW_WAIT_SCALE), (0.640, 0.280, 0.55)); assert_eq!((motion::ORB_LOOP, motion::ORB_BREATH), (20.0, 5.5)); - assert_eq!((motion::REVEAL_ENTER, motion::REVEAL_STEP, motion::REVEAL_MAX_SPAN), (0.300, 0.015, 0.650)); - assert_eq!(motion::REVEAL_TAIL, 11); - assert!((10..=12).contains(&motion::REVEAL_TAIL)); + assert_eq!((motion::REVEAL_ENTER, motion::REVEAL_STEP, motion::REVEAL_MAX_SPAN), (0.460, 0.015, 0.650)); + assert_eq!(motion::REVEAL_TAIL, 13); assert_eq!((motion::REVEAL_WAVE, motion::REVEAL_RISE, motion::REVEAL_FADE), (0.022, 0.070, 0.430)); assert_eq!(motion::REVEAL_SPREAD, 9.0); assert!((0.180..=0.200).contains(&motion::STOP_SETTLE), "停止减速定格收敛在 180–200ms");