Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ade1b7803e | |||
| 71000b6df1 | |||
| c047543825 | |||
| 34b3af1d2a | |||
| f7cba30b6b | |||
| 273f12633c | |||
| 5f5aa17152 | |||
| 3a57d9fbdf | |||
| 382b925ab9 | |||
| c1482012c6 | |||
| c3a17a6efc | |||
| 1bfdc3a760 | |||
| 1e27cd229d | |||
| 774710452f | |||
| aaecb82622 | |||
| 64ad24ac77 | |||
| 75ec3361dc | |||
| bc1dc868a1 | |||
| 50204ff7aa | |||
| 70fa160819 |
@@ -2960,8 +2960,22 @@ impl CodexAppServerConnection {
|
||||
codex_app_server_text_prompt(&request)
|
||||
.map_err(platform_llm::LlmError::InvalidRequest)?
|
||||
};
|
||||
let input =
|
||||
codex_app_server_turn_input(&request, &prompt, &self.inner.workspace_path).await?;
|
||||
let input = if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||
if let Some(item) = direct_user_item {
|
||||
let canonical: DirectCodexUserItem = serde_json::from_value(item.clone())
|
||||
.map_err(|error| platform_llm::LlmError::InvalidRequest(error.to_string()))?;
|
||||
direct_codex_user_item_to_codex_turn_input(
|
||||
&self.inner.workspace_path,
|
||||
&canonical,
|
||||
self.inner._skill_roots.as_deref().unwrap_or_default(),
|
||||
)
|
||||
.map_err(platform_llm::LlmError::InvalidRequest)?
|
||||
} else {
|
||||
codex_app_server_turn_input(&request, &prompt, &self.inner.workspace_path).await?
|
||||
}
|
||||
} else {
|
||||
codex_app_server_turn_input(&request, &prompt, &self.inner.workspace_path).await?
|
||||
};
|
||||
let _direct_tool_bridge_turn_guard =
|
||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||
Some(
|
||||
|
||||
@@ -10,6 +10,6 @@ pub(crate) use model::{
|
||||
};
|
||||
pub(crate) use validation::validate_direct_codex_user_item;
|
||||
pub(crate) use wire::{
|
||||
direct_codex_user_item_to_prompt, direct_codex_user_item_to_response_item,
|
||||
direct_codex_user_item_to_wire_input,
|
||||
direct_codex_user_item_to_codex_turn_input, direct_codex_user_item_to_prompt,
|
||||
direct_codex_user_item_to_response_item, direct_codex_user_item_to_wire_input,
|
||||
};
|
||||
|
||||
@@ -34,6 +34,8 @@ pub(crate) enum DirectCodexUserContentPart {
|
||||
InputText { text: String },
|
||||
#[serde(rename = "agc_resource_reference")]
|
||||
AgcResourceReference { resource_id: String },
|
||||
#[serde(rename = "agc_skill_reference")]
|
||||
AgcSkillReference { name: String },
|
||||
#[serde(rename = "agc_runtime_region_reference")]
|
||||
AgcRuntimeRegionReference(DirectCodexUserRuntimeRegionPart),
|
||||
/// Uploaded project attachment kept inline in canonical content.
|
||||
|
||||
+16
-2
@@ -14,7 +14,7 @@ pub(crate) const MAX_DIRECT_CODEX_REFERENCES: usize = 32;
|
||||
pub(crate) fn validate_direct_codex_user_item(
|
||||
root: &Path,
|
||||
item: &DirectCodexUserItem,
|
||||
) -> Result<(), String> {
|
||||
) -> Result<GameCreationAppManifest, String> {
|
||||
let DirectCodexUserItem::Message(message) = item;
|
||||
if !matches!(message.role, DirectCodexUserRole::User) {
|
||||
return Err("DirectProject 只接受 user message item".to_string());
|
||||
@@ -37,6 +37,20 @@ pub(crate) fn validate_direct_codex_user_item(
|
||||
reference_count = reference_count.saturating_add(1);
|
||||
validate_resource_id_and_manifest(&manifest, resource_id)?;
|
||||
}
|
||||
DirectCodexUserContentPart::AgcSkillReference { name } => {
|
||||
let name = name.trim();
|
||||
if name.is_empty()
|
||||
|| name.chars().count() > 120
|
||||
|| matches!(name, "." | "..")
|
||||
|| name.chars().any(|character| {
|
||||
character.is_control()
|
||||
|| character.is_whitespace()
|
||||
|| matches!(character, '/' | '\\' | ':' | '$')
|
||||
})
|
||||
{
|
||||
return Err("引用的 Skill 名称无效,请移除后重新选择".to_string());
|
||||
}
|
||||
}
|
||||
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
|
||||
reference_count = reference_count.saturating_add(1);
|
||||
validate_runtime_region_reference(&manifest, reference)?;
|
||||
@@ -84,7 +98,7 @@ pub(crate) fn validate_direct_codex_user_item(
|
||||
if reference_count > MAX_DIRECT_CODEX_REFERENCES {
|
||||
return Err(format!("一次最多引用 {MAX_DIRECT_CODEX_REFERENCES} 个素材"));
|
||||
}
|
||||
Ok(())
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// 整条 content 是否还有有效输入:任何一段非空白文本、或任何一个非文本 part 都算。
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use super::model::{DirectCodexUserContentPart, DirectCodexUserItem};
|
||||
use super::model::{
|
||||
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserRuntimeRegionPart,
|
||||
};
|
||||
use super::validation::validate_direct_codex_user_item;
|
||||
use crate::agent::{
|
||||
read_manifest_for_project, sanitize_attachment_local_path, sanitize_attachment_media_type,
|
||||
sanitize_attachment_name,
|
||||
sanitize_attachment_name,GameCreationAppManifest,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
@@ -54,6 +56,47 @@ fn direct_codex_user_item_to_response_content(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resource_reference_summary(
|
||||
manifest: &GameCreationAppManifest,
|
||||
resource_id: &str,
|
||||
) -> Result<String, String> {
|
||||
let resource_id = resource_id.trim();
|
||||
let asset = manifest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.id == resource_id)
|
||||
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
|
||||
let path = sanitize_attachment_local_path(&asset.local_path)
|
||||
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
|
||||
Ok(format!(
|
||||
"[素材引用 resourceId={resource_id};项目路径={path}]"
|
||||
))
|
||||
}
|
||||
|
||||
fn runtime_region_summary(reference: &DirectCodexUserRuntimeRegionPart) -> String {
|
||||
let resources = reference
|
||||
.resource_ids
|
||||
.iter()
|
||||
.map(|id| id.trim())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let mut summary = format!("[运行画面区域:名称={} ", reference.label.trim());
|
||||
if let Some(run_id) = reference.run_id.as_deref() {
|
||||
summary.push_str(&format!("运行标识={} ", run_id.trim()));
|
||||
}
|
||||
if let Some(role) = reference.element_role.as_deref() {
|
||||
summary.push_str(&format!("角色={} ", role.trim()));
|
||||
}
|
||||
if let Some(text) = reference.text.as_deref() {
|
||||
summary.push_str(&format!("文本={} ", text.trim()));
|
||||
}
|
||||
if !resources.is_empty() {
|
||||
summary.push_str(&format!("关联素材={resources}"));
|
||||
}
|
||||
summary.push(']');
|
||||
summary
|
||||
}
|
||||
|
||||
/// 将 canonical user item 转为 app-server `turn/start.input` 可接受的文本数组。
|
||||
/// AGC 私有 part 只在这里投影为安全摘要,canonical item 本身不被修改。
|
||||
pub(crate) fn direct_codex_user_item_to_wire_input(
|
||||
@@ -68,40 +111,13 @@ pub(crate) fn direct_codex_user_item_to_wire_input(
|
||||
let text = match part {
|
||||
DirectCodexUserContentPart::InputText { text } => text.clone(),
|
||||
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
|
||||
let asset = manifest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.id == resource_id.trim())
|
||||
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
|
||||
let path = sanitize_attachment_local_path(&asset.local_path)
|
||||
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
|
||||
format!(
|
||||
"[素材引用 resourceId={};项目路径={path}]",
|
||||
resource_id.trim()
|
||||
)
|
||||
resource_reference_summary(&manifest, resource_id)?
|
||||
}
|
||||
DirectCodexUserContentPart::AgcSkillReference { name } => {
|
||||
format!("${}", name.trim())
|
||||
}
|
||||
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
|
||||
let resources = reference
|
||||
.resource_ids
|
||||
.iter()
|
||||
.map(|id| id.trim())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let mut summary = format!("[运行画面区域:名称={} ", reference.label.trim());
|
||||
if let Some(run_id) = reference.run_id.as_deref() {
|
||||
summary.push_str(&format!("运行标识={} ", run_id.trim()));
|
||||
}
|
||||
if let Some(role) = reference.element_role.as_deref() {
|
||||
summary.push_str(&format!("角色={} ", role.trim()));
|
||||
}
|
||||
if let Some(text) = reference.text.as_deref() {
|
||||
summary.push_str(&format!("文本={} ", text.trim()));
|
||||
}
|
||||
if !resources.is_empty() {
|
||||
summary.push_str(&format!("关联素材={resources}"));
|
||||
}
|
||||
summary.push(']');
|
||||
summary
|
||||
runtime_region_summary(reference)
|
||||
}
|
||||
DirectCodexUserContentPart::AgcAttachmentReference(reference) => {
|
||||
let name = sanitize_attachment_name(&reference.name);
|
||||
@@ -124,6 +140,66 @@ pub(crate) fn direct_codex_user_item_to_wire_input(
|
||||
Ok(Value::Array(input))
|
||||
}
|
||||
|
||||
pub(crate) fn direct_codex_user_item_to_codex_turn_input(
|
||||
root: &Path,
|
||||
item: &DirectCodexUserItem,
|
||||
skill_roots: &[std::path::PathBuf],
|
||||
) -> Result<Value, String> {
|
||||
let manifest = validate_direct_codex_user_item(root, item)?;
|
||||
let DirectCodexUserItem::Message(message) = item;
|
||||
let mut input = Vec::with_capacity(message.content.len());
|
||||
for part in &message.content {
|
||||
match part {
|
||||
DirectCodexUserContentPart::InputText { text } => {
|
||||
input.push(serde_json::json!({ "type": "text", "text": text }));
|
||||
}
|
||||
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
|
||||
input.push(serde_json::json!({
|
||||
"type": "text",
|
||||
"text": resource_reference_summary(&manifest, resource_id)?,
|
||||
}));
|
||||
}
|
||||
DirectCodexUserContentPart::AgcSkillReference { name } => {
|
||||
let name = name.trim();
|
||||
let path = skill_roots
|
||||
.iter()
|
||||
.map(|root| root.join(name).join("SKILL.md"))
|
||||
.find(|path| path.is_file())
|
||||
.ok_or_else(|| "引用的 Skill 当前不可用,请重新选择".to_string())?;
|
||||
input.push(serde_json::json!({
|
||||
"type": "skill",
|
||||
"name": name,
|
||||
"path": path,
|
||||
}));
|
||||
}
|
||||
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
|
||||
input.push(serde_json::json!({
|
||||
"type": "text",
|
||||
"text": runtime_region_summary(reference),
|
||||
}));
|
||||
}
|
||||
DirectCodexUserContentPart::AgcAttachmentReference(reference) => {
|
||||
let mut summary = format!(
|
||||
"[附件:名称={};类型={};大小={} 字节",
|
||||
reference.name.trim(),
|
||||
reference.media_type.trim(),
|
||||
reference.size
|
||||
);
|
||||
if !reference.local_path.trim().is_empty() {
|
||||
summary.push_str(&format!(";项目路径={}", reference.local_path.trim()));
|
||||
}
|
||||
summary.push_str(&format!(";状态={}", reference.status.trim()));
|
||||
summary.push(']');
|
||||
input.push(serde_json::json!({
|
||||
"type": "text",
|
||||
"text": summary,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Value::Array(input))
|
||||
}
|
||||
|
||||
pub(crate) fn direct_codex_user_item_to_prompt(
|
||||
root: &Path,
|
||||
item: &DirectCodexUserItem,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeSet;
|
||||
@@ -121,6 +121,13 @@ struct AgcSkillManifestEntry {
|
||||
sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct AgcSkillCatalogEntry {
|
||||
pub(crate) name: String,
|
||||
pub(crate) description: String,
|
||||
}
|
||||
|
||||
fn is_safe_skill_relative_path(value: &str) -> bool {
|
||||
let path = Path::new(value);
|
||||
!value.is_empty()
|
||||
@@ -234,6 +241,21 @@ pub(crate) fn agc_skill_pack_fingerprint() -> Result<String, String> {
|
||||
Ok(format!("{:x}", Sha256::digest(canonical_manifest.as_ref())))
|
||||
}
|
||||
|
||||
/// 返回当前客户端随 AGC 一起启用的内置 Skill 候选。
|
||||
///
|
||||
/// 前端不得复制审核清单;Skill 名称和描述统一从经过校验的资源 manifest 派生。
|
||||
#[tauri::command]
|
||||
pub(crate) fn list_agc_skill_catalog() -> Result<Vec<AgcSkillCatalogEntry>, String> {
|
||||
Ok(validated_skill_pack_manifest()?
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|entry| AgcSkillCatalogEntry {
|
||||
name: entry.name,
|
||||
description: entry.purpose,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) fn render_agc_skill_pack_index() -> Result<String, String> {
|
||||
let manifest = validated_skill_pack_manifest()?;
|
||||
let mut lines = vec![format!(
|
||||
@@ -328,6 +350,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_catalog_is_derived_from_the_validated_manifest() {
|
||||
let catalog = list_agc_skill_catalog().expect("skill catalog");
|
||||
assert_eq!(catalog.len(), AGC_SKILL_PACK_EXPECTED_NAMES.len());
|
||||
for expected_name in AGC_SKILL_PACK_EXPECTED_NAMES {
|
||||
let entry = catalog
|
||||
.iter()
|
||||
.find(|entry| entry.name == expected_name)
|
||||
.expect("expected bundled skill");
|
||||
assert!(!entry.description.trim().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_content_digest_is_stable_across_lf_and_crlf() {
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
|
||||
@@ -482,43 +482,6 @@ fn automatic_local_game_projects_root(app: &tauri::AppHandle) -> Result<PathBuf,
|
||||
.map_err(|error| format!("无法读取 AGC 应用数据目录:{error}"))
|
||||
}
|
||||
|
||||
/// 校验用户选择的项目创建目录。
|
||||
///
|
||||
/// 目录必须已经存在(原生目录选择器返回的结果),并且先过 AGC 私有路径门禁:门禁失败时
|
||||
/// 这里就拒绝,避免项目被建到 AGC 无法加固、后续无法打开的位置。
|
||||
pub(crate) fn validate_requested_game_project_creation_root(
|
||||
requested: &str,
|
||||
) -> Result<PathBuf, String> {
|
||||
let requested = requested.trim();
|
||||
let root = Path::new(requested);
|
||||
if requested.is_empty() || !root.is_absolute() {
|
||||
return Err("项目创建目录必须是绝对路径".to_string());
|
||||
}
|
||||
if project_path_has_control_chars(root) {
|
||||
return Err("项目创建目录不能包含控制字符".to_string());
|
||||
}
|
||||
let metadata = fs::symlink_metadata(root)
|
||||
.map_err(|error| format!("读取项目创建目录失败:{}: {error}", root.display()))?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
return Err("项目创建目录必须是普通文件夹".to_string());
|
||||
}
|
||||
// 用户选择的外部目录仍走显式的项目根准备:保留 user-selected 范围的一次性修复,
|
||||
// 同时不放弃 reparse point / 非普通目录的失败关闭。
|
||||
prepare_game_creator_project_root_for_read(root, true, "项目创建目录")?;
|
||||
Ok(root.to_path_buf())
|
||||
}
|
||||
|
||||
/// 解析本次建项要使用的根目录:没选就用 AGC 管理的默认目录,选了就用用户指定的目录。
|
||||
pub(crate) fn resolve_game_project_creation_root(
|
||||
app: &tauri::AppHandle,
|
||||
requested: Option<&str>,
|
||||
) -> Result<PathBuf, String> {
|
||||
match requested.map(str::trim).filter(|value| !value.is_empty()) {
|
||||
Some(requested) => validate_requested_game_project_creation_root(requested),
|
||||
None => automatic_local_game_projects_root(app),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_automatic_local_game_project_at(
|
||||
projects_root: &Path,
|
||||
requested_name: Option<&str>,
|
||||
@@ -588,10 +551,9 @@ pub(crate) fn create_automatic_local_game_project(
|
||||
app: tauri::AppHandle,
|
||||
name: Option<String>,
|
||||
planning: Option<bool>,
|
||||
projects_root: Option<String>,
|
||||
) -> Result<InitLocalProjectResult, String> {
|
||||
create_automatic_local_game_project_at(
|
||||
&resolve_game_project_creation_root(&app, projects_root.as_deref())?,
|
||||
&automatic_local_game_projects_root(&app)?,
|
||||
name.as_deref(),
|
||||
planning.unwrap_or(false),
|
||||
)
|
||||
@@ -802,30 +764,13 @@ pub(crate) fn recent_game_creator_run_trace(root: &Path) -> Option<GameCreationA
|
||||
serde_json::from_str::<GameCreationAgentRunTrace>(&content).ok()
|
||||
}
|
||||
|
||||
/// 目录选择器标题:调用方只能给短标题,其余(超长、含控制字符、空白)一律回退默认文案。
|
||||
fn pick_project_directory_title(title: Option<&str>) -> &str {
|
||||
const MAX_TITLE_CHARS: usize = 24;
|
||||
title
|
||||
.map(str::trim)
|
||||
.filter(|value| {
|
||||
!value.is_empty()
|
||||
&& value.chars().count() <= MAX_TITLE_CHARS
|
||||
&& !value.chars().any(char::is_control)
|
||||
})
|
||||
.unwrap_or("选择游戏项目目录")
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn pick_local_project_directory(
|
||||
app: tauri::AppHandle,
|
||||
initial_path: Option<String>,
|
||||
title: Option<String>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel();
|
||||
let mut dialog = app
|
||||
.dialog()
|
||||
.file()
|
||||
.set_title(pick_project_directory_title(title.as_deref()));
|
||||
let mut dialog = app.dialog().file().set_title("选择游戏项目目录");
|
||||
if let Some(initial_path) = initial_path
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
|
||||
@@ -2518,6 +2518,7 @@ fn main() {
|
||||
pick_client_extension_file,
|
||||
pick_client_extension_directory,
|
||||
list_client_extensions,
|
||||
list_agc_skill_catalog,
|
||||
import_client_extension,
|
||||
set_client_extension_enabled,
|
||||
rename_client_extension,
|
||||
|
||||
@@ -880,9 +880,12 @@ pub(crate) async fn create_automatic_local_game_project_from_template(
|
||||
template_version: String,
|
||||
name: Option<String>,
|
||||
planning: Option<bool>,
|
||||
projects_root: Option<String>,
|
||||
) -> Result<InitLocalProjectResult, String> {
|
||||
let projects_root = crate::resolve_game_project_creation_root(&app, projects_root.as_deref())?;
|
||||
let projects_root = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map(|root| root.join("projects"))
|
||||
.map_err(|error| format!("无法读取 AGC 应用数据目录:{error}"))?;
|
||||
let cache_root = template_cache_root(&app)?;
|
||||
ensure_game_creator_private_directory_tree(&cache_root, "模板库缓存目录")?;
|
||||
let record =
|
||||
|
||||
@@ -1549,63 +1549,6 @@ fn automatic_local_game_project_allocates_unique_initialized_workspaces() {
|
||||
fs::remove_dir_all(projects_root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_project_creation_root_accepts_only_an_absolute_regular_directory() {
|
||||
let root = unique_project_path();
|
||||
fs::create_dir_all(&root).expect("create creation-root fixture");
|
||||
let not_a_directory = root.join("not-a-directory.txt");
|
||||
fs::write(¬_a_directory, b"x").expect("write file fixture");
|
||||
|
||||
assert_eq!(
|
||||
validate_requested_game_project_creation_root(" ").expect_err("blank root is rejected"),
|
||||
"项目创建目录必须是绝对路径"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_requested_game_project_creation_root("relative/projects")
|
||||
.expect_err("relative root is rejected"),
|
||||
"项目创建目录必须是绝对路径"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_requested_game_project_creation_root(&format!("{}\\pro\nject", root.display()))
|
||||
.expect_err("control character is rejected"),
|
||||
"项目创建目录不能包含控制字符"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_requested_game_project_creation_root(¬_a_directory.to_string_lossy())
|
||||
.expect_err("file root is rejected"),
|
||||
"项目创建目录必须是普通文件夹"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_requested_game_project_creation_root(&format!(" {}\n", root.display()))
|
||||
.expect("trimmed directory root is accepted"),
|
||||
root
|
||||
);
|
||||
assert!(
|
||||
validate_requested_game_project_creation_root(&root.join("missing").to_string_lossy())
|
||||
.is_err(),
|
||||
"a not-yet-existing creation root must fail instead of being created silently"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_local_game_project_creates_inside_the_requested_creation_root() {
|
||||
let projects_root = unique_project_path();
|
||||
fs::create_dir_all(&projects_root).expect("create creation-root fixture");
|
||||
|
||||
let requested = validate_requested_game_project_creation_root(&projects_root.to_string_lossy())
|
||||
.expect("valid creation root");
|
||||
let result = create_automatic_local_game_project_at(&requested, None, false)
|
||||
.expect("create workspace in requested root");
|
||||
|
||||
let project_root = PathBuf::from(&result.project_path);
|
||||
assert_eq!(project_root.parent(), Some(projects_root.as_path()));
|
||||
assert!(project_root.join(".agent/manifest.json").is_file());
|
||||
|
||||
fs::remove_dir_all(projects_root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_local_game_project_accepts_only_a_safe_custom_name() {
|
||||
let projects_root = unique_project_path();
|
||||
|
||||
@@ -17,15 +17,10 @@ import type {
|
||||
ProjectAgentRuntimeSummary,
|
||||
} from '../../view/project-development';
|
||||
import type { ProjectManifestSnapshotMetadata } from '../../view/project-development/projectResourceLiveUpdateModel';
|
||||
import {
|
||||
isAbsoluteProjectPath,
|
||||
projectPathHasControlCharacter,
|
||||
} from '../project-summary/projectSummary';
|
||||
import { isAbsoluteProjectPath } from '../project-summary/projectSummary';
|
||||
|
||||
const RECENT_WORKSPACES_STORAGE_KEY =
|
||||
'genarrative-ai-game-creator.recent-workspaces.v1';
|
||||
const PROJECT_CREATION_DIRECTORY_STORAGE_KEY =
|
||||
'genarrative-ai-game-creator.project-creation-directory.v1';
|
||||
const SUPERVISOR_CHAT_DRAFT_STORAGE_PREFIX =
|
||||
'genarrative.supervisor-chat.draft';
|
||||
|
||||
@@ -161,57 +156,6 @@ export function removeRecentWorkspace(path: string) {
|
||||
return recent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「项目创建目录」偏好:空串表示沿用 AGC 管理的默认位置(应用数据目录下的 projects)。
|
||||
*
|
||||
* 这里只保存用户意图,不是授权凭据:目录授权来自原生目录选择器,并由 Rust 侧私有路径门禁
|
||||
* 在每次建项时重新复核,所以存储被改坏最坏只是退回默认位置或拿到一次可见的建项失败。
|
||||
*/
|
||||
export function normalizeProjectCreationDirectory(value: string) {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || projectPathHasControlCharacter(trimmed)) {
|
||||
return '';
|
||||
}
|
||||
const withoutTrailingSeparator = trimmed.replace(/[\\/]+$/, '');
|
||||
// `C:\` 这类盘根只去掉分隔符会变成相对路径 `C:`,必须补回来。
|
||||
return /^[a-zA-Z]:$/.test(withoutTrailingSeparator)
|
||||
? `${withoutTrailingSeparator}\\`
|
||||
: withoutTrailingSeparator;
|
||||
}
|
||||
|
||||
export function readProjectCreationDirectory() {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(
|
||||
PROJECT_CREATION_DIRECTORY_STORAGE_KEY,
|
||||
);
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : '';
|
||||
if (typeof parsed !== 'string') {
|
||||
return '';
|
||||
}
|
||||
const directory = normalizeProjectCreationDirectory(parsed);
|
||||
return isAbsoluteProjectPath(directory) ? directory : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function writeProjectCreationDirectory(path: string) {
|
||||
const directory = normalizeProjectCreationDirectory(path);
|
||||
try {
|
||||
if (directory) {
|
||||
window.localStorage.setItem(
|
||||
PROJECT_CREATION_DIRECTORY_STORAGE_KEY,
|
||||
JSON.stringify(directory),
|
||||
);
|
||||
} else {
|
||||
window.localStorage.removeItem(PROJECT_CREATION_DIRECTORY_STORAGE_KEY);
|
||||
}
|
||||
} catch {
|
||||
// WebView storage can be unavailable in restricted test shells.
|
||||
}
|
||||
return directory;
|
||||
}
|
||||
|
||||
export function isTransientProjectOpenMessage(
|
||||
message: ChatMessage,
|
||||
projectPath: string,
|
||||
|
||||
@@ -48,7 +48,6 @@ import {
|
||||
isAbsoluteProjectPath,
|
||||
projectPathHasControlCharacter,
|
||||
} from '../project-summary/projectSummary';
|
||||
import { readProjectCreationDirectory } from './model';
|
||||
import { resolveSessionPreviewOnProjectOpen } from './sessionPreview';
|
||||
|
||||
/** 首页输入框当前的纯文本(Lexical 编辑器状态 -> 文本);没有输入就返回空串。 */
|
||||
@@ -829,9 +828,6 @@ export function useHomeProjectCreation({
|
||||
{
|
||||
name: suggestedName,
|
||||
planning: startMode === 'planning',
|
||||
// 用户在首页选过「项目创建目录」就用它;没选传 null,由 Rust 侧回落到
|
||||
// AGC 管理的默认位置(应用数据目录下的 projects)。
|
||||
projectsRoot: readProjectCreationDirectory() || null,
|
||||
},
|
||||
);
|
||||
createdProjectPath = result.projectPath;
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
|
||||
import { resolveTauriInvoke } from '../../app/tauri';
|
||||
import {
|
||||
readProjectCreationDirectory,
|
||||
writeProjectCreationDirectory,
|
||||
} from './model';
|
||||
|
||||
/**
|
||||
* 「项目创建目录」用户偏好。
|
||||
*
|
||||
* 默认沿用 AGC 管理的应用数据目录(`<app_data>/projects`);用户改选时必须走原生目录
|
||||
* 选择器,因为只有它构成"用户显式选择"边界:选择结果当场按用户选择范围加固,后续建项
|
||||
* 再由 Rust 侧私有路径门禁复核一次。
|
||||
*/
|
||||
export function useProjectCreationDirectory() {
|
||||
const [projectCreationDirectory, setProjectCreationDirectory] = useState(
|
||||
readProjectCreationDirectory,
|
||||
);
|
||||
const [projectCreationDirectoryBusy, setProjectCreationDirectoryBusy] =
|
||||
useState(false);
|
||||
const [projectCreationDirectoryStatus, setProjectCreationDirectoryStatus] =
|
||||
useState('');
|
||||
const pickInFlightRef = useRef(false);
|
||||
|
||||
const pickProjectCreationDirectory = useCallback(async () => {
|
||||
if (pickInFlightRef.current) {
|
||||
return;
|
||||
}
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
setProjectCreationDirectoryStatus('需要在陶泥儿客户端内运行');
|
||||
return;
|
||||
}
|
||||
pickInFlightRef.current = true;
|
||||
setProjectCreationDirectoryBusy(true);
|
||||
setProjectCreationDirectoryStatus('正在选择项目创建目录');
|
||||
try {
|
||||
const selected = await invoke<string | null>(
|
||||
'pick_local_project_directory',
|
||||
{
|
||||
title: '选择项目创建目录',
|
||||
...(projectCreationDirectory
|
||||
? { initialPath: projectCreationDirectory }
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
if (!selected) {
|
||||
setProjectCreationDirectoryStatus('已取消');
|
||||
return;
|
||||
}
|
||||
setProjectCreationDirectory(writeProjectCreationDirectory(selected));
|
||||
setProjectCreationDirectoryStatus('已更新项目创建目录');
|
||||
} catch (error) {
|
||||
setProjectCreationDirectoryStatus(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
} finally {
|
||||
pickInFlightRef.current = false;
|
||||
setProjectCreationDirectoryBusy(false);
|
||||
}
|
||||
}, [projectCreationDirectory]);
|
||||
|
||||
const resetProjectCreationDirectory = useCallback(() => {
|
||||
writeProjectCreationDirectory('');
|
||||
setProjectCreationDirectory('');
|
||||
setProjectCreationDirectoryStatus('已恢复默认位置');
|
||||
}, []);
|
||||
|
||||
return {
|
||||
projectCreationDirectory,
|
||||
projectCreationDirectoryBusy,
|
||||
projectCreationDirectoryStatus,
|
||||
pickProjectCreationDirectory,
|
||||
resetProjectCreationDirectory,
|
||||
};
|
||||
}
|
||||
|
||||
export type ProjectCreationDirectoryController = ReturnType<
|
||||
typeof useProjectCreationDirectory
|
||||
>;
|
||||
+19
-8
@@ -4,6 +4,16 @@ import { X } from 'lucide-react';
|
||||
|
||||
import type { ChatReference } from './resourceReferences';
|
||||
|
||||
function chipTitle(reference: ChatReference) {
|
||||
if (reference.type === 'resource') {
|
||||
return `${reference.label} · ${reference.kind}`;
|
||||
}
|
||||
if (reference.type === 'skill') {
|
||||
return `${reference.name} · Skill`;
|
||||
}
|
||||
return `${reference.label} · 运行区域`;
|
||||
}
|
||||
|
||||
export function ResourceReferenceChip({
|
||||
reference,
|
||||
nodeKey,
|
||||
@@ -21,18 +31,19 @@ export function ResourceReferenceChip({
|
||||
data-runtime-region-reference={
|
||||
reference.type === 'runtime-region' ? 'true' : undefined
|
||||
}
|
||||
contentEditable={false}
|
||||
title={
|
||||
reference.type === 'resource'
|
||||
? `${reference.label} · ${reference.kind}`
|
||||
: `${reference.label} · 运行区域`
|
||||
data-skill-reference-name={
|
||||
reference.type === 'skill' ? reference.name : undefined
|
||||
}
|
||||
contentEditable={false}
|
||||
title={chipTitle(reference)}
|
||||
>
|
||||
<span aria-hidden="true">@</span>
|
||||
<span className="resource-reference-chip-label">{reference.label}</span>
|
||||
<span aria-hidden="true">{reference.type === 'skill' ? '$' : '@'}</span>
|
||||
<span className="resource-reference-chip-label">
|
||||
{reference.type === 'skill' ? reference.name : reference.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`移除引用 ${reference.label}`}
|
||||
aria-label={`移除引用 ${reference.type === 'skill' ? reference.name : reference.label}`}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => {
|
||||
editor.update(() => {
|
||||
|
||||
+169
-31
@@ -98,6 +98,7 @@ import {
|
||||
resourceReferenceMatchesTagSelection,
|
||||
type ResourceReferenceScope,
|
||||
resourceReferenceTagLibrary,
|
||||
type SkillReference,
|
||||
} from './resourceReferences';
|
||||
import { usePromptPolish } from './usePromptPolish';
|
||||
|
||||
@@ -108,6 +109,7 @@ type ResourceReferenceInputProps = {
|
||||
onEditorStateChange?: (editorState: EditorState) => void;
|
||||
initialContent?: DirectCodexUserContentPart[];
|
||||
assets: GameCreationAppAssetManifestEntry[];
|
||||
skills?: SkillReference[];
|
||||
projectPath: string;
|
||||
/**
|
||||
* `@` 面板「当前版本素材」页签使用的版本 id。
|
||||
@@ -181,12 +183,22 @@ class ResourceMentionOption extends MenuOption {
|
||||
}
|
||||
}
|
||||
|
||||
class SkillMentionOption extends MenuOption {
|
||||
skill: SkillReference;
|
||||
|
||||
constructor(skill: SkillReference) {
|
||||
super(skill.name);
|
||||
this.skill = skill;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑器节点 → canonical content part,**原样透传**:段落分隔(root 子节点之间补的
|
||||
* `\n`)、软换行、chip 后的分隔空格都各自成 part,不做空白过滤、不与相邻 part 合并。
|
||||
* 有效输入只在整条 content 上判定(`hasMeaningfulDirectCodexContent` 与 Rust
|
||||
* `validate_direct_codex_user_item` 同口径),前端不替用户改写他输入了什么。
|
||||
*/
|
||||
|
||||
function collectDraftParts(
|
||||
node: LexicalNode,
|
||||
references: ChatReference[],
|
||||
@@ -244,8 +256,12 @@ function readDraftFromNodes(): ChatComposerDraft {
|
||||
const projection = readDraftProjectionFromNodes();
|
||||
const labels = new Map(
|
||||
projection.references.map((reference) => [
|
||||
reference.type === 'resource' ? reference.resourceId : reference.label,
|
||||
`@${reference.label}`,
|
||||
reference.type === 'resource'
|
||||
? reference.resourceId
|
||||
: reference.type === 'skill'
|
||||
? reference.name
|
||||
: reference.label,
|
||||
reference.type === 'skill' ? `$${reference.name}` : `@${reference.label}`,
|
||||
]),
|
||||
);
|
||||
const text = projection.content
|
||||
@@ -256,7 +272,7 @@ function readDraftFromNodes(): ChatComposerDraft {
|
||||
? (labels.get(part.resourceId) ?? `@${part.resourceId}`)
|
||||
: part.type === 'agc_runtime_region_reference'
|
||||
? `@${part.label}`
|
||||
: `@${part.name}`,
|
||||
: `$${part.name}`,
|
||||
)
|
||||
.join('')
|
||||
.trim();
|
||||
@@ -308,7 +324,7 @@ function findDraftMentionToken(line: string, token: string, from: number) {
|
||||
* 把「文本 + 引用列表」这对外部表示切成编辑区要写的内容。
|
||||
*
|
||||
* 不变量:写入编辑器后,编辑器读回的草稿就是唯一当前值。`collectDraftParts`
|
||||
* 会把每个 chip 读成一段 `@显示名` 文本,所以 chip 只能内联嵌在文本里同名 token 的位置上,
|
||||
* 会把每个 chip 读成一段 `@显示名` / `$skill-name` 文本,所以 chip 只能内联嵌在文本里同名 token 的位置上,
|
||||
* 不能另起一段堆在末尾;编辑器本身是唯一 authority,不再通过 props 比较后反复重建。
|
||||
*
|
||||
* 文本里已经没有对应 token 的引用(例如 AI 润色整体改写了文本)内联补到最后一段末尾,
|
||||
@@ -320,7 +336,8 @@ function buildDraftSegments(
|
||||
): DraftBuildSegment[][] {
|
||||
const pending = references.map((reference) => ({
|
||||
reference,
|
||||
token: `@${reference.label}`,
|
||||
token:
|
||||
reference.type === 'skill' ? `$${reference.name}` : `@${reference.label}`,
|
||||
used: false,
|
||||
}));
|
||||
const lines: DraftBuildSegment[][] = [];
|
||||
@@ -393,6 +410,9 @@ function referenceFromContentPart(
|
||||
const asset = assetsById.get(part.resourceId);
|
||||
return asset ? resourceReferenceFromAsset(asset, 'asset-picker') : null;
|
||||
}
|
||||
if (part.type === 'agc_skill_reference') {
|
||||
return { type: 'skill', name: part.name };
|
||||
}
|
||||
if (part.type === 'agc_runtime_region_reference') {
|
||||
return {
|
||||
type: 'runtime-region',
|
||||
@@ -540,6 +560,7 @@ function ResourceReferenceEditor({
|
||||
onEditorStateChange,
|
||||
initialContent,
|
||||
assets,
|
||||
skills = [],
|
||||
projectPath,
|
||||
activeVersionId = null,
|
||||
versions,
|
||||
@@ -556,14 +577,18 @@ function ResourceReferenceEditor({
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const skipInitialDraftChangeRef = useRef(false);
|
||||
const [query, setQuery] = useState<string | null>(null);
|
||||
const [skillQuery, setSkillQuery] = useState<string | null>(null);
|
||||
const [builtinSkills, setBuiltinSkills] = useState<SkillReference[]>([]);
|
||||
const [clientSkills, setClientSkills] = useState<SkillReference[]>([]);
|
||||
const skillCatalogRequestedRef = useRef(false);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
// Enter 提交要避开候选浮层。用 ref 让命令处理器读到最新状态,不必因为
|
||||
// query / pickerOpen 变化反复重注册 HIGH 优先级命令。
|
||||
const mentionMenuOpenRef = useRef(false);
|
||||
const pickerVisibleRef = useRef(false);
|
||||
useEffect(() => {
|
||||
mentionMenuOpenRef.current = query !== null;
|
||||
}, [query]);
|
||||
mentionMenuOpenRef.current = query !== null || skillQuery !== null;
|
||||
}, [query, skillQuery]);
|
||||
useEffect(() => {
|
||||
pickerVisibleRef.current = pickerOpen;
|
||||
}, [pickerOpen]);
|
||||
@@ -577,6 +602,53 @@ function ResourceReferenceEditor({
|
||||
bottom: number;
|
||||
width: number;
|
||||
} | null>(null);
|
||||
// Skill 清单来自宿主:只在用户真正打开 `$` 候选时查一次。输入区挂载即发起
|
||||
// Tauri 调用会让「工作区路径非法时不产生任何后端访问」的边界失效。
|
||||
useEffect(() => {
|
||||
if (skillQuery === null || skillCatalogRequestedRef.current) return;
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) return;
|
||||
skillCatalogRequestedRef.current = true;
|
||||
void invoke<Array<{ name: string; description: string }>>(
|
||||
'list_agc_skill_catalog',
|
||||
)
|
||||
.then((items) => {
|
||||
setBuiltinSkills(
|
||||
items.map((item) => ({
|
||||
type: 'skill' as const,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
})),
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
setBuiltinSkills([]);
|
||||
});
|
||||
void invoke<
|
||||
Array<{
|
||||
name: string;
|
||||
extensionType: string;
|
||||
enabled: boolean;
|
||||
status: string;
|
||||
}>
|
||||
>('list_client_extensions')
|
||||
.then((items) => {
|
||||
setClientSkills(
|
||||
items
|
||||
.filter(
|
||||
(item) =>
|
||||
item.extensionType === 'skill' &&
|
||||
item.enabled &&
|
||||
item.status === 'enabled',
|
||||
)
|
||||
.map((item) => ({ type: 'skill' as const, name: item.name })),
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
setClientSkills([]);
|
||||
});
|
||||
}, [skillQuery]);
|
||||
|
||||
const assetsContentSignature = assetsSignature(assets);
|
||||
const versionsContentSignature = iterationsSignature(versions);
|
||||
const assetsById = useMemo(
|
||||
@@ -641,11 +713,35 @@ function ResourceReferenceEditor({
|
||||
.map((reference) => new ResourceMentionOption(reference));
|
||||
}, [assetReferences, query]);
|
||||
|
||||
const skillOptions = useMemo(() => {
|
||||
if (skillQuery === null) return [];
|
||||
const normalized = skillQuery.trim().toLowerCase();
|
||||
const allSkills = [...builtinSkills, ...clientSkills, ...skills];
|
||||
const seen = new Set<string>();
|
||||
return allSkills
|
||||
.filter((skill) => {
|
||||
if (seen.has(skill.name)) return false;
|
||||
seen.add(skill.name);
|
||||
return (
|
||||
!normalized ||
|
||||
skill.name.toLowerCase().includes(normalized) ||
|
||||
skill.description?.toLowerCase().includes(normalized)
|
||||
);
|
||||
})
|
||||
.slice(0, 8)
|
||||
.map((skill) => new SkillMentionOption(skill));
|
||||
}, [builtinSkills, clientSkills, skillQuery, skills]);
|
||||
|
||||
const triggerFn = useBasicTypeaheadTriggerMatch('@', {
|
||||
minLength: 0,
|
||||
maxLength: 64,
|
||||
allowWhitespace: false,
|
||||
});
|
||||
const skillTriggerFn = useBasicTypeaheadTriggerMatch('$', {
|
||||
minLength: 0,
|
||||
maxLength: 64,
|
||||
allowWhitespace: false,
|
||||
});
|
||||
|
||||
const insertReferences = useCallback(
|
||||
(nextReferences: ChatReference[]) => {
|
||||
@@ -771,13 +867,13 @@ function ResourceReferenceEditor({
|
||||
const currentRefKey = current.references
|
||||
?.map(
|
||||
(reference) =>
|
||||
`${reference.type}:${reference.type === 'resource' ? reference.resourceId : reference.label}`,
|
||||
`${reference.type}:${reference.type === 'resource' ? reference.resourceId : reference.type === 'skill' ? reference.name : reference.label}`,
|
||||
)
|
||||
.join('|');
|
||||
const desiredRefKey = desiredRefs
|
||||
.map(
|
||||
(reference) =>
|
||||
`${reference.type}:${reference.type === 'resource' ? reference.resourceId : reference.label}`,
|
||||
`${reference.type}:${reference.type === 'resource' ? reference.resourceId : reference.type === 'skill' ? reference.name : reference.label}`,
|
||||
)
|
||||
.join('|');
|
||||
if (current.text === desiredValue && currentRefKey === desiredRefKey)
|
||||
@@ -854,30 +950,47 @@ function ResourceReferenceEditor({
|
||||
[editor, pickerOpen],
|
||||
);
|
||||
|
||||
const insertReferenceNode = useCallback(
|
||||
(
|
||||
reference: ChatReference,
|
||||
textNodeContainingQuery: TextNode | null,
|
||||
closeMenu: () => void,
|
||||
) => {
|
||||
textNodeContainingQuery?.remove();
|
||||
const selection = $getSelection();
|
||||
const node = $createResourceReferenceNode(reference);
|
||||
if ($isRangeSelection(selection)) {
|
||||
selection.insertNodes([node, $createTextNode(' ')]);
|
||||
} else {
|
||||
const paragraph = $createParagraphNode();
|
||||
paragraph.append(node, $createTextNode(' '));
|
||||
$getRoot().append(paragraph);
|
||||
}
|
||||
closeMenu();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleSelectMention = useCallback(
|
||||
(
|
||||
option: ResourceMentionOption,
|
||||
textNodeContainingQuery: TextNode | null,
|
||||
closeMenu: () => void,
|
||||
) => {
|
||||
textNodeContainingQuery?.remove();
|
||||
const selection = $getSelection();
|
||||
if ($isRangeSelection(selection)) {
|
||||
selection.insertNodes([
|
||||
$createResourceReferenceNode(option.reference),
|
||||
$createTextNode(' '),
|
||||
]);
|
||||
} else {
|
||||
const paragraph = $createParagraphNode();
|
||||
paragraph.append(
|
||||
$createResourceReferenceNode(option.reference),
|
||||
$createTextNode(' '),
|
||||
);
|
||||
$getRoot().append(paragraph);
|
||||
}
|
||||
closeMenu();
|
||||
insertReferenceNode(option.reference, textNodeContainingQuery, closeMenu);
|
||||
},
|
||||
[],
|
||||
[insertReferenceNode],
|
||||
);
|
||||
|
||||
const handleSelectSkill = useCallback(
|
||||
(
|
||||
option: SkillMentionOption,
|
||||
textNodeContainingQuery: TextNode | null,
|
||||
closeMenu: () => void,
|
||||
) => {
|
||||
insertReferenceNode(option.skill, textNodeContainingQuery, closeMenu);
|
||||
},
|
||||
[insertReferenceNode],
|
||||
);
|
||||
|
||||
// —— C8 AI 润色与发送前提醒 ——
|
||||
@@ -1017,7 +1130,9 @@ function ResourceReferenceEditor({
|
||||
acknowledgedDraftKeyRef.current = null;
|
||||
}, [resetPromptPolish]);
|
||||
|
||||
const renderMentionMenu: MenuRenderFn<ResourceMentionOption> = useCallback(
|
||||
const renderMentionMenu: MenuRenderFn<
|
||||
ResourceMentionOption | SkillMentionOption
|
||||
> = useCallback(
|
||||
(_anchorElementRef, itemProps) => {
|
||||
const inputRect = rootRef.current?.getBoundingClientRect();
|
||||
if (!inputRect || itemProps.options.length === 0) {
|
||||
@@ -1052,7 +1167,7 @@ function ResourceReferenceEditor({
|
||||
<div
|
||||
className="resource-reference-menu"
|
||||
role="listbox"
|
||||
aria-label="候选素材"
|
||||
aria-label="候选引用"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: `${top}px`,
|
||||
@@ -1075,8 +1190,16 @@ function ResourceReferenceEditor({
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => itemProps.selectOptionAndCleanUp(option)}
|
||||
>
|
||||
<span>{option.reference.label}</span>
|
||||
<small>{option.reference.kind}</small>
|
||||
<span>
|
||||
{'reference' in option
|
||||
? `@${option.reference.label}`
|
||||
: `$${option.skill.name}`}
|
||||
</span>
|
||||
<small>
|
||||
{'reference' in option
|
||||
? option.reference.kind
|
||||
: (option.skill.description ?? 'Skill')}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</div>,
|
||||
@@ -1201,7 +1324,22 @@ function ResourceReferenceEditor({
|
||||
onSelectOption={(option, textNode, closeMenu) =>
|
||||
handleSelectMention(option, textNode, closeMenu)
|
||||
}
|
||||
menuRenderFn={renderMentionMenu}
|
||||
menuRenderFn={
|
||||
renderMentionMenu as unknown as MenuRenderFn<ResourceMentionOption>
|
||||
}
|
||||
anchorClassName="resource-reference-menu-anchor"
|
||||
preselectFirstItem
|
||||
/>
|
||||
<LexicalTypeaheadMenuPlugin<SkillMentionOption>
|
||||
options={skillOptions}
|
||||
triggerFn={skillTriggerFn}
|
||||
onQueryChange={setSkillQuery}
|
||||
onSelectOption={(option, textNode, closeMenu) =>
|
||||
handleSelectSkill(option, textNode, closeMenu)
|
||||
}
|
||||
menuRenderFn={
|
||||
renderMentionMenu as unknown as MenuRenderFn<SkillMentionOption>
|
||||
}
|
||||
anchorClassName="resource-reference-menu-anchor"
|
||||
preselectFirstItem
|
||||
/>
|
||||
|
||||
+1
@@ -5,6 +5,7 @@ import type { DirectCodexUserRuntimeRegionPart } from './DirectCodexUserRuntimeR
|
||||
export type DirectCodexUserContentPart =
|
||||
| { type: 'input_text'; text: string }
|
||||
| { type: 'agc_resource_reference'; resourceId: string }
|
||||
| { type: 'agc_skill_reference'; name: string }
|
||||
| ({
|
||||
type: 'agc_runtime_region_reference';
|
||||
} & DirectCodexUserRuntimeRegionPart)
|
||||
|
||||
@@ -46,7 +46,16 @@ export type RuntimeRegionReference = {
|
||||
source: 'runtime-picker';
|
||||
};
|
||||
|
||||
export type ChatReference = ResourceReference | RuntimeRegionReference;
|
||||
export type SkillReference = {
|
||||
type: 'skill';
|
||||
name: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export type ChatReference =
|
||||
| ResourceReference
|
||||
| RuntimeRegionReference
|
||||
| SkillReference;
|
||||
|
||||
export type ChatComposerDraft = {
|
||||
text: string;
|
||||
@@ -107,6 +116,9 @@ export function directCodexContentToPromptText(
|
||||
if (part.type === 'agc_resource_reference') {
|
||||
return `@${labels.get(part.resourceId) ?? part.resourceId}`;
|
||||
}
|
||||
if (part.type === 'agc_skill_reference') {
|
||||
return `$${part.name}`;
|
||||
}
|
||||
if (part.type === 'agc_runtime_region_reference') {
|
||||
return `@${part.label}`;
|
||||
}
|
||||
@@ -134,7 +146,9 @@ export function chatReferenceToContentPart(
|
||||
if (reference.type === 'resource') {
|
||||
return { type: 'agc_resource_reference', resourceId: reference.resourceId };
|
||||
}
|
||||
// 生成绑定里可选字段是 `T | null`(Rust `Option<T>` 会显式序列化成 null,不是省略键)。
|
||||
if (reference.type === 'skill') {
|
||||
return { type: 'agc_skill_reference', name: reference.name };
|
||||
}
|
||||
return {
|
||||
type: 'agc_runtime_region_reference',
|
||||
label: reference.label,
|
||||
@@ -384,6 +398,9 @@ function chatReferenceKey(reference: ChatReference) {
|
||||
if (reference.type === 'resource') {
|
||||
return `resource:${reference.resourceId}:${reference.source}`;
|
||||
}
|
||||
if (reference.type === 'skill') {
|
||||
return `skill:${reference.name}`;
|
||||
}
|
||||
return `runtime-region:${runtimeRegionReferenceDiscriminators(reference)}`;
|
||||
}
|
||||
|
||||
@@ -393,11 +410,15 @@ function chatReferenceKey(reference: ChatReference) {
|
||||
*/
|
||||
export function chatReferenceListKey(references: ChatReference[]) {
|
||||
return references
|
||||
.map((reference) =>
|
||||
reference.type === 'resource'
|
||||
? `resource:${reference.resourceId}:${reference.source}:${reference.label}`
|
||||
: `runtime-region:${runtimeRegionReferenceDiscriminators(reference)}`,
|
||||
)
|
||||
.map((reference) => {
|
||||
if (reference.type === 'resource') {
|
||||
return `resource:${reference.resourceId}:${reference.source}:${reference.label}`;
|
||||
}
|
||||
if (reference.type === 'skill') {
|
||||
return `skill:${reference.name}`;
|
||||
}
|
||||
return `runtime-region:${runtimeRegionReferenceDiscriminators(reference)}`;
|
||||
})
|
||||
.join('\u0001');
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
Bot,
|
||||
CheckCircle2,
|
||||
CircleAlert,
|
||||
FolderOpen,
|
||||
Info,
|
||||
LoaderCircle,
|
||||
Pencil,
|
||||
@@ -45,7 +44,6 @@ import {
|
||||
startAgcPlugin,
|
||||
stopAgcPlugin,
|
||||
} from '../../services/pluginHost';
|
||||
import { useProjectCreationDirectory } from '../app-shell/useProjectCreationDirectory';
|
||||
import { PluginPanelHost } from '../plugins/PluginPanelHost';
|
||||
import { reasoningEffortLabel } from '../project-workspace/composerReasoningEffort';
|
||||
import { CustomLlmSettings } from './CustomLlmSettings';
|
||||
@@ -79,7 +77,6 @@ const defaultRuntimeConfigDraft: GameCreatorAppConfig = {
|
||||
|
||||
type RuntimeSettingsSection =
|
||||
| 'general'
|
||||
| 'workspace'
|
||||
| 'agents'
|
||||
| 'extensions'
|
||||
| 'advanced'
|
||||
@@ -99,12 +96,6 @@ const runtimeSettingsSections = [
|
||||
description: '运行方式与输出偏好',
|
||||
icon: Settings2,
|
||||
},
|
||||
{
|
||||
id: 'workspace',
|
||||
label: '工作区',
|
||||
description: '项目创建目录',
|
||||
icon: FolderOpen,
|
||||
},
|
||||
{
|
||||
id: 'agents',
|
||||
label: 'Agent 分工',
|
||||
@@ -233,11 +224,6 @@ export function RuntimeConfigDialog({
|
||||
const [runtimeConfigBusy, setRuntimeConfigBusy] = useState(false);
|
||||
const [activeSection, setActiveSection] =
|
||||
useState<RuntimeSettingsSection>('general');
|
||||
/**
|
||||
* 「项目创建目录」是客户端本地偏好(localStorage),不随下面的配置文件一起保存:
|
||||
* 选择目录当场生效,做游戏 / 做方案与模板建项下一次建项就落在该目录下。
|
||||
*/
|
||||
const projectCreationDirectory = useProjectCreationDirectory();
|
||||
const [clientExtensions, setClientExtensions] = useState<
|
||||
ClientExtensionItem[]
|
||||
>([]);
|
||||
@@ -889,53 +875,6 @@ export function RuntimeConfigDialog({
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{activeSection === 'workspace' ? (
|
||||
<div className="runtime-settings-readonly-field">
|
||||
<span>项目创建目录</span>
|
||||
<strong
|
||||
title={
|
||||
projectCreationDirectory.projectCreationDirectory ||
|
||||
undefined
|
||||
}
|
||||
>
|
||||
{projectCreationDirectory.projectCreationDirectory ||
|
||||
'默认位置'}
|
||||
</strong>
|
||||
<div className="runtime-settings-field-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
projectCreationDirectory.projectCreationDirectoryBusy
|
||||
}
|
||||
onClick={() =>
|
||||
void projectCreationDirectory.pickProjectCreationDirectory()
|
||||
}
|
||||
>
|
||||
<FolderOpen size={14} aria-hidden="true" />
|
||||
选择目录
|
||||
</button>
|
||||
{projectCreationDirectory.projectCreationDirectory ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
projectCreationDirectory.projectCreationDirectoryBusy
|
||||
}
|
||||
onClick={
|
||||
projectCreationDirectory.resetProjectCreationDirectory
|
||||
}
|
||||
>
|
||||
<RotateCcw size={14} aria-hidden="true" />
|
||||
恢复默认位置
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{projectCreationDirectory.projectCreationDirectoryStatus ? (
|
||||
<small>
|
||||
{projectCreationDirectory.projectCreationDirectoryStatus}
|
||||
</small>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{activeSection === 'advanced' &&
|
||||
runtimeConfigDraft.agentMode !== 'codex_cli' ? (
|
||||
<>
|
||||
|
||||
@@ -10,7 +10,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { resolveTauriInvoke } from '../../app/tauri';
|
||||
import type { InitLocalProjectResult } from '../../app/types';
|
||||
import { readProjectCreationDirectory } from '../app-shell/model';
|
||||
import {
|
||||
collectGameTemplateRuntimes,
|
||||
collectGameTemplateTags,
|
||||
@@ -154,8 +153,6 @@ export function useTemplateLibrary({
|
||||
templateVersion: template.templateVersion,
|
||||
name: null,
|
||||
planning: false,
|
||||
// 与首页自动建项共用一个「项目创建目录」偏好;没选时由 Rust 侧回落到默认位置。
|
||||
projectsRoot: readProjectCreationDirectory() || null,
|
||||
},
|
||||
);
|
||||
await onProjectCreated(result);
|
||||
|
||||
@@ -4247,15 +4247,7 @@ h2 {
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.runtime-settings-field-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
margin-top: 7px;
|
||||
}
|
||||
|
||||
.runtime-settings-section-actions button,
|
||||
.runtime-settings-field-actions button,
|
||||
.runtime-settings-extension-actions button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -4272,14 +4264,12 @@ h2 {
|
||||
}
|
||||
|
||||
.runtime-settings-section-actions button:hover,
|
||||
.runtime-settings-field-actions button:hover,
|
||||
.runtime-settings-extension-actions button:hover {
|
||||
border-color: var(--platform-surface-hover-border);
|
||||
background: var(--platform-button-ghost-fill);
|
||||
}
|
||||
|
||||
.runtime-settings-section-actions button:disabled,
|
||||
.runtime-settings-field-actions button:disabled,
|
||||
.runtime-settings-extension-actions button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.55;
|
||||
|
||||
@@ -1631,7 +1631,6 @@ export function registerHomeProjectCreationTests() {
|
||||
expect(invoke).toHaveBeenCalledWith('create_automatic_local_game_project', {
|
||||
name: null,
|
||||
planning: false,
|
||||
projectsRoot: null,
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith('chat_with_game_creator_direct_codex', {
|
||||
projectPath: automaticProjectPath,
|
||||
@@ -1737,7 +1736,6 @@ export function registerHomeProjectCreationTests() {
|
||||
expect(invoke).toHaveBeenCalledWith('create_automatic_local_game_project', {
|
||||
name: '角色参考游戏',
|
||||
planning: false,
|
||||
projectsRoot: null,
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith('upload_local_asset', {
|
||||
projectPath: automaticProjectPath,
|
||||
@@ -3545,102 +3543,4 @@ export function registerRecentProjectsTests() {
|
||||
);
|
||||
expect(window.localStorage.length).toBe(0);
|
||||
});
|
||||
|
||||
it('creates the automatic workspace inside the project creation directory picked in settings', async () => {
|
||||
const automaticProjectPath =
|
||||
'F:\\Projects\\我的游戏\\gameagent-chosen-directory';
|
||||
const creationDirectory = 'F:\\Projects\\我的游戏';
|
||||
const manifest = createGameCreationAppManifest(
|
||||
'home-creation-directory-project',
|
||||
'自选目录项目',
|
||||
);
|
||||
const supervisorHarness = createProjectSupervisorRuntimeHarness({
|
||||
projectPath: automaticProjectPath,
|
||||
initialSessionExists: false,
|
||||
});
|
||||
const invoke = vi.fn(
|
||||
async (command: string, args?: Record<string, unknown>) => {
|
||||
if (command === 'read_game_creator_app_config') {
|
||||
return {
|
||||
path: 'C:\\Users\\tester\\AppData\\Roaming\\genarrative\\config.json',
|
||||
config: {
|
||||
agentMode: 'codex_app_server',
|
||||
llm: {
|
||||
apiKey: '',
|
||||
baseUrl: 'https://llm.example.test/v1',
|
||||
model: 'gpt-creation-directory',
|
||||
apiKind: 'openai_responses',
|
||||
reasoningEffort: 'high',
|
||||
stream: true,
|
||||
webSearchEnabled: false,
|
||||
contextWindowTokens: 128000,
|
||||
autoCompactTokenLimit: 64000,
|
||||
toolOutputTokenLimit: 12000,
|
||||
requestTimeoutMs: 180000,
|
||||
maxRetries: 2,
|
||||
retryBackoffMs: 500,
|
||||
},
|
||||
agentLlm: {},
|
||||
editorApi: { baseUrl: 'http://127.0.0.1:8082', apiKey: '' },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (command === 'pick_local_project_directory') {
|
||||
return creationDirectory;
|
||||
}
|
||||
if (command === 'create_automatic_local_game_project') {
|
||||
return {
|
||||
projectPath: automaticProjectPath,
|
||||
manifestPath: `${automaticProjectPath}\\.agent\\manifest.json`,
|
||||
manifest,
|
||||
};
|
||||
}
|
||||
if (command === 'chat_with_game_creator_direct_codex') {
|
||||
return '收到,开始搭建。';
|
||||
}
|
||||
return supervisorHarness.invoke(command, args);
|
||||
},
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
core: { invoke },
|
||||
event: { listen: supervisorHarness.listen },
|
||||
};
|
||||
renderLauncherAt('/?launcher', 'home', true);
|
||||
|
||||
// 设置 → 工作区:默认位置就是不选目录,仍然落在 AGC 管理的应用数据目录。
|
||||
fireEvent.click(screen.getByRole('button', { name: '配置' }));
|
||||
const settings = await screen.findByRole('dialog', { name: '运行时配置' });
|
||||
fireEvent.click(within(settings).getByRole('button', { name: /工作区/ }));
|
||||
expect(within(settings).getByText('默认位置')).not.toBeNull();
|
||||
fireEvent.click(within(settings).getByRole('button', { name: '选择目录' }));
|
||||
await waitFor(() => {
|
||||
expect(within(settings).getByText(creationDirectory)).not.toBeNull();
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith('pick_local_project_directory', {
|
||||
title: '选择项目创建目录',
|
||||
});
|
||||
expect(
|
||||
window.localStorage.getItem(
|
||||
'genarrative-ai-game-creator.project-creation-directory.v1',
|
||||
),
|
||||
).toBe(JSON.stringify(creationDirectory));
|
||||
fireEvent.click(
|
||||
within(settings).getByRole('button', { name: '关闭 Agent 设置' }),
|
||||
);
|
||||
|
||||
const promptInput = screen.getByLabelText('创作想法');
|
||||
nativeClipboardMock.text = '做一个花园经营游戏';
|
||||
fireEvent.paste(promptInput);
|
||||
await waitFor(() => {
|
||||
expect(promptInput.textContent).toContain('做一个花园经营游戏');
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: '开启创作' }));
|
||||
|
||||
expect(await screen.findByLabelText('项目开发工作台')).not.toBeNull();
|
||||
expect(invoke).toHaveBeenCalledWith('create_automatic_local_game_project', {
|
||||
name: null,
|
||||
planning: false,
|
||||
projectsRoot: creationDirectory,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -360,70 +360,6 @@ export function registerRuntimeSettingsTests() {
|
||||
expect(screen.getByText('桌面客户端')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the project creation directory in the workspace settings section', async () => {
|
||||
const creationDirectory = 'F:\\Projects\\陶泥儿游戏';
|
||||
const storageKey =
|
||||
'genarrative-ai-game-creator.project-creation-directory.v1';
|
||||
const invoke = vi.fn(async (command: string) => {
|
||||
if (command === 'read_game_creator_app_config') {
|
||||
return {
|
||||
path: '/home/test/AppData/game-creator.config.json',
|
||||
config: {
|
||||
agentMode: 'codex_app_server',
|
||||
llm: {
|
||||
apiKey: '',
|
||||
baseUrl: 'https://llm.example.test/v1',
|
||||
model: 'gpt-workspace',
|
||||
apiKind: 'openai_responses',
|
||||
reasoningEffort: 'high',
|
||||
stream: true,
|
||||
webSearchEnabled: false,
|
||||
contextWindowTokens: 128000,
|
||||
autoCompactTokenLimit: 64000,
|
||||
toolOutputTokenLimit: 12000,
|
||||
requestTimeoutMs: 180000,
|
||||
maxRetries: 2,
|
||||
retryBackoffMs: 500,
|
||||
},
|
||||
agentLlm: {},
|
||||
editorApi: { baseUrl: 'http://127.0.0.1:8082', apiKey: '' },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (command === 'pick_local_project_directory') {
|
||||
return creationDirectory;
|
||||
}
|
||||
throw new Error(`unexpected invoke ${command}`);
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
renderLauncherAt('/?launcher');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '配置' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: '运行时配置' });
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: /工作区/ }));
|
||||
|
||||
// 不选目录时是默认位置,且本地不写任何偏好。
|
||||
expect(within(dialog).getByText('默认位置')).not.toBeNull();
|
||||
expect(window.localStorage.getItem(storageKey)).toBeNull();
|
||||
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: '选择目录' }));
|
||||
expect(await within(dialog).findByText(creationDirectory)).not.toBeNull();
|
||||
expect(invoke).toHaveBeenCalledWith('pick_local_project_directory', {
|
||||
title: '选择项目创建目录',
|
||||
});
|
||||
expect(window.localStorage.getItem(storageKey)).toBe(
|
||||
JSON.stringify(creationDirectory),
|
||||
);
|
||||
expect(within(dialog).getByText('已更新项目创建目录')).not.toBeNull();
|
||||
|
||||
fireEvent.click(
|
||||
within(dialog).getByRole('button', { name: '恢复默认位置' }),
|
||||
);
|
||||
expect(within(dialog).getByText('默认位置')).not.toBeNull();
|
||||
expect(window.localStorage.getItem(storageKey)).toBeNull();
|
||||
expect(within(dialog).getByText('已恢复默认位置')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('locks the Agent mode and official LLM route while dropping legacy credentials', async () => {
|
||||
const invoke = vi.fn(
|
||||
async (command: string, args?: Record<string, unknown>) => {
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
normalizeProjectCreationDirectory,
|
||||
readProjectCreationDirectory,
|
||||
writeProjectCreationDirectory,
|
||||
} from '../src/features/app-shell/model';
|
||||
|
||||
const STORAGE_KEY = 'genarrative-ai-game-creator.project-creation-directory.v1';
|
||||
|
||||
describe('项目创建目录偏好', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it('去掉首尾空白与多余分隔符,并保留盘根', () => {
|
||||
expect(normalizeProjectCreationDirectory(' ')).toBe('');
|
||||
expect(normalizeProjectCreationDirectory(' F:\\Projects\\游戏\\ ')).toBe(
|
||||
'F:\\Projects\\游戏',
|
||||
);
|
||||
expect(normalizeProjectCreationDirectory('F:/Projects/游戏/')).toBe(
|
||||
'F:/Projects/游戏',
|
||||
);
|
||||
expect(normalizeProjectCreationDirectory('C:\\')).toBe('C:\\');
|
||||
// 首尾空白按 trim 处理;目录中间的控制字符必须整条拒绝。
|
||||
expect(normalizeProjectCreationDirectory('F:\\游戏\n')).toBe('F:\\游戏');
|
||||
expect(normalizeProjectCreationDirectory('F:\\游\n戏')).toBe('');
|
||||
});
|
||||
|
||||
it('保存选中的目录,并在恢复默认位置时清空', () => {
|
||||
expect(readProjectCreationDirectory()).toBe('');
|
||||
|
||||
expect(writeProjectCreationDirectory(' F:\\Projects\\游戏 ')).toBe(
|
||||
'F:\\Projects\\游戏',
|
||||
);
|
||||
expect(readProjectCreationDirectory()).toBe('F:\\Projects\\游戏');
|
||||
|
||||
expect(writeProjectCreationDirectory(' ')).toBe('');
|
||||
expect(readProjectCreationDirectory()).toBe('');
|
||||
});
|
||||
|
||||
it('忽略存储里不可用的值,退回默认位置', () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify('relative/games'));
|
||||
expect(readProjectCreationDirectory()).toBe('');
|
||||
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(42));
|
||||
expect(readProjectCreationDirectory()).toBe('');
|
||||
|
||||
window.localStorage.setItem(STORAGE_KEY, '{not json');
|
||||
expect(readProjectCreationDirectory()).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { $getRoot } from 'lexical';
|
||||
import { $getRoot, $getSelection, $isRangeSelection } from 'lexical';
|
||||
import { createRef, StrictMode, useState } from 'react';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
@@ -103,10 +103,12 @@ function draftResourceIds(draft: ChatComposerDraft | undefined) {
|
||||
*/
|
||||
function composerEditor(): {
|
||||
getEditorState: () => { read: <T>(fn: () => T) => T };
|
||||
update: (fn: () => void) => void;
|
||||
} {
|
||||
const element = screen.getByLabelText('聊天') as HTMLElement & {
|
||||
__lexicalEditor?: {
|
||||
getEditorState: () => { read: <T>(fn: () => T) => T };
|
||||
update: (fn: () => void) => void;
|
||||
};
|
||||
};
|
||||
const editor = element.__lexicalEditor;
|
||||
@@ -114,6 +116,18 @@ function composerEditor(): {
|
||||
return editor;
|
||||
}
|
||||
|
||||
/**
|
||||
* jsdom 里键盘输入不会进入 Lexical,所以直接走编辑器 API 写文本;
|
||||
* 它触发的是和真实输入同一条更新链路,typeahead 监听器同样会被唤醒。
|
||||
*/
|
||||
function insertComposerText(text: string) {
|
||||
composerEditor().update(() => {
|
||||
$getRoot().selectEnd();
|
||||
const selection = $getSelection();
|
||||
if ($isRangeSelection(selection)) selection.insertText(text);
|
||||
});
|
||||
}
|
||||
|
||||
function editorTextSize() {
|
||||
return composerEditor()
|
||||
.getEditorState()
|
||||
@@ -169,6 +183,39 @@ async function insertAssetThroughPicker(ariaLabel: string, optionName: RegExp) {
|
||||
afterEach(cleanup);
|
||||
|
||||
describe('ResourceReferenceInput', () => {
|
||||
test('打开 Skill 候选时才向 Tauri command 查询内置 catalog', async () => {
|
||||
const invoke = vi.fn(async (command: string) => {
|
||||
if (command === 'list_agc_skill_catalog') {
|
||||
return [{ name: 'agc-test-skill', description: '测试 Skill' }];
|
||||
}
|
||||
if (command === 'list_client_extensions') return [];
|
||||
throw new Error(`unexpected invoke ${command}`);
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke: invoke as never } };
|
||||
|
||||
try {
|
||||
render(
|
||||
<ResourceReferenceInput
|
||||
onChange={vi.fn()}
|
||||
assets={assets}
|
||||
projectPath="C:/project"
|
||||
ariaLabel="聊天"
|
||||
/>,
|
||||
);
|
||||
|
||||
// 挂载即查询会让「工作区路径非法时不产生任何后端访问」的边界失效。
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
|
||||
insertComposerText('$');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(invoke).toHaveBeenCalledWith('list_agc_skill_catalog');
|
||||
});
|
||||
} finally {
|
||||
delete window.__TAURI__;
|
||||
}
|
||||
});
|
||||
|
||||
test('运行画面引用的判别指纹带上了绑定素材、版本、元素角色与尺寸', () => {
|
||||
const base: RuntimeRegionReference = {
|
||||
type: 'runtime-region',
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# AGC 项目创建目录可选实施计划
|
||||
|
||||
Version: 1.0
|
||||
Status: active
|
||||
Date: 2026-09-17
|
||||
Related Spec: `docs/technical/【技术方案】AGC模板库与模板建项-2026-09-17.md`、`docs/【技术方案】AGC异步操作可恢复闭环-2026-09-14.md`
|
||||
|
||||
## 目标
|
||||
|
||||
让用户在 AGC 里能自己选项目创建目录:首页「做游戏 / 做方案」自动建项与模板库「使用模板」建项都落在用户选定的目录下;不选时保持 AGC 管理的默认位置(`<app_data>/projects`),行为与现状一致。
|
||||
|
||||
## 交接结果
|
||||
|
||||
- `create_automatic_local_game_project`、`create_automatic_local_game_project_from_template` 新增可选参数 `projectsRoot`;为空时由 Rust 侧回落到默认目录。
|
||||
- `pick_local_project_directory` 新增可选参数 `title`(只接受短标题,其余回退「选择游戏项目目录」)。
|
||||
- 新增用户偏好「项目创建目录」:`localStorage` 键 `genarrative-ai-game-creator.project-creation-directory.v1`。
|
||||
- 入口在客户端设置里:侧边栏「配置」→ 设置分类「工作区」;`RuntimeConfigDialog` 内用 `useProjectCreationDirectory` 展示与改选目录,不经过首页或模板库页头。
|
||||
- 首页「做游戏 / 做方案」与模板库「使用模板」建项时读取同一份偏好,用户不需要在建项前再选一次。
|
||||
|
||||
## 行为契约
|
||||
|
||||
- 允许的来源只有一个:本机原生目录选择器(`pick_local_project_directory`)。它返回的目录已在选择时按 user-selected 范围做过一次加固,构成「用户显式选择」边界。
|
||||
- Rust 侧 `validate_requested_game_project_creation_root` 对传入目录要求:非空、绝对路径、无控制字符、已存在的普通目录(符号链接 / Windows reparse point / 普通文件一律拒绝),并通过 `prepare_game_creator_project_root_for_read`(user-selected 范围的一次性修复)。目录不存在时不代为创建,直接失败。
|
||||
- 建出的项目目录仍在所选目录下按 `gameagent-<8位短ID>` 命名,项目名、`.agent` 初始化、首轮投递与既有自动建项完全一致。
|
||||
- 偏好只保存「用户意图」,不是授权凭据:存储被外部改动最坏只是回退默认位置或一次可见的建项失败,不会跳过 Rust 门禁。
|
||||
- 该偏好是客户端本地设置,不写入 `read_game_creator_app_config` / 保存设置的那份运行时配置:在「工作区」里选择目录当场生效,与「保存设置」按钮无关。
|
||||
- 「恢复默认位置」清空偏好即回到应用数据目录;既有项目不迁移。
|
||||
|
||||
## 步骤
|
||||
|
||||
1. **Rust 建项入口**
|
||||
- `commands.rs`:新增 `validate_requested_game_project_creation_root` / `resolve_game_project_creation_root`,`create_automatic_local_game_project` 接受 `projects_root`;`pick_local_project_directory` 接受 `title`。
|
||||
- `template_library.rs`:模板建项复用同一解析函数。
|
||||
- 交付:两条定向单测(校验矩阵、在指定创建目录下建项)。
|
||||
- 验收:`cargo test --bin genarrative-ai-game-creator-shell creation_root` 全绿。
|
||||
|
||||
2. **前端偏好与入口**
|
||||
- `features/app-shell/model.ts`:`normalizeProjectCreationDirectory` / `readProjectCreationDirectory` / `writeProjectCreationDirectory` / `projectCreationDirectoryLabel`。
|
||||
- `useProjectCreationDirectory`:选择目录、恢复默认、状态文案(失败在设置页字段内可见)。
|
||||
- `RuntimeConfigDialog` 新增「工作区」设置分类,承载「项目创建目录」字段与「选择目录 / 恢复默认位置」动作。
|
||||
- `useHomeProjectCreation` 与 `useTemplateLibrary` 在建项时带上 `projectsRoot`。
|
||||
- 交付:偏好模型 4 项单测、设置页 1 项交互测试、appSurface 1 项「设置里选目录后建项」端到端场景。
|
||||
- 验收:`npx vitest run apps/ai-game-creator-shell/tests/projectCreationDirectory.test.ts apps/ai-game-creator-shell/tests/appSurface.test.ts` 全绿。
|
||||
|
||||
3. **文档与共享记忆**
|
||||
- 本实施计划;模板库技术方案的命令表补 `projectsRoot`;`decision-log.md` 记录偏好键与命令参数;`pitfalls.md` 说明用户自选目录与 AGC 管理目录的关系。
|
||||
- 验收:`node scripts/check-doc-index.mjs` 通过。
|
||||
|
||||
## 验证命令
|
||||
|
||||
```bash
|
||||
cargo check --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml --bin genarrative-ai-game-creator-shell
|
||||
cargo test --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml --bin genarrative-ai-game-creator-shell creation_root
|
||||
cargo test --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml --bin genarrative-ai-game-creator-shell template_library
|
||||
cd apps/ai-game-creator-shell && npx tsc -p tsconfig.json --noEmit
|
||||
npx vitest run apps/ai-game-creator-shell/tests
|
||||
npm run check:encoding
|
||||
node scripts/check-doc-index.mjs
|
||||
git diff --check
|
||||
```
|
||||
|
||||
手动验收(客户端内):侧边栏「配置」→「工作区」→「选择目录」选 `F:\Projects\我的游戏`,回首页建项后项目目录应为 `F:\Projects\我的游戏\gameagent-<8位>`;模板库「使用模板」建项同样落在该目录;点「恢复默认位置」后再建项回到应用数据目录。
|
||||
|
||||
## 风险与回退
|
||||
|
||||
- **自选目录无法加固**:`Documents` 等带受保护继承 ACL 的位置可能加固失败。失败发生在选择器或建项前置校验阶段,报错可见且不会留下半成品项目;用户改选其它目录或用默认位置即可。
|
||||
- **偏好漂移**:偏好只是提示值,每次建项都会重新校验;存储被改坏不会绕过门禁。
|
||||
- **回退**:删掉偏好键(或点「恢复默认位置」)即回到默认目录;需要彻底移除该能力时,去掉两个命令的可选参数与设置页字段即可,Rust 默认路径逻辑不变。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user