合入小壹 P2-7 操作过程协作光标

This commit is contained in:
WuYongJie 2026-11-27 23:25:45 +08:00
commit 4d7938d41f
11 changed files with 678 additions and 10 deletions

View File

@ -117,6 +117,44 @@ function details(event) {
export function activitySummary(event) { return details(event).summary; }
// 只将画布定位标识交给叠层。工具参数和未提交的文案不进入展示事件。
export function canvasPresence(event, { toolName, status }) {
const args = event.args;
if (toolName === 'write_copy_fields') {
if (args?.recordOnly) return;
const layer = status === 'started' ? args?.items?.[0]?.layer
: status === 'completed' ? event.result?.details?.appliedLayers?.at(-1) : undefined;
if (safeNumber(layer) > 0) return { nativeLayerId: layer, writing: true };
}
if (status !== 'started') return;
if (toolName === 'canvas_edit' || toolName === 'canvas_preview' || toolName === 'native_call') {
const edit = toolName === 'native_call' ? args?.params : args;
const layer = edit?.params?.layer;
if (safeNumber(layer) > 0) return {
nativeLayerId: layer, writing: toolName !== 'canvas_preview' && edit.command === 'type.edit'
&& (typeof edit.params.text === 'string' || edit.params.replace !== undefined),
};
}
if (toolName === 'canvas_read') {
const layer = args?.layer ?? args?.screenId;
if (safeNumber(layer) > 0) return { nativeLayerId: layer };
}
if (toolName === 'read_copy_fields' || toolName === 'canvas_template_image') {
const fieldId = safeId(args?.fieldId);
const pageId = safeId(args?.pageId);
if (fieldId) return { fieldId, ...(pageId ? { pageId } : {}) };
}
if (toolName === 'read_output_screen') {
const page = safeNumber(args?.page ?? args?.pages?.[0]);
if (page !== undefined) return { page };
}
if (['read_slot_images', 'canvas_candidate_image', 'generate_slot_image', 'prepare_image_request',
'use_product_image', 'transform_slot_image', 'adopt_production_image', 'stage_archived_image'].includes(toolName)) {
const slotId = safeId(typeof args?.slotId === 'string' ? args.slotId.trim() : undefined);
if (slotId) return { slotId };
}
}
export function toolActivity(event, scope, timestampMs = Date.now()) {
if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null;
const toolCallId = safeToolCallId(event.toolCallId);

View File

@ -33,7 +33,7 @@ import { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { projectTools } from './project-tools.mjs';
import { responseUsage } from './usage.mjs';
import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs';
import { activityScope, activitySummary, toolActivity } from './activity-event.mjs';
import { activityScope, activitySummary, canvasPresence, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from './native-tools.mjs';
import { NativeExtensionUI } from './native-ui.mjs';
@ -628,7 +628,8 @@ export class DetailPiAgent {
if (supervisor && host.canvas?.run) agent.subscribe(event => {
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
const activity = toolActivity(event, host.activityScope);
if (activity) void host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{});
if (activity) void host.notifyCanvas('activity', activitySummary(event),
{...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
}
const type = event.type === 'message_update' ? event.assistantMessageEvent?.type : null;
const next = type === 'thinking_start' || type === 'thinking_delta' ? true
@ -845,7 +846,8 @@ export class DetailPiAgent {
}
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
const activity = toolActivity(event, host.activityScope || activityScope(store.identity));
if (canvas) void host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{});
if (canvas) void host.notifyCanvas('activity', activitySummary(event),
activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false,
...(activity ? {status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs} : null) });
void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});

View File

@ -570,7 +570,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
return canvas.delta('',undefined,{heading,outputId,variantId,category,phase:'progress',status:'running',
workers:[...workers.values()],
reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells,
reviews:pendingReviews().map(job=>job.row),
checkingScreens:runningScreens().filter(job=>job.receipt.state==='checking').map(job=>job.receipt.page),
candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells,
...jobProgress});
};
const display=new PresentationBatch(progress);
@ -1477,6 +1479,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
acquiredPermit=true;
activeSignal.throwIfAborted();
job.receipt={page,state:'checking'};
notice('正在按屏复核');
const screen=await operations.read_output_screen({page:page-1},activeSignal);
revision=screen.details.revision;
const screenSlots=slots.filter(slot=>screen.details.fields?.includes(slot.fieldId))

View File

@ -1,6 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { activityScope, toolActivity } from '../src/activity-event.mjs';
import { activityScope, canvasPresence, toolActivity } from '../src/activity-event.mjs';
test('canvas presence projects only the live canvas address', () => {
const event = { type: 'tool_execution_start', toolName: 'write_copy_fields', toolCallId: 'copy',
args: { items: [{ layer: 54, text: '未提交的文案' }, { layer: 55, text: '第二行' }] } };
assert.deepEqual(canvasPresence(event, toolActivity(event, {}, 100)), { nativeLayerId: 54, writing: true });
assert.equal(canvasPresence({ ...event, args: { ...event.args, recordOnly: true } }, toolActivity(event, {}, 100)), undefined);
const end = { type: 'tool_execution_end', toolName: event.toolName, toolCallId: event.toolCallId,
result: { details: { appliedLayers: [54, 55] } } };
assert.deepEqual(canvasPresence(end, toolActivity(end, {}, 100)), { nativeLayerId: 55, writing: true });
assert.equal(canvasPresence({ ...end, result: {} }, toolActivity(end, {}, 100)), undefined);
const screen = { ...event, toolName: 'read_output_screen', args: { pages: [0, 2] } };
assert.deepEqual(canvasPresence(screen, toolActivity(screen, {}, 100)), { page: 0 });
const native = { ...event, toolName: 'native_call', args: { method: 'engine.execute',
params: { command: 'layer.translate', params: { layer: 54, dx: 5 } } } };
assert.deepEqual(canvasPresence(native, toolActivity(native, {}, 100)), { nativeLayerId: 54, writing: false });
assert.equal(toolActivity(event, {}, 100).presence, undefined);
});
test('Responses call IDs join start and completion without widening scope IDs', () => {
const id = 'call_4fca7b5|fc_0c72ae9';

View File

@ -35,6 +35,7 @@ mod copywriting;
mod pi_ui;
mod prompt_library_ui;
pub(crate) mod canvas_workspace;
mod agent_presence;
pub mod production_facts;
pub mod template_preview;
mod professional_mode;
@ -1132,6 +1133,7 @@ pub struct Workspace {
product_start_queued: bool,
product_export: Option<Value>,
canvas_workspace: canvas_workspace::State,
agent_presence: agent_presence::Presence,
reference_intro_doc: Option<u64>,
template_ui: template_slots::UiState,
pending_slot_apply: Option<Value>,
@ -1634,6 +1636,7 @@ impl Workspace {
product_start_queued: false,
product_export: None,
canvas_workspace: canvas_workspace::State::default(),
agent_presence: agent_presence::Presence::default(),
reference_intro_doc: None,
template_ui: template_slots::UiState::default(),
pending_slot_apply: None,
@ -5311,6 +5314,7 @@ mod tests {
("stitch_kit", include_str!("jiansun/stitch_kit.rs")),
("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")),
("agent_stream", include_str!("jiansun/agent_stream.rs")),
("agent_presence", include_str!("jiansun/agent_presence.rs")),
("typing_text", include_str!("jiansun/typing_text.rs")),
];
for (name, source) in library {
@ -5389,6 +5393,7 @@ mod tests {
("stitch_state", include_str!("jiansun/stitch_state.rs")),
("stitch_cache", include_str!("jiansun/stitch_cache.rs")),
("agent_stream", include_str!("jiansun/agent_stream.rs")),
("agent_presence", include_str!("jiansun/agent_presence.rs")),
("typing_text", include_str!("jiansun/typing_text.rs")),
("siri_orb", include_str!("jiansun/siri_orb.rs")),
];

View File

@ -506,7 +506,7 @@ fn production_reference(token: &str) -> Option<String> {
})
}
fn production_reply_text(text: &str, streaming: bool) -> String {
pub(super) fn production_reply_text(text: &str, streaming: bool) -> String {
let tool_tags = [("<tool_calls>", "</tool_calls>"), ("<tool_call>", "</tool_call>")];
let mut visible = String::new();
let mut remaining = text;

View File

@ -0,0 +1,387 @@
//! 小壹协作光标。只读取文档定位目标。
use super::{Instant, Value, Workspace, canvas_workspace};
use crate::theme::{agent_cursor, agent_scale::Type};
use crate::{PhotocraftApp, canvas::ViewXform};
use egui::{Color32, FontId, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, Ui, pos2, vec2};
use photocraft_doc::{Document, LayerId};
use std::time::Duration;
const MOVE: Duration = Duration::from_millis(180);
const FADE: Duration = Duration::from_millis(200);
const COPY_HOLD: Duration = Duration::from_secs(1);
const FRAME: Duration = Duration::from_millis(16);
#[derive(Clone, Copy, PartialEq, Eq)]
enum Actor {
Main,
Image(u64),
Review(u64),
Screen(u64),
}
impl Actor {
fn color(self) -> Color32 {
let index = match self {
Self::Main => return agent_cursor::SELECTION,
Self::Image(number) => number % 7,
Self::Review(number) => (number % 7 + 2) % 7,
Self::Screen(number) => (number % 7 + 4) % 7,
};
agent_cursor::ACTORS[1 + index as usize]
}
}
#[derive(PartialEq, Eq)]
enum Target {
Slot(String),
Field { id: String, page: Option<String> },
Layer(u64),
Screen(usize),
}
impl Target {
fn read(value: &Value) -> Option<Self> {
if let Some(layer) = value["nativeLayerId"].as_u64() {
Some(Self::Layer(layer))
} else if let Some(slot) = value["slotId"].as_str() {
Some(Self::Slot(slot.to_owned()))
} else if let Some(field) = value["fieldId"].as_str() {
Some(Self::Field { id: field.to_owned(), page: value["pageId"].as_str().map(str::to_owned) })
} else {
Some(Self::Screen(usize::try_from(value["page"].as_u64()?).ok()?))
}
}
}
#[derive(PartialEq, Eq)]
struct Scope {
doc: u64,
output: String,
variant: String,
run: String,
}
impl Scope {
fn capture(w: &Workspace, app: &PhotocraftApp) -> Option<Self> {
Some(Self {
doc: app.session.active()?.doc.id.0,
output: w.template_workflow["outputId"].as_str().unwrap_or_default().to_owned(),
variant: w.template_workflow["variantId"].as_str().unwrap_or_default().to_owned(),
run: w.pi_run.as_ref()?.clone(),
})
}
fn visible(&self, doc: u64, workflow: &Value) -> bool {
self.doc == doc
&& self.output == workflow["outputId"].as_str().unwrap_or_default()
&& self.variant == workflow["variantId"].as_str().unwrap_or_default()
}
}
struct Geometry {
bounds: [f32; 4],
dimensions: String,
}
struct Cursor {
actor: Actor,
label: String,
target: Target,
writing: bool,
moved: Instant,
fade_at: Option<Instant>,
from: Option<Pos2>,
revision: Option<u64>,
geometry: Option<Geometry>,
}
impl Cursor {
fn anchor(&self, now: Instant, reduced: bool) -> Option<Pos2> {
let [x, y, w, h] = self.geometry.as_ref()?.bounds;
let to = if self.writing { pos2(x + w, y + h * 0.5) } else { pos2(x, y) };
let elapsed = now.saturating_duration_since(self.moved).as_secs_f32();
let progress = (elapsed / MOVE.as_secs_f32()).min(1.0);
Some(match self.from {
Some(from) if !reduced => from.lerp(to, 1.0 - (1.0 - progress).powi(3)),
_ => to,
})
}
}
#[derive(Default)]
pub(super) struct Presence {
scope: Option<Scope>,
main_call: String,
cursors: Vec<Cursor>,
}
impl Presence {
fn bind(&mut self, scope: Scope) {
if self.scope.as_ref() != Some(&scope) {
*self = Self { scope: Some(scope), ..Self::default() };
}
}
fn position(&mut self, actor: Actor, label: String, target: Target, writing: bool, now: Instant) {
let index = self.cursors.iter().position(|cursor| cursor.actor == actor);
if let Some(cursor) = index.and_then(|index| self.cursors.get_mut(index)) {
cursor.fade_at = None;
if cursor.target != target || cursor.writing != writing {
cursor.from = cursor.anchor(now, false);
cursor.moved = now;
cursor.target = target;
cursor.writing = writing;
cursor.revision = None;
}
cursor.label = label;
} else {
self.cursors.push(Cursor { actor, label, target, writing, moved: now, fade_at: None, from: None, revision: None, geometry: None });
}
}
fn finish(cursor: &mut Cursor, fade_at: Instant) {
cursor.fade_at = Some(cursor.fade_at.map_or(fade_at, |previous| previous.min(fade_at)));
}
pub(super) fn finish_run(&mut self, now: Instant) {
for cursor in &mut self.cursors {
Self::finish(cursor, now);
}
}
}
pub(super) fn tool_activity(w: &mut Workspace, app: &PhotocraftApp, event: &Value, address: &Value) {
let Some(call) = event["toolCallId"].as_str() else { return };
let now = Instant::now();
let started = event["status"] == "started";
let target = Target::read(address);
if started && target.is_none() {
return;
}
if !started && w.agent_presence.main_call != call {
return;
}
let Some(scope) = Scope::capture(w, app) else { return };
let presence = &mut w.agent_presence;
if started {
presence.bind(scope);
presence.main_call = call.to_owned();
} else if presence.scope.as_ref() != Some(&scope) {
return;
}
if let Some(target) = target {
presence.position(Actor::Main, "小壹".to_owned(), target, address["writing"] == true, now);
}
if !started {
presence.main_call.clear();
if let Some(cursor) = presence.cursors.iter_mut().find(|cursor| cursor.actor == Actor::Main) {
let hold = cursor.writing && event["status"] == "completed";
Presence::finish(cursor, if hold { now + COPY_HOLD } else { now });
}
}
}
pub(super) fn production_progress(w: &mut Workspace, app: &PhotocraftApp, progress: &Value) {
let Some(scope) = Scope::capture(w, app) else { return };
if progress["outputId"] != scope.output || progress["variantId"] != scope.variant {
return;
}
let now = Instant::now();
let presence = &mut w.agent_presence;
presence.bind(scope);
let mut active = Vec::new();
for (key, actor) in [("workers", Actor::Image as fn(u64) -> Actor), ("reviews", Actor::Review)] {
for row in progress[key].as_array().into_iter().flatten().filter(|row| row["active"] == true) {
let (Some(number), Some(slot)) = (row["number"].as_u64(), row["slotId"].as_str()) else { continue };
if row["step"] == "排队中" {
continue;
}
let actor = actor(number);
let label = if key == "reviews" {
"验图".to_owned()
} else {
let label = super::agent_panel::production_reply_text(row["label"].as_str().unwrap_or_default(), false);
let name: String = label.lines().next().unwrap_or_default().trim().chars().take(16).collect();
if name.is_empty() { "生图".to_owned() } else { format!("生图 · {name}") }
};
presence.position(actor, label, Target::Slot(slot.to_owned()), false, now);
active.push(actor);
}
}
for page in progress["checkingScreens"].as_array().into_iter().flatten().filter_map(Value::as_u64) {
let Some(index) = page.checked_sub(1).and_then(|value| usize::try_from(value).ok()) else { continue };
let actor = Actor::Screen(page);
presence.position(actor, format!("复核 · 第 {page} 屏"), Target::Screen(index), false, now);
active.push(actor);
}
for cursor in &mut presence.cursors {
if cursor.actor != Actor::Main && !active.contains(&cursor.actor) {
Presence::finish(cursor, now);
}
}
}
fn bounds(doc: &Document, mapping: &Value, target: &Target) -> Option<[f32; 4]> {
if let Target::Screen(index) = target {
let page = mapping["outputs"].as_array()?.get(*index)?;
return Some([0.0, page["top"].as_u64()? as f32, page["width"].as_u64()? as f32, page["height"].as_u64()? as f32]);
}
let fields = || {
mapping["outputs"]
.as_array()
.into_iter()
.flatten()
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten().map(move |field| (page, field)))
};
let field = match target {
Target::Slot(id) => fields()
.find(|(_, field)| field["slotId"] == *id)
.map(|(_, field)| field)
.or_else(|| unique(fields().filter(|(_, field)| field["kind"] == "image" && field["fieldId"] == *id))),
Target::Field { id, page } => {
unique(fields().filter(|(output, field)| field["fieldId"] == *id && page.as_ref().is_none_or(|page| output["documentId"] == *page)))
}
Target::Layer(id) => fields().find(|(_, field)| field["nativeLayerId"] == *id).map(|(_, field)| field),
Target::Screen(_) => None,
};
let id = match target {
Target::Layer(id) => *id,
_ => field?["nativeLayerId"].as_u64()?,
};
let layer = doc.layer(LayerId(id))?;
let area = photocraft_compose::layer_bounds(layer, doc.bounds());
if !area.is_empty() {
return Some([area.x0 as f32, area.y0 as f32, area.width() as f32, area.height() as f32]);
}
let frame = field?["nativeFrame"].as_array()?;
let [x, y, right, bottom] = <&[Value; 4]>::try_from(frame.as_slice()).ok()?;
let (x, y) = (x.as_f64()?, y.as_f64()?);
Some([x as f32, y as f32, (right.as_f64()? - x) as f32, (bottom.as_f64()? - y) as f32])
}
fn unique<'a>(mut fields: impl Iterator<Item = (&'a Value, &'a Value)>) -> Option<&'a Value> {
let (_, first) = fields.next()?;
fields.next().is_none().then_some(first)
}
pub(super) fn paint(w: &mut Workspace, app: &PhotocraftApp, ui: &Ui, xf: ViewXform, doc: u64) {
let state = &mut w.agent_presence;
if state.cursors.is_empty() {
return;
}
let now = Instant::now();
let Some(scope) = state.scope.as_ref() else { return };
if w.agent_effects_paused || w.pi_run.as_ref() != Some(&scope.run) {
for cursor in &mut state.cursors {
Presence::finish(cursor, now);
}
}
state.cursors.retain(|cursor| cursor.fade_at.is_none_or(|start| now < start + FADE));
if w.library
|| w.material
|| (w.creation_open && w.creation_step != 3)
|| !scope.visible(doc, &w.template_workflow)
|| ui.input(|input| input.viewport().minimized == Some(true))
{
return;
}
let Some(active) = app.session.active().filter(|active| active.doc.id.0 == doc) else { return };
state.draw(ui, xf, &active.doc, active.revision, w.reduce_motion, now);
}
impl Presence {
fn draw(&mut self, ui: &Ui, xf: ViewXform, doc: &Document, revision: u64, reduced: bool, now: Instant) {
let clip = xf.rect.intersect(ui.clip_rect());
if !clip.is_positive() {
return;
}
let painter = ui.painter().with_clip_rect(clip);
let mut mapping = None;
let mut labels = Vec::new();
for cursor in &mut self.cursors {
let opacity = match cursor.fade_at {
Some(start) if now >= start && reduced => continue,
Some(start) => 1.0 - (now.saturating_duration_since(start).as_secs_f32() / FADE.as_secs_f32()).min(1.0),
None => 1.0,
};
if opacity <= 0.0 {
continue;
}
if cursor.revision != Some(revision) {
let mapping = mapping.get_or_insert_with(|| canvas_workspace::document_mapping(doc).unwrap_or_default());
cursor.geometry = bounds(doc, mapping, &cursor.target)
.filter(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
.map(|bounds| Geometry { dimensions: format!("{:.0} × {:.0}", bounds[2], bounds[3]), bounds });
cursor.revision = Some(revision);
}
let Some(geometry) = cursor.geometry.as_ref() else { continue };
let rect = canvas_workspace::world_rect(xf, geometry.bounds);
if !clip.intersects(rect) {
continue;
}
let Some(anchor) = cursor.anchor(now, reduced) else { continue };
let point = xf.to_screen(anchor.x, anchor.y).clamp(clip.min, clip.max);
let tint = |color: Color32| color.gamma_multiply(opacity);
selection(&painter, rect, clip, &geometry.dimensions, tint(agent_cursor::SELECTION), tint(Color32::BLACK));
if cursor.writing {
let elapsed = now.saturating_duration_since(cursor.moved);
if reduced || elapsed.as_millis() % 1000 < 500 {
let height = rect.height().clamp(12.0, 22.0) * 0.5;
let tip = pos2(rect.right(), rect.center().y);
painter.line_segment([tip - vec2(0.0, height), tip + vec2(0.0, height)], Stroke::new(3.0, tint(Color32::WHITE)));
painter.line_segment([tip - vec2(0.0, height), tip + vec2(0.0, height)], Stroke::new(1.5, tint(agent_cursor::SELECTION)));
}
if !reduced {
let next = 500 - (elapsed.as_millis() % 500) as u64;
ui.ctx().request_repaint_after(Duration::from_millis(next));
}
}
cursor_label(&painter, point, clip, cursor.actor.color(), &cursor.label, opacity, &mut labels);
let moving = !reduced && cursor.from.is_some() && now.saturating_duration_since(cursor.moved) < MOVE;
if moving || opacity < 1.0 {
ui.ctx().request_repaint_after(FRAME);
} else if let Some(start) = cursor.fade_at {
ui.ctx().request_repaint_after(start.saturating_duration_since(now));
}
}
}
}
fn selection(p: &Painter, rect: Rect, clip: Rect, dimensions: &str, blue: Color32, text: Color32) {
p.rect_stroke(rect, 0, Stroke::new(1.25, blue), StrokeKind::Inside);
let galley = p.layout_no_wrap(dimensions.to_owned(), FontId::monospace(Type::Caption.size()), text);
let size = galley.size() + vec2(8.0, 4.0);
let region = rect.intersect(clip);
let origin = pos2(region.center().x - size.x * 0.5, (rect.bottom() + 3.0).min(clip.bottom() - size.y));
let badge = Rect::from_min_size(origin, size);
p.rect_filled(badge, 2, blue);
p.galley(origin + vec2(4.0, 2.0), galley, text);
}
fn cursor_label(p: &Painter, point: Pos2, clip: Rect, color: Color32, name: &str, opacity: f32, labels: &mut Vec<Rect>) {
let arrow = [point, point + vec2(5.0, 18.0), point + vec2(8.0, 11.0), point + vec2(15.0, 9.0)];
let tint = |color: Color32| color.gamma_multiply(opacity);
for offset in [vec2(0.0, 2.0), vec2(0.0, 1.0)] {
p.add(Shape::convex_polygon([arrow[0] + offset, arrow[1] + offset, arrow[3] + offset].to_vec(), tint(agent_cursor::SHADOW), Stroke::NONE));
}
p.add(Shape::convex_polygon([arrow[0], arrow[1], arrow[3]].to_vec(), tint(color), Stroke::NONE));
p.add(Shape::closed_line(arrow.to_vec(), Stroke::new(1.0, tint(Color32::WHITE))));
let white = tint(Color32::WHITE);
let galley = p.layout(name.to_owned(), Type::Caption.semibold(), white, (clip.width() - 12.0).max(0.0));
let size = galley.size() + vec2(12.0, 6.0);
let left = (point.x + 12.0).min(clip.right() - size.x).max(clip.left());
let top = (point.y + 13.0).min(clip.bottom() - size.y).max(clip.top());
let mut tag = Rect::from_min_size(pos2(left, top), size);
while let Some(previous) = labels.iter().find(|previous| previous.intersects(tag)) {
tag = tag.translate(vec2(0.0, previous.bottom() - tag.top() + 2.0));
}
if tag.bottom() > clip.bottom() {
return;
}
labels.push(tag);
p.rect_filled(tag, 4, tint(agent_cursor::label_background(color)));
p.galley(tag.min + vec2(6.0, 3.0), galley, white);
}
#[cfg(test)]
mod tests;

View File

@ -0,0 +1,187 @@
use super::*;
use crate::jiansun::{Request, agent_motion::requested_delay};
use egui::{RawInput, ViewportId};
use serde_json::json;
use std::sync::mpsc;
fn fixture() -> (PhotocraftApp, mpsc::Receiver<Request>, u64) {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":650,"height":590})).unwrap();
let image = |session: &mut photocraft_engine::Session, rect, fill| {
session.execute("shape.create", json!({"kind":"rect","rect":rect,"fill":fill})).unwrap()["layer"].as_u64().unwrap()
};
image(&mut session, [0, 0, 650, 345], "#F7F2EA");
image(&mut session, [0, 345, 650, 245], "#ECE5DC");
let front = image(&mut session, [50, 115, 265, 185], "#CABCAF");
let detail = image(&mut session, [345, 115, 255, 185], "#A5A99D");
image(&mut session, [95, 155, 175, 90], "#A3846A");
image(&mut session, [392, 145, 161, 120], "#788678");
let title = session.execute("type.create", json!({"text":"NORDIC COLLECTION","size":30,"x":51,"y":78})).unwrap()["layer"].as_u64().unwrap();
session.execute("type.create", json!({"text":"Material and finish","size":25,"x":50,"y":425})).unwrap();
image(&mut session, [51, 464, 230, 56], "#C6B297");
image(&mut session, [302, 464, 121, 56], "#ADA28E");
image(&mut session, [444, 464, 155, 56], "#B9BCAF");
let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"workspace","templateId":"template",
"templateVersion":"1","templateHash":"fixed","variantId":"wood","component":"detail",
"outputs":[
{"documentId":"intro","top":0,"width":650,"height":345,"mapping":{"fields":[
{"kind":"image","fieldId":"front","slotId":"front:wood","nativeLayerId":front},
{"kind":"image","fieldId":"detail","slotId":"detail:wood","nativeLayerId":detail},
{"kind":"text","fieldId":"heading","nativeLayerId":title,"nativeFrame":[51,50,350,83]}]}},
{"documentId":"materials","top":345,"width":650,"height":245,"mapping":{"fields":[]}}]});
let mut doc = session.active().unwrap().doc.as_ref().clone();
doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string()));
let doc_id = doc.id.0;
let mut session = photocraft_engine::Session::new();
session.add_document(doc, None);
let mut app = PhotocraftApp::new(session, crate::Services::default());
app.sync_views();
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut workspace = Workspace::new(tx, rx);
let _ = requests.try_recv();
workspace.account = json!({"id":"test-account"});
workspace.origin = "https://local.test".into();
workspace.owner_doc = Some(doc_id);
workspace.loaded_draft = Some(doc_id);
workspace.creation_doc = Some(doc_id);
let project = workspace.local_identity("presence-qa");
workspace.open_projects.insert(doc_id, project);
workspace.library = false;
workspace.creation_open = false;
workspace.pi_run = Some("visual-fixture".into());
workspace.template_workflow = json!({"canvasFirst":true,"workspaceId":"workspace","templateId":"template",
"templateVersion":"1","templateHash":"fixed","outputId":"detail","variantId":"wood",
"outputs":[{"outputId":"detail","documentId":"intro","height":345},
{"outputId":"detail","documentId":"materials","height":245}],
"slots":[{"id":"front:wood","outputId":"detail","variantId":"wood","documentId":"intro",
"label":"产品正面","nativeLayerId":front,"frame":{"x":50,"y":115,"width":265,"height":185}},
{"id":"detail:wood","outputId":"detail","variantId":"wood","documentId":"intro",
"label":"材质细节","nativeLayerId":detail,"frame":{"x":345,"y":115,"width":255,"height":185}}]});
assert!(workspace.enforce_canvas_scope(&app));
app.jiansun = Some(workspace);
(app, requests, title)
}
fn progress() -> Value {
json!({"outputId":"detail","variantId":"wood",
"workers":[{"number":1,"slotId":"front:wood","label":"产品正面","step":"正在生图","active":true},
{"number":3,"slotId":"front:wood","label":"未开始","step":"排队中","active":true}],
"reviews":[{"number":2,"slotId":"detail:wood","active":true}],
"checkingScreens":[2]})
}
fn activate(app: &mut PhotocraftApp, title: u64) {
let mut workspace = app.jiansun.take().unwrap();
production_progress(&mut workspace, app, &progress());
tool_activity(&mut workspace, app, &json!({"status":"started","toolCallId":"copy-1"}), &json!({"nativeLayerId":title,"writing":true}));
app.jiansun = Some(workspace);
}
#[test]
fn tool_and_worker_receipts_locate_native_targets_without_mutating_the_document() {
let (mut app, requests, title) = fixture();
let original = app.session.active().unwrap().doc.clone();
let revision = app.session.active().unwrap().revision;
activate(&mut app, title);
let mut w = app.jiansun.take().unwrap();
assert_eq!(w.agent_presence.cursors.len(), 4);
let mapping = canvas_workspace::document_mapping(&original).unwrap();
assert_eq!(bounds(&original, &mapping, &Target::Screen(1)), Some([0.0, 345.0, 650.0, 245.0]));
assert_eq!(
bounds(&original, &mapping, &Target::Slot("front:wood".into())),
bounds(&original, &mapping, &Target::Field { id: "front".into(), page: Some("intro".into()) })
);
assert!(bounds(&original, &mapping, &Target::Layer(title)).is_some());
assert!(bounds(&original, &mapping, &Target::Screen(2)).is_none());
let before = w.agent_presence.scope.as_ref().unwrap();
assert!(before.visible(original.id.0, &w.template_workflow));
assert!(!before.visible(original.id.0, &json!({"outputId":"main","variantId":"wood"})));
assert!(!before.visible(original.id.0, &json!({"outputId":"detail","variantId":"white"})));
assert!(!before.visible(original.id.0 + 1, &w.template_workflow));
production_progress(&mut w, &app, &json!({"outputId":"sku","variantId":"wood"}));
assert!(w.agent_presence.cursors.iter().all(|cursor| cursor.fade_at.is_none()));
production_progress(&mut w, &app, &json!({"outputId":"detail","variantId":"wood"}));
assert_eq!(w.agent_presence.cursors.iter().filter(|cursor| cursor.fade_at.is_some()).count(), 3);
assert!(w.messages.is_empty());
let active = app.session.active().unwrap();
assert_eq!(active.revision, revision);
assert!(std::sync::Arc::ptr_eq(&active.doc, &original));
assert_eq!(requests.try_iter().count(), 0);
}
#[test]
fn cursor_motion_stops_and_hidden_views_do_not_request_repaint() {
let (mut app, _, title) = fixture();
activate(&mut app, title);
let mut w = app.jiansun.take().unwrap();
let doc = app.session.active().unwrap().doc.id.0;
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let rect = Rect::from_min_size(Pos2::ZERO, vec2(720.0, 650.0));
let xf = ViewXform { rect, zoom: 1.0, center: [325.0, 295.0], flip: false, rotation: 0.0, aspect: 1.0 };
let frame = |w: &mut Workspace, minimized| {
let mut input = RawInput { screen_rect: Some(rect), ..Default::default() };
input.viewports.get_mut(&ViewportId::ROOT).unwrap().minimized = Some(minimized);
ctx.run_ui(input, |ui| paint(w, &app, ui, xf, doc))
};
for _ in 0..3 {
frame(&mut w, false).drop_without_applying_deltas();
}
assert!(requested_delay(&frame(&mut w, false)).is_some());
assert_eq!(requested_delay(&frame(&mut w, true)), None);
w.reduce_motion = true;
assert_eq!(requested_delay(&frame(&mut w, false)), None);
w.template_workflow["outputId"] = json!("sku");
w.reduce_motion = false;
assert_eq!(requested_delay(&frame(&mut w, false)), None);
w.template_workflow["outputId"] = json!("detail");
w.pi_run = None;
w.agent_presence.finish_run(Instant::now() - FADE);
assert_eq!(requested_delay(&frame(&mut w, false)), None);
assert!(w.agent_presence.cursors.is_empty());
}
#[test]
#[ignore = "离屏画布验收,输出到 PHOTOCRAFT_AGENT_QA_OUT"]
fn presence_visual_acceptance() {
struct Preview(PhotocraftApp);
impl eframe::App for Preview {
fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) {
let app = &mut self.0;
crate::panels::title_bar(app, ui);
crate::panels::options_bar(app, ui);
crate::panels::status_bar(app, ui);
crate::panels::toolbar(app, ui);
crate::panels::dock_area(app, ui);
}
}
let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap());
for (width, height) in [(1100, 720), (1440, 900)] {
let (mut app, requests, title) = fixture();
app.ui.dock_tabs.color = 4;
let mut h =
egui_kittest::Harness::builder().with_size(vec2(width as f32, height as f32)).with_step_dt(1.0 / 60.0).with_max_steps(64).wgpu().build_eframe(
move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium);
crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx);
app.gpu_render_state = cc.wgpu_render_state.clone();
Preview(app)
},
);
h.run();
activate(&mut h.state_mut().0, title);
// 减少动态效果开启时,截图中应保留静态插入符。
h.state_mut().0.jiansun.as_mut().unwrap().reduce_motion = true;
h.step();
let image = h.render().unwrap();
image.save(directory.join(format!("小壹协作光标-{width}x{height}.png"))).unwrap();
assert_eq!((image.width(), image.height()), (width, height));
let workspace = h.state().0.jiansun.as_ref().unwrap();
assert_eq!(workspace.agent_presence.cursors.iter().filter(|cursor| cursor.geometry.is_some()).count(), 4);
assert_eq!(requests.try_iter().filter(|request| matches!(request, Request::Action(method, _) if method == "slot-append")).count(), 0);
}
}

