-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathrouter.rs
More file actions
2499 lines (2254 loc) · 92.9 KB
/
Copy pathrouter.rs
File metadata and controls
2499 lines (2254 loc) · 92.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Forge Router
//!
//! Routes forge-specific APIs under `/api/forge/*` and upstream APIs under `/api/*`.
//! Serves single frontend (with overlay architecture) at `/`.
use axum::{
Json, Router,
extract::{
FromRef, Path, Query, State,
ws::{WebSocket, WebSocketUpgrade},
},
http::{HeaderValue, Method, StatusCode, header},
response::{Html, IntoResponse, Response},
routing::{get, post},
};
use futures_util::{SinkExt, StreamExt, TryStreamExt};
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tower_http::cors::{Any, CorsLayer};
use uuid::Uuid;
use crate::services::ForgeServices;
use db::models::{
image::TaskImage,
project::Project,
task::{Task, TaskWithAttemptStatus},
task_attempt::{CreateTaskAttempt, TaskAttempt},
};
use deployment::Deployment;
use executors::profile::ExecutorProfileId;
use forge_config::ForgeProjectSettings;
use server::routes::{
self as upstream, approvals, auth, config as upstream_config, containers, drafts, events,
execution_processes, filesystem, images, projects, tags, task_attempts, tasks,
};
use server::{DeploymentImpl, error::ApiError, routes::tasks::CreateAndStartTaskRequest};
use services::services::container::ContainerService;
use sqlx::{self, Error as SqlxError, Row};
use utils::log_msg::LogMsg;
use utils::response::ApiResponse;
use utils::text::{git_branch_id, short_uuid};
#[derive(RustEmbed)]
#[folder = "../frontend/dist"]
struct Frontend;
/// Type alias for TaskWithAttemptStatus which now includes attempt_count from upstream.
/// Kept for API compatibility during transition.
pub type ForgeTaskWithAttemptStatus = TaskWithAttemptStatus;
#[derive(Clone)]
struct ForgeAppState {
services: ForgeServices,
deployment: DeploymentImpl,
auth_required: bool,
}
impl ForgeAppState {
fn new(services: ForgeServices, deployment: DeploymentImpl, auth_required: bool) -> Self {
Self {
services,
deployment,
auth_required,
}
}
}
impl FromRef<ForgeAppState> for ForgeServices {
fn from_ref(state: &ForgeAppState) -> ForgeServices {
state.services.clone()
}
}
impl FromRef<ForgeAppState> for DeploymentImpl {
fn from_ref(state: &ForgeAppState) -> DeploymentImpl {
state.deployment.clone()
}
}
pub fn create_router(services: ForgeServices, auth_required: bool) -> Router {
let deployment = services.deployment.as_ref().clone();
let state = ForgeAppState::new(services, deployment.clone(), auth_required);
let upstream_api = upstream_api_router(&deployment);
// Configure CORS for Swagger UI and external API access
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::OPTIONS,
])
.allow_headers(Any);
Router::new()
.route("/health", get(health_check))
.route("/docs", get(serve_swagger_ui))
.route("/api/openapi.json", get(serve_openapi_spec))
.route("/api/routes", get(list_routes))
// Public PWA manifest - must be accessible without authentication
.route("/site.webmanifest", get(serve_assets_public))
.merge(forge_api_routes())
// Upstream API at /api
.nest("/api", upstream_api)
// Single frontend with overlay architecture
.fallback(frontend_handler)
.layer(cors)
.with_state(state)
}
fn forge_api_routes() -> Router<ForgeAppState> {
Router::new()
.route("/api/forge/auth-required", get(get_auth_required))
.route(
"/api/forge/config",
get(get_forge_config).put(update_forge_config),
)
.route(
"/api/forge/projects/{project_id}/settings",
get(get_project_settings).put(update_project_settings),
)
.route(
"/api/forge/projects/{project_id}/profiles",
get(get_project_profiles),
)
.route(
"/api/forge/projects/{project_id}/branch-status",
get(get_project_branch_status),
)
.route(
"/api/forge/projects/{project_id}/pull",
post(post_project_pull),
)
.route("/api/forge/omni/status", get(get_omni_status))
.route("/api/forge/omni/instances", get(list_omni_instances))
.route("/api/forge/omni/validate", post(validate_omni_config))
.route(
"/api/forge/omni/notifications",
get(list_omni_notifications),
)
.route("/api/forge/releases", get(get_github_releases))
.route(
"/api/forge/master-genie/{attempt_id}/neurons",
get(get_master_genie_neurons),
)
.route(
"/api/forge/neurons/{neuron_attempt_id}/subtasks",
get(get_neuron_subtasks),
)
.route(
"/api/forge/agents",
get(get_forge_agents).post(create_forge_agent),
)
// Branch-templates extension removed - using simple forge/ prefix
}
/// Forge-specific CreateTask that includes is_agent field
#[derive(Debug, Serialize, Deserialize)]
struct ForgeCreateTask {
pub project_id: Uuid,
pub title: String,
pub description: Option<String>,
pub parent_task_attempt: Option<Uuid>,
pub image_ids: Option<Vec<Uuid>>,
pub is_agent: Option<bool>, // Forge extension: mark as agent-managed task
}
/// Forge override: create task (standard behavior, no special status handling)
/// The is_agent field is kept for future use but not currently used in task creation
async fn forge_create_task(
State(deployment): State<DeploymentImpl>,
Json(payload): Json<ForgeCreateTask>,
) -> Result<Json<ApiResponse<Task>>, ApiError> {
let task_id = Uuid::new_v4();
let task = Task::create(
&deployment.db().pool,
&db::models::task::CreateTask {
project_id: payload.project_id,
title: payload.title,
description: payload.description,
parent_task_attempt: payload.parent_task_attempt,
image_ids: payload.image_ids.clone(),
},
task_id,
)
.await?;
if let Some(image_ids) = &payload.image_ids {
TaskImage::associate_many(&deployment.db().pool, task.id, image_ids).await?;
}
deployment
.track_if_analytics_allowed(
"task_created",
serde_json::json!({
"task_id": task.id.to_string(),
"project_id": task.project_id,
"has_description": task.description.is_some(),
"has_images": payload.image_ids.is_some(),
}),
)
.await;
Ok(Json(ApiResponse::success(task)))
}
/// Forge-specific CreateTaskAttemptBody that includes use_worktree field
#[derive(Debug, Serialize, Deserialize)]
struct ForgeCreateTaskAttemptBody {
pub task_id: Uuid,
pub executor_profile_id: ExecutorProfileId,
pub base_branch: String,
pub use_worktree: Option<bool>,
}
impl ForgeCreateTaskAttemptBody {
pub fn get_executor_profile_id(&self) -> ExecutorProfileId {
self.executor_profile_id.clone()
}
}
/// Forge override: create task attempt with forge/ branch prefix (vk -> forge only)
async fn forge_create_task_attempt(
State(deployment): State<DeploymentImpl>,
State(forge_services): State<ForgeServices>,
Json(payload): Json<ForgeCreateTaskAttemptBody>,
) -> Result<Json<ApiResponse<TaskAttempt>>, ApiError> {
let executor_profile_id = payload.get_executor_profile_id();
let task = Task::find_by_id(&deployment.db().pool, payload.task_id)
.await?
.ok_or(ApiError::Database(SqlxError::RowNotFound))?;
let attempt_id = Uuid::new_v4();
let use_worktree = payload.use_worktree.unwrap_or(true);
// If use_worktree is false, use the current branch (base_branch) directly
// Otherwise, generate a new branch name for the worktree with "forge" prefix
let git_branch_name = if use_worktree {
let task_title_id = git_branch_id(&task.title);
let short_id = short_uuid(&attempt_id);
format!("forge/{}-{}", short_id, task_title_id)
} else {
payload.base_branch.clone()
};
let mut task_attempt = TaskAttempt::create(
&deployment.db().pool,
&CreateTaskAttempt {
executor: executor_profile_id.executor,
base_branch: payload.base_branch.clone(),
branch: git_branch_name.clone(),
},
attempt_id,
payload.task_id,
)
.await?;
// Insert use_worktree flag into forge_task_attempt_config
sqlx::query(
"INSERT INTO forge_task_attempt_config (task_attempt_id, use_worktree) VALUES (?, ?)",
)
.bind(attempt_id)
.bind(use_worktree)
.execute(&deployment.db().pool)
.await?;
// Store executor with variant for agent task filtering
if let Some(variant) = &executor_profile_id.variant {
let executor_with_variant = format!("{}:{}", executor_profile_id.executor, variant);
sqlx::query(
"UPDATE task_attempts SET executor = ?, updated_at = datetime('now') WHERE id = ?",
)
.bind(&executor_with_variant)
.bind(attempt_id)
.execute(&deployment.db().pool)
.await?;
task_attempt.executor = executor_with_variant;
}
// Get project to determine workspace root
let project = task
.parent_project(&deployment.db().pool)
.await?
.ok_or(ApiError::Database(SqlxError::RowNotFound))?;
// Load workspace-specific .genie profiles and inject into global cache just-in-time
if let Ok(workspace_profiles) = forge_services
.load_profiles_for_workspace(&project.git_repo_path)
.await
{
// Log profile details for validation
let variant_count = workspace_profiles
.executors
.values()
.map(|config| config.configurations.len())
.sum::<usize>();
let variant_list: Vec<String> = workspace_profiles
.executors
.iter()
.flat_map(|(executor, config)| {
config
.configurations
.iter()
.map(move |(variant, coding_agent)| {
// Extract append_prompt from the CodingAgent enum
let prompt_preview = match coding_agent {
executors::executors::CodingAgent::ClaudeCode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Codex(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Amp(cfg) => cfg.append_prompt.get(),
executors::executors::CodingAgent::Gemini(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Opencode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::CursorAgent(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::QwenCode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Copilot(cfg) => {
cfg.append_prompt.get()
}
}
.map(|p| {
let trimmed = p.trim();
if trimmed.len() > 60 {
format!("{}...", &trimmed[..60])
} else {
trimmed.to_string()
}
})
.unwrap_or_else(|| "<none>".to_string());
format!("{}:{} ({})", executor, variant, prompt_preview)
})
})
.collect();
tracing::info!(
"🔧 Injected {} .genie profile variant(s) for workspace: {} | Profiles: [{}]",
variant_count,
project.git_repo_path.display(),
variant_list.join(", ")
);
executors::profile::ExecutorConfigs::set_cached(workspace_profiles);
// Register project in profile cache for subsequent API lookups
forge_services
.profile_cache
.register_project(project.id, project.git_repo_path.clone())
.await;
} else {
tracing::warn!(
"⚠️ Failed to load .genie profiles for workspace: {}, using defaults",
project.git_repo_path.display()
);
}
let _execution_process = deployment
.container()
.start_attempt(&task_attempt, executor_profile_id.clone())
.await?;
deployment
.track_if_analytics_allowed(
"task_attempt_started",
serde_json::json!({
"task_id": task.id.to_string(),
"executor": &executor_profile_id.executor,
"attempt_id": task_attempt.id.to_string(),
}),
)
.await;
Ok(Json(ApiResponse::success(task_attempt)))
}
/// Forge override: create task and start with forge/ branch prefix (vk -> forge only)
async fn forge_create_task_and_start(
State(deployment): State<DeploymentImpl>,
State(forge_services): State<ForgeServices>,
Json(payload): Json<CreateAndStartTaskRequest>,
) -> Result<Json<ApiResponse<ForgeTaskWithAttemptStatus>>, ApiError> {
let task_id = Uuid::new_v4();
let task = Task::create(&deployment.db().pool, &payload.task, task_id).await?;
if let Some(image_ids) = &payload.task.image_ids {
TaskImage::associate_many(&deployment.db().pool, task.id, image_ids).await?;
}
// If this is a non-worktree task (Genie chat), register in forge_agents to hide from kanban
let use_worktree = payload.use_worktree.unwrap_or(true);
if !use_worktree {
// Use transaction for atomicity (both succeed or both fail)
let mut tx = deployment.db().pool.begin().await?;
sqlx::query(
r#"INSERT INTO forge_agents (id, project_id, agent_type, task_id, created_at, updated_at)
VALUES (?, ?, 'genie_chat', ?, datetime('now'), datetime('now'))"#,
)
.bind(Uuid::new_v4())
.bind(task.project_id)
.bind(task.id)
.execute(&mut *tx)
.await?;
// Also set task status to 'agent' so it's filtered from kanban board
sqlx::query(
"UPDATE tasks SET status = 'agent', updated_at = datetime('now') WHERE id = ?",
)
.bind(task.id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
}
deployment
.track_if_analytics_allowed(
"task_created",
serde_json::json!({
"task_id": task.id.to_string(),
"project_id": task.project_id,
"has_description": task.description.is_some(),
"has_images": payload.task.image_ids.is_some(),
}),
)
.await;
let task_attempt_id = Uuid::new_v4();
// Branch naming respects use_worktree: if false, run on base branch directly (no worktree isolation)
let branch_name = if use_worktree {
// Use same logic as upstream but replace "vk" with "forge" prefix
let task_title_id = git_branch_id(&task.title);
let short_id = short_uuid(&task_attempt_id);
format!("forge/{}-{}", short_id, task_title_id)
} else {
// Non-worktree mode: run directly on base branch (e.g., Genie chat)
payload.base_branch.clone()
};
let mut task_attempt = TaskAttempt::create(
&deployment.db().pool,
&CreateTaskAttempt {
executor: payload.executor_profile_id.executor,
base_branch: payload.base_branch.clone(),
branch: branch_name,
},
task_attempt_id,
task.id,
)
.await?;
// Insert use_worktree flag into forge_task_attempt_config
sqlx::query(
"INSERT INTO forge_task_attempt_config (task_attempt_id, use_worktree) VALUES (?, ?)",
)
.bind(task_attempt_id)
.bind(use_worktree)
.execute(&deployment.db().pool)
.await?;
// Store executor with variant for agent task filtering
if let Some(variant) = &payload.executor_profile_id.variant {
let executor_with_variant = format!("{}:{}", payload.executor_profile_id.executor, variant);
sqlx::query(
"UPDATE task_attempts SET executor = ?, updated_at = datetime('now') WHERE id = ?",
)
.bind(&executor_with_variant)
.bind(task_attempt_id)
.execute(&deployment.db().pool)
.await?;
task_attempt.executor = executor_with_variant;
}
// Get project to determine workspace root
let project = task
.parent_project(&deployment.db().pool)
.await?
.ok_or(ApiError::Database(SqlxError::RowNotFound))?;
// Load workspace-specific .genie profiles and inject into global cache just-in-time
if let Ok(workspace_profiles) = forge_services
.load_profiles_for_workspace(&project.git_repo_path)
.await
{
// Log profile details for validation
let variant_count = workspace_profiles
.executors
.values()
.map(|config| config.configurations.len())
.sum::<usize>();
let variant_list: Vec<String> = workspace_profiles
.executors
.iter()
.flat_map(|(executor, config)| {
config
.configurations
.iter()
.map(move |(variant, coding_agent)| {
// Extract append_prompt from the CodingAgent enum
let prompt_preview = match coding_agent {
executors::executors::CodingAgent::ClaudeCode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Codex(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Amp(cfg) => cfg.append_prompt.get(),
executors::executors::CodingAgent::Gemini(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Opencode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::CursorAgent(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::QwenCode(cfg) => {
cfg.append_prompt.get()
}
executors::executors::CodingAgent::Copilot(cfg) => {
cfg.append_prompt.get()
}
}
.map(|p| {
let trimmed = p.trim();
if trimmed.len() > 60 {
format!("{}...", &trimmed[..60])
} else {
trimmed.to_string()
}
})
.unwrap_or_else(|| "<none>".to_string());
format!("{}:{} ({})", executor, variant, prompt_preview)
})
})
.collect();
tracing::info!(
"🔧 Injected {} .genie profile variant(s) for workspace: {} | Profiles: [{}]",
variant_count,
project.git_repo_path.display(),
variant_list.join(", ")
);
executors::profile::ExecutorConfigs::set_cached(workspace_profiles);
// Register project in profile cache for subsequent API lookups
forge_services
.profile_cache
.register_project(project.id, project.git_repo_path.clone())
.await;
} else {
tracing::warn!(
"⚠️ Failed to load .genie profiles for workspace: {}, using defaults",
project.git_repo_path.display()
);
}
let execution_process = deployment
.container()
.start_attempt(&task_attempt, payload.executor_profile_id.clone())
.await?;
deployment
.track_if_analytics_allowed(
"task_attempt_started",
serde_json::json!({
"task_id": task.id.to_string(),
"executor": &payload.executor_profile_id.executor,
"variant": &payload.executor_profile_id.variant,
"attempt_id": task_attempt.id.to_string(),
}),
)
.await;
let task = Task::find_by_id(&deployment.db().pool, task.id)
.await?
.ok_or(ApiError::Database(SqlxError::RowNotFound))?;
tracing::info!(
"Started execution process {} with forge/ branch",
execution_process.id
);
Ok(Json(ApiResponse::success(TaskWithAttemptStatus {
task,
has_in_progress_attempt: true,
has_merged_attempt: false,
last_attempt_failed: false,
executor: task_attempt.executor,
attempt_count: 1, // First attempt just created
})))
}
fn upstream_api_router(deployment: &DeploymentImpl) -> Router<ForgeAppState> {
let mut router = Router::new().route("/health", get(upstream::health::health_check));
let dep_clone = deployment.clone();
// Forge override: config router with increased body limit for /profiles
router = router.merge(forge_config_router().with_state::<ForgeAppState>(dep_clone.clone()));
router =
router.merge(containers::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
router =
router.merge(projects::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
router =
router.merge(drafts::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
// Build custom tasks router with forge override (already typed as ForgeAppState)
let tasks_router_with_override = build_tasks_router_with_forge_override(deployment);
router = router.merge(tasks_router_with_override);
// Build custom task_attempts router with forge override (already typed as ForgeAppState)
let task_attempts_router_with_override =
build_task_attempts_router_with_forge_override(deployment);
router = router.merge(task_attempts_router_with_override);
router = router.merge(
execution_processes::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()),
);
router = router.merge(auth::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
router = router.merge(tags::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
router = router.merge(filesystem::router().with_state::<ForgeAppState>(dep_clone.clone()));
router =
router.merge(events::router(deployment).with_state::<ForgeAppState>(dep_clone.clone()));
router = router.merge(approvals::router().with_state::<ForgeAppState>(dep_clone.clone()));
router.nest(
"/images",
forge_images_router().with_state::<ForgeAppState>(dep_clone),
)
}
/// Build tasks router with forge override for create-and-start endpoint
fn build_tasks_router_with_forge_override(deployment: &DeploymentImpl) -> Router<ForgeAppState> {
use axum::middleware::from_fn_with_state;
use server::middleware::load_task_middleware;
let task_id_router = Router::new()
.route(
"/",
get(tasks::get_task)
.put(tasks::update_task)
.delete(tasks::delete_task),
)
.layer(from_fn_with_state(deployment.clone(), load_task_middleware));
let inner = Router::new()
.route("/", get(forge_get_tasks).post(forge_create_task)) // Forge: override list to exclude agent tasks; creation only
.route("/stream/ws", get(forge_stream_tasks_ws)) // Forge: WebSocket stream with agent filtering
.route("/create-and-start", post(forge_create_task_and_start)) // Forge: create + start
.nest("/{task_id}", task_id_router);
Router::new().nest("/tasks", inner)
}
#[derive(Deserialize)]
struct GetTasksParams {
project_id: Uuid,
}
/// Forge override for list tasks: Exclude agent tasks (those in forge_agents table)
/// Agent tasks are managed separately via /api/forge/agents
async fn forge_get_tasks(
State(deployment): State<DeploymentImpl>,
Query(params): Query<GetTasksParams>,
) -> Result<Json<ApiResponse<Vec<ForgeTaskWithAttemptStatus>>>, ApiError> {
let pool = &deployment.db().pool;
// Exclude tasks that are registered as agent tasks in forge_agents table
let query_str = r#"SELECT
t.id AS "id",
t.project_id AS "project_id",
t.title,
t.description,
t.status AS "status",
t.parent_task_attempt AS "parent_task_attempt",
t.created_at AS "created_at",
t.updated_at AS "updated_at",
CASE WHEN EXISTS (
SELECT 1
FROM task_attempts ta
JOIN execution_processes ep
ON ep.task_attempt_id = ta.id
WHERE ta.task_id = t.id
AND ep.status = 'running'
AND ep.run_reason IN ('setupscript','cleanupscript','codingagent')
LIMIT 1
) THEN 1 ELSE 0 END AS has_in_progress_attempt,
CASE WHEN (
SELECT ep.status
FROM task_attempts ta
JOIN execution_processes ep
ON ep.task_attempt_id = ta.id
WHERE ta.task_id = t.id
AND ep.run_reason IN ('setupscript','cleanupscript','codingagent')
ORDER BY ep.created_at DESC
LIMIT 1
) IN ('failed','killed') THEN 1 ELSE 0 END
AS last_attempt_failed,
( SELECT ta.executor
FROM task_attempts ta
WHERE ta.task_id = t.id
ORDER BY ta.created_at DESC
LIMIT 1
) AS executor,
( SELECT COUNT(*)
FROM task_attempts ta
WHERE ta.task_id = t.id
) AS attempt_count
FROM tasks t
WHERE t.project_id = ?
AND t.id NOT IN (SELECT task_id FROM forge_agents)
ORDER BY t.created_at DESC"#;
let rows = sqlx::query(query_str)
.bind(params.project_id)
.fetch_all(pool)
.await?;
let mut items: Vec<ForgeTaskWithAttemptStatus> = Vec::with_capacity(rows.len());
for row in rows {
let task_id: Uuid = row.try_get("id").map_err(ApiError::Database)?;
let task = db::models::task::Task::find_by_id(pool, task_id)
.await?
.ok_or(ApiError::Database(SqlxError::RowNotFound))?;
let has_in_progress_attempt = row
.try_get::<i64, _>("has_in_progress_attempt")
.map(|v| v != 0)
.unwrap_or(false);
let last_attempt_failed = row
.try_get::<i64, _>("last_attempt_failed")
.map(|v| v != 0)
.unwrap_or(false);
let executor: String = row.try_get("executor").unwrap_or_else(|_| String::new());
let attempt_count: i64 = row.try_get::<i64, _>("attempt_count").unwrap_or(0);
items.push(TaskWithAttemptStatus {
task,
has_in_progress_attempt,
has_merged_attempt: false,
last_attempt_failed,
executor,
attempt_count,
});
}
Ok(Json(ApiResponse::success(items)))
}
/// Forge WebSocket stream handler with agent task filtering
/// Streams tasks for a project via WebSocket, excluding agent tasks
#[derive(Deserialize)]
struct TaskQuery {
project_id: Uuid,
}
async fn forge_stream_tasks_ws(
ws: WebSocketUpgrade,
State(deployment): State<DeploymentImpl>,
Query(query): Query<TaskQuery>,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| async move {
if let Err(e) = handle_forge_tasks_ws(socket, deployment, query.project_id).await {
tracing::warn!("forge tasks WS closed: {}", e);
}
})
}
async fn handle_forge_tasks_ws(
socket: WebSocket,
deployment: DeploymentImpl,
project_id: Uuid,
) -> anyhow::Result<()> {
let pool = deployment.db().pool.clone();
// Batch query for all agent task IDs at initialization (fixes N+1 pattern)
let agent_task_ids: Arc<RwLock<HashSet<Uuid>>> = {
let agent_tasks: Vec<Uuid> = sqlx::query_scalar(
"SELECT task_id FROM forge_agents fa
INNER JOIN tasks t ON fa.task_id = t.id
WHERE t.project_id = ?",
)
.bind(project_id)
.fetch_all(&pool)
.await
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to fetch initial agent task IDs for project {}: {}",
project_id,
e
);
Vec::new()
});
Arc::new(RwLock::new(agent_tasks.into_iter().collect()))
};
// Spawn background task to refresh agent task IDs periodically
// Store the handle so we can abort it when the WebSocket closes
let refresh_cache = agent_task_ids.clone();
let refresh_pool = pool.clone();
let refresh_project_id = project_id;
let refresh_task_handle = tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(5));
loop {
interval.tick().await;
match sqlx::query_scalar::<_, Uuid>(
"SELECT task_id FROM forge_agents fa
INNER JOIN tasks t ON fa.task_id = t.id
WHERE t.project_id = ?",
)
.bind(refresh_project_id)
.fetch_all(&refresh_pool)
.await
{
Ok(tasks) => {
let mut cache = refresh_cache.write().await;
cache.clear();
cache.extend(tasks);
tracing::trace!(
"Refreshed agent task cache for project {}: {} tasks",
refresh_project_id,
cache.len()
);
}
Err(e) => {
tracing::warn!(
"Failed to refresh agent task cache for project {}: {}",
refresh_project_id,
e
);
}
}
}
});
// Get the raw stream from upstream (includes initial snapshot + live updates)
// Filter out agent tasks using cache with DB fallback for unknown tasks
let stream = deployment
.events()
.stream_tasks_raw(project_id)
.await?
.filter_map(move |msg_result| {
let agent_task_ids = agent_task_ids.clone();
let pool = pool.clone();
async move {
match msg_result {
Ok(LogMsg::JsonPatch(patch)) => {
// Check if this patch contains agent tasks we need to filter out
if let Some(patch_op) = patch.0.first() {
// Handle direct task patches (new format)
if patch_op.path().starts_with("/tasks/") {
match patch_op {
json_patch::PatchOperation::Add(op) => {
if let Ok(task_with_status) =
serde_json::from_value::<TaskWithAttemptStatus>(
op.value.clone(),
)
{
let task_id = task_with_status.task.id;
// First check cache (read lock, released before any await)
let in_cache = {
let cache = agent_task_ids.read().await;
cache.contains(&task_id)
};
let is_agent = if in_cache {
true
} else {
// Fallback: DB query for tasks not in cache
// This ensures newly created agent tasks are filtered immediately
let is_agent_db: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM forge_agents WHERE task_id = ?)",
)
.bind(task_id)
.fetch_one(&pool)
.await
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to check forge_agents for task {}: {}",
task_id,
e
);
false
});
// If it's an agent, update cache so subsequent patches don't hit DB
if is_agent_db {
let mut cache = agent_task_ids.write().await;
cache.insert(task_id);
}
is_agent_db
};
if !is_agent {
// Upstream patches now include attempt_count, pass through directly
let patch = json_patch::Patch(vec![
json_patch::PatchOperation::Add(
json_patch::AddOperation {
path: op.path.clone(),
value: op.value.clone(),
},
),
]);
return Some(Ok(LogMsg::JsonPatch(patch)));
}
// Filter out agent tasks
return None;
}
}
json_patch::PatchOperation::Replace(op) => {
if let Ok(task_with_status) =
serde_json::from_value::<TaskWithAttemptStatus>(
op.value.clone(),
)
{
let task_id = task_with_status.task.id;
// First check cache (read lock, released before any await)
let in_cache = {
let cache = agent_task_ids.read().await;
cache.contains(&task_id)
};
let is_agent = if in_cache {
true
} else {
// Fallback: DB query for tasks not in cache
// This ensures newly created agent tasks are filtered immediately
let is_agent_db: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM forge_agents WHERE task_id = ?)",
)
.bind(task_id)
.fetch_one(&pool)
.await
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to check forge_agents for task {}: {}",
task_id,
e
);
false
});
// If it's an agent, update cache so subsequent patches don't hit DB
if is_agent_db {
let mut cache = agent_task_ids.write().await;
cache.insert(task_id);
}
is_agent_db
};
if !is_agent {
// Upstream patches now include attempt_count, pass through directly
let patch = json_patch::Patch(vec![
json_patch::PatchOperation::Replace(
json_patch::ReplaceOperation {
path: op.path.clone(),
value: op.value.clone(),
},
),
]);
return Some(Ok(LogMsg::JsonPatch(patch)));
}
// Filter out agent tasks
return None;
}
}
json_patch::PatchOperation::Remove(_) => {
// Allow all remove operations