docs(canvas): explain AI and resource picker state ownership

This commit is contained in:
2026-11-12 16:29:49 +08:00
parent d2068d416a
commit 3ef07cd00c
4 changed files with 16 additions and 0 deletions
+5
View File
@@ -30,6 +30,7 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
const reference = useRef(tree); reference.current = tree;
const wake = useRef<() => void>(() => {});
// cache是跟踪结果缓存,runs是发布给React的副本;每个run有自己的活动边集合,合并后供连线动画使用。
// 这些 ref/state 不因 workspace/root/live 改变而清空;宿主应按作用域重建 Hook 所在视图,避免沿用旧跟踪表。
const cache = useRef(new Map<string, AIRun>());
const edgeStates = useRef(new Map<string, Set<string>>());
// 每个board只保留最高待刷版本,避免同一批step.applied触发多次重复整画布读取。
@@ -45,6 +46,7 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
/** 所有发现/分页GET共享取消信号并协商旧v2响应格式。 */
const request = <T,>(path: string) => api<T>(path, { signal: controller.signal, headers: { Accept: CANVAS_ACCEPT } });
/** 分页发现根和后代活动run,每页50;已跟踪run不覆盖,重复cursor判为协议异常避免无限循环。 */
// alive 只控制继续分页/发布等交接点;await 返回后仍可能先写共享 ref,不是每次赋值都有代次护栏。
async function discover() {
let cursor = ""; const seen = new Set<string>();
do {
@@ -77,6 +79,7 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
}
if (!active(page.status)) edges.clear(); edgeStates.current.set(id, edges);
current = { ...page, board_id: previous.board_id, events: [...(current.events || []), ...(page.events || [])].slice(-1000) };
// dirty 只比较该 run 原游标和状态;同游标/同状态下其它响应字段变化不一定立即发布给 React。
if (current.next_seq !== previous.next_seq || current.status !== previous.status) dirty = true;
cache.current.set(id, current);
} while (current.has_more && alive);
@@ -115,11 +118,13 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
const id = result.run_id as string; cache.current.set(id, { run_id: id, board_id: boardId, status: "queued", next_seq: 0, steps: [{ step_id: "pending", board_id: boardId, node_id: node, status: "queued" }] }); changed(); wake.current();
}
/** 以新幂等键发送取消命令后继续查询终态;暂记queued用于保持轮询,不表示服务端重新执行任务。 */
// 此写请求没有轮询 effect 的 signal,也未检查 live;按键是否可用由调用方和服务端权限共同约束。
async function cancel(run: AIRun) {
await api(canvasPath(workspace, run.board_id) + `/ai/runs/${run.run_id}/cancel`, { method: "POST", headers: { Accept: CANVAS_ACCEPT, "Idempotency-Key": crypto.randomUUID() }, body: "{}" });
const next = cache.current.get(run.run_id); if (next) { next.status = "queued"; } wake.current(); // Poll canonical terminal state, including already applied steps.
}
/** 先prepareApply协调目标本地状态,再发显式采用命令;成功后移除冲突提示并继续跟踪服务端最终状态。 */
// run/apply 同样不由 effect 清理自动取消;卸载只停跟踪,不撤销已经发起的命令副作用。
async function apply(run: AIRun, node: string, output: string, targetBoard: string) {
await reference.current.prepareApply(targetBoard, node);
await reference.current.command(run.board_id, `ai/runs/${run.run_id}/apply`, { node_id: node, output_id: output }, undefined, false, targetBoard);