Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/automation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3907,6 +3907,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
}
}

Expand Down Expand Up @@ -5186,6 +5187,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};

let dir = std::env::temp_dir().join("tutti-test-resolver-control-steps");
Expand Down
1 change: 1 addition & 0 deletions src/budget/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ mod tests {
workspace_weekly_tokens: Some(200),
agent_weekly_tokens: caps,
}),
webhooks: vec![],
}
}

Expand Down
1 change: 1 addition & 0 deletions src/cli/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
}
}

Expand Down
1 change: 1 addition & 0 deletions src/cli/handoff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ mod tests {
}),
observe: None,
budget: None,
webhooks: vec![],
}
}

Expand Down
125 changes: 125 additions & 0 deletions src/cli/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::scheduler;
use crate::session::TmuxSession;
use crate::state;
use crate::state::ControlEvent;
use crate::webhook;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
Expand Down Expand Up @@ -506,6 +507,14 @@ fn route_request(request: &mut Request, targets: &[WorkspaceTarget]) -> (StatusC
api_err("action", "action_failed", e.to_string()).to_string(),
),
}
} else if method == Method::Post && path == "/v1/webhooks/generic" {
match route_webhook(request, targets) {
Ok(value) => (StatusCode(200), value.to_string()),
Err(e) => (
StatusCode(400),
api_err("webhook", "webhook_failed", e.to_string()).to_string(),
),
}
} else {
(
StatusCode(404),
Expand Down Expand Up @@ -753,6 +762,122 @@ fn execute_action(action: &str, body: &Value, target: &WorkspaceTarget) -> Resul
}
}

/// Maximum webhook payload size (1 MB)
const WEBHOOK_MAX_BODY_BYTES: usize = 1_048_576;

/// Handle POST /v1/webhooks/generic
fn route_webhook(request: &mut Request, targets: &[WorkspaceTarget]) -> Result<Value> {
// Payload size guard
let content_length = request
.headers()
.iter()
.find(|h| h.field.equiv("Content-Length"))
.and_then(|h| h.value.as_str().parse::<usize>().ok())
.unwrap_or(0);
if content_length > WEBHOOK_MAX_BODY_BYTES {
return Err(TuttiError::ConfigValidation(format!(
"webhook payload too large ({content_length} bytes, max {WEBHOOK_MAX_BODY_BYTES})"
)));
}

let body = read_json_body(request)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

let source = body
.get("source")
.and_then(Value::as_str)
.unwrap_or("generic");
let event_type = body
.get("event")
.and_then(Value::as_str)
.unwrap_or("unknown");
let workspace_hint = body.get("workspace").and_then(Value::as_str);

let payload = body.get("payload").cloned().unwrap_or_else(|| body.clone());
let target = resolve_action_workspace(targets, workspace_hint)?;
let matched = webhook::match_triggers(&target.config.webhooks, source, event_type);
Comment thread
nutt-adam marked this conversation as resolved.
Resolved

if matched.is_empty() {
webhook::log_event(&target.project_root, source, event_type, None, "no_match");
return Ok(api_ok(
"webhook.received",
json!({
"source": source,
"event": event_type,
"matched": false,
"triggers_fired": 0
}),
));
}

let mut dispatched = Vec::new();
for wh in &matched {
if let Some(workflow) = &wh.workflow {
with_project_root(&target.project_root, || {
super::run::run(
Some(workflow),
None,
false,
wh.agent.as_deref(),
false,
false,
false,
)
})?;
webhook::log_event(
&target.project_root,
source,
event_type,
Some(workflow),
"dispatched_workflow",
);
dispatched.push(json!({
"type": "workflow",
"workflow": workflow,
"agent": wh.agent,
}));
} else if let Some(agent) = &wh.agent {
let raw_prompt = wh
.prompt
.as_deref()
.unwrap_or("Webhook event received — check recent events for details.");
let prompt = webhook::expand_template(raw_prompt, &payload);
let options = super::send::SendOptions {
auto_up: false,
wait: false,
timeout_secs: 900,
idle_stable_secs: 5,
output: false,
output_lines: 200,
};
with_project_root(&target.project_root, || {
super::send::run(agent, std::slice::from_ref(&prompt), options).map(|_| ())
})?;
webhook::log_event(
&target.project_root,
source,
event_type,
Some(agent),
"dispatched_send",
);
dispatched.push(json!({
"type": "send",
"agent": agent,
}));
}
}
Comment thread
nutt-adam marked this conversation as resolved.
Resolved

Ok(api_ok(
"webhook.received",
json!({
"source": source,
"event": event_type,
"matched": true,
"triggers_fired": dispatched.len(),
"dispatched": dispatched
}),
))
}

