mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-26 15:40:18 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a08e487831 | ||
|
|
d029f487cd | ||
|
|
f2ea66b0c1 |
@@ -6,7 +6,7 @@
|
||||
|
||||
## Change Type
|
||||
|
||||
<!-- Check one -->
|
||||
<!-- Check all that apply. Refactor-only PRs are for core team or maintainer-requested work. -->
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
@@ -18,16 +18,19 @@
|
||||
|
||||
## Linked Issue
|
||||
|
||||
<!-- Closes #N, or "None" -->
|
||||
<!-- Closes #N, Fixes #N, Related #N, or "None". New feature PRs must link an approved issue. -->
|
||||
|
||||
## Validation
|
||||
|
||||
<!-- How did you verify this works? -->
|
||||
|
||||
- [ ] `cargo fmt`
|
||||
- [ ] `cargo clippy --all --benches --tests --examples --all-features`
|
||||
- [ ] `cargo fmt --all -- --check`
|
||||
- [ ] `cargo clippy --all --benches --tests --examples --all-features -- -D warnings`
|
||||
- [ ] `cargo build`
|
||||
- [ ] Relevant tests pass: <!-- list specific tests -->
|
||||
- [ ] `cargo test --features integration` if database-backed or integration behavior changed
|
||||
- [ ] Manual testing: <!-- describe what you tested -->
|
||||
- [ ] If a coding agent was used and supports it, `review-pr` or `pr-shepherd --fix` was run before requesting review
|
||||
|
||||
## Security Impact
|
||||
|
||||
@@ -45,6 +48,10 @@
|
||||
|
||||
<!-- How to revert if this causes problems? For Track C changes, this is mandatory. -->
|
||||
|
||||
## Review Follow-Through
|
||||
|
||||
<!-- Review conversations are author-owned. Summarize any known follow-up or areas where reviewer judgment is still needed. -->
|
||||
|
||||
---
|
||||
|
||||
**Review track**: <!-- A (docs/tests/chore) | B (feature/refactor) | C (security/runtime/DB/CI) -->
|
||||
**Review track**: <!-- A (docs/tests/chore) | B (feature/maintainer-requested refactor) | C (security/runtime/DB/CI) -->
|
||||
|
||||
+76
-1
@@ -10,6 +10,42 @@ cd ironclaw
|
||||
|
||||
This installs the Rust toolchain, WASM targets, git hooks, and runs initial checks.
|
||||
|
||||
## How to Contribute
|
||||
|
||||
- Bug fixes, docs improvements, and focused cleanup tied to a concrete problem are welcome.
|
||||
- Search existing issues and PRs before opening a new one to avoid duplicates.
|
||||
- Keep changes scoped. One bug, one feature, or one documentation improvement per PR.
|
||||
|
||||
### Creating Issues
|
||||
|
||||
Open an issue when you are reporting a bug, proposing a feature, or documenting a gap in behavior.
|
||||
|
||||
For bug reports, include:
|
||||
|
||||
- What you expected to happen
|
||||
- What actually happened
|
||||
- Clear reproduction steps
|
||||
- Relevant logs, screenshots, or error output
|
||||
- Environment details when they matter (OS, database backend, feature flags, commit/branch)
|
||||
|
||||
For feature requests:
|
||||
|
||||
- Open an issue first before writing code
|
||||
- Explain the problem being solved, not just the implementation idea
|
||||
- Wait for maintainer feedback before investing in a large PR
|
||||
|
||||
We require an issue for new features so maintainers can prioritize the work and confirm it fits the roadmap before anyone spends time implementing it.
|
||||
|
||||
### Fixing Bugs
|
||||
|
||||
- Small, targeted bug-fix PRs are welcome
|
||||
- If there is already an issue, link it in your PR
|
||||
- If the bug is non-trivial, security-sensitive, or changes behavior across subsystems, open or confirm an issue first so the approach can be aligned before implementation
|
||||
|
||||
### Refactor-Only PRs
|
||||
|
||||
Refactor-only PRs are not accepted from contributors outside the core team. If a refactor is necessary to land a bug fix or approved feature, keep it minimal and clearly tied to that change.
|
||||
|
||||
## Development Workflow
|
||||
|
||||
```bash
|
||||
@@ -19,6 +55,45 @@ cargo test # unit tests
|
||||
cargo test --features integration # + PostgreSQL tests
|
||||
```
|
||||
|
||||
These commands are for day-to-day iteration while you are developing locally. The pre-submission checks below are intentionally stricter and use CI-style flags so you can catch formatting drift and clippy warnings before requesting review.
|
||||
|
||||
## Before You Open a PR
|
||||
|
||||
Run the local validation checks required before requesting a review. These are stricter than the commands for iterative development:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --all --benches --tests --examples --all-features -- -D warnings
|
||||
cargo build
|
||||
cargo test
|
||||
```
|
||||
|
||||
Also run this when your change touches database-backed or integration behavior:
|
||||
|
||||
```bash
|
||||
cargo test --features integration
|
||||
```
|
||||
|
||||
Before asking for review:
|
||||
|
||||
- Build and exercise the changed path locally, not just the narrowest unit test
|
||||
- Keep the PR focused and avoid mixing unrelated concerns
|
||||
- Fill out the PR template with a clear summary, validation notes, and impact assessment
|
||||
- If your change affects tracked behavior, update `FEATURE_PARITY.md` in the same branch
|
||||
- If onboarding or setup behavior changes, update the relevant setup docs in the same branch
|
||||
- If you are using a coding agent and it supports them, run `review-pr` or `pr-shepherd --fix` before opening or updating the PR
|
||||
- `codex review --base origin/main` is also encouraged before requesting review
|
||||
|
||||
## Review Follow-Through
|
||||
|
||||
Review conversations are author-owned.
|
||||
|
||||
- Address each review comment with a code change or a clear explanation
|
||||
- Resolve conversations you have handled; leave them open only when reviewer judgment is still needed
|
||||
- Do not leave review cleanup for maintainers when the follow-through belongs to the author
|
||||
|
||||
If a PR is stale for more than 48 hours after review feedback is posted, maintainers may take over the follow-up work and land the changes needed to accomplish the original PR or issue intent.
|
||||
|
||||
## Code Style
|
||||
|
||||
- Zero clippy warnings policy
|
||||
@@ -46,7 +121,7 @@ All PRs follow a risk-based review process:
|
||||
| Track | Scope | Requirements |
|
||||
|-------|-------|-------------|
|
||||
| **A** | Docs, tests, chore, dependency bumps | 1 approval + CI green |
|
||||
| **B** | Features, refactors, new tools/channels | 1 approval + CI green + test evidence |
|
||||
| **B** | Features, maintainer-requested refactors, new tools/channels | 1 approval + CI green + test evidence |
|
||||
| **C** | Security (`src/safety/`, `src/secrets/`), runtime (`src/agent/`, `src/worker/`), database schema, CI workflows | 2 approvals + rollback plan documented |
|
||||
|
||||
Select the appropriate track in the PR template based on what your changes touch.
|
||||
|
||||
@@ -14,7 +14,6 @@ use uuid::Uuid;
|
||||
use crate::channels::web::auth::AuthenticatedUser;
|
||||
use crate::channels::web::server::GatewayState;
|
||||
use crate::channels::web::types::*;
|
||||
use crate::channels::web::util::{sanitized_db_error, sanitized_internal_error_response};
|
||||
|
||||
pub async fn jobs_list_handler(
|
||||
State(state): State<Arc<GatewayState>>,
|
||||
@@ -214,7 +213,10 @@ pub async fn jobs_detail_handler(
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get sandbox job detail"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +257,10 @@ pub async fn jobs_detail_handler(
|
||||
}))
|
||||
}
|
||||
Ok(None) => Err((StatusCode::NOT_FOUND, "Job not found".to_string())),
|
||||
Err(e) => Err(sanitized_db_error(e, "get agent job detail")),
|
||||
Err(e) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +295,7 @@ pub async fn jobs_cancel_handler(
|
||||
Some(chrono::Utc::now()),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "persist sandbox job cancellation"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
}
|
||||
return Ok(Json(serde_json::json!({
|
||||
"status": "cancelled",
|
||||
@@ -299,7 +304,10 @@ pub async fn jobs_cancel_handler(
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get sandbox job for cancellation"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,7 +341,7 @@ pub async fn jobs_cancel_handler(
|
||||
Some("Cancelled by user"),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "persist agent job cancellation"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
}
|
||||
return Ok(Json(serde_json::json!({
|
||||
"status": "cancelled",
|
||||
@@ -342,7 +350,10 @@ pub async fn jobs_cancel_handler(
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get agent job for cancellation"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -410,7 +421,7 @@ pub async fn jobs_restart_handler(
|
||||
store
|
||||
.save_sandbox_job(&record)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "persist restarted sandbox job"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let mode = match store.get_sandbox_job_mode(old_job_id).await {
|
||||
Ok(Some(m)) if m == "claude_code" => {
|
||||
@@ -441,13 +452,16 @@ pub async fn jobs_restart_handler(
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
sanitized_internal_error_response(e, "create restarted sandbox container")
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Failed to create container: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
store
|
||||
.update_sandbox_job_status(new_job_id, "running", None, None, Some(now), None)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "mark restarted sandbox job running"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
return Ok(Json(serde_json::json!({
|
||||
"status": "restarted",
|
||||
@@ -457,7 +471,10 @@ pub async fn jobs_restart_handler(
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get sandbox job for restart"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -504,9 +521,7 @@ pub async fn jobs_restart_handler(
|
||||
let new_job_id = scheduler
|
||||
.dispatch_job(&old_job.user_id, &title, &old_job.description, None)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
sanitized_internal_error_response(e, "dispatch restarted agent job")
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "restarted",
|
||||
@@ -515,7 +530,10 @@ pub async fn jobs_restart_handler(
|
||||
})))
|
||||
}
|
||||
Ok(None) => Err((StatusCode::NOT_FOUND, "Job not found".to_string())),
|
||||
Err(e) => Err(sanitized_db_error(e, "get agent job for restart")),
|
||||
Err(e) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -591,7 +609,10 @@ pub async fn jobs_prompt_handler(
|
||||
return Err((StatusCode::NOT_FOUND, "Job not found".to_string()));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get agent job for prompt"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,9 +625,10 @@ pub async fn jobs_prompt_handler(
|
||||
if let Some(ref scheduler) = *scheduler_guard
|
||||
&& scheduler.is_running(job_id).await
|
||||
{
|
||||
scheduler.send_message(job_id, content).await.map_err(|e| {
|
||||
sanitized_internal_error_response(e, "send prompt to running agent job")
|
||||
})?;
|
||||
scheduler
|
||||
.send_message(job_id, content)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
return Ok(Json(serde_json::json!({
|
||||
"status": "sent",
|
||||
"job_id": job_id.to_string(),
|
||||
@@ -645,14 +667,17 @@ pub async fn jobs_events_handler(
|
||||
return Err((StatusCode::NOT_FOUND, "Job not found".to_string()));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(sanitized_db_error(e, "get sandbox job events"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let events = store
|
||||
.list_job_events(job_id, None)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "list job events"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let events_json: Vec<serde_json::Value> = events
|
||||
.into_iter()
|
||||
@@ -696,7 +721,7 @@ pub async fn job_files_list_handler(
|
||||
let job = store
|
||||
.get_sandbox_job(job_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get sandbox job file list"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Job not found".to_string()))?;
|
||||
|
||||
if job.user_id != user.user_id {
|
||||
@@ -764,7 +789,7 @@ pub async fn job_files_read_handler(
|
||||
let job = store
|
||||
.get_sandbox_job(job_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get sandbox job file read"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Job not found".to_string()))?;
|
||||
|
||||
if job.user_id != user.user_id {
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::agent::routine::{Trigger, next_cron_fire};
|
||||
use crate::channels::web::auth::AuthenticatedUser;
|
||||
use crate::channels::web::server::GatewayState;
|
||||
use crate::channels::web::types::*;
|
||||
use crate::channels::web::util::{sanitized_db_error, sanitized_routine_error};
|
||||
use crate::error::RoutineError;
|
||||
|
||||
pub async fn routines_list_handler(
|
||||
State(state): State<Arc<GatewayState>>,
|
||||
@@ -28,7 +28,7 @@ pub async fn routines_list_handler(
|
||||
let routines = store
|
||||
.list_routines(&user.user_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "list routines"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let items: Vec<RoutineInfo> = routines.iter().map(RoutineInfo::from_routine).collect();
|
||||
|
||||
@@ -47,7 +47,7 @@ pub async fn routines_summary_handler(
|
||||
let routines = store
|
||||
.list_routines(&user.user_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "list routines summary"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let total = routines.len() as u64;
|
||||
let enabled = routines.iter().filter(|r| r.enabled).count() as u64;
|
||||
@@ -95,7 +95,7 @@ pub async fn routines_detail_handler(
|
||||
let routine = store
|
||||
.get_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get routine detail"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Routine not found".to_string()))?;
|
||||
|
||||
if routine.user_id != user.user_id {
|
||||
@@ -105,7 +105,7 @@ pub async fn routines_detail_handler(
|
||||
let runs = store
|
||||
.list_routine_runs(routine_id, 20)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "list routine detail runs"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let recent_runs: Vec<RoutineRunInfo> = runs
|
||||
.iter()
|
||||
@@ -163,7 +163,7 @@ pub async fn routines_trigger_handler(
|
||||
let run_id = engine
|
||||
.fire_manual(routine_id, Some(&user.user_id))
|
||||
.await
|
||||
.map_err(|e| sanitized_routine_error(e, "trigger routine manually"))?;
|
||||
.map_err(|e| (routine_error_status(&e), e.to_string()))?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "triggered",
|
||||
@@ -194,7 +194,7 @@ pub async fn routines_toggle_handler(
|
||||
let mut routine = store
|
||||
.get_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get routine for toggle"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Routine not found".to_string()))?;
|
||||
|
||||
if routine.user_id != user.user_id {
|
||||
@@ -228,7 +228,7 @@ pub async fn routines_toggle_handler(
|
||||
store
|
||||
.update_routine(&routine)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "update routine toggle state"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
// Refresh the in-memory event trigger cache so event/system_event
|
||||
// routines reflect the new enabled state immediately (issue #1076).
|
||||
@@ -259,7 +259,7 @@ pub async fn routines_delete_handler(
|
||||
let routine = store
|
||||
.get_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get routine for delete"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Routine not found".to_string()))?;
|
||||
|
||||
if routine.user_id != user.user_id {
|
||||
@@ -269,7 +269,7 @@ pub async fn routines_delete_handler(
|
||||
let deleted = store
|
||||
.delete_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "delete routine"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
if deleted {
|
||||
// Refresh the in-memory event trigger cache so deleted event/system_event
|
||||
@@ -305,7 +305,7 @@ pub async fn routines_runs_handler(
|
||||
let routine = store
|
||||
.get_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get routine runs"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Routine not found".to_string()))?;
|
||||
|
||||
if routine.user_id != user.user_id {
|
||||
@@ -315,7 +315,7 @@ pub async fn routines_runs_handler(
|
||||
let runs = store
|
||||
.list_routine_runs(routine_id, 50)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "list routine runs"))?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let run_infos: Vec<RoutineRunInfo> = runs
|
||||
.iter()
|
||||
@@ -336,3 +336,15 @@ pub async fn routines_runs_handler(
|
||||
"runs": run_infos,
|
||||
})))
|
||||
}
|
||||
|
||||
/// Map `RoutineError` variants to appropriate HTTP status codes.
|
||||
fn routine_error_status(err: &RoutineError) -> StatusCode {
|
||||
match err {
|
||||
RoutineError::NotFound { .. } => StatusCode::NOT_FOUND,
|
||||
RoutineError::NotAuthorized { .. } => StatusCode::FORBIDDEN,
|
||||
RoutineError::Disabled { .. }
|
||||
| RoutineError::Cooldown { .. }
|
||||
| RoutineError::MaxConcurrent { .. } => StatusCode::CONFLICT,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ use subtle::ConstantTimeEq;
|
||||
|
||||
use crate::agent::routine::Trigger;
|
||||
use crate::channels::web::server::GatewayState;
|
||||
use crate::channels::web::util::{sanitized_db_error, sanitized_routine_error};
|
||||
|
||||
/// Validate the webhook secret for a routine.
|
||||
///
|
||||
@@ -104,7 +103,7 @@ async fn fire_webhook_inner(
|
||||
let routine = store
|
||||
.get_webhook_routine_by_path(path, user_id)
|
||||
.await
|
||||
.map_err(|e| sanitized_db_error(e, "get webhook routine by path"))?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((
|
||||
StatusCode::NOT_FOUND,
|
||||
"No routine matches this webhook path".to_string(),
|
||||
@@ -127,10 +126,16 @@ async fn fire_webhook_inner(
|
||||
))?
|
||||
};
|
||||
|
||||
let run_id = engine
|
||||
.fire_webhook(routine.id, path)
|
||||
.await
|
||||
.map_err(|e| sanitized_routine_error(e, "trigger routine from webhook"))?;
|
||||
let run_id = engine.fire_webhook(routine.id, path).await.map_err(|e| {
|
||||
let status = match &e {
|
||||
crate::error::RoutineError::NotFound { .. } => StatusCode::NOT_FOUND,
|
||||
crate::error::RoutineError::Disabled { .. }
|
||||
| crate::error::RoutineError::Cooldown { .. }
|
||||
| crate::error::RoutineError::MaxConcurrent { .. } => StatusCode::CONFLICT,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
(status, e.to_string())
|
||||
})?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "triggered",
|
||||
|
||||
+16
-127
@@ -1717,13 +1717,7 @@ async fn chat_history_handler(
|
||||
let (messages, has_more) = store
|
||||
.list_conversation_messages_paginated(thread_id, before_cursor, limit as i64)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "DB error listing paginated messages");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Database error".to_string(),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let oldest_timestamp = messages.first().map(|m| m.created_at.to_rfc3339());
|
||||
let turns = build_turns_from_db_messages(&messages);
|
||||
@@ -1796,13 +1790,7 @@ async fn chat_history_handler(
|
||||
let (messages, has_more) = store
|
||||
.list_conversation_messages_paginated(thread_id, None, limit as i64)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "DB error listing messages");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Database error".to_string(),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
if !messages.is_empty() {
|
||||
let oldest_timestamp = messages.first().map(|m| m.created_at.to_rfc3339());
|
||||
@@ -1845,13 +1833,7 @@ async fn chat_threads_handler(
|
||||
let assistant_id = store
|
||||
.get_or_create_assistant_conversation(&user.user_id, "gateway")
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "DB error getting assistant conversation");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Database error".to_string(),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
match store
|
||||
.list_conversations_all_channels(&user.user_id, 50)
|
||||
@@ -2073,13 +2055,7 @@ async fn extensions_list_handler(
|
||||
let installed = ext_mgr
|
||||
.list(None, false, &user.user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "Error listing extensions");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Internal error".to_string(),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let pairing_store = crate::pairing::PairingStore::new();
|
||||
let mut owner_bound_channels = std::collections::HashSet::new();
|
||||
@@ -2509,13 +2485,7 @@ async fn extensions_setup_handler(
|
||||
let setup = ext_mgr
|
||||
.get_setup_schema(&name, &user.user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "Error getting extension setup schema");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Internal error".to_string(),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let kind = ext_mgr
|
||||
.list(None, false, &user.user_id)
|
||||
@@ -2589,13 +2559,9 @@ async fn pairing_list_handler(
|
||||
Path(channel): Path<String>,
|
||||
) -> Result<Json<PairingListResponse>, (StatusCode, String)> {
|
||||
let store = crate::pairing::PairingStore::new();
|
||||
let requests = store.list_pending(&channel).map_err(|e| {
|
||||
tracing::error!(error = %e, "Error listing pairing requests");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Internal error".to_string(),
|
||||
)
|
||||
})?;
|
||||
let requests = store
|
||||
.list_pending(&channel)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let infos = requests
|
||||
.into_iter()
|
||||
@@ -2651,26 +2617,17 @@ async fn routines_runs_handler(
|
||||
let routine = store
|
||||
.get_routine(routine_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "DB error getting routine");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Database error".to_string(),
|
||||
)
|
||||
})?
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((StatusCode::NOT_FOUND, "Routine not found".to_string()))?;
|
||||
|
||||
if routine.user_id != user.user_id {
|
||||
return Err((StatusCode::NOT_FOUND, "Routine not found".to_string()));
|
||||
}
|
||||
|
||||
let runs = store.list_routine_runs(routine_id, 50).await.map_err(|e| {
|
||||
tracing::error!(error = %e, "DB error listing routine runs");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Database error".to_string(),
|
||||
)
|
||||
})?;
|
||||
let runs = store
|
||||
.list_routine_runs(routine_id, 50)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let run_infos: Vec<RoutineRunInfo> = runs
|
||||
.iter()
|
||||
@@ -3068,10 +3025,8 @@ mod tests {
|
||||
|
||||
// --- OAuth callback handler tests ---
|
||||
|
||||
fn test_gateway_state_inner(
|
||||
ext_mgr: Option<Arc<ExtensionManager>>,
|
||||
store: Option<Arc<dyn crate::db::Database>>,
|
||||
) -> Arc<GatewayState> {
|
||||
/// Build a minimal `GatewayState` for testing the OAuth callback handler.
|
||||
fn test_gateway_state(ext_mgr: Option<Arc<ExtensionManager>>) -> Arc<GatewayState> {
|
||||
Arc::new(GatewayState {
|
||||
msg_tx: tokio::sync::RwLock::new(None),
|
||||
sse: Arc::new(SseManager::new()),
|
||||
@@ -3082,7 +3037,7 @@ mod tests {
|
||||
log_level_handle: None,
|
||||
extension_manager: ext_mgr,
|
||||
tool_registry: None,
|
||||
store,
|
||||
store: None,
|
||||
job_manager: None,
|
||||
prompt_queue: None,
|
||||
owner_id: "test".to_string(),
|
||||
@@ -3104,31 +3059,6 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a minimal `GatewayState` for testing the OAuth callback handler.
|
||||
fn test_gateway_state(ext_mgr: Option<Arc<ExtensionManager>>) -> Arc<GatewayState> {
|
||||
test_gateway_state_inner(ext_mgr, None)
|
||||
}
|
||||
|
||||
fn test_gateway_state_with_store(
|
||||
store: Arc<dyn crate::db::Database>,
|
||||
ext_mgr: Option<Arc<ExtensionManager>>,
|
||||
) -> Arc<GatewayState> {
|
||||
test_gateway_state_inner(ext_mgr, Some(store))
|
||||
}
|
||||
|
||||
#[cfg(feature = "libsql")]
|
||||
async fn create_unmigrated_test_db() -> (Arc<dyn crate::db::Database>, tempfile::TempDir) {
|
||||
use crate::db::libsql::LibSqlBackend;
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let db_path = temp_dir.path().join("test.db");
|
||||
let backend = LibSqlBackend::new_local(&db_path)
|
||||
.await
|
||||
.expect("LibSqlBackend");
|
||||
let db: Arc<dyn crate::db::Database> = Arc::new(backend);
|
||||
(db, temp_dir)
|
||||
}
|
||||
|
||||
/// Build a test router with just the OAuth callback route.
|
||||
fn test_oauth_router(state: Arc<GatewayState>) -> Router {
|
||||
Router::new()
|
||||
@@ -3370,47 +3300,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "libsql")]
|
||||
#[tokio::test]
|
||||
async fn test_routines_list_sanitizes_database_errors() {
|
||||
use axum::body::Body;
|
||||
use tower::ServiceExt;
|
||||
|
||||
let (db, _tmp) = create_unmigrated_test_db().await;
|
||||
let state = test_gateway_state_with_store(db, None);
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/api/routines",
|
||||
get(crate::channels::web::handlers::routines::routines_list_handler),
|
||||
)
|
||||
.with_state(state);
|
||||
|
||||
let mut req = axum::http::Request::builder()
|
||||
.method("GET")
|
||||
.uri("/api/routines")
|
||||
.body(Body::empty())
|
||||
.expect("request");
|
||||
req.extensions_mut().insert(UserIdentity {
|
||||
user_id: "test".to_string(),
|
||||
workspace_read_scopes: Vec::new(),
|
||||
});
|
||||
|
||||
let resp = ServiceExt::<axum::http::Request<Body>>::oneshot(app, req)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
let body = axum::body::to_bytes(resp.into_body(), 1024 * 64)
|
||||
.await
|
||||
.expect("body");
|
||||
let text = String::from_utf8(body.to_vec()).expect("utf8 body");
|
||||
assert_eq!(text, "Database error");
|
||||
assert!(
|
||||
!text.contains("no such table"),
|
||||
"client response should not leak backend error details"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_extensions_setup_submit_telegram_verification_does_not_broadcast_auth_required() {
|
||||
use axum::body::Body;
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
//! Shared utility functions for the web gateway.
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use crate::channels::web::types::{ToolCallInfo, TurnInfo};
|
||||
|
||||
pub use ironclaw_common::truncate_preview;
|
||||
@@ -13,59 +9,6 @@ pub fn tool_error_for_display(error: &str) -> String {
|
||||
ironclaw_safety::SafetyLayer::unwrap_tool_output(error).unwrap_or_else(|| error.to_string())
|
||||
}
|
||||
|
||||
fn sanitized_internal_error<E: Display>(
|
||||
error: E,
|
||||
context: &str,
|
||||
client_message: &str,
|
||||
) -> (StatusCode, String) {
|
||||
tracing::error!(error = %error, context, "Web gateway request failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
client_message.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Log a detailed backend error while returning a generic DB message to the client.
|
||||
pub fn sanitized_db_error<E: Display>(error: E, context: &str) -> (StatusCode, String) {
|
||||
sanitized_internal_error(error, context, "Database error")
|
||||
}
|
||||
|
||||
/// Log a detailed backend error while returning a generic internal message to the client.
|
||||
pub fn sanitized_internal_error_response<E: Display>(
|
||||
error: E,
|
||||
context: &str,
|
||||
) -> (StatusCode, String) {
|
||||
sanitized_internal_error(error, context, "Internal error")
|
||||
}
|
||||
|
||||
/// Return safe client responses for `RoutineError` while preserving user-actionable variants.
|
||||
pub fn sanitized_routine_error(
|
||||
error: crate::error::RoutineError,
|
||||
context: &str,
|
||||
) -> (StatusCode, String) {
|
||||
use crate::error::RoutineError;
|
||||
|
||||
match error {
|
||||
err @ RoutineError::NotFound { .. } => (StatusCode::NOT_FOUND, err.to_string()),
|
||||
err @ RoutineError::NotAuthorized { .. } => (StatusCode::FORBIDDEN, err.to_string()),
|
||||
err @ RoutineError::Disabled { .. }
|
||||
| err @ RoutineError::Cooldown { .. }
|
||||
| err @ RoutineError::MaxConcurrent { .. } => (StatusCode::CONFLICT, err.to_string()),
|
||||
err @ RoutineError::Database { .. } => sanitized_db_error(err, context),
|
||||
err @ RoutineError::LlmFailed { .. }
|
||||
| err @ RoutineError::JobDispatchFailed { .. }
|
||||
| err @ RoutineError::EmptyResponse
|
||||
| err @ RoutineError::TruncatedResponse
|
||||
| err @ RoutineError::UnknownTriggerType { .. }
|
||||
| err @ RoutineError::UnknownActionType { .. }
|
||||
| err @ RoutineError::MissingField { .. }
|
||||
| err @ RoutineError::InvalidCron { .. }
|
||||
| err @ RoutineError::UnknownRunStatus { .. } => {
|
||||
sanitized_internal_error_response(err, context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse tool call summary JSON objects into `ToolCallInfo` structs.
|
||||
fn parse_tool_call_infos(calls: &[serde_json::Value]) -> Vec<ToolCallInfo> {
|
||||
calls
|
||||
@@ -185,30 +128,6 @@ mod tests {
|
||||
use super::*;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[test]
|
||||
fn test_sanitized_db_error_hides_internal_details() {
|
||||
let (_, body) = sanitized_db_error("sqlite: no such table: routines", "list routines");
|
||||
assert_eq!(body, "Database error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sanitized_internal_error_hides_internal_details() {
|
||||
let (_, body) =
|
||||
sanitized_internal_error_response("container launch failed: timeout", "restart job");
|
||||
assert_eq!(body, "Internal error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sanitized_routine_error_hides_database_details() {
|
||||
let (_, body) = sanitized_routine_error(
|
||||
crate::error::RoutineError::Database {
|
||||
reason: "sqlite: no such table: routine_runs".to_string(),
|
||||
},
|
||||
"trigger routine",
|
||||
);
|
||||
assert_eq!(body, "Database error");
|
||||
}
|
||||
|
||||
// ---- build_turns_from_db_messages tests ----
|
||||
|
||||
fn make_msg(role: &str, content: &str, offset_ms: i64) -> crate::history::ConversationMessage {
|
||||
|
||||
Reference in New Issue
Block a user