Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 46d395763d | |||
| 7eaaa1a499 | |||
| 8ee50e8b94 | |||
| 492e9e63af | |||
| 2bcfa10647 | |||
| e777236817 | |||
| d11c74212d | |||
| 82b2f853e7 | |||
| 31f83a751a | |||
| a1cafde7e9 | |||
| 0594a90bdd | |||
| aee862532c | |||
| 42be8ea060 | |||
| 737a2266b9 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@genarrative/ai-game-creator-shell",
|
||||
"private": true,
|
||||
"version": "0.1.45",
|
||||
"version": "0.1.47",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
|
||||
+1
-1
@@ -1725,7 +1725,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.45"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"agent-runtime-core",
|
||||
"axum",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.45"
|
||||
version = "0.1.47"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -195,6 +195,20 @@ impl CodexAppServerStderrSummary {
|
||||
}
|
||||
}
|
||||
|
||||
/// 派发 app-server 的收尾与中断任务。
|
||||
///
|
||||
/// 这个入口会被**没有 tokio runtime 上下文的线程**调用:`cancel_direct_codex_turn`
|
||||
/// 是同步 Tauri 命令,直接跑在 IPC 回调线程(Windows 上是 WebView2 的 UI 线程);
|
||||
/// [`CodexThreadLease`] 与 [`CodexTurnGuard`] 的 `Drop` 也在调用方线程上执行。
|
||||
/// `tokio::spawn` 在那样的线程上会经 `Handle::current()` panic("there is no reactor
|
||||
/// running"),而 panic 跨不过 Tauri 的 IPC 回调边界,整个进程会以 `0xC0000409`
|
||||
/// (FAST_FAIL_FATAL_APP_EXIT)abort——现场就是"点终止,App 闪退"(2026-09-16 的 WER
|
||||
/// 记录:`genarrative-ai-game-creator-shell.exe`,异常代码 `0xc0000409`,fail-fast
|
||||
/// 参数 `7`)。一律走 Tauri 的全局异步 runtime:`main` 已把深栈 runtime 装进去。
|
||||
fn spawn_codex_app_server_task(task: impl std::future::Future<Output = ()> + Send + 'static) {
|
||||
tauri::async_runtime::spawn(task);
|
||||
}
|
||||
|
||||
struct CodexTurnStartCancellation {
|
||||
inner: Weak<CodexAppServerInner>,
|
||||
thread_id: String,
|
||||
@@ -256,7 +270,7 @@ impl CodexTurnStartCancellation {
|
||||
};
|
||||
let connection = CodexAppServerConnection { inner };
|
||||
let thread_id = self.thread_id.clone();
|
||||
tokio::spawn(async move {
|
||||
spawn_codex_app_server_task(async move {
|
||||
let _ = connection
|
||||
.request(
|
||||
"turn/interrupt",
|
||||
@@ -3566,7 +3580,7 @@ impl Drop for CodexThreadLease {
|
||||
let connection = self.connection.clone();
|
||||
let key = self.key.clone();
|
||||
let thread_id = self.thread_id.clone();
|
||||
tokio::spawn(async move {
|
||||
spawn_codex_app_server_task(async move {
|
||||
let mut threads = connection.inner.threads.lock().await;
|
||||
if let Some(entry) = threads.get_mut(&key) {
|
||||
if entry.thread_id == thread_id {
|
||||
@@ -3593,7 +3607,7 @@ impl Drop for CodexTurnGuard {
|
||||
let connection = self.connection.clone();
|
||||
let thread_id = self.thread_id.clone();
|
||||
let turn_id = self.turn_id.clone();
|
||||
tokio::spawn(async move {
|
||||
spawn_codex_app_server_task(async move {
|
||||
connection.inner.turns.lock().await.remove(&turn_id);
|
||||
connection.inner.turn_backlog.lock().await.remove(&turn_id);
|
||||
let _ = connection
|
||||
@@ -4489,6 +4503,19 @@ mod tests {
|
||||
assert!(table.select(&key, None).is_err());
|
||||
}
|
||||
|
||||
/// 终止路径会从同步命令线程和 `Drop` 里派发 app-server 任务:那些线程没有 tokio
|
||||
/// runtime 上下文。`tokio::spawn` 在那里 panic,panic 跨不过 IPC 回调边界就把整个
|
||||
/// 进程 abort(0xC0000409,"点终止就闪退")。这条用例把派发入口钉在没有 runtime
|
||||
/// 上下文的线程上,回退到 `tokio::spawn` 时它会失败。
|
||||
#[test]
|
||||
fn codex_app_server_task_dispatch_needs_no_tokio_runtime_context() {
|
||||
let joined = std::thread::spawn(|| spawn_codex_app_server_task(async {}));
|
||||
assert!(
|
||||
joined.join().is_ok(),
|
||||
"没有 tokio runtime 上下文的线程也必须能派发 app-server 收尾任务"
|
||||
);
|
||||
}
|
||||
|
||||
/// 注册键:前端传的项目路径与回合注册时的路径必须归一化成同一个键(Windows 上
|
||||
/// `canonicalize` 会带 `\\?\` 前缀,去掉后两边才相等)。
|
||||
#[test]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,8 +2,9 @@ use super::*;
|
||||
|
||||
pub(super) static GAME_CREATOR_AGENT_RUNTIME_UPDATE_APP_HANDLE: OnceLock<tauri::AppHandle> =
|
||||
OnceLock::new();
|
||||
pub(super) static GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK: OnceLock<
|
||||
std::sync::Mutex<Option<GameCreatorManifestInvalidationEventSink>>,
|
||||
/// 同一 AppData 允许多个界面窗口同时挂载事件接收端,因此这里是按 token 去重的注册表。
|
||||
pub(super) static GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINKS: OnceLock<
|
||||
std::sync::Mutex<Vec<GameCreatorManifestInvalidationEventSink>>,
|
||||
> = OnceLock::new();
|
||||
#[cfg(test)]
|
||||
pub(super) static GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK_TEST_LOCK: std::sync::Mutex<()> =
|
||||
@@ -293,8 +294,8 @@ pub(crate) use entrypoints::{
|
||||
configure_game_creator_manifest_invalidation_event_sink, emit_direct_game_creator_progress,
|
||||
emit_game_creator_agent_runtime_update, emit_game_creator_manifest_invalidated,
|
||||
game_creator_agent_runtime_update_event, generate_local_game_draft_at,
|
||||
install_game_creator_manifest_invalidation_event_sink, read_game_creator_agent_runtime_at,
|
||||
read_game_creator_agent_runtime_for_session_at, read_game_creator_agent_runtimes_at,
|
||||
read_game_creator_agent_runtime_at, read_game_creator_agent_runtime_for_session_at,
|
||||
read_game_creator_agent_runtimes_at, register_game_creator_manifest_invalidation_event_sink,
|
||||
set_game_creator_agent_runtime_update_app_handle,
|
||||
start_game_creator_manifest_invalidation_event_sink,
|
||||
validate_game_creator_manifest_invalidation_event_sink,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::*;
|
||||
|
||||
const GAME_CREATOR_MANIFEST_INVALIDATION_RELAY_MAX_BYTES: u64 = 64 * 1024;
|
||||
const GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK_MAX: usize = 16;
|
||||
|
||||
fn lock_game_creator_manifest_invalidation_event_sink(
|
||||
) -> std::sync::MutexGuard<'static, Option<GameCreatorManifestInvalidationEventSink>> {
|
||||
GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK
|
||||
.get_or_init(|| Mutex::new(None))
|
||||
fn lock_game_creator_manifest_invalidation_event_sinks(
|
||||
) -> std::sync::MutexGuard<'static, Vec<GameCreatorManifestInvalidationEventSink>> {
|
||||
GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINKS
|
||||
.get_or_init(|| Mutex::new(Vec::new()))
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
@@ -219,7 +220,7 @@ pub(crate) fn configure_game_creator_manifest_invalidation_event_sink(
|
||||
token: &str,
|
||||
) -> Result<(), String> {
|
||||
let sink = validate_game_creator_manifest_invalidation_event_sink(port, token)?;
|
||||
install_game_creator_manifest_invalidation_event_sink(sink);
|
||||
register_game_creator_manifest_invalidation_event_sink(sink);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -240,10 +241,29 @@ pub(crate) fn validate_game_creator_manifest_invalidation_event_sink(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn install_game_creator_manifest_invalidation_event_sink(
|
||||
/// 登记一个界面窗口的事件接收端。
|
||||
///
|
||||
/// 同一窗口重复 attach 用同一个 token,按 token 覆盖旧登记;不同窗口各自持有
|
||||
/// 自己的 token,注册表按登记顺序保留,最多 `GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK_MAX` 个。
|
||||
pub(crate) fn register_game_creator_manifest_invalidation_event_sink(
|
||||
sink: GameCreatorManifestInvalidationEventSink,
|
||||
) {
|
||||
*lock_game_creator_manifest_invalidation_event_sink() = Some(sink);
|
||||
let mut sinks = lock_game_creator_manifest_invalidation_event_sinks();
|
||||
if let Some(existing) = sinks
|
||||
.iter_mut()
|
||||
.find(|existing| existing.token == sink.token)
|
||||
{
|
||||
*existing = sink;
|
||||
return;
|
||||
}
|
||||
if sinks.len() >= GAME_CREATOR_MANIFEST_INVALIDATION_EVENT_SINK_MAX {
|
||||
sinks.remove(0);
|
||||
}
|
||||
sinks.push(sink);
|
||||
}
|
||||
|
||||
fn remove_game_creator_manifest_invalidation_event_sink(token: &str) {
|
||||
lock_game_creator_manifest_invalidation_event_sinks().retain(|sink| sink.token != token);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -258,14 +278,20 @@ impl GameCreatorManifestInvalidationEventSinkTestGuard {
|
||||
}
|
||||
|
||||
pub(crate) fn configured_sink(&self) -> Option<GameCreatorManifestInvalidationEventSink> {
|
||||
lock_game_creator_manifest_invalidation_event_sink().clone()
|
||||
lock_game_creator_manifest_invalidation_event_sinks()
|
||||
.first()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn configured_sinks(&self) -> Vec<GameCreatorManifestInvalidationEventSink> {
|
||||
lock_game_creator_manifest_invalidation_event_sinks().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Drop for GameCreatorManifestInvalidationEventSinkTestGuard {
|
||||
fn drop(&mut self) {
|
||||
*lock_game_creator_manifest_invalidation_event_sink() = None;
|
||||
lock_game_creator_manifest_invalidation_event_sinks().clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,16 +307,43 @@ pub(crate) fn acquire_game_creator_manifest_invalidation_event_sink_test_guard(
|
||||
}
|
||||
|
||||
fn relay_game_creator_manifest_invalidation(root: &Path, agent_id: &str) -> Result<(), String> {
|
||||
let sink = lock_game_creator_manifest_invalidation_event_sink().clone();
|
||||
let Some(sink) = sink else {
|
||||
let sinks = lock_game_creator_manifest_invalidation_event_sinks().clone();
|
||||
if sinks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let event = GameCreatorManifestInvalidatedEvent {
|
||||
project_path: root.to_string_lossy().into_owned(),
|
||||
agent_id: agent_id.to_string(),
|
||||
};
|
||||
let mut failed_tokens = Vec::new();
|
||||
let mut last_error = None;
|
||||
for sink in &sinks {
|
||||
match relay_game_creator_manifest_invalidation_to_sink(sink, &event) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
// 窗口已退出或接收端已释放时只淘汰该接收端,不能影响其它窗口。
|
||||
failed_tokens.push(sink.token.clone());
|
||||
last_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !failed_tokens.is_empty() {
|
||||
lock_game_creator_manifest_invalidation_event_sinks()
|
||||
.retain(|sink| !failed_tokens.contains(&sink.token));
|
||||
}
|
||||
match last_error {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn relay_game_creator_manifest_invalidation_to_sink(
|
||||
sink: &GameCreatorManifestInvalidationEventSink,
|
||||
event: &GameCreatorManifestInvalidatedEvent,
|
||||
) -> Result<(), String> {
|
||||
let envelope = GameCreatorManifestInvalidationRelayEnvelope {
|
||||
token: sink.token,
|
||||
event: GameCreatorManifestInvalidatedEvent {
|
||||
project_path: root.to_string_lossy().into_owned(),
|
||||
agent_id: agent_id.to_string(),
|
||||
},
|
||||
token: sink.token.clone(),
|
||||
event: event.clone(),
|
||||
};
|
||||
let payload = serde_json::to_vec(&envelope)
|
||||
.map_err(|error| format!("序列化 manifest 失效事件失败:{error}"))?;
|
||||
|
||||
@@ -284,6 +284,7 @@ mod resource_inspect;
|
||||
mod resource_preview_scheduler;
|
||||
mod runner;
|
||||
mod swarm_cli;
|
||||
mod template_library;
|
||||
mod tool_plan_handoff;
|
||||
mod user_input;
|
||||
mod windows;
|
||||
@@ -323,6 +324,7 @@ use resource_inspect::*;
|
||||
use resource_preview_scheduler::*;
|
||||
use runner::*;
|
||||
use swarm_cli::*;
|
||||
use template_library::*;
|
||||
use user_input::*;
|
||||
use windows::*;
|
||||
#[tauri::command]
|
||||
@@ -2219,6 +2221,8 @@ fn game_creator_gui_run_event_requests_runner_shutdown(event: &tauri::RunEvent)
|
||||
enum GameCreatorGuiRunnerShutdownOutcome {
|
||||
NotRequested,
|
||||
Requested,
|
||||
/// 仍有其它界面窗口持有参与锁,Runner 必须保留给它们。
|
||||
Retained,
|
||||
Failed(GameCreatorGuiRunnerShutdownFailure),
|
||||
}
|
||||
|
||||
@@ -2256,7 +2260,8 @@ fn classify_game_creator_gui_runner_shutdown_error(
|
||||
GameCreatorGuiRunnerShutdownFailure::ProcessIdentity
|
||||
} else if error.contains("当前平台不支持") || error.contains("macOS 不提供") {
|
||||
GameCreatorGuiRunnerShutdownFailure::PlatformUnsupported
|
||||
} else if error.contains("实例锁") || error.contains("owner 锁") {
|
||||
} else if error.contains("实例锁") || error.contains("参与锁") || error.contains("owner 锁")
|
||||
{
|
||||
GameCreatorGuiRunnerShutdownFailure::LockTimeout
|
||||
} else if error.contains("endpoint") {
|
||||
GameCreatorGuiRunnerShutdownFailure::EndpointUnavailable
|
||||
@@ -2272,13 +2277,14 @@ fn resolve_game_creator_gui_runner_shutdown<F>(
|
||||
shutdown: F,
|
||||
) -> GameCreatorGuiRunnerShutdownOutcome
|
||||
where
|
||||
F: FnOnce() -> Result<(), String>,
|
||||
F: FnOnce() -> Result<bool, String>,
|
||||
{
|
||||
if !game_creator_gui_run_event_requests_runner_shutdown(event) {
|
||||
return GameCreatorGuiRunnerShutdownOutcome::NotRequested;
|
||||
}
|
||||
match shutdown() {
|
||||
Ok(()) => GameCreatorGuiRunnerShutdownOutcome::Requested,
|
||||
Ok(true) => GameCreatorGuiRunnerShutdownOutcome::Requested,
|
||||
Ok(false) => GameCreatorGuiRunnerShutdownOutcome::Retained,
|
||||
Err(error) => GameCreatorGuiRunnerShutdownOutcome::Failed(
|
||||
classify_game_creator_gui_runner_shutdown_error(&error),
|
||||
),
|
||||
@@ -2298,11 +2304,17 @@ fn handle_game_creator_gui_run_event(event: &tauri::RunEvent) {
|
||||
app_log!("agent.direct_codex.gui_exit.shutdown_failed: {error}");
|
||||
}
|
||||
}
|
||||
match resolve_game_creator_gui_runner_shutdown(event, shutdown_external_agent_runner) {
|
||||
match resolve_game_creator_gui_runner_shutdown(
|
||||
event,
|
||||
shutdown_external_agent_runner_for_gui_exit,
|
||||
) {
|
||||
GameCreatorGuiRunnerShutdownOutcome::NotRequested => {}
|
||||
GameCreatorGuiRunnerShutdownOutcome::Requested => {
|
||||
app_log!("agent.runner.gui_exit.shutdown_requested")
|
||||
}
|
||||
GameCreatorGuiRunnerShutdownOutcome::Retained => {
|
||||
app_log!("agent.runner.gui_exit.retained_for_other_windows")
|
||||
}
|
||||
GameCreatorGuiRunnerShutdownOutcome::Failed(failure) => {
|
||||
app_log!("agent.runner.gui_exit.shutdown_failed.{}", failure.code())
|
||||
}
|
||||
@@ -2611,27 +2623,25 @@ fn main() {
|
||||
)
|
||||
})?;
|
||||
setup_log.append("startup.runner.configure.complete");
|
||||
let gui_owner_lock = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
hold_external_agent_runner_gui_participant_lock(&config_dir)
|
||||
.inspect_err(|error| {
|
||||
let details = sanitize_diagnostic_message(error, Some(config_dir.as_path()));
|
||||
setup_log.fail(&format!(
|
||||
"startup.runner.owner-lock.failed details={details}"
|
||||
"startup.runner.participant-lock.failed details={details}"
|
||||
));
|
||||
})
|
||||
.map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
format!("获取 GUI owner 锁失败:{error}"),
|
||||
format!("建立 AGC 界面参与锁失败:{error}"),
|
||||
)
|
||||
})?;
|
||||
let gui_owner_epoch = gui_owner_lock.owner_epoch().to_string();
|
||||
app.manage(gui_owner_lock);
|
||||
setup_log.append("startup.runner.start.begin");
|
||||
set_game_creator_agent_runtime_update_app_handle(app.handle().clone());
|
||||
set_direct_thread_manager_app_handle(app.handle().clone());
|
||||
let manifest_event_sink =
|
||||
start_game_creator_manifest_invalidation_event_sink(app.handle().clone())?;
|
||||
attach_external_agent_runner_gui_owner(&manifest_event_sink, &gui_owner_epoch)
|
||||
attach_external_agent_runner_gui_owner(&manifest_event_sink)
|
||||
.inspect_err(|error| {
|
||||
let details = sanitize_diagnostic_message(error, Some(config_dir.as_path()));
|
||||
setup_log.fail(&format!(
|
||||
@@ -2652,7 +2662,10 @@ fn main() {
|
||||
start_game_creator_external_mcp,
|
||||
stop_game_creator_external_mcp,
|
||||
create_automatic_local_game_project,
|
||||
create_automatic_local_game_project_from_template,
|
||||
init_local_game_project,
|
||||
fetch_game_template_library,
|
||||
download_game_template,
|
||||
import_local_godot_project,
|
||||
import_local_cocos_project,
|
||||
is_local_project_directory_non_empty,
|
||||
|
||||
@@ -12,21 +12,20 @@ pub(crate) use client::{
|
||||
clear_external_agent_runner_platform_session, compact_external_agent_runner_context,
|
||||
configure_external_agent_runner, configure_external_agent_runner_read_only,
|
||||
continue_external_agent_runner_action, ensure_external_agent_runner_started,
|
||||
ensure_external_agent_runner_started_for_gui, install_external_agent_runner_platform_session,
|
||||
ensure_external_agent_runner_started_for_gui, hold_external_agent_runner_gui_participant_lock,
|
||||
install_external_agent_runner_platform_session,
|
||||
interrupt_external_agent_runner_provider_for_steer_decision, notify_external_agent_runner,
|
||||
pause_external_agent_runner, read_external_agent_runner_status,
|
||||
require_external_agent_runner_configured_for_cli_runtime_write,
|
||||
require_external_agent_runner_for_cli_runtime_write, resume_external_agent_runner,
|
||||
shutdown_external_agent_runner, shutdown_external_agent_runner_for_client_exit,
|
||||
shutdown_external_agent_runner_if_idle, steer_external_agent_runner,
|
||||
wake_external_agent_runner_pending, wake_external_agent_runner_pending_for_run,
|
||||
shutdown_external_agent_runner_for_gui_exit, shutdown_external_agent_runner_if_idle,
|
||||
steer_external_agent_runner, wake_external_agent_runner_pending,
|
||||
wake_external_agent_runner_pending_for_run,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
pub(crate) use endpoint::validate_windows_regular_file_handle;
|
||||
pub(crate) use endpoint::{
|
||||
acquire_external_agent_runner_gui_owner_lock, external_agent_runner_enabled,
|
||||
external_agent_runner_is_server_process,
|
||||
};
|
||||
pub(crate) use endpoint::{external_agent_runner_enabled, external_agent_runner_is_server_process};
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use protocol::{ExternalAgentRunnerStatus, EXTERNAL_AGENT_RUNNER_PROTOCOL_VERSION};
|
||||
pub(crate) use server::{
|
||||
|
||||
@@ -25,35 +25,76 @@ pub(super) struct ExternalAgentRunnerGuiOwnerAttachmentState {
|
||||
|
||||
struct ExternalAgentRunnerGuiOwnerRegistration {
|
||||
generation: u64,
|
||||
claim_mode: ExternalAgentRunnerGuiOwnerClaimMode,
|
||||
config_dir: PathBuf,
|
||||
params: ExternalAgentRunnerRequestParams,
|
||||
attached_boot_id: Option<String>,
|
||||
}
|
||||
|
||||
/// claim 解析模式。
|
||||
///
|
||||
/// `Adopt` 用于窗口启动:沿用现有 durable claim,只有 claim 缺失或不可读时才发布。
|
||||
/// `Publish` 用于本窗口改动了平台登录态:发布新 epoch,成为新的登录态权威。
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) enum ExternalAgentRunnerGuiOwnerClaimMode {
|
||||
Adopt,
|
||||
Publish,
|
||||
}
|
||||
|
||||
static EXTERNAL_AGENT_RUNNER_GUI_OWNER_ATTACHMENT_STATE: OnceLock<
|
||||
Mutex<ExternalAgentRunnerGuiOwnerAttachmentState>,
|
||||
> = OnceLock::new();
|
||||
|
||||
static EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK: OnceLock<
|
||||
Mutex<Option<ExternalAgentRunnerGuiParticipantLock>>,
|
||||
> = OnceLock::new();
|
||||
|
||||
fn external_agent_runner_gui_owner_attachment_state(
|
||||
) -> &'static Mutex<ExternalAgentRunnerGuiOwnerAttachmentState> {
|
||||
EXTERNAL_AGENT_RUNNER_GUI_OWNER_ATTACHMENT_STATE
|
||||
.get_or_init(|| Mutex::new(ExternalAgentRunnerGuiOwnerAttachmentState::default()))
|
||||
}
|
||||
|
||||
fn external_agent_runner_gui_participant_lock(
|
||||
) -> &'static Mutex<Option<ExternalAgentRunnerGuiParticipantLock>> {
|
||||
EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 取得并持有本窗口的界面参与锁,直到窗口退出。
|
||||
///
|
||||
/// 参与锁是共享句柄锁:同一 AppData 的多个窗口可以同时持有,Runner 用独占探测
|
||||
/// 判断是否仍有窗口存活,因此这个锁同时也是“Runner 不能先退出”的存活凭据。
|
||||
pub(crate) fn hold_external_agent_runner_gui_participant_lock(
|
||||
config_dir: &Path,
|
||||
) -> Result<(), String> {
|
||||
let lock = acquire_external_agent_runner_gui_participant_lock(config_dir)?;
|
||||
*lock_unpoisoned(external_agent_runner_gui_participant_lock()) = Some(lock);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn release_external_agent_runner_gui_participant_lock() {
|
||||
drop(lock_unpoisoned(external_agent_runner_gui_participant_lock()).take());
|
||||
}
|
||||
|
||||
/// 登记本窗口的 owner claim 与 attach 参数。
|
||||
///
|
||||
/// 这里不做 claim 文件 IO:claim 由调用方按 `claim_mode` 解析后写进 `params`,
|
||||
/// 因此该函数可以在没有真实 AppData 的单元测试里使用。
|
||||
pub(super) fn register_external_agent_runner_gui_owner_attachment(
|
||||
state: &Mutex<ExternalAgentRunnerGuiOwnerAttachmentState>,
|
||||
config_dir: &Path,
|
||||
claim_mode: ExternalAgentRunnerGuiOwnerClaimMode,
|
||||
mut params: ExternalAgentRunnerRequestParams,
|
||||
) -> Result<(), String> {
|
||||
let mut state = lock_unpoisoned(state);
|
||||
state.generation = state.generation.wrapping_add(1);
|
||||
let generation = state.generation;
|
||||
params.gui_owner_session_revision = Some(generation);
|
||||
if let Some(owner_epoch) = params.gui_owner_epoch.as_deref() {
|
||||
write_external_agent_runner_gui_owner_claim_atomic(config_dir, owner_epoch, generation)?;
|
||||
if params.gui_owner_session_revision.is_none() {
|
||||
params.gui_owner_session_revision = Some(generation);
|
||||
}
|
||||
state.registration = Some(ExternalAgentRunnerGuiOwnerRegistration {
|
||||
generation,
|
||||
claim_mode,
|
||||
config_dir: config_dir.to_path_buf(),
|
||||
params,
|
||||
attached_boot_id: None,
|
||||
@@ -61,6 +102,29 @@ pub(super) fn register_external_agent_runner_gui_owner_attachment(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn reserve_external_agent_runner_gui_owner_claim_revision(
|
||||
state: &Mutex<ExternalAgentRunnerGuiOwnerAttachmentState>,
|
||||
) -> u64 {
|
||||
let mut state = lock_unpoisoned(state);
|
||||
state.generation = state.generation.wrapping_add(1);
|
||||
state.generation
|
||||
}
|
||||
|
||||
pub(super) fn resolve_external_agent_runner_gui_owner_claim(
|
||||
config_dir: &Path,
|
||||
claim_mode: ExternalAgentRunnerGuiOwnerClaimMode,
|
||||
session_revision: u64,
|
||||
) -> Result<ExternalAgentRunnerGuiOwnerClaim, String> {
|
||||
match claim_mode {
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt => {
|
||||
adopt_or_publish_external_agent_runner_gui_owner_claim(config_dir, session_revision)
|
||||
}
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Publish => {
|
||||
publish_external_agent_runner_gui_owner_claim(config_dir, session_revision)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn attach_registered_external_agent_runner_gui_owner_if_needed_with<F>(
|
||||
state: &Mutex<ExternalAgentRunnerGuiOwnerAttachmentState>,
|
||||
config_dir: &Path,
|
||||
@@ -68,27 +132,72 @@ pub(super) fn attach_registered_external_agent_runner_gui_owner_if_needed_with<F
|
||||
attach: F,
|
||||
) -> Result<(), String>
|
||||
where
|
||||
F: FnOnce(&ExternalAgentRunnerEndpoint, ExternalAgentRunnerRequestParams) -> Result<(), String>,
|
||||
F: Fn(&ExternalAgentRunnerEndpoint, ExternalAgentRunnerRequestParams) -> Result<(), String>,
|
||||
{
|
||||
let Some((generation, params)) = ({
|
||||
let state = lock_unpoisoned(state);
|
||||
state.registration.as_ref().and_then(|registration| {
|
||||
(registration.config_dir == config_dir
|
||||
&& registration.attached_boot_id.as_deref() != Some(endpoint.boot_id.as_str()))
|
||||
.then(|| (registration.generation, registration.params.clone()))
|
||||
})
|
||||
}) else {
|
||||
return Ok(());
|
||||
};
|
||||
const ATTACH_CLAIM_RETRY_LIMIT: usize = 3;
|
||||
let mut last_claim_error = None;
|
||||
for attempt in 0..ATTACH_CLAIM_RETRY_LIMIT {
|
||||
let Some((generation, params, claim_mode)) = ({
|
||||
let state = lock_unpoisoned(state);
|
||||
state.registration.as_ref().and_then(|registration| {
|
||||
(registration.config_dir == config_dir
|
||||
&& registration.attached_boot_id.as_deref() != Some(endpoint.boot_id.as_str()))
|
||||
.then(|| {
|
||||
(
|
||||
registration.generation,
|
||||
registration.params.clone(),
|
||||
registration.claim_mode,
|
||||
)
|
||||
})
|
||||
})
|
||||
}) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
attach(endpoint, params)?;
|
||||
|
||||
let mut state = lock_unpoisoned(state);
|
||||
if let Some(registration) = state.registration.as_mut() {
|
||||
if registration.generation == generation && registration.config_dir == config_dir {
|
||||
registration.attached_boot_id = Some(endpoint.boot_id.clone());
|
||||
match attach(endpoint, params) {
|
||||
Ok(()) => {
|
||||
let mut state = lock_unpoisoned(state);
|
||||
if let Some(registration) = state.registration.as_mut() {
|
||||
if registration.generation == generation
|
||||
&& registration.config_dir == config_dir
|
||||
{
|
||||
registration.attached_boot_id = Some(endpoint.boot_id.clone());
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) if attempt + 1 < ATTACH_CLAIM_RETRY_LIMIT && error.contains("claim") => {
|
||||
// 另一个窗口在本次 attach 前后发布了新 claim:按最新 claim 重新解析后重试。
|
||||
last_claim_error = Some(error);
|
||||
refresh_registered_external_agent_runner_gui_owner_claim(
|
||||
state, config_dir, claim_mode,
|
||||
)?;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(last_claim_error.unwrap_or_else(|| "Agent Runner attach 重试后仍然失败".to_string()))
|
||||
}
|
||||
|
||||
fn refresh_registered_external_agent_runner_gui_owner_claim(
|
||||
state: &Mutex<ExternalAgentRunnerGuiOwnerAttachmentState>,
|
||||
config_dir: &Path,
|
||||
claim_mode: ExternalAgentRunnerGuiOwnerClaimMode,
|
||||
) -> Result<(), String> {
|
||||
let session_revision = reserve_external_agent_runner_gui_owner_claim_revision(state);
|
||||
let claim =
|
||||
resolve_external_agent_runner_gui_owner_claim(config_dir, claim_mode, session_revision)?;
|
||||
let mut state = lock_unpoisoned(state);
|
||||
let Some(registration) = state.registration.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
if registration.config_dir != config_dir {
|
||||
return Ok(());
|
||||
}
|
||||
registration.claim_mode = claim_mode;
|
||||
registration.params.gui_owner_epoch = Some(claim.owner_epoch);
|
||||
registration.params.gui_owner_session_revision = Some(claim.session_revision);
|
||||
registration.attached_boot_id = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -963,7 +1072,6 @@ pub(crate) fn shutdown_external_agent_runner() -> Result<(), String> {
|
||||
|
||||
pub(crate) fn attach_external_agent_runner_gui_owner(
|
||||
event_sink: &GameCreatorManifestInvalidationEventSink,
|
||||
gui_owner_epoch: &str,
|
||||
) -> Result<(), String> {
|
||||
EXTERNAL_AGENT_RUNNER_GUI_OWNER_REQUIRED_CLIENT
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
@@ -971,13 +1079,25 @@ pub(crate) fn attach_external_agent_runner_gui_owner(
|
||||
let config_dir = external_agent_runner_config_dir()
|
||||
.ok_or_else(|| "外部 Agent Runner 尚未配置 AppData;请显式传入 --config-dir".to_string())?;
|
||||
let platform_session = crate::current_platform_session();
|
||||
// 启动阶段先采纳现有 durable claim:第二个及后续窗口与第一个窗口共享同一
|
||||
// epoch,因此不会被判定为抢走登录态权威;claim 缺失或不可读时才发布新 claim。
|
||||
let session_revision = reserve_external_agent_runner_gui_owner_claim_revision(
|
||||
external_agent_runner_gui_owner_attachment_state(),
|
||||
);
|
||||
let claim = resolve_external_agent_runner_gui_owner_claim(
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
session_revision,
|
||||
)?;
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
external_agent_runner_gui_owner_attachment_state(),
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(event_sink.port),
|
||||
event_sink_token: Some(event_sink.token.clone()),
|
||||
gui_owner_epoch: Some(gui_owner_epoch.to_string()),
|
||||
gui_owner_epoch: Some(claim.owner_epoch),
|
||||
gui_owner_session_revision: Some(claim.session_revision),
|
||||
platform_user_id: platform_session
|
||||
.as_ref()
|
||||
.map(|session| session.user_id.clone()),
|
||||
@@ -1122,7 +1242,7 @@ pub(super) fn remember_external_agent_runner_platform_session(
|
||||
session,
|
||||
identity_generation,
|
||||
revision,
|
||||
write_external_agent_runner_gui_owner_claim_atomic,
|
||||
publish_external_agent_runner_gui_owner_claim,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1131,7 +1251,7 @@ pub(super) fn remember_external_agent_runner_platform_session_with(
|
||||
session: Option<(&str, &str, &str)>,
|
||||
identity_generation: u64,
|
||||
revision: u64,
|
||||
write_claim: impl FnOnce(&Path, &str, u64) -> Result<(), String>,
|
||||
publish_claim: impl FnOnce(&Path, u64) -> Result<ExternalAgentRunnerGuiOwnerClaim, String>,
|
||||
) -> Result<(), String> {
|
||||
let mut state = lock_unpoisoned(state);
|
||||
let Some(registration) = state.registration.as_ref() else {
|
||||
@@ -1167,21 +1287,23 @@ pub(super) fn remember_external_agent_runner_platform_session_with(
|
||||
}
|
||||
state.generation = state.generation.wrapping_add(1);
|
||||
let registration_generation = state.generation;
|
||||
let claim = state.registration.as_ref().and_then(|registration| {
|
||||
registration
|
||||
.params
|
||||
.gui_owner_epoch
|
||||
.as_deref()
|
||||
.map(|owner_epoch| (registration.config_dir.clone(), owner_epoch.to_string()))
|
||||
});
|
||||
if let Some((config_dir, owner_epoch)) = claim {
|
||||
write_claim(&config_dir, &owner_epoch, registration_generation)?;
|
||||
}
|
||||
// 本窗口改动了平台登录态:发布新 epoch 的 claim,成为新的登录态权威。
|
||||
// 并发发布以最后一次成功写入为准,落败窗口在 attach 阶段按最新 claim 重试。
|
||||
// 只有已经建立过 claim 的登记才需要发布:没有 epoch 的登记(纯 CLI / 单元测试替身)
|
||||
// 不写任何 claim 文件。
|
||||
let published_claim = state
|
||||
.registration
|
||||
.as_ref()
|
||||
.filter(|registration| registration.params.gui_owner_epoch.is_some())
|
||||
.map(|registration| registration.config_dir.clone())
|
||||
.map(|config_dir| publish_claim(&config_dir, registration_generation))
|
||||
.transpose()?;
|
||||
let registration = state
|
||||
.registration
|
||||
.as_mut()
|
||||
.expect("checked GUI owner registration must remain present while locked");
|
||||
registration.generation = registration_generation;
|
||||
registration.claim_mode = ExternalAgentRunnerGuiOwnerClaimMode::Publish;
|
||||
registration.attached_boot_id = None;
|
||||
registration.params.platform_user_id = session.map(|(user_id, _, _)| user_id.to_string());
|
||||
registration.params.platform_access_token =
|
||||
@@ -1190,7 +1312,10 @@ pub(super) fn remember_external_agent_runner_platform_session_with(
|
||||
session.map(|(_, _, api_base_url)| api_base_url.to_string());
|
||||
registration.params.platform_auth_generation = Some(identity_generation);
|
||||
registration.params.platform_auth_revision = Some(revision);
|
||||
registration.params.gui_owner_session_revision = Some(registration_generation);
|
||||
if let Some(claim) = published_claim {
|
||||
registration.params.gui_owner_epoch = Some(claim.owner_epoch);
|
||||
registration.params.gui_owner_session_revision = Some(claim.session_revision);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1284,6 +1409,25 @@ pub(crate) fn shutdown_external_agent_runner_for_client_exit() -> Result<bool, S
|
||||
shutdown_external_agent_runner_for_client_exit_at(&config_dir)
|
||||
}
|
||||
|
||||
/// 窗口退出的收尾:先释放本窗口参与锁,再决定 Runner 是否需要关闭。
|
||||
///
|
||||
/// 返回 `Ok(false)` 表示仍检测到其它窗口持有参与锁,Runner 必须保留给它们;
|
||||
/// 返回 `Ok(true)` 表示本窗口是最后一个界面进程,Runner 已请求关闭。
|
||||
pub(crate) fn shutdown_external_agent_runner_for_gui_exit() -> Result<bool, String> {
|
||||
let _configure = lock_unpoisoned(external_agent_runner_configure_lock());
|
||||
let Some(config_dir) = external_agent_runner_config_dir() else {
|
||||
return Ok(true);
|
||||
};
|
||||
release_external_agent_runner_gui_participant_lock();
|
||||
if external_agent_runner_lock_is_held(&external_agent_runner_gui_participant_lock_path(
|
||||
&config_dir,
|
||||
))? {
|
||||
return Ok(false);
|
||||
}
|
||||
shutdown_external_agent_runner_at(&config_dir)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_external_agent_runner(
|
||||
config_dir: &Path,
|
||||
child: &mut Child,
|
||||
@@ -1322,34 +1466,12 @@ pub(super) fn ensure_external_agent_runner(
|
||||
) -> Result<ExternalAgentRunnerEndpoint, String> {
|
||||
let endpoint_path = external_agent_runner_endpoint_path(config_dir);
|
||||
let executable_fingerprint = current_external_agent_runner_executable_fingerprint()?;
|
||||
if let Ok(endpoint) = read_external_agent_runner_endpoint(&endpoint_path) {
|
||||
match external_agent_runner_endpoint_reuse_decision(&endpoint, &executable_fingerprint) {
|
||||
ExternalAgentRunnerReuseDecision::Reuse => {
|
||||
if ping_external_agent_runner(&endpoint).is_ok() {
|
||||
attach_registered_external_agent_runner_gui_owner_if_needed(
|
||||
config_dir, &endpoint,
|
||||
)?;
|
||||
return Ok(endpoint);
|
||||
}
|
||||
}
|
||||
ExternalAgentRunnerReuseDecision::Retire => {
|
||||
let incompatible_ping = send_external_agent_runner_request_with_protocol_and_id(
|
||||
&endpoint,
|
||||
endpoint.protocol_version,
|
||||
random_identifier(b"genarrative-agent-runner-upgrade-ping-id")?,
|
||||
"runner.ping",
|
||||
ExternalAgentRunnerRequestParams::default(),
|
||||
);
|
||||
if incompatible_ping.is_ok() {
|
||||
retire_incompatible_external_agent_runner(
|
||||
&endpoint_path,
|
||||
&endpoint,
|
||||
EXTERNAL_AGENT_RUNNER_GUI_OWNER_REQUIRED_CLIENT
|
||||
.load(std::sync::atomic::Ordering::Acquire),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(endpoint) = reuse_or_retire_external_agent_runner_endpoint(
|
||||
config_dir,
|
||||
&endpoint_path,
|
||||
&executable_fingerprint,
|
||||
)? {
|
||||
return Ok(endpoint);
|
||||
}
|
||||
let mut launched = launch_external_agent_runner(config_dir)?;
|
||||
match wait_for_external_agent_runner(config_dir, &mut launched.child, &executable_fingerprint) {
|
||||
@@ -1366,11 +1488,57 @@ pub(super) fn ensure_external_agent_runner(
|
||||
Err(error) => {
|
||||
let _ = launched.child.kill();
|
||||
let _ = launched.child.wait();
|
||||
// 同一 AppData 的另一个窗口可能在这段时间里已经启动了 Runner:
|
||||
// 实例锁竞争失败不能立刻报成启动失败,先按最新 endpoint 复用一次。
|
||||
if let Some(endpoint) = reuse_or_retire_external_agent_runner_endpoint(
|
||||
config_dir,
|
||||
&endpoint_path,
|
||||
&executable_fingerprint,
|
||||
)? {
|
||||
return Ok(endpoint);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reuse_or_retire_external_agent_runner_endpoint(
|
||||
config_dir: &Path,
|
||||
endpoint_path: &Path,
|
||||
executable_fingerprint: &str,
|
||||
) -> Result<Option<ExternalAgentRunnerEndpoint>, String> {
|
||||
if let Ok(endpoint) = read_external_agent_runner_endpoint(&endpoint_path) {
|
||||
match external_agent_runner_endpoint_reuse_decision(&endpoint, executable_fingerprint) {
|
||||
ExternalAgentRunnerReuseDecision::Reuse => {
|
||||
if ping_external_agent_runner(&endpoint).is_ok() {
|
||||
attach_registered_external_agent_runner_gui_owner_if_needed(
|
||||
config_dir, &endpoint,
|
||||
)?;
|
||||
return Ok(Some(endpoint));
|
||||
}
|
||||
}
|
||||
ExternalAgentRunnerReuseDecision::Retire => {
|
||||
let incompatible_ping = send_external_agent_runner_request_with_protocol_and_id(
|
||||
&endpoint,
|
||||
endpoint.protocol_version,
|
||||
random_identifier(b"genarrative-agent-runner-upgrade-ping-id")?,
|
||||
"runner.ping",
|
||||
ExternalAgentRunnerRequestParams::default(),
|
||||
);
|
||||
if incompatible_ping.is_ok() {
|
||||
retire_incompatible_external_agent_runner(
|
||||
endpoint_path,
|
||||
&endpoint,
|
||||
EXTERNAL_AGENT_RUNNER_GUI_OWNER_REQUIRED_CLIENT
|
||||
.load(std::sync::atomic::Ordering::Acquire),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn configure_external_agent_runner(config_dir: impl AsRef<Path>) -> Result<(), String> {
|
||||
let _configure = lock_unpoisoned(external_agent_runner_configure_lock());
|
||||
let config_dir = normalize_external_agent_runner_config_dir(config_dir.as_ref())?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{endpoint::*, project_owner::*, protocol::*, state::*};
|
||||
use crate::{
|
||||
install_game_creator_manifest_invalidation_event_sink,
|
||||
register_game_creator_manifest_invalidation_event_sink,
|
||||
validate_game_creator_manifest_invalidation_event_sink,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
@@ -116,9 +116,9 @@ fn apply_external_agent_runner_gui_owner_attachment(
|
||||
.gui_owner_session_revision
|
||||
.ok_or_else(|| "Agent Runner GUI owner 缺少 session revision".to_string())?;
|
||||
let config_dir = state
|
||||
.gui_owner_lock_path
|
||||
.gui_participant_lock_path
|
||||
.parent()
|
||||
.ok_or_else(|| "Agent Runner GUI owner 锁缺少 AppData 父目录".to_string())?;
|
||||
.ok_or_else(|| "AGC 界面参与锁缺少 AppData 父目录".to_string())?;
|
||||
let mut active_claim = lock_unpoisoned(&state.gui_owner_platform_session_claim);
|
||||
let durable_claim = read_external_agent_runner_gui_owner_claim(config_dir)?;
|
||||
if durable_claim.owner_epoch != requested_epoch
|
||||
@@ -127,7 +127,14 @@ fn apply_external_agent_runner_gui_owner_attachment(
|
||||
return Err("Agent Runner GUI owner claim 已过期".to_string());
|
||||
}
|
||||
let requested_claim = (requested_epoch.to_string(), requested_revision);
|
||||
let replace_claim = active_claim.as_ref() != Some(&requested_claim);
|
||||
// 同一 AppData 的多个窗口共享同一个 epoch:只有 epoch 变化(本窗口发布了新的
|
||||
// 登录态权威)才允许强制替换会话。同一 epoch 内的重复 attach 只做单调校验,
|
||||
// 因此后开窗口的“无登录态 attach”不会清空已有会话。
|
||||
let epoch_changed = match active_claim.as_ref() {
|
||||
Some(active) => active.0 != requested_epoch,
|
||||
None => true,
|
||||
};
|
||||
let replace_claim = epoch_changed;
|
||||
let result = match (
|
||||
params.platform_user_id.as_deref(),
|
||||
params.platform_access_token.as_deref(),
|
||||
@@ -168,7 +175,7 @@ fn apply_external_agent_runner_gui_owner_attachment(
|
||||
crate::clear_platform_session_checked(identity_generation, revision)
|
||||
}
|
||||
}
|
||||
(None, None, None, None, None) if replace_claim => {
|
||||
(None, None, None, None, None) if epoch_changed => {
|
||||
crate::clear_platform_session_for_gui_owner(0, 0);
|
||||
Ok(())
|
||||
}
|
||||
@@ -194,7 +201,7 @@ fn apply_external_agent_runner_gui_owner_attachment(
|
||||
return Err("Agent Runner GUI owner claim 在 attach 提交期间已变化".to_string());
|
||||
}
|
||||
if let Some(event_sink) = event_sink {
|
||||
install_game_creator_manifest_invalidation_event_sink(event_sink);
|
||||
register_game_creator_manifest_invalidation_event_sink(event_sink);
|
||||
}
|
||||
*active_claim = Some(requested_claim);
|
||||
Ok(())
|
||||
@@ -204,9 +211,9 @@ pub(super) fn validate_external_agent_runner_gui_owner_claim_current(
|
||||
state: &ExternalAgentRunnerServerState,
|
||||
) -> Result<(), String> {
|
||||
let config_dir = state
|
||||
.gui_owner_lock_path
|
||||
.gui_participant_lock_path
|
||||
.parent()
|
||||
.ok_or_else(|| "Agent Runner GUI owner 锁缺少 AppData 父目录".to_string())?;
|
||||
.ok_or_else(|| "AGC 界面参与锁缺少 AppData 父目录".to_string())?;
|
||||
let mut active_claim = lock_unpoisoned(&state.gui_owner_platform_session_claim);
|
||||
let durable_claim = read_external_agent_runner_gui_owner_claim(config_dir);
|
||||
let matches = durable_claim.as_ref().is_ok_and(|claim| {
|
||||
@@ -777,7 +784,7 @@ pub(super) fn dispatch_external_agent_runner_runtime_request_with_owner_claim(
|
||||
}
|
||||
}
|
||||
"runner.attach_gui_owner" => {
|
||||
match external_agent_runner_gui_owner_is_locked(&state.gui_owner_lock_path) {
|
||||
match external_agent_runner_lock_is_held(&state.gui_participant_lock_path) {
|
||||
Ok(true) => {
|
||||
let event_sink = request
|
||||
.params
|
||||
@@ -819,7 +826,7 @@ pub(super) fn dispatch_external_agent_runner_runtime_request_with_owner_claim(
|
||||
Ok(false) => ExternalAgentRunnerResponse::failure(
|
||||
&request.request_id,
|
||||
"gui-owner-missing",
|
||||
"Agent Runner 未检测到活跃 GUI owner 锁",
|
||||
"Agent Runner 未检测到活跃的 AGC 界面进程",
|
||||
),
|
||||
Err(error) => ExternalAgentRunnerResponse::failure(
|
||||
&request.request_id,
|
||||
|
||||
@@ -6,7 +6,12 @@ use std::io::{self, Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_RETRY_INTERVAL: Duration =
|
||||
Duration::from_millis(40);
|
||||
|
||||
pub(super) fn external_agent_runner_config_dir_lock() -> &'static Mutex<Option<PathBuf>> {
|
||||
EXTERNAL_AGENT_RUNNER_CONFIG_DIR.get_or_init(|| Mutex::new(None))
|
||||
@@ -305,8 +310,8 @@ pub(super) fn external_agent_runner_lock_path(config_dir: &Path) -> PathBuf {
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_LOCK_FILE_NAME)
|
||||
}
|
||||
|
||||
pub(super) fn external_agent_runner_gui_owner_lock_path(config_dir: &Path) -> PathBuf {
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_GUI_OWNER_LOCK_FILE_NAME)
|
||||
pub(super) fn external_agent_runner_gui_participant_lock_path(config_dir: &Path) -> PathBuf {
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_FILE_NAME)
|
||||
}
|
||||
|
||||
pub(super) fn external_agent_runner_gui_owner_claim_path(config_dir: &Path) -> PathBuf {
|
||||
@@ -341,8 +346,9 @@ pub(super) fn read_external_agent_runner_gui_owner_claim(
|
||||
Ok(claim)
|
||||
}
|
||||
|
||||
pub(super) fn external_agent_runner_gui_owner_is_locked(path: &Path) -> Result<bool, String> {
|
||||
match try_open_external_agent_runner_lock(path, "Agent Runner GUI owner 锁")? {
|
||||
/// 独占探测:返回 `true` 表示仍有界面进程持有该参与锁。
|
||||
pub(super) fn external_agent_runner_lock_is_held(path: &Path) -> Result<bool, String> {
|
||||
match try_open_external_agent_runner_lock(path, "AGC 界面参与锁")? {
|
||||
Some(lock) => {
|
||||
drop(lock);
|
||||
Ok(false)
|
||||
@@ -743,10 +749,21 @@ pub(super) fn read_current_external_agent_runner_endpoint(
|
||||
})
|
||||
}
|
||||
|
||||
/// 锁文件的两种打开方式。
|
||||
///
|
||||
/// `Exclusive` 是权威探测:能否独占取得句柄决定“还有没有存活持有者”。
|
||||
/// `Shared` 是参与者持有:同一 AppData 的多个界面进程可以同时持有。
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) enum ExternalAgentRunnerLockMode {
|
||||
Exclusive,
|
||||
Shared,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) fn try_open_external_agent_runner_lock(
|
||||
pub(super) fn open_external_agent_runner_lock_file(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
mode: ExternalAgentRunnerLockMode,
|
||||
) -> Result<Option<File>, String> {
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
|
||||
@@ -809,14 +826,30 @@ pub(super) fn try_open_external_agent_runner_lock(
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
let flock_operation = match mode {
|
||||
ExternalAgentRunnerLockMode::Exclusive => libc::LOCK_EX | libc::LOCK_NB,
|
||||
ExternalAgentRunnerLockMode::Shared => libc::LOCK_SH | libc::LOCK_NB,
|
||||
};
|
||||
// SAFETY: flock only observes the valid fd owned by `file`; `file` remains alive on success.
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), flock_operation) };
|
||||
if result == 0 {
|
||||
return Ok(Some(file));
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::WouldBlock {
|
||||
Ok(None)
|
||||
return match mode {
|
||||
ExternalAgentRunnerLockMode::Exclusive => Ok(None),
|
||||
ExternalAgentRunnerLockMode::Shared => Err(format!(
|
||||
"{label} 正被独占探测或持有,稍后重试:{}",
|
||||
path.display()
|
||||
)),
|
||||
};
|
||||
}
|
||||
if mode == ExternalAgentRunnerLockMode::Shared {
|
||||
Err(format!(
|
||||
"以共享方式获取 {label} 失败:{}: {error}",
|
||||
path.display()
|
||||
))
|
||||
} else {
|
||||
Err(format!(
|
||||
"获取 {label} 系统锁失败:{}: {error}",
|
||||
@@ -825,39 +858,58 @@ pub(super) fn try_open_external_agent_runner_lock(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) fn try_open_external_agent_runner_lock(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
) -> Result<Option<File>, String> {
|
||||
open_external_agent_runner_lock_file(path, label, ExternalAgentRunnerLockMode::Exclusive)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) fn windows_external_agent_runner_lock_is_busy_error(error: &io::Error) -> bool {
|
||||
matches!(error.raw_os_error(), Some(32 | 33))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) fn try_open_external_agent_runner_lock(
|
||||
pub(super) fn open_external_agent_runner_lock_file(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
mode: ExternalAgentRunnerLockMode,
|
||||
) -> Result<Option<File>, String> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const FILE_SHARE_READ: u32 = 0x0000_0001;
|
||||
const FILE_SHARE_WRITE: u32 = 0x0000_0002;
|
||||
const FILE_SHARE_DELETE: u32 = 0x0000_0004;
|
||||
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| format!("{label} 缺少 AppData 父目录:{}", path.display()))?;
|
||||
let private_parent = crate::inspect_game_creator_runtime_config_dir(parent)?;
|
||||
let runner_lock_path = private_parent.join(EXTERNAL_AGENT_RUNNER_LOCK_FILE_NAME);
|
||||
let gui_owner_lock_path = private_parent.join(EXTERNAL_AGENT_RUNNER_GUI_OWNER_LOCK_FILE_NAME);
|
||||
if path != runner_lock_path && path != gui_owner_lock_path {
|
||||
let gui_participant_lock_path =
|
||||
private_parent.join(EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_FILE_NAME);
|
||||
if path != runner_lock_path && path != gui_participant_lock_path {
|
||||
return Err(format!(
|
||||
"{label} 必须位于已验证的私有 AppData 固定锁路径:{} 或 {}",
|
||||
runner_lock_path.display(),
|
||||
gui_owner_lock_path.display()
|
||||
gui_participant_lock_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
let share_mode = match mode {
|
||||
ExternalAgentRunnerLockMode::Exclusive => 0,
|
||||
ExternalAgentRunnerLockMode::Shared => {
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
|
||||
}
|
||||
};
|
||||
match OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.share_mode(0)
|
||||
.share_mode(share_mode)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)
|
||||
{
|
||||
@@ -875,16 +927,30 @@ pub(super) fn try_open_external_agent_runner_lock(
|
||||
));
|
||||
}
|
||||
validate_windows_regular_file_handle(&file, label)?;
|
||||
// share_mode(0) gives this process an exclusive handle. At this point the fixed
|
||||
// lock path is known to be a stale, single-link, non-reparse regular file inside
|
||||
// the current TokenUser's private AppData. Repairing its owner is therefore safe
|
||||
// and is required when Windows creates it with TokenOwner=Administrators.
|
||||
// The fixed lock path is known to be a single-link, non-reparse regular file
|
||||
// inside the current TokenUser's private AppData. Repairing its owner is
|
||||
// therefore safe and is required when Windows creates it with
|
||||
// TokenOwner=Administrators.
|
||||
crate::initialize_windows_game_creator_file_owner_for_current_user(path)?;
|
||||
validate_windows_regular_file_handle(&file, label)?;
|
||||
crate::secure_windows_game_creator_path_for_current_user(path, false, false)?;
|
||||
Ok(Some(file))
|
||||
}
|
||||
Err(error) if windows_external_agent_runner_lock_is_busy_error(&error) => Ok(None),
|
||||
Err(error)
|
||||
if mode == ExternalAgentRunnerLockMode::Exclusive
|
||||
&& windows_external_agent_runner_lock_is_busy_error(&error) =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
Err(error)
|
||||
if mode == ExternalAgentRunnerLockMode::Shared
|
||||
&& windows_external_agent_runner_lock_is_busy_error(&error) =>
|
||||
{
|
||||
Err(format!(
|
||||
"{label} 正被独占探测或持有,稍后重试:{}",
|
||||
path.display()
|
||||
))
|
||||
}
|
||||
Err(error) => Err(format!(
|
||||
"安全打开 {label} 失败:{}: {error}",
|
||||
path.display()
|
||||
@@ -892,12 +958,29 @@ pub(super) fn try_open_external_agent_runner_lock(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) fn try_open_external_agent_runner_lock(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
) -> Result<Option<File>, String> {
|
||||
open_external_agent_runner_lock_file(path, label, ExternalAgentRunnerLockMode::Exclusive)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
pub(super) fn open_external_agent_runner_lock_file(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
_mode: ExternalAgentRunnerLockMode,
|
||||
) -> Result<Option<File>, String> {
|
||||
Err(format!("当前平台不支持 {label} 系统锁:{}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
pub(super) fn try_open_external_agent_runner_lock(
|
||||
path: &Path,
|
||||
label: &str,
|
||||
) -> Result<Option<File>, String> {
|
||||
Err(format!("当前平台不支持 {label} 系统锁:{}", path.display()))
|
||||
open_external_agent_runner_lock_file(path, label, ExternalAgentRunnerLockMode::Exclusive)
|
||||
}
|
||||
|
||||
pub(super) fn acquire_external_agent_runner_instance_lock(
|
||||
@@ -929,40 +1012,90 @@ pub(super) fn acquire_external_agent_runner_instance_lock(
|
||||
Ok(ExternalAgentRunnerInstanceLock { _file: file })
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_external_agent_runner_gui_owner_lock(
|
||||
/// 取得本窗口在该 AppData 下的界面参与锁。
|
||||
///
|
||||
/// 参与锁以共享句柄打开:同一 AppData 可以同时持有任意数量的界面窗口。
|
||||
/// Runner 侧用同文件的独占探测判断“是否仍有界面进程存活”,探测窗口很短,
|
||||
/// 所以这里遇到瞬时冲突时按 `EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_RETRY_INTERVAL`
|
||||
/// 重试,直到 `EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_ACQUIRE_TIMEOUT` 截止。
|
||||
pub(crate) fn acquire_external_agent_runner_gui_participant_lock(
|
||||
config_dir: &Path,
|
||||
) -> Result<ExternalAgentRunnerGuiOwnerLock, String> {
|
||||
let path = external_agent_runner_gui_owner_lock_path(config_dir);
|
||||
let Some(mut file) = try_open_external_agent_runner_lock(&path, "Agent Runner GUI owner 锁")?
|
||||
else {
|
||||
return Err("AI 游戏创作界面已由同一 AppData 目录中的其他进程运行".to_string());
|
||||
};
|
||||
let owner_epoch = uuid::Uuid::new_v4().to_string();
|
||||
let acquired_at = unix_millis();
|
||||
) -> Result<ExternalAgentRunnerGuiParticipantLock, String> {
|
||||
let path = external_agent_runner_gui_participant_lock_path(config_dir);
|
||||
let deadline = Instant::now() + EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_ACQUIRE_TIMEOUT;
|
||||
let mut last_error = "AGC 界面参与锁未知失败".to_string();
|
||||
loop {
|
||||
match open_external_agent_runner_lock_file(
|
||||
&path,
|
||||
"AGC 界面参与锁",
|
||||
ExternalAgentRunnerLockMode::Shared,
|
||||
) {
|
||||
Ok(Some(mut file)) => {
|
||||
write_external_agent_runner_gui_participant_diagnostic(&mut file, &path)?;
|
||||
return Ok(ExternalAgentRunnerGuiParticipantLock { _file: file });
|
||||
}
|
||||
Ok(None) => {
|
||||
last_error = format!("AGC 界面参与锁无法以共享方式取得:{}", path.display());
|
||||
}
|
||||
Err(error) => last_error = error,
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(format!("取得 AGC 界面参与锁失败:{last_error}"));
|
||||
}
|
||||
thread::sleep(EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_RETRY_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
/// 参与锁诊断内容只由首个窗口写入,后续窗口不覆写,避免并发写坏 JSON。
|
||||
fn write_external_agent_runner_gui_participant_diagnostic(
|
||||
file: &mut File,
|
||||
path: &Path,
|
||||
) -> Result<(), String> {
|
||||
let existing_len = file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
|
||||
if existing_len > 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let diagnostic = serde_json::to_vec(&json!({
|
||||
"protocolVersion": EXTERNAL_AGENT_RUNNER_PROTOCOL_VERSION,
|
||||
"pid": std::process::id(),
|
||||
"ownerEpoch": owner_epoch,
|
||||
"acquiredAt": acquired_at,
|
||||
"instanceId": uuid::Uuid::new_v4().to_string(),
|
||||
"acquiredAt": unix_millis(),
|
||||
}))
|
||||
.map_err(|error| format!("生成 Agent Runner GUI owner 锁信息失败:{error}"))?;
|
||||
.map_err(|error| format!("生成 AGC 界面参与锁信息失败:{error}"))?;
|
||||
file.set_len(0)
|
||||
.and_then(|_| file.seek(SeekFrom::Start(0)).map(|_| ()))
|
||||
.and_then(|_| file.write_all(&diagnostic))
|
||||
.and_then(|_| file.sync_data())
|
||||
.map_err(|error| {
|
||||
format!(
|
||||
"写入 Agent Runner GUI owner 锁信息失败:{}: {error}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
write_external_agent_runner_gui_owner_claim_atomic(config_dir, &owner_epoch, 0)?;
|
||||
Ok(ExternalAgentRunnerGuiOwnerLock {
|
||||
_file: file,
|
||||
.map_err(|error| format!("写入 AGC 界面参与锁信息失败:{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// 发布新的 durable claim:新 epoch + 本次会话 revision。
|
||||
///
|
||||
/// 发布是“谁改动登录态谁成为新 epoch 权威”的实现;并发发布以最后一次
|
||||
/// 成功写入为准,落败窗口按最新 claim 重试。
|
||||
pub(crate) fn publish_external_agent_runner_gui_owner_claim(
|
||||
config_dir: &Path,
|
||||
session_revision: u64,
|
||||
) -> Result<ExternalAgentRunnerGuiOwnerClaim, String> {
|
||||
let owner_epoch = uuid::Uuid::new_v4().to_string();
|
||||
write_external_agent_runner_gui_owner_claim_atomic(config_dir, &owner_epoch, session_revision)?;
|
||||
Ok(ExternalAgentRunnerGuiOwnerClaim {
|
||||
owner_epoch,
|
||||
session_revision,
|
||||
})
|
||||
}
|
||||
|
||||
/// 采纳现有 durable claim;只有 claim 缺失或不可读时才发布新 claim。
|
||||
pub(crate) fn adopt_or_publish_external_agent_runner_gui_owner_claim(
|
||||
config_dir: &Path,
|
||||
session_revision: u64,
|
||||
) -> Result<ExternalAgentRunnerGuiOwnerClaim, String> {
|
||||
match read_external_agent_runner_gui_owner_claim(config_dir) {
|
||||
Ok(claim) => Ok(claim),
|
||||
Err(_) => publish_external_agent_runner_gui_owner_claim(config_dir, session_revision),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_external_agent_runner_gui_owner_claim_atomic(
|
||||
config_dir: &Path,
|
||||
owner_epoch: &str,
|
||||
|
||||
@@ -13,8 +13,8 @@ pub(crate) const EXTERNAL_AGENT_RUNNER_PROTOCOL_VERSION: u32 = 7;
|
||||
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME: &str = "agent-runner.endpoint.json";
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_LOCK_FILE_NAME: &str = "agent-runner.lock";
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_GUI_OWNER_LOCK_FILE_NAME: &str =
|
||||
"agent-runner.gui-owner.lock";
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_FILE_NAME: &str =
|
||||
"agent-runner.gui-participant.lock";
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_GUI_OWNER_CLAIM_FILE_NAME: &str =
|
||||
"agent-runner.gui-owner.claim.json";
|
||||
pub(super) const EXTERNAL_AGENT_RUNNER_PROJECT_OWNER_FILE_NAME: &str = "execution-owner.lock";
|
||||
|
||||
@@ -156,7 +156,7 @@ fn external_agent_runner_watchdog_tick(state: &ExternalAgentRunnerServerState) -
|
||||
if !state.gui_owner_attached.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
match external_agent_runner_gui_owner_is_locked(&state.gui_owner_lock_path) {
|
||||
match external_agent_runner_lock_is_held(&state.gui_participant_lock_path) {
|
||||
Ok(true) => {
|
||||
let _ = validate_external_agent_runner_gui_owner_claim_current(state);
|
||||
false
|
||||
@@ -224,7 +224,7 @@ pub(crate) fn run_external_agent_runner_server(
|
||||
)?;
|
||||
let gui_owner_present_at_start = resolve_external_agent_runner_initial_gui_owner(
|
||||
gui_owner_required,
|
||||
external_agent_runner_gui_owner_is_locked(&external_agent_runner_gui_owner_lock_path(
|
||||
external_agent_runner_lock_is_held(&external_agent_runner_gui_participant_lock_path(
|
||||
&config_dir,
|
||||
))?,
|
||||
)?;
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(super) struct ExternalAgentRunnerServerState {
|
||||
pub(super) draining: AtomicBool,
|
||||
pub(super) active_connections: AtomicUsize,
|
||||
pub(super) known_roots: Mutex<BTreeSet<PathBuf>>,
|
||||
pub(super) gui_owner_lock_path: PathBuf,
|
||||
pub(super) gui_participant_lock_path: PathBuf,
|
||||
pub(super) project_execution_owners:
|
||||
Mutex<BTreeMap<PathBuf, ExternalAgentRunnerProjectExecutionOwnerEntry>>,
|
||||
project_execution_owner_recovery_changed: Condvar,
|
||||
@@ -80,10 +80,10 @@ impl Drop for ExternalAgentRunnerProjectExecutionOwnerRecoveryGuard<'_> {
|
||||
|
||||
impl ExternalAgentRunnerServerState {
|
||||
pub(super) fn new(endpoint_path: PathBuf, endpoint: ExternalAgentRunnerEndpoint) -> Self {
|
||||
let gui_owner_lock_path = endpoint_path
|
||||
let gui_participant_lock_path = endpoint_path
|
||||
.parent()
|
||||
.map(external_agent_runner_gui_owner_lock_path)
|
||||
.unwrap_or_else(|| PathBuf::from(EXTERNAL_AGENT_RUNNER_GUI_OWNER_LOCK_FILE_NAME));
|
||||
.map(external_agent_runner_gui_participant_lock_path)
|
||||
.unwrap_or_else(|| PathBuf::from(EXTERNAL_AGENT_RUNNER_GUI_PARTICIPANT_LOCK_FILE_NAME));
|
||||
Self {
|
||||
endpoint_path,
|
||||
endpoint: Mutex::new(endpoint),
|
||||
@@ -94,7 +94,7 @@ impl ExternalAgentRunnerServerState {
|
||||
draining: AtomicBool::new(false),
|
||||
active_connections: AtomicUsize::new(0),
|
||||
known_roots: Mutex::new(BTreeSet::new()),
|
||||
gui_owner_lock_path,
|
||||
gui_participant_lock_path,
|
||||
project_execution_owners: Mutex::new(BTreeMap::new()),
|
||||
project_execution_owner_recovery_changed: Condvar::new(),
|
||||
write_request_cache: Mutex::new(ExternalAgentRunnerRequestCache::default()),
|
||||
@@ -231,16 +231,10 @@ pub(super) struct ExternalAgentRunnerInstanceLock {
|
||||
pub(super) _file: File,
|
||||
}
|
||||
|
||||
/// 界面进程持有的参与锁。共享句柄,同一 AppData 可同时存在多个窗口。
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ExternalAgentRunnerGuiOwnerLock {
|
||||
pub(crate) struct ExternalAgentRunnerGuiParticipantLock {
|
||||
pub(super) _file: File,
|
||||
pub(super) owner_epoch: String,
|
||||
}
|
||||
|
||||
impl ExternalAgentRunnerGuiOwnerLock {
|
||||
pub(crate) fn owner_epoch(&self) -> &str {
|
||||
&self.owner_epoch
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ExternalAgentRunnerProjectOwnerStorage {
|
||||
|
||||
@@ -44,6 +44,23 @@ fn private_runner_test_config_dir(directory: &TestDirectoryGuard) -> PathBuf {
|
||||
.expect("prepare private runner AppData")
|
||||
}
|
||||
|
||||
/// 模拟一个界面窗口:持有界面参与锁,并发布自己的 owner claim。
|
||||
struct TestGuiParticipant {
|
||||
_lock: ExternalAgentRunnerGuiParticipantLock,
|
||||
owner_epoch: String,
|
||||
}
|
||||
|
||||
fn acquire_test_gui_participant(config_dir: &Path, session_revision: u64) -> TestGuiParticipant {
|
||||
let lock = acquire_external_agent_runner_gui_participant_lock(config_dir)
|
||||
.expect("acquire GUI participant lock");
|
||||
let claim = publish_external_agent_runner_gui_owner_claim(config_dir, session_revision)
|
||||
.expect("publish GUI owner claim");
|
||||
TestGuiParticipant {
|
||||
_lock: lock,
|
||||
owner_epoch: claim.owner_epoch,
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_project_owner_after_release(
|
||||
root: &Path,
|
||||
boot_id: &str,
|
||||
@@ -574,8 +591,13 @@ fn gui_owner_registration_replays_once_for_each_runner_boot() {
|
||||
event_sink_token: Some(event_sink_token.clone()),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
};
|
||||
register_external_agent_runner_gui_owner_attachment(&state, &config_dir, params)
|
||||
.expect("register GUI owner attachment");
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
params,
|
||||
)
|
||||
.expect("register GUI owner attachment");
|
||||
|
||||
let calls = std::cell::RefCell::new(Vec::new());
|
||||
let endpoint_a = test_endpoint(
|
||||
@@ -657,6 +679,7 @@ fn gui_owner_registration_replays_only_the_latest_platform_session() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_330),
|
||||
event_sink_token: Some("f".repeat(64)),
|
||||
@@ -729,6 +752,7 @@ fn gui_owner_platform_session_change_marks_the_same_boot_for_reattach() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_331),
|
||||
event_sink_token: Some("d".repeat(64)),
|
||||
@@ -781,6 +805,7 @@ fn stale_gui_owner_attach_completion_cannot_mark_new_session_as_attached() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
platform_user_id: Some("user-a".to_string()),
|
||||
platform_access_token: Some("token-a".to_string()),
|
||||
@@ -834,8 +859,7 @@ fn stale_gui_owner_attach_completion_cannot_mark_new_session_as_attached() {
|
||||
fn gui_owner_platform_session_payload_clears_runner_session() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let owner = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire platform-session clear owner");
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
let state = ExternalAgentRunnerServerState::new(
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME),
|
||||
test_endpoint("platform-clear-token", "platform-clear-boot", 31_333),
|
||||
@@ -848,7 +872,7 @@ fn gui_owner_platform_session_payload_clears_runner_session() {
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
platform_auth_generation: Some(2),
|
||||
platform_auth_revision: Some(2),
|
||||
@@ -863,8 +887,7 @@ fn gui_owner_platform_session_payload_clears_runner_session() {
|
||||
fn gui_owner_partial_platform_session_payload_fails_without_mutation() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let owner = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire partial-session owner");
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
let state = ExternalAgentRunnerServerState::new(
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME),
|
||||
test_endpoint("platform-partial-token", "platform-partial-boot", 31_334),
|
||||
@@ -878,7 +901,7 @@ fn gui_owner_partial_platform_session_payload_fails_without_mutation() {
|
||||
let error = apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
platform_user_id: Some("runner-owner-b".to_string()),
|
||||
platform_api_base_url: Some("https://dev.genarrative.world".to_string()),
|
||||
@@ -905,9 +928,8 @@ fn new_gui_owner_epoch_replaces_higher_generation_runner_session_and_rejects_old
|
||||
"runner-token-seed",
|
||||
"https://dev.genarrative.world",
|
||||
);
|
||||
let owner_a = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire old GUI owner epoch");
|
||||
let owner_a_epoch = owner_a.owner_epoch().to_string();
|
||||
let owner_a = acquire_test_gui_participant(&config_dir, 0);
|
||||
let owner_a_epoch = owner_a.owner_epoch.clone();
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
@@ -924,12 +946,11 @@ fn new_gui_owner_epoch_replaces_higher_generation_runner_session_and_rejects_old
|
||||
.expect("old GUI installs high-generation owner A");
|
||||
drop(owner_a);
|
||||
|
||||
let owner_b = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire new GUI owner epoch");
|
||||
let owner_b = acquire_test_gui_participant(&config_dir, 0);
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner_b.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner_b.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
platform_user_id: Some("runner-owner-b".to_string()),
|
||||
platform_access_token: Some("runner-token-b".to_string()),
|
||||
@@ -976,8 +997,7 @@ fn durable_claim_revision_change_clears_runner_session_and_blocks_runtime_until_
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME),
|
||||
test_endpoint(token, "platform-claim-gate-boot", 31_337),
|
||||
);
|
||||
let owner = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire claim gate owner");
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
let _session = crate::install_test_platform_session(
|
||||
"runner-owner-seed",
|
||||
"runner-token-seed",
|
||||
@@ -986,7 +1006,7 @@ fn durable_claim_revision_change_clears_runner_session_and_blocks_runtime_until_
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
platform_user_id: Some("runner-owner-a".to_string()),
|
||||
platform_access_token: Some("runner-token-a".to_string()),
|
||||
@@ -999,7 +1019,7 @@ fn durable_claim_revision_change_clears_runner_session_and_blocks_runtime_until_
|
||||
.expect("attach owner A claim");
|
||||
state.gui_owner_attached.store(true, Ordering::Release);
|
||||
|
||||
write_external_agent_runner_gui_owner_claim_atomic(&config_dir, owner.owner_epoch(), 1)
|
||||
write_external_agent_runner_gui_owner_claim_atomic(&config_dir, owner.owner_epoch.as_str(), 1)
|
||||
.expect("advance durable claim before reattach");
|
||||
assert!(
|
||||
!external_agent_runner_shutdown_if_gui_owner_lost(&state)
|
||||
@@ -1010,7 +1030,7 @@ fn durable_claim_revision_change_clears_runner_session_and_blocks_runtime_until_
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(1),
|
||||
platform_user_id: Some("runner-owner-b".to_string()),
|
||||
platform_access_token: Some("runner-token-b".to_string()),
|
||||
@@ -1057,14 +1077,14 @@ fn failed_platform_session_sync_fences_runner_before_returning_error() {
|
||||
fn failed_gui_owner_claim_write_is_fenced_before_local_session_can_change() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let owner = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("acquire claim-write failure owner");
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
let state = Mutex::new(ExternalAgentRunnerGuiOwnerAttachmentState::default());
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
platform_user_id: Some("runner-owner-a".to_string()),
|
||||
platform_access_token: Some("runner-token-a".to_string()),
|
||||
platform_api_base_url: Some("https://dev.genarrative.world".to_string()),
|
||||
@@ -1087,7 +1107,7 @@ fn failed_gui_owner_claim_write_is_fenced_before_local_session_can_change() {
|
||||
)),
|
||||
2,
|
||||
2,
|
||||
|_, _, _| Err("injected durable claim write failure".to_string()),
|
||||
|_, _| Err("injected durable claim write failure".to_string()),
|
||||
)
|
||||
},
|
||||
|| {
|
||||
@@ -1136,6 +1156,7 @@ fn gui_owner_registration_failed_replay_remains_pending_for_same_boot() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams::default(),
|
||||
)
|
||||
.expect("register GUI owner attachment");
|
||||
@@ -1184,6 +1205,7 @@ fn gui_owner_registration_missing_event_sink_confirmation_retries_same_boot() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_322),
|
||||
event_sink_token: Some("c".repeat(64)),
|
||||
@@ -1233,6 +1255,7 @@ fn gui_owner_registration_false_event_sink_confirmation_retries_same_boot() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
&config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_323),
|
||||
event_sink_token: Some("d".repeat(64)),
|
||||
@@ -1285,6 +1308,7 @@ fn gui_owner_registration_does_not_cross_config_dirs() {
|
||||
register_external_agent_runner_gui_owner_attachment(
|
||||
&state,
|
||||
®istered_config_dir,
|
||||
ExternalAgentRunnerGuiOwnerClaimMode::Adopt,
|
||||
ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_324),
|
||||
event_sink_token: Some(event_sink_token.clone()),
|
||||
@@ -1334,18 +1358,116 @@ fn gui_owner_registration_does_not_cross_config_dirs() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gui_owner_lock_allows_only_one_frontend_process_per_appdata() {
|
||||
fn gui_participant_lock_allows_multiple_windows_and_tracks_liveness() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let first =
|
||||
acquire_external_agent_runner_gui_owner_lock(&config_dir).expect("first GUI owns AppData");
|
||||
let error = acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect_err("second GUI must not share the same Runner owner");
|
||||
assert!(error.contains("其他进程运行"));
|
||||
let participant_lock_path = external_agent_runner_gui_participant_lock_path(&config_dir);
|
||||
assert!(!external_agent_runner_lock_is_held(&participant_lock_path)
|
||||
.expect("probe without any window"));
|
||||
|
||||
let first = acquire_external_agent_runner_gui_participant_lock(&config_dir)
|
||||
.expect("first window participates");
|
||||
assert!(external_agent_runner_lock_is_held(&participant_lock_path)
|
||||
.expect("first window keeps the runner alive"));
|
||||
let second = acquire_external_agent_runner_gui_participant_lock(&config_dir)
|
||||
.expect("second window shares the same AppData");
|
||||
|
||||
drop(second);
|
||||
assert!(
|
||||
external_agent_runner_lock_is_held(&participant_lock_path)
|
||||
.expect("remaining window keeps the runner alive"),
|
||||
"runner must survive while any window is still open"
|
||||
);
|
||||
drop(first);
|
||||
acquire_external_agent_runner_gui_owner_lock(&config_dir)
|
||||
.expect("GUI owner lock is recoverable after the first frontend exits");
|
||||
assert!(
|
||||
!external_agent_runner_lock_is_held(&participant_lock_path)
|
||||
.expect("last window releases the participant lock"),
|
||||
"runner may stop once every window has exited"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gui_owner_claim_adoption_keeps_epoch_and_publication_rotates_it() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let published =
|
||||
publish_external_agent_runner_gui_owner_claim(&config_dir, 3).expect("publish claim");
|
||||
assert_eq!(published.session_revision, 3);
|
||||
|
||||
let adopted = adopt_or_publish_external_agent_runner_gui_owner_claim(&config_dir, 9)
|
||||
.expect("adopt existing claim");
|
||||
assert_eq!(adopted.owner_epoch, published.owner_epoch);
|
||||
assert_eq!(
|
||||
adopted.session_revision, 3,
|
||||
"采纳路径必须沿用现有 claim,不能推进 revision 或换 epoch"
|
||||
);
|
||||
|
||||
let rotated =
|
||||
publish_external_agent_runner_gui_owner_claim(&config_dir, 9).expect("publish new claim");
|
||||
assert_ne!(rotated.owner_epoch, published.owner_epoch);
|
||||
assert_eq!(rotated.session_revision, 9);
|
||||
assert_eq!(
|
||||
read_external_agent_runner_gui_owner_claim(&config_dir)
|
||||
.expect("read durable claim")
|
||||
.session_revision,
|
||||
9
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_window_attach_with_same_claim_keeps_runner_platform_session() {
|
||||
let directory = unique_test_directory();
|
||||
let config_dir = private_runner_test_config_dir(&directory);
|
||||
let state = ExternalAgentRunnerServerState::new(
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME),
|
||||
test_endpoint(
|
||||
"multi-window-claim-token-multi-window-claim-token",
|
||||
"multi-window-claim-boot",
|
||||
31_338,
|
||||
),
|
||||
);
|
||||
let _session = crate::install_test_platform_session(
|
||||
"runner-owner-a",
|
||||
"runner-token-a",
|
||||
"https://dev.genarrative.world",
|
||||
);
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
platform_user_id: Some("runner-owner-a".to_string()),
|
||||
platform_access_token: Some("runner-token-a".to_string()),
|
||||
platform_api_base_url: Some("https://dev.genarrative.world".to_string()),
|
||||
platform_auth_generation: Some(7),
|
||||
platform_auth_revision: Some(7),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
},
|
||||
)
|
||||
.expect("first window installs its session");
|
||||
assert_eq!(
|
||||
crate::current_platform_session()
|
||||
.map(|session| (session.user_id, session.identity_generation)),
|
||||
Some(("runner-owner-a".to_string(), 7))
|
||||
);
|
||||
|
||||
// 第二个窗口启动时本身还没有登录态:同 claim 的 attach 只能是空操作。
|
||||
apply_external_agent_runner_gui_owner_platform_session(
|
||||
&state,
|
||||
&ExternalAgentRunnerRequestParams {
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
},
|
||||
)
|
||||
.expect("second window attaches with the same claim");
|
||||
assert_eq!(
|
||||
crate::current_platform_session()
|
||||
.map(|session| (session.user_id, session.identity_generation)),
|
||||
Some(("runner-owner-a".to_string(), 7)),
|
||||
"同一 claim 的第二个窗口不得清空平台登录态"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1359,8 +1481,7 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
config_dir.join(EXTERNAL_AGENT_RUNNER_ENDPOINT_FILE_NAME),
|
||||
test_endpoint(token, "gui-owner-monitor-boot", 31319),
|
||||
);
|
||||
let owner =
|
||||
acquire_external_agent_runner_gui_owner_lock(&config_dir).expect("acquire GUI owner lock");
|
||||
let owner = acquire_test_gui_participant(&config_dir, 0);
|
||||
let attached = handle_external_agent_runner_request(
|
||||
ExternalAgentRunnerRequest {
|
||||
protocol_version: EXTERNAL_AGENT_RUNNER_PROTOCOL_VERSION,
|
||||
@@ -1370,7 +1491,7 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
params: ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_318),
|
||||
event_sink_token: Some("b".repeat(64)),
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
},
|
||||
@@ -1390,7 +1511,7 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
!external_agent_runner_shutdown_if_gui_owner_lost(&state).expect("owner remains present")
|
||||
);
|
||||
|
||||
write_external_agent_runner_gui_owner_claim_atomic(&config_dir, owner.owner_epoch(), 1)
|
||||
write_external_agent_runner_gui_owner_claim_atomic(&config_dir, owner.owner_epoch.as_str(), 1)
|
||||
.expect("advance owner claim revision");
|
||||
let replacement = handle_external_agent_runner_request(
|
||||
ExternalAgentRunnerRequest {
|
||||
@@ -1401,7 +1522,7 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
params: ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_319),
|
||||
event_sink_token: Some("c".repeat(64)),
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(1),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
},
|
||||
@@ -1410,11 +1531,18 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
);
|
||||
assert!(replacement.ok);
|
||||
assert_eq!(
|
||||
sink_guard.configured_sink(),
|
||||
Some(crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_319,
|
||||
token: "c".repeat(64),
|
||||
})
|
||||
sink_guard.configured_sinks(),
|
||||
vec![
|
||||
crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_318,
|
||||
token: "b".repeat(64),
|
||||
},
|
||||
crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_319,
|
||||
token: "c".repeat(64),
|
||||
},
|
||||
],
|
||||
"第二个窗口 attach 必须让两个接收端同时保留"
|
||||
);
|
||||
|
||||
let stale_replay = handle_external_agent_runner_request(
|
||||
@@ -1426,7 +1554,7 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
params: ExternalAgentRunnerRequestParams {
|
||||
event_sink_port: Some(31_318),
|
||||
event_sink_token: Some("b".repeat(64)),
|
||||
gui_owner_epoch: Some(owner.owner_epoch().to_string()),
|
||||
gui_owner_epoch: Some(owner.owner_epoch.clone()),
|
||||
gui_owner_session_revision: Some(0),
|
||||
..ExternalAgentRunnerRequestParams::default()
|
||||
},
|
||||
@@ -1439,11 +1567,17 @@ fn manifest_invalidation_sink_isolation_gui_owner_attach_configures_and_cleans_u
|
||||
Some("platform-session-invalid")
|
||||
);
|
||||
assert_eq!(
|
||||
sink_guard.configured_sink(),
|
||||
Some(crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_319,
|
||||
token: "c".repeat(64),
|
||||
}),
|
||||
sink_guard.configured_sinks(),
|
||||
vec![
|
||||
crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_318,
|
||||
token: "b".repeat(64),
|
||||
},
|
||||
crate::GameCreatorManifestInvalidationEventSink {
|
||||
port: 31_319,
|
||||
token: "c".repeat(64),
|
||||
},
|
||||
],
|
||||
"旧 claim 的迟到或缓存 attach 不能覆盖当前事件接收端"
|
||||
);
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -202,9 +202,13 @@ fn gui_final_exit_is_the_only_run_event_that_requests_runner_shutdown() {
|
||||
GameCreatorGuiRunnerShutdownOutcome::NotRequested
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_game_creator_gui_runner_shutdown(&tauri::RunEvent::Exit, || Ok(())),
|
||||
resolve_game_creator_gui_runner_shutdown(&tauri::RunEvent::Exit, || Ok(true)),
|
||||
GameCreatorGuiRunnerShutdownOutcome::Requested
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_game_creator_gui_runner_shutdown(&tauri::RunEvent::Exit, || Ok(false)),
|
||||
GameCreatorGuiRunnerShutdownOutcome::Retained
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_game_creator_gui_runner_shutdown(&tauri::RunEvent::Exit, || {
|
||||
Err("private shutdown diagnostic".to_string())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "陶泥儿",
|
||||
"version": "0.1.45",
|
||||
"version": "0.1.47",
|
||||
"identifier": "world.genarrative.ai-game-creator",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm --prefix ../.. run agc:serve",
|
||||
@@ -24,8 +24,8 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob:; media-src 'self' asset: data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*",
|
||||
"devCsp": "default-src 'self' customprotocol: asset: http://127.0.0.1:*; img-src 'self' asset: http://127.0.0.1:* data: blob:; media-src 'self' asset: http://127.0.0.1:* data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*"
|
||||
"csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; media-src 'self' asset: data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*",
|
||||
"devCsp": "default-src 'self' customprotocol: asset: http://127.0.0.1:*; img-src 'self' asset: http://127.0.0.1:* data: blob: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; media-src 'self' asset: http://127.0.0.1:* data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
{
|
||||
"schemaVersion": "agc-template-library.v1",
|
||||
"library": "agc-game-templates",
|
||||
"libraryVersion": 1,
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"templates": [
|
||||
{
|
||||
"id": "blank-2d-canvas",
|
||||
"title": "空白二维画布工程",
|
||||
"summary": "原生 Canvas 二维空白工程:自适应画布、按设备像素比缩放与 requestAnimationFrame 主循环已就绪。",
|
||||
"tags": [
|
||||
"空白",
|
||||
"起步工程",
|
||||
"2d",
|
||||
"canvas"
|
||||
],
|
||||
"runtime": "html",
|
||||
"engine": "canvas",
|
||||
"engineVersion": "",
|
||||
"templateVersion": "0.1.0",
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"entry": "game/index.html",
|
||||
"zipKey": "templates/v1/blank-2d-canvas/template.zip",
|
||||
"zipSizeBytes": 1534,
|
||||
"zipSha256": "ff8f84e4793941acaf161738c2795f65c5d5390de8614f51aa9e3a5771767134",
|
||||
"coverKey": "templates/v1/blank-2d-canvas/cover.svg",
|
||||
"coverWidth": 960,
|
||||
"coverHeight": 540,
|
||||
"coverSha256": "afb753dc6d3de0f9fb6e03ec94f2be7221dd04c9d4ab3cf92311879f0af25192",
|
||||
"metadataKey": "templates/v1/blank-2d-canvas/template.json"
|
||||
},
|
||||
{
|
||||
"id": "blank-3d-scene",
|
||||
"title": "空白三维场景工程",
|
||||
"summary": "Three.js 空白场景:空场景、透视相机、网格地面与自适应视口已就绪,适合从零搭三维玩法。",
|
||||
"tags": [
|
||||
"空白",
|
||||
"起步工程",
|
||||
"3d",
|
||||
"three.js"
|
||||
],
|
||||
"runtime": "html",
|
||||
"engine": "three.js",
|
||||
"engineVersion": "0.180.0",
|
||||
"templateVersion": "0.1.0",
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"entry": "game/index.html",
|
||||
"zipKey": "templates/v1/blank-3d-scene/template.zip",
|
||||
"zipSizeBytes": 1644,
|
||||
"zipSha256": "f3f295f4e5adcf1445d75229dc1b583376a9bc96d3f27a257d69ee3b7cace892",
|
||||
"coverKey": "templates/v1/blank-3d-scene/cover.svg",
|
||||
"coverWidth": 960,
|
||||
"coverHeight": 540,
|
||||
"coverSha256": "1429232adaf6df4457e45b4fc8d7ee9fab2e6bffce9f3f0016e91b81bb66c6a7",
|
||||
"metadataKey": "templates/v1/blank-3d-scene/template.json"
|
||||
},
|
||||
{
|
||||
"id": "blank-web",
|
||||
"title": "空白网页工程",
|
||||
"summary": "最小网页工程(HTML + CSS + 原生 JS + Vite),没有任何引擎依赖,适合从零写玩法。",
|
||||
"tags": [
|
||||
"空白",
|
||||
"起步工程",
|
||||
"网页",
|
||||
"原生"
|
||||
],
|
||||
"runtime": "html",
|
||||
"engine": "none",
|
||||
"engineVersion": "",
|
||||
"templateVersion": "0.1.0",
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"entry": "game/index.html",
|
||||
"zipKey": "templates/v1/blank-web/template.zip",
|
||||
"zipSizeBytes": 1212,
|
||||
"zipSha256": "6fa4391f30342e8dcbdcf735f990d2534ea50405f119e4fa5879b83e8f00119e",
|
||||
"coverKey": "templates/v1/blank-web/cover.svg",
|
||||
"coverWidth": 960,
|
||||
"coverHeight": 540,
|
||||
"coverSha256": "326a2753386618971b1311043effa46c2e74bc1cfb116862c0ee4097dcd5086a",
|
||||
"metadataKey": "templates/v1/blank-web/template.json"
|
||||
},
|
||||
{
|
||||
"id": "phaser-2d-starter",
|
||||
"title": "Phaser 2D 起步工程",
|
||||
"summary": "AGC 新建项目使用的默认二维起步工程(Phaser 4 + Vite),解压后即为可运行项目根。",
|
||||
"tags": [
|
||||
"起步工程",
|
||||
"2d",
|
||||
"phaser",
|
||||
"像素"
|
||||
],
|
||||
"runtime": "html",
|
||||
"engine": "phaser",
|
||||
"engineVersion": "4.2.1",
|
||||
"templateVersion": "0.1.0",
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"entry": "game/index.html",
|
||||
"zipKey": "templates/v1/phaser-2d-starter/template.zip",
|
||||
"zipSizeBytes": 8770,
|
||||
"zipSha256": "9026856c3c0b3a42401172e36ce8b450a65e9f11eb9096624d8990d51449d8ce",
|
||||
"coverKey": "templates/v1/phaser-2d-starter/cover.svg",
|
||||
"coverWidth": 960,
|
||||
"coverHeight": 540,
|
||||
"coverSha256": "fdb422027bf54bf755b2b91cd21fa10fdd7ce3f5c7e3ccd9ac3ffba602b12b96",
|
||||
"metadataKey": "templates/v1/phaser-2d-starter/template.json"
|
||||
},
|
||||
{
|
||||
"id": "threejs-3d-starter",
|
||||
"title": "Three.js 3D 起步工程",
|
||||
"summary": "网页三维起步工程(Three.js + Vite),自带可旋转立方体场景、方向光与自适应视口。",
|
||||
"tags": [
|
||||
"起步工程",
|
||||
"3d",
|
||||
"three.js",
|
||||
"网页"
|
||||
],
|
||||
"runtime": "html",
|
||||
"engine": "three.js",
|
||||
"engineVersion": "0.180.0",
|
||||
"templateVersion": "0.1.0",
|
||||
"updatedAt": "2026-09-17T03:22:43Z",
|
||||
"entry": "game/index.html",
|
||||
"zipKey": "templates/v1/threejs-3d-starter/template.zip",
|
||||
"zipSizeBytes": 1697,
|
||||
"zipSha256": "03096152b17cd6d55e7f6ccd518485136133cb54fd2a5a5d0ac8e0974149155c",
|
||||
"coverKey": "templates/v1/threejs-3d-starter/cover.svg",
|
||||
"coverWidth": 960,
|
||||
"coverHeight": 540,
|
||||
"coverSha256": "7ba013e8a8b515d7aff7146fe401afe5ba3416b9c69db181179705e1bce01beb",
|
||||
"metadataKey": "templates/v1/threejs-3d-starter/template.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const RUNNER_ENDPOINT_FILE_NAME: &str = "agent-runner.endpoint.json";
|
||||
const RUNNER_LOCK_FILE_NAME: &str = "agent-runner.lock";
|
||||
const GUI_OWNER_LOCK_FILE_NAME: &str = "agent-runner.gui-owner.lock";
|
||||
const GUI_PARTICIPANT_LOCK_FILE_NAME: &str = "agent-runner.gui-participant.lock";
|
||||
|
||||
struct TestDirectory(PathBuf);
|
||||
|
||||
@@ -50,8 +50,9 @@ fn open_locked_file(path: &Path) -> File {
|
||||
.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW)
|
||||
.open(path)
|
||||
.expect("open isolated lock file");
|
||||
// 模拟一个界面窗口:参与锁以共享锁持有,多个窗口可以同时持有。
|
||||
// SAFETY: file owns a live descriptor and flock does not retain pointers.
|
||||
assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }, 0);
|
||||
assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH) }, 0);
|
||||
file
|
||||
}
|
||||
|
||||
@@ -101,7 +102,7 @@ fn runner_binary() -> &'static str {
|
||||
#[test]
|
||||
fn gui_owned_runner_rejects_start_when_owner_dies_before_first_check() {
|
||||
let directory = TestDirectory::new("owner-lost-before-check");
|
||||
let owner = open_locked_file(&directory.path().join(GUI_OWNER_LOCK_FILE_NAME));
|
||||
let owner = open_locked_file(&directory.path().join(GUI_PARTICIPANT_LOCK_FILE_NAME));
|
||||
let script =
|
||||
"kill -STOP $$; exec \"$1\" --agent-runner --config-dir \"$2\" --gui-owner-required";
|
||||
let mut child = Command::new("/bin/sh")
|
||||
@@ -139,7 +140,7 @@ fn gui_owned_runner_rejects_start_when_owner_dies_before_first_check() {
|
||||
#[test]
|
||||
fn gui_owned_runner_exits_and_cleans_endpoint_after_established_owner_dies() {
|
||||
let directory = TestDirectory::new("owner-lost-after-start");
|
||||
let owner = open_locked_file(&directory.path().join(GUI_OWNER_LOCK_FILE_NAME));
|
||||
let owner = open_locked_file(&directory.path().join(GUI_PARTICIPANT_LOCK_FILE_NAME));
|
||||
let mut child = Command::new(runner_binary())
|
||||
.arg("--agent-runner")
|
||||
.arg("--config-dir")
|
||||
|
||||
@@ -25,8 +25,10 @@ import {
|
||||
type ProjectManifestSnapshotSource,
|
||||
rereadAuthoritativeProjectManifestSnapshot,
|
||||
} from '../../view/project-development/projectResourceLiveUpdateModel';
|
||||
import TemplateLibraryView from '../../view/template-library';
|
||||
import { useDirectActiveTurns } from '../agent-runtime/directActiveTurns';
|
||||
import { RuntimeConfigDialog } from '../runtime-config/RuntimeConfigDialog';
|
||||
import { useTemplateLibrary } from '../template-library/useTemplateLibrary';
|
||||
import { AccountWalletBar, AccountWalletDialogs } from './AccountWallet';
|
||||
import {
|
||||
DeveloperAgentDialogs,
|
||||
@@ -83,6 +85,11 @@ export function WorkspaceLauncherShell({
|
||||
setAgentChatProjectPath: developerAgent.setAgentChatProjectPath,
|
||||
rememberRecentWorkspace,
|
||||
});
|
||||
const templateLibrary = useTemplateLibrary({
|
||||
onProjectCreated: async (result) => {
|
||||
await homeProject.enterCreatedTemplateProject(result);
|
||||
},
|
||||
});
|
||||
const {
|
||||
projectPath,
|
||||
setProjectPath,
|
||||
@@ -567,6 +574,13 @@ export function WorkspaceLauncherShell({
|
||||
void openProject(path, 'open');
|
||||
}}
|
||||
onProjectPick={() => void homeProject.pickAndOpenProject()}
|
||||
templateRecommendations={templateLibrary.templates}
|
||||
templateLibraryLoading={
|
||||
templateLibrary.status === 'loading' ||
|
||||
templateLibrary.status === 'idle'
|
||||
}
|
||||
templateLibraryError={templateLibrary.error}
|
||||
onTemplateLibraryOpen={() => setLauncherView('template-library')}
|
||||
/>
|
||||
) : launcherView === 'projects' ? (
|
||||
<ProjectsPage
|
||||
@@ -574,6 +588,11 @@ export function WorkspaceLauncherShell({
|
||||
homeProject={homeProject}
|
||||
recentProjects={recentProjects}
|
||||
/>
|
||||
) : launcherView === 'template-library' ? (
|
||||
<TemplateLibraryView
|
||||
controller={templateLibrary}
|
||||
onBack={() => setLauncherView('home')}
|
||||
/>
|
||||
) : launcherView === 'agent-chat' ? (
|
||||
<DeveloperAgentPanel
|
||||
controller={developerAgent}
|
||||
|
||||
@@ -555,6 +555,35 @@ export function useHomeProjectCreation({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板库建出的项目:模板文件与项目脚手架已在 Rust 侧一次落盘,
|
||||
* 这里只负责登记最近项目并走标准进项目通道(含会话预览核验与代次闸门)。
|
||||
*/
|
||||
async function enterCreatedTemplateProject(result: InitLocalProjectResult) {
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
throw new Error('需要在陶泥儿客户端内运行');
|
||||
}
|
||||
await enterProjectDevelopment({
|
||||
projectPath: result.projectPath,
|
||||
projectName:
|
||||
result.manifest.name || projectNameFromPath(result.projectPath),
|
||||
projectKind: 'web',
|
||||
manifest: result.manifest,
|
||||
projectRevision: await readCurrentProjectRevision(
|
||||
invoke,
|
||||
result.projectPath,
|
||||
),
|
||||
creationType: null,
|
||||
startMode: null,
|
||||
initialPrompt: '',
|
||||
attachments: [],
|
||||
recentRunStatus: null,
|
||||
recentRunStopReason: null,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
async function openProject(nextProjectPath: string, mode: 'open' | 'create') {
|
||||
if (mode === 'create') {
|
||||
await createProjectFromProjectPage(nextProjectPath);
|
||||
@@ -1005,6 +1034,7 @@ export function useHomeProjectCreation({
|
||||
renameProject,
|
||||
pickAndOpenProject,
|
||||
pickAndCreateProject,
|
||||
enterCreatedTemplateProject,
|
||||
confirmCreateInNonEmptyFolder,
|
||||
cancelCreateInNonEmptyFolder,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* AGC 模板库的前端模型:清单类型、搜索与筛选的纯函数。
|
||||
*
|
||||
* 真源在 OSS 清单与 Rust 侧(`fetch_game_template_library`);这里只做展示层派生,
|
||||
* 不缓存业务真相,也不拼远端地址(URL 由 Rust 侧按受信任 OSS 前缀给出)。
|
||||
*/
|
||||
|
||||
export type GameTemplateLibrarySource = 'network' | 'cache';
|
||||
|
||||
export type GameTemplateEntry = {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
tags: string[];
|
||||
runtime: string;
|
||||
engine: string;
|
||||
engineVersion: string;
|
||||
templateVersion: string;
|
||||
updatedAt: string;
|
||||
entry: string;
|
||||
zipUrl: string;
|
||||
zipSizeBytes: number;
|
||||
zipSha256: string;
|
||||
coverUrl: string;
|
||||
coverWidth: number;
|
||||
coverHeight: number;
|
||||
installed: boolean;
|
||||
installedVersion: string | null;
|
||||
installedAtMillis: number | null;
|
||||
};
|
||||
|
||||
export type GameTemplateLibrarySnapshot = {
|
||||
schemaVersion: string;
|
||||
library: string;
|
||||
libraryVersion: number;
|
||||
updatedAt: string;
|
||||
fetchedAtMillis: number;
|
||||
source: GameTemplateLibrarySource;
|
||||
templates: GameTemplateEntry[];
|
||||
};
|
||||
|
||||
export type InstalledGameTemplate = {
|
||||
templateId: string;
|
||||
templateVersion: string;
|
||||
installedAtMillis: number;
|
||||
zipSha256: string;
|
||||
fileCount: number;
|
||||
projectDir: string;
|
||||
};
|
||||
|
||||
export type TemplateLibraryFilters = {
|
||||
query: string;
|
||||
tags: readonly string[];
|
||||
runtime: string;
|
||||
installedOnly: boolean;
|
||||
};
|
||||
|
||||
export const EMPTY_TEMPLATE_LIBRARY_FILTERS: TemplateLibraryFilters = {
|
||||
query: '',
|
||||
tags: [],
|
||||
runtime: '',
|
||||
installedOnly: false,
|
||||
};
|
||||
|
||||
const RUNTIME_LABELS: Record<string, string> = {
|
||||
html: '网页',
|
||||
unity: 'Unity',
|
||||
godot: 'Godot',
|
||||
cocos: 'Cocos',
|
||||
};
|
||||
|
||||
export function templateRuntimeLabel(runtime: string): string {
|
||||
const normalized = runtime.trim().toLowerCase();
|
||||
if (!normalized) return '未标注运行时';
|
||||
return RUNTIME_LABELS[normalized] ?? runtime.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 空白分隔的多个关键词之间是「与」关系:每个词都必须命中标题、简介、标签或引擎,
|
||||
* 这样「三消 像素」不会退化成命中任意一个就出现的宽泛搜索。
|
||||
*/
|
||||
export function templateMatchesQuery(
|
||||
template: GameTemplateEntry,
|
||||
query: string,
|
||||
): boolean {
|
||||
const terms = query
|
||||
.toLowerCase()
|
||||
.split(/\s+/u)
|
||||
.filter((term) => term.length > 0);
|
||||
if (terms.length === 0) {
|
||||
return true;
|
||||
}
|
||||
const haystack = [
|
||||
template.title,
|
||||
template.summary,
|
||||
template.engine,
|
||||
template.runtime,
|
||||
template.tags.join(' '),
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return terms.every((term) => haystack.includes(term));
|
||||
}
|
||||
|
||||
export function filterGameTemplates(
|
||||
templates: readonly GameTemplateEntry[],
|
||||
filters: TemplateLibraryFilters,
|
||||
): GameTemplateEntry[] {
|
||||
const selectedTags = filters.tags
|
||||
.map((tag) => tag.trim().toLowerCase())
|
||||
.filter((tag) => tag.length > 0);
|
||||
const runtime = filters.runtime.trim().toLowerCase();
|
||||
return templates.filter((template) => {
|
||||
if (filters.installedOnly && !template.installed) {
|
||||
return false;
|
||||
}
|
||||
if (runtime && template.runtime.trim().toLowerCase() !== runtime) {
|
||||
return false;
|
||||
}
|
||||
if (selectedTags.length > 0) {
|
||||
const templateTags = template.tags.map((tag) => tag.toLowerCase());
|
||||
if (!selectedTags.some((tag) => templateTags.includes(tag))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return templateMatchesQuery(template, filters.query);
|
||||
});
|
||||
}
|
||||
|
||||
/** 标签按出现次数降序,次数相同按名称排序,保证筛选条顺序稳定。 */
|
||||
export function collectGameTemplateTags(
|
||||
templates: readonly GameTemplateEntry[],
|
||||
): string[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const template of templates) {
|
||||
for (const tag of template.tags) {
|
||||
const trimmed = tag.trim();
|
||||
if (!trimmed) continue;
|
||||
counts.set(trimmed, (counts.get(trimmed) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return [...counts.entries()]
|
||||
.sort(
|
||||
([leftTag, leftCount], [rightTag, rightCount]) =>
|
||||
rightCount - leftCount || leftTag.localeCompare(rightTag, 'zh-CN'),
|
||||
)
|
||||
.map(([tag]) => tag);
|
||||
}
|
||||
|
||||
export function collectGameTemplateRuntimes(
|
||||
templates: readonly GameTemplateEntry[],
|
||||
): string[] {
|
||||
const runtimes = new Set<string>();
|
||||
for (const template of templates) {
|
||||
const runtime = template.runtime.trim().toLowerCase();
|
||||
if (runtime) runtimes.add(runtime);
|
||||
}
|
||||
return [...runtimes].sort((left, right) =>
|
||||
left.localeCompare(right, 'zh-CN'),
|
||||
);
|
||||
}
|
||||
|
||||
export function formatGameTemplateSize(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) {
|
||||
return '--';
|
||||
}
|
||||
if (bytes < 1024) {
|
||||
return `${Math.round(bytes)} B`;
|
||||
}
|
||||
if (bytes < 1024 * 1024) {
|
||||
return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function isTemplateLibraryFiltersEmpty(
|
||||
filters: TemplateLibraryFilters,
|
||||
): boolean {
|
||||
return (
|
||||
!filters.query.trim() &&
|
||||
filters.tags.length === 0 &&
|
||||
!filters.runtime.trim() &&
|
||||
!filters.installedOnly
|
||||
);
|
||||
}
|
||||
|
||||
export function toggleGameTemplateTag(
|
||||
filters: TemplateLibraryFilters,
|
||||
tag: string,
|
||||
): TemplateLibraryFilters {
|
||||
const exists = filters.tags.includes(tag);
|
||||
return {
|
||||
...filters,
|
||||
tags: exists
|
||||
? filters.tags.filter((value) => value !== tag)
|
||||
: [...filters.tags, tag],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 已安装版本低于清单版本时必须重新下载;已安装且版本一致才算可直接使用。
|
||||
*/
|
||||
export function needsTemplateDownload(template: GameTemplateEntry): boolean {
|
||||
return (
|
||||
!template.installed ||
|
||||
template.installedVersion !== template.templateVersion
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* 模板库状态链路:拉取清单、下载模板、用模板建项目。
|
||||
*
|
||||
* 远端真相全在 Rust 侧命令里(受信任 OSS 前缀 + 摘要校验 + 本机安装记录);
|
||||
* 这里只维护界面状态,并在下载成功后把对应条目的安装状态就地更新,
|
||||
* 避免为了一个"已下载"徽标再打一次清单请求。
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { resolveTauriInvoke } from '../../app/tauri';
|
||||
import type { InitLocalProjectResult } from '../../app/types';
|
||||
import {
|
||||
collectGameTemplateRuntimes,
|
||||
collectGameTemplateTags,
|
||||
EMPTY_TEMPLATE_LIBRARY_FILTERS,
|
||||
filterGameTemplates,
|
||||
type GameTemplateEntry,
|
||||
type GameTemplateLibrarySnapshot,
|
||||
type InstalledGameTemplate,
|
||||
isTemplateLibraryFiltersEmpty,
|
||||
needsTemplateDownload,
|
||||
type TemplateLibraryFilters,
|
||||
toggleGameTemplateTag,
|
||||
} from './templateLibraryModel';
|
||||
|
||||
export type TemplateLibraryStatus = 'idle' | 'loading' | 'ready' | 'error';
|
||||
export type TemplateLibraryBusyKind = 'download' | 'create';
|
||||
|
||||
type UseTemplateLibraryOptions = {
|
||||
/** 项目已建好:由调用方负责进入项目工作区(模板库不碰工作区状态)。 */
|
||||
onProjectCreated: (result: InitLocalProjectResult) => Promise<void> | void;
|
||||
};
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export function useTemplateLibrary({
|
||||
onProjectCreated,
|
||||
}: UseTemplateLibraryOptions) {
|
||||
const [snapshot, setSnapshot] = useState<GameTemplateLibrarySnapshot | null>(
|
||||
null,
|
||||
);
|
||||
const [status, setStatus] = useState<TemplateLibraryStatus>('idle');
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [filters, setFilters] = useState<TemplateLibraryFilters>(
|
||||
EMPTY_TEMPLATE_LIBRARY_FILTERS,
|
||||
);
|
||||
const [busyTemplateId, setBusyTemplateId] = useState<string | null>(null);
|
||||
const [busyKind, setBusyKind] = useState<TemplateLibraryBusyKind | null>(
|
||||
null,
|
||||
);
|
||||
const loadingRef = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (loadingRef.current) {
|
||||
return;
|
||||
}
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
setStatus('error');
|
||||
setError('需要在陶泥儿客户端内运行');
|
||||
return;
|
||||
}
|
||||
loadingRef.current = true;
|
||||
setStatus('loading');
|
||||
setError('');
|
||||
try {
|
||||
const next = await invoke<GameTemplateLibrarySnapshot>(
|
||||
'fetch_game_template_library',
|
||||
);
|
||||
setSnapshot(next);
|
||||
setStatus('ready');
|
||||
setNotice(
|
||||
next.source === 'cache' ? '远端清单暂时读不到,当前展示本机缓存' : '',
|
||||
);
|
||||
} catch (nextError) {
|
||||
setStatus('error');
|
||||
setError(errorMessage(nextError));
|
||||
} finally {
|
||||
loadingRef.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const downloadTemplate = useCallback(async (template: GameTemplateEntry) => {
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
throw new Error('需要在陶泥儿客户端内运行');
|
||||
}
|
||||
setBusyTemplateId(template.id);
|
||||
setBusyKind('download');
|
||||
setError('');
|
||||
try {
|
||||
const installed = await invoke<InstalledGameTemplate>(
|
||||
'download_game_template',
|
||||
{
|
||||
templateId: template.id,
|
||||
templateVersion: template.templateVersion,
|
||||
},
|
||||
);
|
||||
setSnapshot((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
templates: current.templates.map((entry) =>
|
||||
entry.id === template.id
|
||||
? {
|
||||
...entry,
|
||||
installed: true,
|
||||
installedVersion: installed.templateVersion,
|
||||
installedAtMillis: installed.installedAtMillis,
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
}
|
||||
: current,
|
||||
);
|
||||
setNotice(`已下载模板「${template.title}」`);
|
||||
return installed;
|
||||
} catch (nextError) {
|
||||
setError(errorMessage(nextError));
|
||||
throw nextError;
|
||||
} finally {
|
||||
setBusyTemplateId(null);
|
||||
setBusyKind(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const createProjectFromTemplate = useCallback(
|
||||
async (template: GameTemplateEntry) => {
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
throw new Error('需要在陶泥儿客户端内运行');
|
||||
}
|
||||
try {
|
||||
if (needsTemplateDownload(template)) {
|
||||
await downloadTemplate(template);
|
||||
}
|
||||
setBusyTemplateId(template.id);
|
||||
setBusyKind('create');
|
||||
setError('');
|
||||
setNotice(`正在用模板「${template.title}」创建项目`);
|
||||
const result = await invoke<InitLocalProjectResult>(
|
||||
'create_automatic_local_game_project_from_template',
|
||||
{
|
||||
templateId: template.id,
|
||||
templateVersion: template.templateVersion,
|
||||
name: null,
|
||||
planning: false,
|
||||
},
|
||||
);
|
||||
await onProjectCreated(result);
|
||||
setNotice(`已用模板「${template.title}」创建项目`);
|
||||
return result;
|
||||
} catch (nextError) {
|
||||
setError(errorMessage(nextError));
|
||||
throw nextError;
|
||||
} finally {
|
||||
setBusyTemplateId(null);
|
||||
setBusyKind(null);
|
||||
}
|
||||
},
|
||||
[downloadTemplate, onProjectCreated],
|
||||
);
|
||||
|
||||
const templates = useMemo(
|
||||
() => snapshot?.templates ?? [],
|
||||
[snapshot?.templates],
|
||||
);
|
||||
const visibleTemplates = useMemo(
|
||||
() => filterGameTemplates(templates, filters),
|
||||
[templates, filters],
|
||||
);
|
||||
const tagOptions = useMemo(
|
||||
() => collectGameTemplateTags(templates),
|
||||
[templates],
|
||||
);
|
||||
const runtimeOptions = useMemo(
|
||||
() => collectGameTemplateRuntimes(templates),
|
||||
[templates],
|
||||
);
|
||||
const installedCount = useMemo(
|
||||
() => templates.filter((template) => template.installed).length,
|
||||
[templates],
|
||||
);
|
||||
const filtersActive = !isTemplateLibraryFiltersEmpty(filters);
|
||||
|
||||
const setQuery = useCallback((query: string) => {
|
||||
setFilters((current) => ({ ...current, query }));
|
||||
}, []);
|
||||
|
||||
const selectRuntime = useCallback((runtime: string) => {
|
||||
setFilters((current) => ({
|
||||
...current,
|
||||
runtime: current.runtime === runtime ? '' : runtime,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const toggleTag = useCallback((tag: string) => {
|
||||
setFilters((current) => toggleGameTemplateTag(current, tag));
|
||||
}, []);
|
||||
|
||||
const setInstalledOnly = useCallback((installedOnly: boolean) => {
|
||||
setFilters((current) => ({ ...current, installedOnly }));
|
||||
}, []);
|
||||
|
||||
const clearFilters = useCallback(() => {
|
||||
setFilters(EMPTY_TEMPLATE_LIBRARY_FILTERS);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
snapshot,
|
||||
status,
|
||||
error,
|
||||
notice,
|
||||
templates,
|
||||
visibleTemplates,
|
||||
tagOptions,
|
||||
runtimeOptions,
|
||||
installedCount,
|
||||
filters,
|
||||
filtersActive,
|
||||
setQuery,
|
||||
selectRuntime,
|
||||
toggleTag,
|
||||
setInstalledOnly,
|
||||
clearFilters,
|
||||
busyTemplateId,
|
||||
busyKind,
|
||||
refresh,
|
||||
downloadTemplate,
|
||||
createProjectFromTemplate,
|
||||
clearNotice: useCallback(() => setNotice(''), []),
|
||||
};
|
||||
}
|
||||
|
||||
export type TemplateLibraryController = ReturnType<typeof useTemplateLibrary>;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user