View File

@ -484,7 +484,7 @@ fn frame(row: &Row) -> Option<[f32; 4]> {
(result.iter().all(|n| n.is_finite()) && result[2] > 0.0 && result[3] > 0.0).then_some(result)
}
fn world_rect(xf: ViewXform, r: [f32; 4]) -> Rect {
pub(super) fn world_rect(xf: ViewXform, r: [f32; 4]) -> Rect {
let points = [(r[0], r[1]), (r[0] + r[2], r[1]), (r[0], r[1] + r[3]), (r[0] + r[2], r[1] + r[3])];
points.into_iter().fold(Rect::NOTHING, |b, (x, y)| {
let p = xf.to_screen(x, y);
@ -3630,6 +3630,7 @@ pub(crate) fn overlay(app: &mut PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc:
return (false, true, None);
};
let (blocked, camera) = workspace.workspace_canvas(app, ui, xf, doc, width);
super::agent_presence::paint(&mut workspace, app, ui, xf, doc);
let navigation = workspace.canvas_workspace.regen.is_none();
app.jiansun = Some(workspace);
(blocked, navigation, camera)

View File

@ -643,10 +643,12 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
if production_progress
&& input["production"]["outputId"] == w.pi_request_scope["outputId"]
&& input["production"]["variantId"] == w.pi_request_scope["variantId"]
&& let Some(notice) = w.workflow.set_production_progress(&input["production"])
{
w.messages.push(json!({"role":"assistant","kind":"activity","text":notice,"run":w.pi_run}));
w.draft_changed = true;
super::agent_presence::production_progress(w, app, &input["production"]);
if let Some(notice) = w.workflow.set_production_progress(&input["production"]) {
w.messages.push(json!({"role":"assistant","kind":"activity","text":notice,"run":w.pi_run}));
w.draft_changed = true;
}
}
if let Some(thinking) = thinking {
let output = stream_output(&input["output"]);
@ -686,6 +688,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
// Discard invalid/foreign events instead of storing untrusted
// text or interrupting the SDK subscriber.
if let Ok(event) = tool_activity(w, &input["event"]) {
super::agent_presence::tool_activity(w, app, &event, &input["event"]["presence"]);
record_tool_activity(w, event);
}
} else {
@ -746,6 +749,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
w.busy = if w.pi_native { Some("agent".into()) } else { None };
}
w.allow_apply = false;
w.agent_presence.finish_run(Instant::now());
w.pi_run = None;
if !w.pi_native {
w.pi_request_scope = Value::Null;

View File

@ -1539,6 +1539,30 @@ pub(crate) const AGENT_SEMANTIC: AgentSemantic = AgentSemantic {
],
};
/// 小壹画布协作标记的配色。
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod agent_cursor {
use egui::Color32;
pub(crate) const SELECTION: Color32 = Color32::from_rgb(13, 153, 255);
pub(crate) const SHADOW: Color32 = Color32::from_black_alpha(55);
pub(crate) const ACTORS: [Color32; 8] = [
SELECTION,
Color32::from_rgb(162, 89, 255),
Color32::from_rgb(242, 78, 30),
Color32::from_rgb(255, 114, 98),
Color32::from_rgb(26, 188, 254),
Color32::from_rgb(20, 174, 92),
Color32::from_rgb(255, 199, 0),
Color32::from_rgb(151, 71, 255),
];
pub(crate) fn label_background(color: Color32) -> Color32 {
let dark = |channel: u8| (f32::from(channel) * 0.48) as u8;
Color32::from_rgb(dark(color.r()), dark(color.g()), dark(color.b()))
}
}
/// 小壹具名阶梯:字体、间距、圆角、控件高度、图标与动效时长。
/// 原生编辑器有自己的 `ROW_GAP`、`TOOLTIP_DELAY` 等常量,互不相干;库内不再手写这些字面量。
/// 这是一张词汇表:第 1 批先把库内用到的档位接上,其余档位留给第 2、3 批迁移业务代码时取用,