Compare commits

..

2 Commits

Author SHA1 Message Date
kdletters 920bf90e5a 合并主线更新并保留后端依赖收敛改动
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 7m22s
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 7m43s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 7m50s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 8m4s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m13s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m6s
Project CI / Backend tests (pull_request) Successful in 9m38s
Project CI / Repository checks (pull_request) Successful in 14m27s
Project CI / Native shell tests (pull_request) Successful in 17m24s
Project CI / Frontend tests (pull_request) Successful in 22m13s
Project CI / AI game creator shell web tests (pull_request) Successful in 16m24s
同步最新主线代码与协作约定,保留本次窄依赖、鉴权和追踪实现
2026-09-18 20:59:05 +08:00
kdletters 896fcecbc1 收敛后端依赖装配并完善异步追踪与鉴权
集中装配后台、External API 与编辑器受保护路由并保持既有方法和请求大小限制
将项目元数据及 External/MCP 鉴权迁移为组合根装配的窄依赖并补齐替代依赖测试
使用 RAII 修复请求取消和 panic 的在途计数并统一 HTTP 路由模板追踪
补齐 LLM 普通与流式调用的安全异步追踪和本地 Provider 回归
同步两处依赖锁文件、后端规范、运维指标合同及团队协作约定
2026-09-18 20:58:46 +08:00
74 changed files with 3702 additions and 2847 deletions
+1
View File
@@ -3931,6 +3931,7 @@ dependencies = [
"serde",
"serde_json",
"tokio",
"tracing",
]
[[package]]
@@ -1,12 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main",
"description": "AI 游戏创作主窗口允许读系统剪贴板,用于粘贴素材附件和复制生成文件路径;允许弹出原生打开/保存对话框用于素材上传与导出。",
"description": "AI 游戏创作主窗口允许读系统剪贴板图片,用于粘贴素材附件;允许弹出原生打开/保存对话框用于素材上传与导出。",
"windows": ["client"],
"permissions": [
"clipboard-manager:allow-read-image",
"clipboard-manager:allow-read-text",
"clipboard-manager:allow-write-text",
"core:image:allow-rgba",
"core:image:allow-size",
"core:resources:allow-close",
@@ -2,7 +2,7 @@ use crate::config::build_game_creator_llm_client_from_llm_config;
use crate::config::load_game_creator_app_config;
use crate::ui_editor::commands::utils::{
parse_limited_llm_tool_arguments, read_ui_reference_image_data_url, request_ui_editor_llm,
required_tool_call_arguments, strict_json_schema,
strict_json_schema,
};
use crate::ui_editor::component::text::FontSource;
use crate::ui_editor::component::{Component, NodeComponent};
@@ -406,8 +406,12 @@ pub(crate) async fn bind_components_impl_with_provider(
.await
}
.map_err(|error| format!("组件绑定失败:{error}"))?;
let arguments = required_tool_call_arguments(&response, "bind_ui_components")?;
let parsed = parse_binding_response(arguments, editable_nodes.len())?;
let call = response
.tool_calls
.iter()
.find(|call| call.name == "bind_ui_components")
.ok_or_else(|| "LLM 未返回 bind_ui_components 工具调用".to_string())?;
let parsed = parse_binding_response(&call.arguments, editable_nodes.len())?;
let known_sprite_ids = state.sprite_assets.keys().cloned().collect::<HashSet<_>>();
let known_font_ids = state.font_assets.keys().cloned().collect::<HashSet<_>>();
let result = validate_and_materialize(
@@ -1,8 +1,7 @@
use crate::config::build_game_creator_llm_client_from_llm_config;
use crate::config::load_game_creator_app_config;
use crate::ui_editor::commands::utils::{
parse_limited_llm_tool_arguments, request_ui_editor_llm, required_tool_call_arguments,
strict_json_schema,
parse_limited_llm_tool_arguments, request_ui_editor_llm, strict_json_schema,
};
use crate::ui_editor::state::{State, UITree};
use platform_llm::{LlmFunctionTool, LlmMessage, LlmRunRequest, LlmToolChoice};
@@ -173,7 +172,6 @@ mod materialize {
use crate::ui_editor::layout::node::{
Node as LayoutNode, NodeMetadata, NodeSource, StageStatus,
};
use crate::ui_editor::layout::offset::NodeOffset;
use crate::ui_editor::layout::transform::Transform;
use crate::ui_editor::state::{State, UITree};
use crate::ui_editor::utils::{random_node_id, NodeId, UIDesignImageId};
@@ -304,7 +302,6 @@ mod materialize {
component: None,
children_display_mode: ChildrenDisplayMode::Exclusive,
children: members.into_iter().map(|member| member.node).collect(),
offset: NodeOffset::default(),
},
priority,
src_ui_design,
@@ -488,11 +485,15 @@ pub(crate) async fn merge_ui_impl_with_provider(
app_log!("ui_merge.error stage=llm_request error={error}");
format!("UI 树合并失败:{error}")
})?;
let arguments = required_tool_call_arguments(&response, MERGE_TOOL_NAME).map_err(|error| {
app_log!("ui_merge.error stage=parse_tool_call reason=missing_tool_call error={error}");
format!("LLM 未返回 {MERGE_TOOL_NAME} 工具调用")
})?;
let arguments = parse_limited_llm_tool_arguments(arguments).map_err(|error| {
let call = response
.tool_calls
.iter()
.find(|call| call.name == MERGE_TOOL_NAME)
.ok_or_else(|| {
app_log!("ui_merge.error stage=parse_tool_call reason=missing_tool_call");
format!("LLM 未返回 {MERGE_TOOL_NAME} 工具调用")
})?;
let arguments = parse_limited_llm_tool_arguments(&call.arguments).map_err(|error| {
app_log!("ui_merge.error stage=parse_arguments error={error}");
format!("UI 合并工具参数无效:{error}")
})?;
@@ -526,7 +527,6 @@ mod tests {
use crate::ui_editor::layout::children_display_mode::ChildrenDisplayMode;
use crate::ui_editor::layout::control_layout::ControlLayout;
use crate::ui_editor::layout::node::{Node, NodeMetadata, NodeSource, StageStatus};
use crate::ui_editor::layout::offset::NodeOffset;
use crate::ui_editor::layout::transform::Transform;
use crate::ui_editor::state::{State, UITree};
use crate::ui_editor::utils::{NodeId, UIDesignImageId};
@@ -548,7 +548,6 @@ mod tests {
component: None,
children_display_mode: ChildrenDisplayMode::Stack,
children,
offset: NodeOffset::default(),
}
}
@@ -2,18 +2,17 @@ use crate::config::build_game_creator_llm_client_from_llm_config;
use crate::config::load_game_creator_app_config;
use crate::ui_editor::commands::utils::{
parse_limited_llm_tool_arguments, read_ui_reference_image_data_url, request_ui_editor_llm,
required_tool_call_arguments, strict_json_schema,
strict_json_schema,
};
use crate::ui_editor::component::{Component, NodeComponent};
use crate::ui_editor::layout::children_display_mode::ChildrenDisplayMode;
use crate::ui_editor::layout::control_layout::ControlLayout;
use crate::ui_editor::layout::dimension::UIRect;
use crate::ui_editor::layout::node::{Node as LayoutNode, NodeMetadata, NodeSource, StageStatus};
use crate::ui_editor::layout::offset::NodeOffset;
use crate::ui_editor::layout::transform::Transform;
use crate::ui_editor::resource::ui_design_image::UIDesignImage;
use crate::ui_editor::state::{State, UITree};
use crate::ui_editor::utils::{random_node_id, UIDesignImageId};
use crate::ui_editor::utils::{random_node_id, NodeId, UIDesignImageId};
use nalgebra::{Point2, Vector2};
use platform_llm::{
LlmFunctionTool, LlmMessage, LlmMessageContentPart, LlmRunRequest, LlmToolChoice,
@@ -323,7 +322,6 @@ fn convert_node(
component: source.component.clone().into_option(),
children_display_mode: ChildrenDisplayMode::Stack,
children,
offset: NodeOffset::default(),
})
}
@@ -770,18 +768,21 @@ pub(crate) async fn recognize_ui_impl_with_provider(
!response.text.trim().is_empty(),
response.tool_calls.len()
);
let arguments = required_tool_call_arguments(&response, "recognize_ui_structure")
.map_err(|error| {
let call = response
.tool_calls
.iter()
.find(|call| call.name == "recognize_ui_structure")
.ok_or_else(|| {
app_log!(
"ui_recognition.error stage=parse_tool_call reason=missing_tool_call root={} error={error}",
"ui_recognition.error stage=parse_tool_call root={} reason=missing_tool_call",
root_id.as_str()
);
format!(
"LLM 未返回 recognize_ui_structure 工具调用(根界面图 {}",
"根界面图 {}LLM 未返回 recognize_ui_structure 工具调用",
root_id.as_str()
)
})?;
let arguments = parse_limited_llm_tool_arguments(arguments).map_err(|error| {
let arguments = parse_limited_llm_tool_arguments(&call.arguments).map_err(|error| {
app_log!(
"ui_recognition.error stage=parse_arguments root={} error={error}",
root_id.as_str()
@@ -857,7 +858,6 @@ pub(crate) async fn recognize_ui_impl_with_provider(
component: recognition_root.component.into_option(),
children_display_mode: ChildrenDisplayMode::Stack,
children,
offset: NodeOffset::default(),
};
// Tree identity and root identity are assigned by Rust, never chosen by the model.
ui_trees.push(UITree {
@@ -22,7 +22,6 @@ mod tests {
use crate::ui_editor::layout::control_layout::ControlLayout;
use crate::ui_editor::layout::node::Node;
use crate::ui_editor::layout::node::{NodeMetadata, NodeSource, StageStatus};
use crate::ui_editor::layout::offset::NodeOffset;
use crate::ui_editor::resource::ui_design_image::UIDesignImage;
use crate::ui_editor::state::{State, UITree};
use crate::ui_editor::utils::{NodeId, UIDesignImageId};
@@ -47,7 +46,6 @@ mod tests {
component,
children_display_mode: ChildrenDisplayMode::Stack,
children,
offset: NodeOffset::default(),
}
}
fn state(root: Node) -> State {
@@ -2,7 +2,7 @@ use crate::config::build_game_creator_llm_client_from_llm_config;
use crate::config::load_game_creator_app_config;
use crate::ui_editor::commands::utils::{
parse_limited_llm_tool_arguments, read_ui_reference_image_data_url, request_ui_editor_llm,
required_tool_call_arguments, strict_json_schema,
strict_json_schema,
};
use crate::ui_editor::resource::ui_design_image::UIDesignImageRole;
use crate::ui_editor::state::State;
@@ -214,14 +214,15 @@ pub(crate) async fn suggest_ui_design_semantic_impl(
!response.text.trim().is_empty(),
response.tool_calls.len()
);
let arguments = required_tool_call_arguments(&response, "suggest_ui_design_semantics")
.map_err(|error| {
app_log!(
"ui_design_suggestion.error stage=parse_tool_call reason=missing_tool_call error={error}"
);
let call = response
.tool_calls
.iter()
.find(|call| call.name == "suggest_ui_design_semantics")
.ok_or_else(|| {
app_log!("ui_design_suggestion.error stage=parse_tool_call reason=missing_tool_call");
"LLM 响应无效(详情:未返回 suggest_ui_design_semantics 工具调用)".to_string()
})?;
let arguments = parse_limited_llm_tool_arguments(arguments).map_err(|error| {
let arguments = parse_limited_llm_tool_arguments(&call.arguments).map_err(|error| {
app_log!("ui_design_suggestion.error stage=parse_arguments error={error}");
format!("LLM 响应无效(详情:UI 语义建议工具参数无效:{error}")
})?;
@@ -95,29 +95,6 @@ pub(crate) fn parse_limited_llm_tool_arguments(
serde_json::from_str(arguments).map_err(|error| format!("LLM 工具参数不是有效 JSON{error}"))
}
/// Stable structured-action adapter: locate the required tool call and parse its
/// bounded JSON arguments. Prompt, schema and materialization stay in each
/// operation-specific command.
pub(crate) fn required_tool_arguments(
response: &LlmRunResponse,
tool_name: &str,
) -> Result<serde_json::Value, String> {
let arguments = required_tool_call_arguments(response, tool_name)?;
parse_limited_llm_tool_arguments(arguments)
}
pub(crate) fn required_tool_call_arguments<'a>(
response: &'a LlmRunResponse,
tool_name: &str,
) -> Result<&'a str, String> {
response
.tool_calls
.iter()
.find(|call| call.name == tool_name)
.map(|call| call.arguments.as_str())
.ok_or_else(|| format!("LLM 未返回 {tool_name} 工具调用"))
}
pub(crate) async fn read_ui_reference_image_data_url(path: PathBuf) -> Result<String, String> {
tokio::task::spawn_blocking(move || read_ui_reference_image_data_url_blocking(&path))
.await
@@ -2,5 +2,4 @@ pub mod children_display_mode;
pub mod control_layout;
pub mod dimension;
pub mod node;
pub mod offset;
pub mod transform;
@@ -1,7 +1,6 @@
use crate::ui_editor::component::Component;
use crate::ui_editor::layout::children_display_mode::ChildrenDisplayMode;
use crate::ui_editor::layout::control_layout::ControlLayout;
use crate::ui_editor::layout::offset::NodeOffset;
use crate::ui_editor::utils::NodeId;
use serde::{Deserialize, Serialize};
use ts_rs::TS;
@@ -15,7 +14,6 @@ pub struct Node {
pub component: Option<Component>,
pub children_display_mode: ChildrenDisplayMode,
pub children: Vec<Node>,
pub offset: NodeOffset,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TS)]
@@ -1,20 +0,0 @@
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TS)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/ui-editor/types/"))]
pub struct NodeOffset {
#[ts(as = "[f32; 2]")]
pub min: [f32; 2],
#[ts(as = "[f32; 2]")]
pub max: [f32; 2],
}
impl Default for NodeOffset {
fn default() -> Self {
Self {
min: [0.0, 0.0],
max: [0.0, 0.0],
}
}
}
@@ -1126,10 +1126,8 @@ mod tests {
}
},
"children_display_mode": "Stack",
"children": [],
"offset": { "min": [0.0, 0.0], "max": [0.0, 0.0] }
}],
"offset": { "min": [0.0, 0.0], "max": [0.0, 0.0] }
"children": []
}]
}
}],
"ui_design_images": {
@@ -1311,8 +1309,7 @@ mod tests {
},
"component": null,
"children_display_mode": "Stack",
"children": [],
"offset": { "min": [0.0, 0.0], "max": [0.0, 0.0] }
"children": []
}
}],
"ui_design_images": {
@@ -1546,8 +1543,7 @@ mod tests {
}
},
"children_display_mode": "Stack",
"children": [],
"offset": { "min": [0.0, 0.0], "max": [0.0, 0.0] }
"children": []
}
}],
"ui_design_images": {
@@ -78,11 +78,7 @@ export function ResourceCanvasGenerationPlaceholderCardView({
<Sparkles size={18} aria-hidden="true" />
<strong>{placeholder.assetName}</strong>
<small>
{
RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS[
placeholder.status
]
}
{RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS[placeholder.status]}
</small>
<button
type="button"
@@ -155,7 +155,9 @@ export function createResourceCanvasAssetGenerationQueue(
referenceAssetIds: task.referenceAssetIds,
outputPath: task.outputPath,
// 入口栏目:原生支持时按它登记归类;不支持时后端忽略,落点仍按正式归类走。
...(task.targetCategory ? { targetCategory: task.targetCategory } : {}),
...(task.targetCategory
? { targetCategory: task.targetCategory }
: {}),
})) as LocalProjectAssetGenerationTaskRecord;
let started: LocalProjectAssetGenerationTaskRecord;
try {
@@ -175,9 +175,7 @@ export function resourceCanvasGenerationPlaceholdersForProject(
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
projectId: string,
): ResourceCanvasGenerationPlaceholder[] {
return placeholders.filter(
(placeholder) => placeholder.projectId === projectId,
);
return placeholders.filter((placeholder) => placeholder.projectId === projectId);
}
/** 按任务找回占位:成功落点与失败收口都以 taskId 为准,不按素材名猜。 */
@@ -185,18 +183,14 @@ export function resourceCanvasGenerationPlaceholderByTaskId(
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
taskId: string,
): ResourceCanvasGenerationPlaceholder | null {
return (
placeholders.find((placeholder) => placeholder.taskId === taskId) ?? null
);
return placeholders.find((placeholder) => placeholder.taskId === taskId) ?? null;
}
export function resourceCanvasGenerationPlaceholderByDraftId(
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
draftId: string,
): ResourceCanvasGenerationPlaceholder | null {
return (
placeholders.find((placeholder) => placeholder.draftId === draftId) ?? null
);
return placeholders.find((placeholder) => placeholder.draftId === draftId) ?? null;
}
export const RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS: Record<
@@ -208,10 +208,8 @@ export function useResourceCanvasGenerationPlaceholders({
return;
}
event.stopPropagation();
const nextX =
drag.startX + (event.clientX - drag.startClientX) / drag.scale;
const nextY =
drag.startY + (event.clientY - drag.startClientY) / drag.scale;
const nextX = drag.startX + (event.clientX - drag.startClientX) / drag.scale;
const nextY = drag.startY + (event.clientY - drag.startClientY) / drag.scale;
drag.changed = true;
move(drag.draftId, nextX, nextY);
},
@@ -235,8 +233,7 @@ export function useResourceCanvasGenerationPlaceholders({
);
const projectPlaceholders = useMemo(
() =>
resourceCanvasGenerationPlaceholdersForProject(placeholders, projectId),
() => resourceCanvasGenerationPlaceholdersForProject(placeholders, projectId),
[placeholders, projectId],
);
@@ -1,8 +1,6 @@
import type { Node } from './types/Node';
import type { NodeId } from './types/NodeId';
import type { State } from './types/State';
import type { Transform } from './types/Transform';
import type { UIDesignImageId } from './types/UIDesignImageId';
export type ResizeAxis = 'horizontal' | 'vertical';
@@ -19,32 +17,6 @@ export type NodePageContext = {
parentRect: PageRect;
};
/** State-level geometry seam shared by preview, inspector and transitions. */
export function findStateNodePageContext(
state: State,
treeId: UIDesignImageId,
nodeId: NodeId,
): NodePageContext | null {
const tree = state.ui_trees.find(
(candidate) => candidate.src_ui_design === treeId,
);
const image = state.ui_design_images[treeId];
if (
!tree ||
!image ||
!Number.isFinite(image.pixels_per_unit) ||
image.pixels_per_unit <= 0
) {
return null;
}
const size: [number, number] = [
image.pixel_size[0] / image.pixels_per_unit,
image.pixel_size[1] / image.pixels_per_unit,
];
if (!size.every((value) => Number.isFinite(value) && value > 0)) return null;
return findNodePageContext(tree.root, nodeId, pageRectFromSize(size));
}
const MIN_NODE_SIZE = 1;
export function pageRectFromSize(size: [number, number]): PageRect {
@@ -1,5 +1,4 @@
import type { Node as UiNode } from './types/Node';
import type { NodeId } from './types/NodeId';
import type { NodeMetadata } from './types/NodeMetadata';
import type { StageStatus } from './types/StageStatus';
import type { UIDesignImageId } from './types/UIDesignImageId';
@@ -15,11 +14,6 @@ export type UiTreeNodeTarget = {
node: UiNode;
};
export type UiTreeNodeCursor = {
treeId: UIDesignImageId;
nodeId: NodeId;
};
export type StageStatusOverview = {
total: number;
needsAttention: number;
@@ -85,28 +79,22 @@ export function getStageStatusTargets(
export function getNextUiTreeNodeTarget(
targets: UiTreeNodeTarget[],
previous: string | UiTreeNodeCursor | null,
previousNodeId: string | null,
): UiTreeNodeTarget | null {
if (targets.length === 0) return null;
let previousIndex = -1;
if (typeof previous === 'string') {
previousIndex = targets.findIndex(({ node }) => node.id === previous);
} else if (previous) {
previousIndex = targets.findIndex(
({ treeId, node }) =>
treeId === previous.treeId && node.id === previous.nodeId,
);
}
const previousIndex = targets.findIndex(
({ node }) => node.id === previousNodeId,
);
return targets[(previousIndex + 1) % targets.length] ?? null;
}
export function getNextMatchingUiTreeNodeTarget(
uiTrees: UITree[],
previous: string | UiTreeNodeCursor | null,
previousNodeId: string | null,
matches: (target: UiTreeNodeTarget) => boolean,
): UiTreeNodeTarget | null {
return getNextUiTreeNodeTarget(
collectUiTreeNodeTargets(uiTrees).filter(matches),
previous,
previousNodeId,
);
}
@@ -1,53 +0,0 @@
import type { Node } from './types/Node';
import type { State } from './types/State';
export type UiDesignInvariantIssue = {
code: 'duplicate-node' | 'invalid-image' | 'missing-tree-image';
message: string;
};
/** Frontend display/save projection of persistable State invariants.
* Rust remains authoritative; this seam only prevents obviously invalid saves
* and gives the view a stable, user-visible failure message.
*/
export function validateUiDesignState(state: State): UiDesignInvariantIssue[] {
const issues: UiDesignInvariantIssue[] = [];
const nodeIds = new Set<string>();
for (const [id, image] of Object.entries(state.ui_design_images)) {
if (
image.path.trim() === '' ||
!image.pixel_size.every((value) => Number.isFinite(value) && value > 0) ||
!Number.isFinite(image.pixels_per_unit) ||
image.pixels_per_unit <= 0
) {
issues.push({
code: 'invalid-image',
message: `界面图 ${id} 的尺寸或路径无效`,
});
}
}
const visit = (node: Node) => {
if (nodeIds.has(node.id)) {
issues.push({
code: 'duplicate-node',
message: `节点 ID 重复:${node.id}`,
});
}
nodeIds.add(node.id);
for (const child of node.children) visit(child);
};
for (const tree of state.ui_trees) {
if (!state.ui_design_images[tree.src_ui_design]) {
issues.push({
code: 'missing-tree-image',
message: `UI 树引用了缺失界面图:${tree.src_ui_design}`,
});
}
visit(tree.root);
}
return issues;
}
export function firstUiDesignInvariantMessage(state: State): string | null {
return validateUiDesignState(state)[0]?.message ?? null;
}
@@ -1,125 +0,0 @@
import type { Component } from './types/Component';
import type { Node } from './types/Node';
import type { NodeId } from './types/NodeId';
import type { NodeMetadata } from './types/NodeMetadata';
import type { State } from './types/State';
import type { UIDesignImageId } from './types/UIDesignImageId';
export type StateTransitionFailure =
| 'missing'
| 'invalid'
| `invalid:${string}`;
export type StateTransitionResult =
| { ok: true; state: State }
| { ok: false; reason: StateTransitionFailure };
export type UiEditorCommand =
| {
type: 'set-tree-offset';
treeId: UIDesignImageId;
min: [number, number];
}
| {
type: 'set-node-metadata';
treeId: UIDesignImageId;
nodeId: NodeId;
patch: Partial<
Pick<
NodeMetadata,
| 'name'
| 'description'
| 'layout_status'
| 'component_status'
| 'allow_llm_edit_layout'
| 'allow_llm_edit_component'
>
>;
}
| {
type: 'set-node-component';
treeId: UIDesignImageId;
nodeId: NodeId;
component: Component | null;
};
function cloneState(state: State): State {
return structuredClone(state);
}
function findNode(node: Node, id: NodeId): Node | null {
if (node.id === id) return node;
for (const child of node.children) {
const found = findNode(child, id);
if (found) return found;
}
return null;
}
function imageLogicalSize(
state: State,
treeId: UIDesignImageId,
): [number, number] | null {
const image = state.ui_design_images[treeId];
if (
!image ||
!Number.isFinite(image.pixels_per_unit) ||
image.pixels_per_unit <= 0
) {
return null;
}
const size: [number, number] = [
image.pixel_size[0] / image.pixels_per_unit,
image.pixel_size[1] / image.pixels_per_unit,
];
return size.every((value) => Number.isFinite(value) && value > 0)
? size
: null;
}
/**
* React-free semantic State transition seam. The hook is an adapter that adds
* locking/history; callers provide a command and receive a complete next State
* or a typed failure, never a partially-mutated tree.
*/
export function applyUiEditorCommand(
current: State,
command: UiEditorCommand,
): StateTransitionResult {
const next = cloneState(current);
const tree = next.ui_trees.find(
(candidate) => candidate.src_ui_design === command.treeId,
);
if (!tree) return { ok: false, reason: 'missing' };
if (command.type === 'set-tree-offset') {
if (!command.min.every(Number.isFinite))
return { ok: false, reason: 'invalid' };
const size = imageLogicalSize(next, command.treeId);
if (!size) return { ok: false, reason: 'invalid' };
tree.root.offset = {
min: [...command.min],
max: [command.min[0] + size[0], command.min[1] + size[1]],
};
return { ok: true, state: next };
}
const node = findNode(tree.root, command.nodeId);
if (!node) return { ok: false, reason: 'missing' };
if (command.type === 'set-node-component') {
node.component = structuredClone(command.component);
node.metadata.component_status = 'NoProblem';
return { ok: true, state: next };
}
if (command.patch.component_status !== undefined && node.component === null) {
const status = command.patch.component_status;
if (status !== 'NoProblem') return { ok: false, reason: 'invalid' };
}
const patch = Object.fromEntries(
Object.entries(command.patch).filter(([, value]) => value !== undefined),
) as Partial<NodeMetadata>;
node.metadata = { ...node.metadata, ...structuredClone(patch) };
return { ok: true, state: next };
}
@@ -4,6 +4,5 @@ import type { Component } from "./Component";
import type { ControlLayout } from "./ControlLayout";
import type { NodeId } from "./NodeId";
import type { NodeMetadata } from "./NodeMetadata";
import type { NodeOffset } from "./NodeOffset";
export type Node = { id: NodeId, layout: ControlLayout, metadata: NodeMetadata, component: Component | null, children_display_mode: ChildrenDisplayMode, children: Array<Node>, offset: NodeOffset };
export type Node = { id: NodeId, layout: ControlLayout, metadata: NodeMetadata, component: Component | null, children_display_mode: ChildrenDisplayMode, children: Array<Node>, };
@@ -1,3 +0,0 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type NodeOffset = { min: [number, number], max: [number, number], };
@@ -10,7 +10,6 @@ import {
resolveReparentTransform,
} from './nodeTransformGeometry';
import { validateSpriteBorder } from './spriteBorder';
import { applyUiEditorCommand } from './stateTransition';
import type { ChildrenDisplayMode } from './types/ChildrenDisplayMode';
import type { Component } from './types/Component';
import type { FontAsset } from './types/FontAsset';
@@ -18,7 +17,6 @@ import type { FontAssetId } from './types/FontAssetId';
import type { Node } from './types/Node';
import type { NodeId } from './types/NodeId';
import type { NodeMetadata } from './types/NodeMetadata';
import type { NodeOffset } from './types/NodeOffset';
import type { SpriteAsset } from './types/SpriteAsset';
import type { SpriteAssetId } from './types/SpriteAssetId';
import type { SpriteBorder } from './types/SpriteBorder';
@@ -36,7 +34,6 @@ export const EMPTY_UI_EDITOR_STATE: State = {
};
const MAX_HISTORY_LENGTH = 100;
export const UI_TREE_PADDING = 48;
export type UiEditorOperationFailureReason =
| 'locked'
@@ -107,6 +104,12 @@ function visitNodes(node: Node, visit: (node: Node) => void): void {
for (const child of node.children) visitNodes(child, visit);
}
function isProblematicComponentStatus(
status: NodeMetadata['component_status'],
): boolean {
return typeof status !== 'string';
}
function existingNodeIds(state: State): Set<NodeId> {
const ids = new Set<NodeId>();
for (const tree of state.ui_trees) {
@@ -153,7 +156,6 @@ function createPageRoot(state: State): Node {
component: null,
children_display_mode: 'Stack',
children: [],
offset: { min: [0, 0], max: [0, 0] },
};
}
@@ -185,56 +187,9 @@ function createHumanNode(state: State): Node {
component: null,
children_display_mode: 'Stack',
children: [],
offset: { min: [0, 0], max: [0, 0] },
};
}
function treeSize(state: State, treeId: UIDesignImageId): [number, number] {
const image = state.ui_design_images[treeId];
if (
!image ||
!Number.isFinite(image.pixels_per_unit) ||
image.pixels_per_unit <= 0
) {
throw new Error(`界面图 ${treeId} 缺少合法尺寸`);
}
return [
image.pixel_size[0] / image.pixels_per_unit,
image.pixel_size[1] / image.pixels_per_unit,
];
}
function deriveTreeOffset(state: State, treeId: UIDesignImageId): NodeOffset {
const [width, height] = treeSize(state, treeId);
const existing = state.ui_trees.filter(
(tree) => tree.src_ui_design !== treeId,
);
if (existing.length === 0) return { min: [0, 0], max: [width, height] };
const maxX = Math.max(
...existing.map(
(tree) =>
(tree.root.offset?.min?.[0] ?? 0) +
treeSize(state, tree.src_ui_design)[0],
),
);
const minY = Math.min(
...existing.map((tree) => tree.root.offset?.min?.[1] ?? 0),
);
return {
min: [maxX + UI_TREE_PADDING, minY],
max: [maxX + UI_TREE_PADDING + width, minY + height],
};
}
export function createTree(
state: State,
treeId: UIDesignImageId,
root = createPageRoot(state),
) {
root.offset = deriveTreeOffset(state, treeId);
return { src_ui_design: treeId, root };
}
function synchronizeDesignImageTrees(state: State): void {
const imageIds = new Set(Object.keys(state.ui_design_images));
state.ui_trees = state.ui_trees.filter((tree) =>
@@ -242,7 +197,7 @@ function synchronizeDesignImageTrees(state: State): void {
);
for (const [id] of Object.entries(state.ui_design_images)) {
if (!state.ui_trees.some((tree) => tree.src_ui_design === id)) {
state.ui_trees.push(createTree(state, id));
state.ui_trees.push({ src_ui_design: id, root: createPageRoot(state) });
}
}
}
@@ -996,26 +951,6 @@ export function useUiEditorState(initialState: State = EMPTY_UI_EDITOR_STATE) {
[commit, guard],
);
const setTreeOffset = useCallback(
(
treeId: UIDesignImageId,
min: [number, number],
): UiEditorOperationResult => {
const blocked = guard();
if (blocked) return blocked;
if (!min.every(Number.isFinite)) return { ok: false, reason: 'invalid' };
const result = applyUiEditorCommand(stateRef.current, {
type: 'set-tree-offset',
treeId,
min,
});
if (!result.ok) return result;
commit(result.state);
return { ok: true, value: undefined };
},
[commit, guard],
);
const insertNodeAfter = useCallback(
(
treeId: UIDesignImageId,
@@ -1199,14 +1134,21 @@ export function useUiEditorState(initialState: State = EMPTY_UI_EDITOR_STATE) {
if (component && !isValidComponent(component)) {
return { ok: false, reason: 'invalid' };
}
const result = applyUiEditorCommand(stateRef.current, {
type: 'set-node-component',
treeId,
nodeId,
component,
});
if (!result.ok) return result;
commit(result.state);
const current = stateRef.current;
const tree = current.ui_trees.find(
(candidate) => candidate.src_ui_design === treeId,
);
if (!tree) return { ok: false, reason: 'missing' };
const location = findNodeLocation(tree.root, nodeId);
if (!location) return { ok: false, reason: 'missing' };
const next = cloneState(current);
const nextTree = next.ui_trees.find(
(candidate) => candidate.src_ui_design === treeId,
)!;
const nextNode = findNodeLocation(nextTree.root, nodeId)!.node;
nextNode.component = structuredClone(component);
nextNode.metadata.component_status = 'NoProblem';
commit(next);
return { ok: true, value: undefined };
},
[commit, guard],
@@ -1220,14 +1162,38 @@ export function useUiEditorState(initialState: State = EMPTY_UI_EDITOR_STATE) {
): UiEditorOperationResult => {
const blocked = guard();
if (blocked) return blocked;
const result = applyUiEditorCommand(stateRef.current, {
type: 'set-node-metadata',
treeId,
const current = stateRef.current;
const tree = current.ui_trees.find(
(candidate) => candidate.src_ui_design === treeId,
);
if (!tree) return { ok: false, reason: 'missing' };
if (!findNodeLocation(tree.root, nodeId))
return { ok: false, reason: 'missing' };
const next = cloneState(current);
const node = findNodeLocation(
next.ui_trees.find((candidate) => candidate.src_ui_design === treeId)!
.root,
nodeId,
patch,
});
if (!result.ok) return result;
commit(result.state);
)!.node;
if (
patch.component_status !== undefined &&
node.component === null &&
isProblematicComponentStatus(patch.component_status)
) {
return { ok: false, reason: 'invalid' };
}
if (patch.name !== undefined) node.metadata.name = patch.name;
if (patch.description !== undefined)
node.metadata.description = patch.description;
if (patch.layout_status !== undefined)
node.metadata.layout_status = patch.layout_status;
if (patch.component_status !== undefined)
node.metadata.component_status = patch.component_status;
if (patch.allow_llm_edit_layout !== undefined)
node.metadata.allow_llm_edit_layout = patch.allow_llm_edit_layout;
if (patch.allow_llm_edit_component !== undefined)
node.metadata.allow_llm_edit_component = patch.allow_llm_edit_component;
commit(next);
return { ok: true, value: undefined };
},
[commit, guard],
@@ -1498,7 +1464,6 @@ export function useUiEditorState(initialState: State = EMPTY_UI_EDITOR_STATE) {
setSpriteBorder,
insertNode,
insertNodeAfter,
setTreeOffset,
deleteNode,
setNodeTransform,
setNodeLayout,
@@ -421,9 +421,7 @@ function ResourceBatchClassificationPanel({
setTagDraft('');
onSaved(result);
} catch (saveError) {
setError(
resourceClassificationErrorMessage(saveError, '批量追加标签失败'),
);
setError(resourceClassificationErrorMessage(saveError, '批量追加标签失败'));
} finally {
inFlightRef.current = false;
setSaving(false);
@@ -70,7 +70,6 @@ export function InputSidebar({ input }: { input: UiEditorInputProjection }) {
component: null,
children_display_mode: 'Stack',
children: uiTrees.map((tree) => tree.root),
offset: { min: [0, 0], max: [0, 0] },
};
}, [uiTrees]);
@@ -83,18 +82,9 @@ export function InputSidebar({ input }: { input: UiEditorInputProjection }) {
focusRequest={focusRequest}
treeIdForNode={(nodeId) => treeIdByNodeId.get(nodeId) ?? null}
isNodePreviewVisible={input.isNodePreviewVisible}
onSelectNode={(_treeId, nodeId) => {
// react-arborist emits `onSelect` when its controlled `selection`
// prop is updated. Overview navigation updates the selection and
// the status highlight in the same render, so treating that
// programmatic notification as a fresh user selection would clear
// the highlight before it can be painted. Only mutate selection
// state when the target actually differs from the current one.
const sameNode = input.selectedNodeId === nodeId;
if (!sameNode) {
input.selectDesignImage(_treeId);
input.selectNode(nodeId);
}
onSelectNode={(treeId, nodeId) => {
input.selectDesignImage(treeId);
input.selectNode(nodeId);
}}
onToggleNodeVisibility={(nodeId) =>
input.toggleNodePreviewVisibility(nodeId)

Some files were not shown because too many files have changed in this diff Show More