From ced4b56dee0e70bf56edb69ed1d6513ba6c69f84 Mon Sep 17 00:00:00 2001 From: kdletters Date: Mon, 17 Aug 2026 10:47:58 +0800 Subject: [PATCH 1/8] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E8=A7=88?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E8=AE=B0=E5=BD=95=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 发布记录增加后端校验后的 Web 端口号 列表隐藏已成功卸载的容器记录 兼容恢复旧运行记录并回填 Web 端口 补充后端、前端测试和技术说明 --- .../src/PreviewDeployerApp.test.tsx | 2 + .../src/PreviewDeployerApp.tsx | 3 + apps/preview-deployer-web/src/styles.css | 5 ++ apps/preview-deployer-web/src/types.ts | 1 + ...Jenkins容器预览部署控制面技术方案-2026-08-15.md | 2 + .../preview-deployer-server/src/jenkins.rs | 1 + .../crates/preview-deployer-server/src/lib.rs | 47 +++++++++++++- .../preview-deployer-server/src/tests.rs | 62 +++++++++++++++++++ 8 files changed, 122 insertions(+), 1 deletion(-) diff --git a/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx b/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx index d0b68bc21..261e5a6ae 100644 --- a/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx +++ b/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx @@ -86,6 +86,7 @@ test('shows health and web url, then confirms uninstall', async () => { resolvedCommit: '1234567890abcdef', status: 'running', health: 'healthy', + webPort: 8400, webUrl: 'http://192.168.35.82:8400', createdAt: 1_787_270_400, updatedAt: 1_787_270_460, @@ -94,6 +95,7 @@ test('shows health and web url, then confirms uninstall', async () => { render(); expect(await screen.findByText('健康')).toBeTruthy(); + expect(screen.getByText('端口 8400')).toBeTruthy(); expect( screen.getByRole('link', { name: /打开 Web/u }).getAttribute('href'), ).toBe('http://192.168.35.82:8400'); diff --git a/apps/preview-deployer-web/src/PreviewDeployerApp.tsx b/apps/preview-deployer-web/src/PreviewDeployerApp.tsx index 290e6d3cf..2bfd2482a 100644 --- a/apps/preview-deployer-web/src/PreviewDeployerApp.tsx +++ b/apps/preview-deployer-web/src/PreviewDeployerApp.tsx @@ -530,6 +530,9 @@ function DeploymentCard({ {HEALTH_LABELS[deployment.health]} + {deployment.webPort ? ( + 端口 {deployment.webPort} + ) : null} diff --git a/apps/preview-deployer-web/src/styles.css b/apps/preview-deployer-web/src/styles.css index 3316766b6..a7c3a531c 100644 --- a/apps/preview-deployer-web/src/styles.css +++ b/apps/preview-deployer-web/src/styles.css @@ -381,6 +381,11 @@ a { font-size: 11px; font-weight: 700; } +.port-badge { + color: #475569; + background: #f1f5f9; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} .badge-running { color: #14734a; background: #e9f9f0; diff --git a/apps/preview-deployer-web/src/types.ts b/apps/preview-deployer-web/src/types.ts index d538aee26..da08df216 100644 --- a/apps/preview-deployer-web/src/types.ts +++ b/apps/preview-deployer-web/src/types.ts @@ -17,6 +17,7 @@ export interface PreviewDeployment { resolvedCommit?: string | null; status: DeploymentStatus; health: DeploymentHealth; + webPort?: number | null; webUrl?: string | null; jenkinsBuildUrl?: string | null; createdAt: string | number; diff --git a/docs/technical/【开发运维】Jenkins容器预览部署控制面技术方案-2026-08-15.md b/docs/technical/【开发运维】Jenkins容器预览部署控制面技术方案-2026-08-15.md index 786295289..cb68b9542 100644 --- a/docs/technical/【开发运维】Jenkins容器预览部署控制面技术方案-2026-08-15.md +++ b/docs/technical/【开发运维】Jenkins容器预览部署控制面技术方案-2026-08-15.md @@ -92,6 +92,8 @@ SpacetimeDB 2.7 CLI 发布到受控 Compose 网络地址时固定使用 `--yes=r 页面状态统一为 `queued / building / deploying / running / uninstalling / stopped / failed / cancelled`,健康状态统一为 `pending / healthy / unhealthy / unknown`。 +发布记录卡片直接展示后端校验后的 `webPort`。卸载成功的 `stopped` 记录仍保留在服务端持久状态中用于审计和所有权校验,但列表 API 不再返回,页面刷新后立即从发布记录中消失。 + Jenkins 在构建完成、归档 artifact 和更新 REST 状态之间可能短暂返回不可解析的状态正文。控制服务对队列、构建状态和 artifact 查询执行有限重试;单次瞬态响应不得把已经成功并健康的部署永久写成 `failed`。 控制服务查询 Jenkins 队列与构建状态时必须使用 `tree` 参数限制到所需字段,避免完整 `api/json` 的大体积深层对象触发 JSON 递归深度限制。预览 Compose 中的外部生成 worker 使用 `restart: on-failure`;它若早于 API 完成模型定价运行时身份初始化而启动失败,应由 Docker 自动重启并在身份就绪后稳定运行。 diff --git a/server-rs/crates/preview-deployer-server/src/jenkins.rs b/server-rs/crates/preview-deployer-server/src/jenkins.rs index 74cf27217..9bb553a68 100644 --- a/server-rs/crates/preview-deployer-server/src/jenkins.rs +++ b/server-rs/crates/preview-deployer-server/src/jenkins.rs @@ -58,6 +58,7 @@ pub struct PreviewResult { pub health: Option, pub phase: Option, pub health_status: Option, + pub web_port: Option, pub web_url: Option, pub message: Option, } diff --git a/server-rs/crates/preview-deployer-server/src/lib.rs b/server-rs/crates/preview-deployer-server/src/lib.rs index 11e79db54..0c021b2b0 100644 --- a/server-rs/crates/preview-deployer-server/src/lib.rs +++ b/server-rs/crates/preview-deployer-server/src/lib.rs @@ -24,6 +24,7 @@ use tower_http::{ trace::TraceLayer, }; use tracing::{error, warn}; +use url::Url; use uuid::Uuid; pub use config::Config; @@ -86,6 +87,8 @@ pub struct Deployment { pub resolved_commit: Option, pub status: DeploymentStatus, pub health: HealthStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub web_port: Option, #[serde(skip_serializing_if = "Option::is_none")] pub web_url: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -385,6 +388,7 @@ async fn list_deployments( .read() .await .values() + .filter(|record| record.public.status != DeploymentStatus::Stopped) .map(|record| record.public.clone()) .collect(); deployments.sort_by(|left, right| right.created_at.cmp(&left.created_at)); @@ -494,6 +498,7 @@ async fn create_deployment( resolved_commit: None, status: DeploymentStatus::Queued, health: HealthStatus::Pending, + web_port: None, web_url: None, jenkins_build_url: None, created_at: now, @@ -770,8 +775,23 @@ async fn apply_outcome(state: &AppState, id: &str, outcome: JenkinsOutcome) { record.public.status = DeploymentStatus::Failed; record.public.health = HealthStatus::Unknown; record.public.message = Some("Jenkins 返回了无效 Web 地址".to_string()); + } else if result + .web_port + .is_some_and(|value| !(8400..=8499).contains(&value)) + || result + .web_url + .as_deref() + .zip(result.web_port) + .is_some_and(|(url, port)| { + Url::parse(url).ok().and_then(|url| url.port()) != Some(port) + }) + { + record.public.status = DeploymentStatus::Failed; + record.public.health = HealthStatus::Unknown; + record.public.message = Some("Jenkins 返回了无效 Web 端口".to_string()); } else if record.operation == Operation::Deploy && (result.resolved_commit.is_none() + || result.web_port.is_none() || result.web_url.is_none() || result.phase.as_deref() != Some("RUNNING") || result.health_status.as_deref() != Some("HEALTHY")) @@ -794,6 +814,9 @@ async fn apply_outcome(state: &AppState, id: &str, outcome: JenkinsOutcome) { if let Some(value) = result.web_url { record.public.web_url = Some(value); } + if let Some(value) = result.web_port { + record.public.web_port = Some(value); + } if let Some(value) = result.health { record.public.health = value; } @@ -838,6 +861,7 @@ async fn apply_outcome(state: &AppState, id: &str, outcome: JenkinsOutcome) { Operation::Uninstall => { record.public.status = DeploymentStatus::Stopped; record.public.health = HealthStatus::Unknown; + record.public.web_port = None; record.public.web_url = None; record.public.can_uninstall = false; if record.public.message.is_none() { @@ -877,7 +901,7 @@ fn load_deployments(config: &Config) -> Result return Err("预览部署状态文件 schemaVersion 不受支持".to_string()); } let mut deployments = HashMap::new(); - for record in persisted.deployments { + for mut record in persisted.deployments { validate_deployment_id(&record.public.id) .map_err(|_| "状态文件包含无效部署 ID".to_string())?; let branch = validate_branch(&record.public.branch) @@ -896,6 +920,27 @@ fn load_deployments(config: &Config) -> Result { return Err("状态文件包含无效 Web 地址".to_string()); } + let url_port = record + .public + .web_url + .as_deref() + .and_then(|value| Url::parse(value).ok()) + .and_then(|url| url.port()); + if record + .public + .web_port + .is_some_and(|value| !(8400..=8499).contains(&value)) + || record + .public + .web_port + .zip(url_port) + .is_some_and(|(saved, parsed)| saved != parsed) + { + return Err("状态文件包含无效 Web 端口".to_string()); + } + if record.public.web_port.is_none() { + record.public.web_port = url_port; + } if deployments .insert(record.public.id.clone(), record) .is_some() diff --git a/server-rs/crates/preview-deployer-server/src/tests.rs b/server-rs/crates/preview-deployer-server/src/tests.rs index dc13bf960..a7d25d42d 100644 --- a/server-rs/crates/preview-deployer-server/src/tests.rs +++ b/server-rs/crates/preview-deployer-server/src/tests.rs @@ -133,6 +133,7 @@ async fn mock_artifact(axum::extract::Path(build): axum::extract::Path) -> "resolvedCommit": "0123456789abcdef0123456789abcdef01234567", "phase": "RUNNING", "healthStatus": "HEALTHY", + "webPort": 8400, "webUrl": "http://192.168.35.82:8400", "message": "预览实例已发布" })) @@ -365,6 +366,7 @@ async fn deploy_and_uninstall_use_fixed_job_and_apply_owned_artifacts() { .clone(); assert_eq!(deployment.status, super::DeploymentStatus::Running); assert_eq!(deployment.health, super::HealthStatus::Healthy); + assert_eq!(deployment.web_port, Some(8400)); assert_eq!( deployment.web_url.as_deref(), Some("http://192.168.35.82:8400") @@ -421,8 +423,27 @@ async fn deploy_and_uninstall_use_fixed_job_and_apply_owned_artifacts() { .clone(); assert_eq!(deployment.status, super::DeploymentStatus::Stopped); assert_eq!(deployment.health, super::HealthStatus::Unknown); + assert_eq!(deployment.web_port, None); assert_eq!(deployment.web_url, None); assert!(!deployment.can_uninstall); + + let list_request = axum::http::Request::builder() + .method("GET") + .uri("/api/preview-deployer/deployments") + .header(header::HOST, HOST) + .header(header::COOKIE, &cookie) + .body(Body::empty()) + .unwrap(); + let list_response = app.clone().oneshot(list_request).await.unwrap(); + assert_eq!(list_response.status(), StatusCode::OK); + let list_body = list_response + .into_body() + .collect() + .await + .unwrap() + .to_bytes(); + let list: Value = serde_json::from_slice(&list_body).unwrap(); + assert_eq!(list["deployments"], json!([])); let state_file = state.config.state_file.clone(); let mut recovered_config = test_config(state.config.jenkins_root_url.clone()); recovered_config.state_file = state_file.clone(); @@ -499,6 +520,7 @@ async fn duplicate_active_branch_is_rejected_without_second_jenkins_trigger() { resolved_commit: None, status: super::DeploymentStatus::Building, health: super::HealthStatus::Pending, + web_port: None, web_url: None, jenkins_build_url: None, created_at: now, @@ -576,3 +598,43 @@ fn branch_commit_and_web_url_validation_are_strict() { "192.168.35.82" )); } + +#[test] +fn legacy_running_state_recovers_web_port_from_validated_url() { + let config = test_config(Url::parse("http://127.0.0.1:18080/jenkins/").unwrap()); + let id = super::derive_deployment_id("feature/legacy-running"); + std::fs::write( + &config.state_file, + serde_json::to_vec(&json!({ + "schemaVersion": 1, + "deployments": [{ + "public": { + "id": id, + "branch": "feature/legacy-running", + "status": "running", + "health": "healthy", + "webUrl": "http://192.168.35.82:8407", + "createdAt": 1, + "updatedAt": 2, + "canUninstall": true + }, + "operation": "deploy" + }] + })) + .unwrap(), + ) + .unwrap(); + + let state = AppState::new(config).unwrap(); + assert_eq!( + state + .deployments + .blocking_read() + .get(&id) + .unwrap() + .public + .web_port, + Some(8407) + ); + std::fs::remove_file(&state.config.state_file).unwrap(); +} From c89a13e682c42257d06ea15f714b787eb14cd142 Mon Sep 17 00:00:00 2001 From: Linghong Date: Mon, 17 Aug 2026 03:28:24 +0000 Subject: [PATCH 2/8] =?UTF-8?q?=E6=8A=8A=20Fast=20GDD=20=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E7=AD=89=E5=BE=85=E7=9A=84=E5=8F=AF=E6=81=A2=E5=A4=8D=E5=88=A4?= =?UTF-8?q?=E6=8D=AE=E9=92=89=E6=88=90=E4=B8=8D=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 判据在 task record 的 status 而不是 phase:审批等待只改 phase、保留 status=running,恢复扫描仍会拉起;真正的澄清等待才会把 status 一并写成 waiting-for-user-input。一旦有人把审批等待也写成后者,审批命令的通用 wake 会静默变成 no-op,用户点完批准/修改/退回不会有任何东西继续跑,且无报错。 Co-Authored-By: Claude Opus 5 --- .../src/agent/runtime_driver/recovery_scan.rs | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs index 155bf3571..4827b3228 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs @@ -1770,3 +1770,76 @@ mod orphaned_external_generation_recovery_tests { ); } } + +#[cfg(test)] +mod plan_gdd_approval_wait_recovery_tests { + use super::*; + + /// Fast GDD 审批等待期,根 Supervisor 到底还能不能被恢复扫描拉起。 + /// + /// 判据不在 `phase` 上:`read_recoverable_game_creator_agent_runtime_task` 按 + /// task record 的 **status** 分类,而 record 的 status 由 + /// `game_creator_agent_runtime_task_status` 从 `state.status` 推导。审批等待 + /// (`main_loop` 的 `runtime.plan_gdd` 分支)只改 phase、保留 `status="running"`; + /// 真正的澄清等待(`action_projection`)才会把 status 一并写成 + /// `waiting-for-user-input`,那才是恢复扫描要让路的外部输入等待。 + /// + /// 这个区别决定了审批决定之后还有没有生产路径驱动父 run:审批命令只调通用 + /// wake,一旦有人把审批等待也写成 `status="waiting-for-user-input"`,通用 wake + /// 会静默变成 no-op,用户点了批准/修改/退回之后不会有任何东西继续跑。这条测试 + /// 把这个区别钉成不变量。 + #[test] + fn plan_gdd_approval_wait_stays_recoverable_while_real_user_input_wait_does_not() { + let temporary = crate::tests::canonical_test_tempdir("plan-gdd-approval-wait-recovery-"); + let root = temporary.path(); + init_local_game_project_at(root, "plan-gdd-approval-wait", "Fast GDD 审批等待恢复判定") + .expect("init project"); + let mut runtime = start_game_creator_agent_runtime_task_at( + root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + "推进立项策划", + "plan-gdd-approval-wait-run", + "agent-ready-task-scheduler", + "准备推进立项策划", + vec!["推进立项策划".to_string()], + ) + .expect("start plan-root supervisor runtime"); + + // main_loop.rs 的 Fast GDD 审批等待形状。 + runtime.status = "running".to_string(); + runtime.phase = "waiting-for-user-input".to_string(); + runtime.current_action = "等待 Fast GDD 审批决定".to_string(); + runtime.waiting_on = "用户在审批卡选择批准、修改或退回".to_string(); + runtime.updated_at = unix_timestamp(); + append_game_creator_agent_runtime_task(root, &runtime).expect("append approval wait task"); + refresh_game_creator_agent_runtime_task_queue(root, &mut runtime) + .expect("refresh approval wait task queue"); + write_game_creator_agent_runtime_state(root, &runtime).expect("write approval wait state"); + + let task = + read_recoverable_runnable_game_creator_agent_runtime_task(root, &runtime.agent_id) + .expect("read approval wait task") + .expect("审批等待态必须仍可被恢复扫描拉起,否则审批决定后没有生产路径驱动父 run"); + assert_eq!(task.status, "running"); + assert_eq!(task.phase, "waiting-for-user-input"); + assert!(has_recoverable_game_creator_agent_background_tasks_at(root) + .expect("public preflight must agree with the recoverable task read")); + + // 对照组:真正的用户输入等待把 status 一并写成 waiting-for-user-input。 + runtime.status = "waiting-for-user-input".to_string(); + runtime.updated_at = unix_timestamp(); + append_game_creator_agent_runtime_task(root, &runtime) + .expect("append user input wait task"); + refresh_game_creator_agent_runtime_task_queue(root, &mut runtime) + .expect("refresh user input wait task queue"); + write_game_creator_agent_runtime_state(root, &runtime) + .expect("write user input wait state"); + + assert!( + read_recoverable_runnable_game_creator_agent_runtime_task(root, &runtime.agent_id) + .expect("read user input wait task") + .is_none(), + "status 写成 waiting-for-user-input 才是恢复扫描让路的外部输入等待" + ); + } +} From a40080d5257c06d0eb15964b5761178fd19638ec Mon Sep 17 00:00:00 2001 From: Linghong Date: Mon, 17 Aug 2026 04:02:54 +0000 Subject: [PATCH 3/8] =?UTF-8?q?P1=EF=BC=9A=E7=AA=84=E6=8A=95=E5=BD=B1?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D=E6=8E=90?= =?UTF-8?q?=E6=8E=89=E6=95=B4=E8=BD=AE=20resume=EF=BC=8Cplan=5Fgdd=20block?= =?UTF-8?q?er=20=E6=94=B9=E7=B1=BB=E5=9E=8B=E5=8C=96=E5=88=A4=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A. reconcile_plan_gdd_approval_projections_at 挂在 resume 的第一行却用 `?` 强传播, 一次 Fast GDD 投影失败会掐掉全项目所有 Agent 的恢复;而它本身正是 receipt 投影失败 后的重试入口,掐掉它等于连兜底一起废掉。改成把 fail-closed 收敛到策划根 Supervisor 这个 run,其余 Agent 照常恢复;无法归属时才退回全局上抛。 B. main_loop 原来用 contains("approvalPending=awaiting_decision") 区分 plan_gdd blocker 的子状态,而三个 blocked 里只有一个含这个子串——尚未提交(下一步是 agent.delegate)和 receipt 锚点收尾都会掉进 else 被打成 needs-reconciliation,把最 正常的推进态当成故障停掉。改由构造方给出 PlanGddCompletionBlockerKind,消费方穷尽 match,判不出 kind 时保持 fail-closed。这两个推进态不再产生等待态,和 runtime.plan_update 一样让本轮循环继续。 映射抽成纯函数并建起 main_loop 至今没有的 mod tests:四个 kind × 两条映射全覆盖。 Co-Authored-By: Claude Opus 5 --- .../src/agent/runtime_driver/main_loop.rs | 204 +++++++++++++++--- .../src/agent/runtime_driver/recovery_scan.rs | 129 ++++++++++- .../runtime_protocol/planning_approval.rs | 88 ++++++-- .../agent/runtime_protocol/planning_submit.rs | 33 +++ 4 files changed, 406 insertions(+), 48 deletions(-) diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs index a1657d25d..acd19576d 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs @@ -1,5 +1,86 @@ use super::*; +struct PlanGddBlockerRuntimeProjection { + phase: &'static str, + current_action: &'static str, + waiting_on: &'static str, + next_step: &'static str, +} + +/// `runtime.plan_gdd` blocker 的类型化子状态 → 运行时投影。 +/// +/// 抽成纯函数是为了让这条分支可测:主循环整个文件此前没有 `mod tests`,而原来的 +/// 判别是对 detail 做 `contains("approvalPending=awaiting_decision")`——三个 blocked +/// 子状态里只有一个含这个子串,另外两个会掉进 else 被打成 needs-reconciliation, +/// 把最正常的早期推进态和收尾态当成故障停掉。判不出 kind 时保持 fail-closed。 +fn plan_gdd_blocker_runtime_projection( + kind: Option, +) -> PlanGddBlockerRuntimeProjection { + match kind { + Some(PlanGddCompletionBlockerKind::SubmissionNotStarted) => { + PlanGddBlockerRuntimeProjection { + phase: "planning", + current_action: "推进本根 Run 的 Fast GDD 提交", + waiting_on: "策划子 Agent 完成本根 Run 的 plan.submit_gdd", + next_step: "调用 agent.delegate 派出策划子 Agent;上一根 Run 遗留的 game/fast_gdd.md 或 Acceptance Graph 不能代替本根提交", + } + } + Some(PlanGddCompletionBlockerKind::AwaitingApprovalDecision) => { + PlanGddBlockerRuntimeProjection { + phase: "waiting-for-user-input", + current_action: "等待 Fast GDD 审批决定", + waiting_on: "用户在审批卡选择批准、修改或退回", + next_step: "等待 decide_game_creator_plan_gdd;不得重新提交同一 GDD 或自行创建审批 pending", + } + } + Some(PlanGddCompletionBlockerKind::ReceiptAnchorCleanupPending) => { + PlanGddBlockerRuntimeProjection { + phase: "planning", + current_action: "等待 Fast GDD 审批投影收尾", + waiting_on: "原 plan.submit_gdd 恢复锚点由审批投影清理", + next_step: "等待审批投影恢复清理锚点后继续;不得重新提交同一 GDD 或自行创建审批 pending", + } + } + Some(PlanGddCompletionBlockerKind::NeedsReconciliation) | None => { + PlanGddBlockerRuntimeProjection { + phase: "needs-reconciliation", + current_action: "Fast GDD 审批投影需要人工核对", + waiting_on: + "planning pending、receipt、原提交锚点、terminal observation、audit 与 session 的精确身份", + next_step: "先恢复或核对现有 durable 事实,不能请求新 Provider 计划", + } + } + } +} + +/// 只有「等用户决定」和「要人工核对」才终结本轮后台任务;尚未提交与锚点收尾都是 +/// 继续推进态,和 `runtime.plan_update` 一样不产生等待态,让本轮循环继续。 +fn plan_gdd_blocker_waiting_kind( + kind: Option, +) -> Option<( + &'static str, + &'static str, + &'static str, + AgentBackgroundTaskOutcome, +)> { + match kind { + Some(PlanGddCompletionBlockerKind::AwaitingApprovalDecision) => Some(( + "agent.runtime.plan.gdd.waiting", + "waiting-for-user-input", + "Fast GDD 审批等待状态持久化失败", + AgentBackgroundTaskOutcome::WaitingForUserInput, + )), + Some(PlanGddCompletionBlockerKind::NeedsReconciliation) | None => Some(( + "agent.runtime.plan.gdd.reconciliation", + "needs-reconciliation", + "Fast GDD 审批投影需要人工核对", + AgentBackgroundTaskOutcome::NeedsReconciliation, + )), + Some(PlanGddCompletionBlockerKind::SubmissionNotStarted) + | Some(PlanGddCompletionBlockerKind::ReceiptAnchorCleanupPending) => None, + } +} + pub(in crate::agent) fn autonomous_registered_derived_visuals_need_repair_at(root: &Path) -> bool { let Ok(manifest) = read_manifest_for_project(root) else { return false; @@ -1889,6 +1970,9 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( } if plan.actions.is_empty() { + // blocked 的 plan_gdd blocker 有三种截然不同的继续推进态,phase 与 + // next_step 必须按类型化子状态选,不能回去猜 detail 字符串。 + let mut plan_gdd_blocker_kind: Option = None; let completion_blocker = structured_plan_completion_blocker(&runtime) .or_else(|| { provider_action_batch_completion_blocker_at_locked( @@ -1898,7 +1982,11 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( ) }) .or_else(|| { - plan_gdd_completion_blocker_at_locked(&root, &agent_id, &runtime.run_id) + plan_gdd_typed_completion_blocker_at_locked(&root, &agent_id, &runtime.run_id) + .map(|blocker| { + plan_gdd_blocker_kind = Some(blocker.kind); + blocker.observation + }) }) .or_else(|| game_creator_agent_goal_completion_blocker_at_locked(&root, &runtime)) .or_else(|| goal_contract_acceptance_completion_blocker_at_locked(&root, &runtime)) @@ -1948,22 +2036,11 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( runtime.next_step = "先恢复原批次,不能请求新计划或提交最终回复".to_string(); } else if blocker.tool == "runtime.plan_gdd" { runtime.status = "running".to_string(); - if blocker.status == "blocked" - && blocker.detail.as_deref().is_some_and(|detail| { - detail.contains("approvalPending=awaiting_decision") - }) - { - runtime.phase = "waiting-for-user-input".to_string(); - runtime.current_action = "等待 Fast GDD 审批决定".to_string(); - runtime.waiting_on = "用户在审批卡选择批准、修改或退回".to_string(); - runtime.next_step = "等待 decide_game_creator_plan_gdd;不得重新提交同一 GDD 或自行创建审批 pending".to_string(); - } else { - runtime.phase = "needs-reconciliation".to_string(); - runtime.current_action = "Fast GDD 审批投影需要人工核对".to_string(); - runtime.waiting_on = "planning pending、receipt、原提交锚点、terminal observation、audit 与 session 的精确身份".to_string(); - runtime.next_step = - "先恢复或核对现有 durable 事实,不能请求新 Provider 计划".to_string(); - } + let projection = plan_gdd_blocker_runtime_projection(plan_gdd_blocker_kind); + runtime.phase = projection.phase.to_string(); + runtime.current_action = projection.current_action.to_string(); + runtime.waiting_on = projection.waiting_on.to_string(); + runtime.next_step = projection.next_step.to_string(); } else if blocker.tool == "runtime.collaboration_policy" { runtime.status = "running".to_string(); runtime.phase = "planning".to_string(); @@ -2126,23 +2203,7 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( AgentBackgroundTaskOutcome::WaitingForDelegateReceipts, )) } else if observation.tool == "runtime.plan_gdd" { - if observation.status == "blocked" - && detail.contains("approvalPending=awaiting_decision") - { - Some(( - "agent.runtime.plan.gdd.waiting", - "waiting-for-user-input", - "Fast GDD 审批等待状态持久化失败", - AgentBackgroundTaskOutcome::WaitingForUserInput, - )) - } else { - Some(( - "agent.runtime.plan.gdd.reconciliation", - "needs-reconciliation", - "Fast GDD 审批投影需要人工核对", - AgentBackgroundTaskOutcome::NeedsReconciliation, - )) - } + plan_gdd_blocker_waiting_kind(plan_gdd_blocker_kind) } else { None } @@ -4211,3 +4272,78 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( } } } + +#[cfg(test)] +mod plan_gdd_blocker_projection_tests { + use super::*; + + /// 三个 blocked 子状态必须落到各自的 phase。旧的子串判别只认得 + /// AwaitingApprovalDecision,另外两个会被打成 needs-reconciliation。 + #[test] + fn each_blocked_kind_projects_its_own_phase() { + assert_eq!( + plan_gdd_blocker_runtime_projection(Some( + PlanGddCompletionBlockerKind::SubmissionNotStarted + )) + .phase, + "planning" + ); + assert_eq!( + plan_gdd_blocker_runtime_projection(Some( + PlanGddCompletionBlockerKind::AwaitingApprovalDecision + )) + .phase, + "waiting-for-user-input" + ); + assert_eq!( + plan_gdd_blocker_runtime_projection(Some( + PlanGddCompletionBlockerKind::ReceiptAnchorCleanupPending + )) + .phase, + "planning" + ); + } + + /// 判不出 kind 与显式的人工核对一样,保持 fail-closed。 + #[test] + fn reconciliation_and_unknown_kind_stay_fail_closed() { + assert_eq!( + plan_gdd_blocker_runtime_projection(Some( + PlanGddCompletionBlockerKind::NeedsReconciliation + )) + .phase, + "needs-reconciliation" + ); + assert_eq!( + plan_gdd_blocker_runtime_projection(None).phase, + "needs-reconciliation" + ); + assert!(matches!( + plan_gdd_blocker_waiting_kind(None), + Some((_, _, _, AgentBackgroundTaskOutcome::NeedsReconciliation)) + )); + } + + /// 继续推进态不产生等待态,本轮后台任务不该在这里终结。 + #[test] + fn only_user_decision_and_reconciliation_end_the_background_task() { + assert!(matches!( + plan_gdd_blocker_waiting_kind(Some( + PlanGddCompletionBlockerKind::AwaitingApprovalDecision + )), + Some((_, "waiting-for-user-input", _, _)) + )); + assert!(matches!( + plan_gdd_blocker_waiting_kind(Some(PlanGddCompletionBlockerKind::NeedsReconciliation)), + Some((_, "needs-reconciliation", _, _)) + )); + assert!(plan_gdd_blocker_waiting_kind(Some( + PlanGddCompletionBlockerKind::SubmissionNotStarted + )) + .is_none()); + assert!(plan_gdd_blocker_waiting_kind(Some( + PlanGddCompletionBlockerKind::ReceiptAnchorCleanupPending + )) + .is_none()); + } +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs index 4827b3228..2fc3e0f43 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs @@ -819,12 +819,79 @@ fn durable_process_session_recovery_exists_at(root: &Path) -> bool { false } +/// Fast GDD approval 投影恢复失败时,把 fail-closed 收敛到受影响的那个 run。 +/// +/// 返回 `Ok(true)` 表示已经把策划根 Supervisor 标成 needs-reconciliation,调用方可以 +/// 继续扫描其余 Agent;`Ok(false)` 表示当前没有可归属的 run,无法精确收敛,调用方必须 +/// 把原错误照旧上抛,保持全局 fail-closed。 +fn contain_plan_gdd_approval_recovery_failure_at(root: &Path, error: &str) -> Result { + let Some(_runtime_lock) = try_acquire_game_creator_agent_runtime_task_lock( + root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + )? + else { + return Ok(false); + }; + let mut runtime = + read_game_creator_agent_runtime_at(root, GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID)?.state; + if runtime.run_id.trim().is_empty() + || matches!( + runtime.phase.as_str(), + "completed" | "cancelled" | "needs-reconciliation" + ) + { + return Ok(false); + } + let error = sanitize_agent_runtime_text(error, 500); + runtime.status = "failed".to_string(); + runtime.phase = "needs-reconciliation".to_string(); + runtime.current_action = "Fast GDD 审批投影恢复需要人工核对".to_string(); + runtime.waiting_on = "开发者核对 planning pending、receipt 与原提交锚点".to_string(); + runtime.next_step = "修复审批投影后显式恢复该 run".to_string(); + runtime.error = Some(error.clone()); + runtime.updated_at = unix_timestamp(); + append_game_creator_agent_runtime_task(root, &runtime)?; + refresh_game_creator_agent_runtime_task_queue(root, &mut runtime)?; + write_game_creator_agent_runtime_state(root, &runtime)?; + let _ = append_game_creator_agent_runtime_event( + root, + &runtime, + "plan.gdd.approval_recovery.needs_reconciliation", + "failed", + "needs-reconciliation", + "Fast GDD 审批投影恢复已停止自动重放,等待开发者核对。", + Some(&error), + ); + let _ = append_agent_db_record( + root, + serde_json::json!({ + "recordType": "agent.runtime.plan.gdd.approval_recovery.needs_reconciliation", + "agentId": runtime.agent_id, + "taskId": runtime.task_id, + "sessionId": runtime.session_id, + "runId": runtime.run_id, + "error": error, + }), + ); + emit_game_creator_agent_runtime_update(root, &runtime.agent_id); + Ok(true) +} + pub(in crate::agent) fn resume_game_creator_agent_background_tasks_unredacted_at( root: &Path, ) -> Result, String> { validate_project_root(root)?; - reconcile_plan_gdd_approval_projections_at(root) - .map_err(|error| format!("恢复 GDD approval 投影失败:{error}"))?; + // 这是一条只覆盖策划根 Supervisor 的窄投影恢复,却挂在整轮 resume 的最前面。 + // 原来用 `?` 强传播:一次 Fast GDD 投影失败会掐掉全项目所有 Agent 的恢复——而它 + // 本身正是 receipt 投影失败后的重试入口,掐掉它等于连兜底一起废掉。改成把 + // fail-closed 精确收敛到受影响的那个 run,其余 Agent 照常恢复;实在无法归属时 + // 才退回原来的全局上抛。 + if let Err(error) = reconcile_plan_gdd_approval_projections_at(root) { + let error = format!("恢复 GDD approval 投影失败:{error}"); + if !contain_plan_gdd_approval_recovery_failure_at(root, &error)? { + return Err(error); + } + } if external_agent_runner_owns_background_execution() { resume_external_agent_runner(root)?; return read_game_creator_agent_runtimes_at(root); @@ -1842,4 +1909,62 @@ mod plan_gdd_approval_wait_recovery_tests { "status 写成 waiting-for-user-input 才是恢复扫描让路的外部输入等待" ); } + + /// Fast GDD approval 投影恢复失败,不能再掐掉整轮 resume。 + /// + /// 它挂在 `resume_game_creator_agent_background_tasks_unredacted_at` 的第一行, + /// 原来用 `?` 强传播;而这条 reconcile 本身正是 receipt 投影失败后的重试入口, + /// 掐掉它等于连兜底一起废掉。现在 fail-closed 精确收敛到策划根 Supervisor 这个 run。 + #[test] + fn failed_plan_gdd_approval_recovery_contains_itself_instead_of_aborting_the_scan() { + let temporary = crate::tests::canonical_test_tempdir("plan-gdd-approval-recovery-contain-"); + let root = temporary.path(); + init_local_game_project_at(root, "plan-gdd-approval-contain", "审批投影恢复失败收敛") + .expect("init project"); + let runtime = start_game_creator_agent_runtime_task_at( + root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + "推进立项策划", + "plan-gdd-approval-contain-run", + "agent-ready-task-scheduler", + "准备推进立项策划", + vec!["推进立项策划".to_string()], + ) + .expect("start plan-root supervisor runtime"); + + let planning_directory = root.join(".agent/planning"); + fs::create_dir_all(&planning_directory).expect("create planning directory"); + fs::write(planning_directory.join("gdd.v1.json"), b"{") + .expect("corrupt the GDD lineage so approval recovery fails"); + assert!(reconcile_plan_gdd_approval_projections_at(root).is_err()); + + let resumed = resume_game_creator_agent_background_tasks_at(root) + .expect("窄投影恢复失败不能把整轮 resume 掐掉"); + assert!(resumed + .iter() + .all(|result| result.state.phase != "completed")); + + let contained = read_game_creator_agent_runtime_at(root, &runtime.agent_id) + .expect("read contained supervisor runtime"); + assert_eq!(contained.state.phase, "needs-reconciliation"); + assert!( + contained + .state + .error + .as_deref() + .is_some_and(|error| error.contains("恢复 GDD approval 投影失败")), + "unexpected error: {:?}", + contained.state.error + ); + let audit_count = read_agent_db_records_bounded(root, 1024 * 1024) + .expect("read approval recovery audit") + .0 + .iter() + .filter(|record| { + record.get("recordType").and_then(|value| value.as_str()) + == Some("agent.runtime.plan.gdd.approval_recovery.needs_reconciliation") + }) + .count(); + assert_eq!(audit_count, 1); + } } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_approval.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_approval.rs index 078645d70..9238c6d70 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_approval.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_approval.rs @@ -1288,16 +1288,69 @@ pub(crate) fn decide_plan_gdd_at( const PLAN_GDD_COMPLETION_BLOCKER_TOOL: &str = "runtime.plan_gdd"; +/// 为什么 `runtime.plan_gdd` 的 blocker 需要一个类型化的子状态: +/// +/// `status == "needs-reconciliation"` 已经把「要人工核对」和「继续推进」分开了, +/// 但 `"blocked"` 一侧有三种彼此完全不同的继续推进态,驱动侧必须区分才能选对 +/// phase 与 next_step。原来的做法是在 `main_loop` 里对 detail 做 +/// `contains("approvalPending=awaiting_decision")`:三个 blocked 里只有一个含这个 +/// 子串,另外两个会掉进 else 被打成 needs-reconciliation——把最正常的早期推进态和 +/// 收尾态当成故障停掉。子状态判别必须由构造方给出,不能让消费方去猜字符串。 +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum PlanGddCompletionBlockerKind { + /// 根 Run 还没提交 Fast GDD,下一步是 `agent.delegate`。 + SubmissionNotStarted, + /// Fast GDD 已提交,等待用户在审批卡上做决定。 + AwaitingApprovalDecision, + /// receipt 已落盘,原 `plan.submit_gdd` 恢复锚点还没清理完。 + ReceiptAnchorCleanupPending, + /// 其余一律要人工核对。 + NeedsReconciliation, +} + +pub(crate) struct PlanGddCompletionBlocker { + pub(crate) observation: AgentRuntimeToolObservation, + pub(crate) kind: PlanGddCompletionBlockerKind, +} + fn plan_gdd_completion_blocker( status: &str, summary: impl Into, detail: impl Into, -) -> AgentRuntimeToolObservation { - AgentRuntimeToolObservation { - tool: PLAN_GDD_COMPLETION_BLOCKER_TOOL.to_string(), - status: status.to_string(), - summary: summary.into(), - detail: Some(detail.into()), +) -> PlanGddCompletionBlocker { + debug_assert_ne!( + status, "blocked", + "blocked 子状态必须走 plan_gdd_blocked_completion_blocker 显式给出 kind" + ); + PlanGddCompletionBlocker { + observation: AgentRuntimeToolObservation { + tool: PLAN_GDD_COMPLETION_BLOCKER_TOOL.to_string(), + status: status.to_string(), + summary: summary.into(), + detail: Some(detail.into()), + }, + kind: PlanGddCompletionBlockerKind::NeedsReconciliation, + } +} + +fn plan_gdd_blocked_completion_blocker( + kind: PlanGddCompletionBlockerKind, + summary: impl Into, + detail: impl Into, +) -> PlanGddCompletionBlocker { + debug_assert_ne!( + kind, + PlanGddCompletionBlockerKind::NeedsReconciliation, + "blocked blocker 不能声明成人工核对" + ); + PlanGddCompletionBlocker { + observation: AgentRuntimeToolObservation { + tool: PLAN_GDD_COMPLETION_BLOCKER_TOOL.to_string(), + status: "blocked".to_string(), + summary: summary.into(), + detail: Some(detail.into()), + }, + kind, } } @@ -1585,11 +1638,22 @@ fn plan_root_completion_identity_at( /// committed GDD therefore remains blocked until the pending/receipt, /// generic child anchors, terminal observation, decision audit and planning /// session all form one exact durable state. +/// 只要 blocker 本身,不关心 blocked 的子状态。驱动侧(`main_loop`)必须改用 +/// `plan_gdd_typed_completion_blocker_at_locked`,否则又要去猜 detail 字符串。 pub(crate) fn plan_gdd_completion_blocker_at_locked( root: &Path, agent_id: &str, run_id: &str, ) -> Option { + plan_gdd_typed_completion_blocker_at_locked(root, agent_id, run_id) + .map(|blocker| blocker.observation) +} + +pub(crate) fn plan_gdd_typed_completion_blocker_at_locked( + root: &Path, + agent_id: &str, + run_id: &str, +) -> Option { let is_plan_root = match plan_root_completion_identity_at(root, agent_id, run_id) { Ok(value) => value, Err(error) => { @@ -1629,8 +1693,8 @@ pub(crate) fn plan_gdd_completion_blocker_at_locked( GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, run_id, ) { - Ok(Some(_)) => Some(plan_gdd_completion_blocker( - "blocked", + Ok(Some(_)) => Some(plan_gdd_blocked_completion_blocker( + PlanGddCompletionBlockerKind::SubmissionNotStarted, "当前立项策划根 Run 尚未提交 Fast GDD,不能收束任务", format!( "rootRunId={run_id} · nextRequiredAction=agent.delegate;上一根 Run 遗留的 game/fast_gdd.md 或 Acceptance Graph 不能代替本根提交" @@ -1818,8 +1882,8 @@ pub(crate) fn plan_gdd_completion_blocker_at_locked( ), )); } - return Some(plan_gdd_completion_blocker( - "blocked", + return Some(plan_gdd_blocked_completion_blocker( + PlanGddCompletionBlockerKind::AwaitingApprovalDecision, "Fast GDD 已提交,等待用户审批决定,不能收束任务", format!( "gddVersion={} · approvalPending=awaiting_decision · childPending={} · childBatch={};pending 只能由验收取证通过后的 acceptance-gate caller 创建", @@ -1852,8 +1916,8 @@ pub(crate) fn plan_gdd_completion_blocker_at_locked( } } if pending_anchor != PlanGddAnchorState::Absent || batch_anchor != PlanGddAnchorState::Absent { - return Some(plan_gdd_completion_blocker( - "blocked", + return Some(plan_gdd_blocked_completion_blocker( + PlanGddCompletionBlockerKind::ReceiptAnchorCleanupPending, "Fast GDD receipt 已提交,但原 plan.submit_gdd 恢复锚点尚未清理", format!( "gddVersion={} · terminalObservation={} · childPending={} · childBatch={}", diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_submit.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_submit.rs index d8667748e..5a7d4da17 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_submit.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_submit.rs @@ -3267,6 +3267,17 @@ mod tests { .expect("awaiting approval must block completion"); assert_eq!(blocker.status, "blocked"); assert!(blocker.summary.contains("等待用户审批")); + // 驱动侧按类型化子状态选 phase:这一条必须是「等用户决定」,不能被当成人工核对。 + assert_eq!( + plan_gdd_typed_completion_blocker_at_locked( + &root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + &context.root_run_id, + ) + .expect("awaiting approval blocker") + .kind, + PlanGddCompletionBlockerKind::AwaitingApprovalDecision + ); let decision_input = approval_input( &gdd, @@ -3377,6 +3388,18 @@ mod tests { .expect("current root without submission must block"); assert_eq!(blocker.status, "blocked"); assert!(blocker.summary.contains("尚未提交 Fast GDD")); + // 这是策划最正常的早期推进态,下一步是 agent.delegate。它的 detail 里没有 + // approvalPending 字段,旧的子串判别会把它打成 needs-reconciliation 停掉整条 run。 + assert_eq!( + plan_gdd_typed_completion_blocker_at_locked( + &root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + &context.root_run_id, + ) + .expect("submission-not-started blocker") + .kind, + PlanGddCompletionBlockerKind::SubmissionNotStarted + ); cleanup_fixture(root); } @@ -3421,6 +3444,16 @@ mod tests { "unexpected blocker: {}", blocker.summary ); + assert_eq!( + plan_gdd_typed_completion_blocker_at_locked( + &root, + GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, + &context.root_run_id, + ) + .expect("mismatched pending blocker") + .kind, + PlanGddCompletionBlockerKind::NeedsReconciliation + ); cleanup_fixture(root); } From abb39125303d326c92083512c3dbb6ee3bf306e9 Mon Sep 17 00:00:00 2001 From: kdletters Date: Mon, 17 Aug 2026 12:04:31 +0800 Subject: [PATCH 4/8] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=86=E6=94=AF?= =?UTF-8?q?=E4=B8=8E=E6=8F=90=E4=BA=A4=E6=90=9C=E7=B4=A2=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加分支和 commit 的输入搜索下拉构建前复核固定仓库中的分支与 commit 归属补充预览控制面接口合同、配置和测试 --- .../src/PreviewDeployerApp.test.tsx | 85 ++++ .../src/PreviewDeployerApp.tsx | 380 +++++++++++++++++- apps/preview-deployer-web/src/api.test.ts | 44 ++ apps/preview-deployer-web/src/api.ts | 31 ++ apps/preview-deployer-web/src/styles.css | 67 ++- deploy/env/preview-deployer.env.example | 4 + ...Jenkins容器预览部署控制面技术方案-2026-08-15.md | 5 + ...发运维】本地开发验证与生产运维-2026-05-15.md | 2 +- .../crates/preview-deployer-server/Cargo.toml | 2 +- .../preview-deployer-server/src/config.rs | 40 +- .../preview-deployer-server/src/git_refs.rs | 282 +++++++++++++ .../crates/preview-deployer-server/src/lib.rs | 153 ++++++- .../preview-deployer-server/src/tests.rs | 76 +++- 13 files changed, 1147 insertions(+), 24 deletions(-) create mode 100644 server-rs/crates/preview-deployer-server/src/git_refs.rs diff --git a/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx b/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx index 261e5a6ae..21f2b900d 100644 --- a/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx +++ b/apps/preview-deployer-web/src/PreviewDeployerApp.test.tsx @@ -24,6 +24,8 @@ beforeEach(() => { vi.mocked(api.createSession).mockResolvedValue({ authenticated: true }); vi.mocked(api.deleteSession).mockResolvedValue(undefined); vi.mocked(api.listDeployments).mockResolvedValue([]); + vi.mocked(api.searchBranches).mockResolvedValue([]); + vi.mocked(api.searchCommits).mockResolvedValue([]); vi.mocked(api.createDeployment).mockResolvedValue({ id: 'preview-1', branch: 'master', @@ -108,3 +110,86 @@ test('shows health and web url, then confirms uninstall', async () => { expect(api.uninstallDeployment).toHaveBeenCalledWith('preview-2'); }); }); + +test('shows debounced branch results and selects one with the keyboard', async () => { + const user = userEvent.setup(); + vi.mocked(api.searchBranches).mockResolvedValue([ + { name: 'feature/search-one', commitHash: '111111111111' }, + { name: 'feature/search-two', commitHash: '222222222222' }, + ]); + render(); + + const branchInput = await screen.findByRole('combobox', { name: '分支名' }); + await user.clear(branchInput); + await user.type(branchInput, 'feature/search'); + + expect( + await screen.findByRole('option', { name: /feature\/search-one/u }), + ).toBeTruthy(); + expect(api.searchBranches).toHaveBeenLastCalledWith( + 'feature/search', + expect.any(AbortSignal), + ); + await user.keyboard('{ArrowDown}{ArrowDown}{Enter}'); + expect((branchInput as HTMLInputElement).value).toBe('feature/search-two'); +}); + +test('searches commits in the current branch and selects a result', async () => { + const user = userEvent.setup(); + vi.mocked(api.searchCommits).mockResolvedValue([ + { + commitHash: 'aa5221abcdef0123456789', + shortHash: 'aa5221a', + subject: '补充预览搜索', + }, + ]); + render(); + + const commitInput = await screen.findByRole('combobox', { + name: 'Commit Hash', + }); + await user.type(commitInput, 'aa5221a'); + + const option = await screen.findByRole('option', { + name: /aa5221a.*补充预览搜索/u, + }); + expect(api.searchCommits).toHaveBeenCalledWith( + 'master', + 'aa5221a', + expect.any(AbortSignal), + ); + await user.click(option); + expect((commitInput as HTMLInputElement).value).toBe( + 'aa5221abcdef0123456789', + ); +}); + +test('clears commit and ignores stale commit responses when branch changes', async () => { + const user = userEvent.setup(); + let resolveOldSearch: ((items: api.CommitRef[]) => void) | undefined; + vi.mocked(api.searchCommits).mockImplementation( + () => + new Promise((resolve) => { + resolveOldSearch = resolve; + }), + ); + render(); + + const branchInput = await screen.findByRole('combobox', { name: '分支名' }); + const commitInput = screen.getByRole('combobox', { name: 'Commit Hash' }); + await user.type(commitInput, 'abcdef1'); + await waitFor(() => expect(api.searchCommits).toHaveBeenCalled()); + await user.clear(branchInput); + await user.type(branchInput, 'feature/new'); + + expect((commitInput as HTMLInputElement).value).toBe(''); + resolveOldSearch?.([ + { + commitHash: 'abcdef1234567890', + shortHash: 'abcdef1', + subject: '旧分支提交', + }, + ]); + await Promise.resolve(); + expect(screen.queryByText('旧分支提交')).toBeNull(); +}); diff --git a/apps/preview-deployer-web/src/PreviewDeployerApp.tsx b/apps/preview-deployer-web/src/PreviewDeployerApp.tsx index 2bfd2482a..45f7e7d80 100644 --- a/apps/preview-deployer-web/src/PreviewDeployerApp.tsx +++ b/apps/preview-deployer-web/src/PreviewDeployerApp.tsx @@ -13,15 +13,27 @@ import { TriangleAlert, XCircle, } from 'lucide-react'; -import { FormEvent, useCallback, useEffect, useMemo, useState } from 'react'; +import { + FormEvent, + KeyboardEvent as ReactKeyboardEvent, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; import { + type BranchRef, + type CommitRef, createDeployment, createSession, deleteSession, getSession, listDeployments, PreviewDeployerApiError, + searchBranches, + searchCommits, uninstallDeployment, } from './api'; import type { @@ -32,6 +44,7 @@ import type { import { validateBranch, validateCommitHash } from './validation'; const POLL_INTERVAL_MS = 5000; +const SEARCH_DEBOUNCE_MS = 300; const STATUS_LABELS: Record = { queued: '排队中', @@ -66,6 +79,16 @@ export function PreviewDeployerApp() { const [submitting, setSubmitting] = useState(false); const [notice, setNotice] = useState(''); const [error, setError] = useState(''); + const [branchSearch, setBranchSearch] = + useState>(emptySearchState()); + const [commitSearch, setCommitSearch] = + useState>(emptySearchState()); + const [branchActiveIndex, setBranchActiveIndex] = useState(-1); + const [commitActiveIndex, setCommitActiveIndex] = useState(-1); + const [branchSearchEnabled, setBranchSearchEnabled] = useState(false); + const [commitSearchEnabled, setCommitSearchEnabled] = useState(false); + const branchRequestId = useRef(0); + const commitRequestId = useRef(0); const [pendingUninstall, setPendingUninstall] = useState(null); const [uninstallingId, setUninstallingId] = useState(''); @@ -129,6 +152,94 @@ export function PreviewDeployerApp() { return () => window.clearInterval(interval); }, [refresh, sessionStatus]); + useEffect(() => { + const query = branch.trim(); + const requestId = ++branchRequestId.current; + const controller = new AbortController(); + if (sessionStatus !== 'authenticated' || !branchSearchEnabled || !query) { + setBranchSearch(emptySearchState()); + setBranchActiveIndex(-1); + return () => controller.abort(); + } + setBranchSearch({ items: [], loading: true, open: true, error: '' }); + setBranchActiveIndex(-1); + const timer = window.setTimeout(() => { + void searchBranches(query, controller.signal) + .then((items) => { + if (requestId !== branchRequestId.current) return; + setBranchSearch({ items, loading: false, open: true, error: '' }); + }) + .catch((searchError) => { + if ( + controller.signal.aborted || + requestId !== branchRequestId.current + ) + return; + if (isUnauthorized(searchError)) { + handleUnauthorized(); + return; + } + setBranchSearch({ + items: [], + loading: false, + open: true, + error: formatError(searchError), + }); + }); + }, SEARCH_DEBOUNCE_MS); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + }, [branch, branchSearchEnabled, sessionStatus]); + + useEffect(() => { + const query = commitHash.trim(); + const selectedBranch = branch.trim(); + const requestId = ++commitRequestId.current; + const controller = new AbortController(); + if ( + sessionStatus !== 'authenticated' || + !commitSearchEnabled || + !query || + validateBranch(selectedBranch) + ) { + setCommitSearch(emptySearchState()); + setCommitActiveIndex(-1); + return () => controller.abort(); + } + setCommitSearch({ items: [], loading: true, open: true, error: '' }); + setCommitActiveIndex(-1); + const timer = window.setTimeout(() => { + void searchCommits(selectedBranch, query, controller.signal) + .then((items) => { + if (requestId !== commitRequestId.current) return; + setCommitSearch({ items, loading: false, open: true, error: '' }); + }) + .catch((searchError) => { + if ( + controller.signal.aborted || + requestId !== commitRequestId.current + ) + return; + if (isUnauthorized(searchError)) { + handleUnauthorized(); + return; + } + setCommitSearch({ + items: [], + loading: false, + open: true, + error: formatError(searchError), + }); + }); + }, SEARCH_DEBOUNCE_MS); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + }, [branch, commitHash, commitSearchEnabled, sessionStatus]); + const runningCount = useMemo( () => deployments.filter((deployment) => deployment.status === 'running') @@ -356,36 +467,166 @@ export function PreviewDeployerApp() { className="deploy-form" onSubmit={(event) => void handleSubmit(event)} > -