/// Resolve the target workspace for an action, defaulting to the only one if singular
fn resolve_action_workspace<'a>(
targets: &'a [WorkspaceTarget],
Expand Down
9 changes: 9 additions & 0 deletions src/cli/up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1814,6 +1814,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let env = build_workspace_env(&config);
assert_eq!(env.get("GIT_AUTHOR_NAME").unwrap(), "Test User");
Expand Down Expand Up @@ -1848,6 +1849,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let mut env = build_workspace_env(&config);
// Simulate agent-level override
Expand Down Expand Up @@ -1883,6 +1885,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let global = GlobalConfig {
user: None,
Expand Down Expand Up @@ -1933,6 +1936,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let global = GlobalConfig {
user: None,
Expand Down Expand Up @@ -1995,6 +1999,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let global = GlobalConfig {
user: None,
Expand Down Expand Up @@ -2046,6 +2051,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let global = GlobalConfig {
user: None,
Expand Down Expand Up @@ -2106,6 +2112,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let global = GlobalConfig {
user: None,
Expand Down Expand Up @@ -2191,6 +2198,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};

let resolved = resolve_launch_settings(
Expand Down Expand Up @@ -2223,6 +2231,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
};
let launch_settings = LaunchSettings {
mode: LaunchMode::Auto,
Expand Down
1 change: 1 addition & 0 deletions src/cli/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,7 @@ mod tests {
handoff: None,
observe: None,
budget: None,
webhooks: vec![],
}
}

Expand Down
64 changes: 64 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub struct TuttiConfig {
pub observe: Option<ObserveConfig>,
#[serde(default)]
pub budget: Option<BudgetConfig>,
#[serde(default, rename = "webhook")]
pub webhooks: Vec<WebhookConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -310,6 +312,24 @@ pub struct BudgetConfig {
pub agent_weekly_tokens: HashMap<String, u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
/// Source identifier (e.g. "github", "slack", "generic")
pub source: String,
/// Event types to match (e.g. ["issues.labeled", "push"]). Use ["*"] for all.
#[serde(default)]
pub events: Vec<String>,
/// Workflow name to trigger on match
#[serde(default)]
pub workflow: Option<String>,
/// Agent to send a prompt to on match (alternative to workflow)
#[serde(default)]
pub agent: Option<String>,
/// Prompt to send when using agent dispatch
#[serde(default)]
pub prompt: Option<String>,
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// ── Global config (~/.config/tutti/config.toml) ──

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
Expand Down Expand Up @@ -2180,4 +2200,48 @@ workflow_source = "run"
PathBuf::from("/tmp/test2")
);
}

#[test]
fn webhook_config_serde_round_trip() {
let toml_str = r#"
[workspace]
name = "test"

[[webhook]]
source = "github"
events = ["issues.labeled", "push"]
workflow = "sdlc-auto"

[[webhook]]
source = "generic"
events = ["*"]
agent = "implementer"
prompt = "Handle incoming event"
"#;
let config: TuttiConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.webhooks.len(), 2);

let wh0 = &config.webhooks[0];
assert_eq!(wh0.source, "github");
assert_eq!(wh0.events, vec!["issues.labeled", "push"]);
assert_eq!(wh0.workflow.as_deref(), Some("sdlc-auto"));
assert!(wh0.agent.is_none());

let wh1 = &config.webhooks[1];
assert_eq!(wh1.source, "generic");
assert_eq!(wh1.events, vec!["*"]);
assert!(wh1.workflow.is_none());
assert_eq!(wh1.agent.as_deref(), Some("implementer"));
assert_eq!(wh1.prompt.as_deref(), Some("Handle incoming event"));
}

#[test]
fn webhook_config_empty_is_default() {
let toml_str = r#"
[workspace]
name = "test"
"#;
let config: TuttiConfig = toml::from_str(toml_str).unwrap();
assert!(config.webhooks.is_empty());
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod scheduler;
mod session;
mod state;
mod usage;
mod webhook;
mod worktree;

use clap::Parser;
Expand Down
Loading
Loading