Style loop webhook notifications as cards

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-09 11:46:09 -08:00
1 parent 1a17578aa9
commit f24a254f96
2 files changed
+410 -30

No files matched your search

+9 -3
View File
@@ -176,12 +176,18 @@ Done: 5 tasks, committed "Add votes" (abc1234). Next: Phase 3, Results. Elapsed:
| Send to | Request | Where the message goes |
| --- | --- | --- |
| A web address, query string | GET | A parameter you name (`message` by default), added to the address's own |
| Discord webhook | POST JSON | `content`, with mentions turned off |
| Slack webhook | POST JSON | `text` |
| Discord webhook | POST JSON | An embed with a colored bar, mentions turned off |
| Slack webhook | POST JSON | An attachment with a colored bar |
| Microsoft Teams webhook | POST JSON | An Adaptive Card, for a Workflows "when a webhook request is received" trigger |
| Google Chat webhook | POST JSON | `text` |
| Google Chat webhook | POST JSON | A `cardsV2` card |
| A web address, JSON body | POST JSON | A field you name (`message` by default) |
The four chat services get a card, not a line of text: a title with an emoji that says what happened
(`✅ Loop complete`, `✅ Phase complete`, `❓ Waiting for you`, `❓ Stopped on a question`, `🛑 Loop stopped`), the
message, **Project**, **Spec** and **Elapsed** fields, and a footer. Discord, Slack and Teams color it by outcome
(green done, yellow waiting on you, red stopped); Google Chat has no color bar, so the emoji carries it. The
two plain web-address choices still get the message exactly as written.
**Send a test** saves the setup and sends a test message right away, after the app names the address in its
own window, so a wrong address shows up before a long run. A name can use letters, digits and `- _ . ~`. Pasting a Discord, Slack, Teams or Google Chat address picks
its choice for you, since a plain GET to a Discord webhook answers 200 and posts nothing. The call has 10
+401 -27
View File
@@ -107,6 +107,125 @@ pub fn valid_setup(kind: NotifyKind, url: &str, param: &str) -> bool {
valid_url(url) && (!kind.uses_param() || valid_param(param))
}
/// What an outcome looks like on a card.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tone {
Done,
Waiting,
Stopped,
Plain,
}
/// A loop message read into the parts of a card.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Look {
pub tone: Tone,
pub title: String,
pub description: String,
/// Project, Spec and Elapsed, in that order, each only when the message has it.
pub fields: Vec<(&'static str, String)>,
}
impl Tone {
fn discord_color(self) -> u32 {
match self {
Tone::Done => 0x57F287,
Tone::Waiting => 0xFEE75C,
Tone::Stopped => 0xED4245,
Tone::Plain => 0x5865F2,
}
}
fn slack_color(self) -> &'static str {
match self {
Tone::Done => "#2EB67D",
Tone::Waiting => "#ECB22E",
Tone::Stopped => "#E01E5A",
Tone::Plain => "#5865F2",
}
}
/// An Adaptive Card text color.
fn teams_color(self) -> &'static str {
match self {
Tone::Done => "Good",
Tone::Waiting => "Warning",
Tone::Stopped => "Attention",
Tone::Plain => "Accent",
}
}
}
const FOOTER: &str = "Plan2Code loop";
/// Discord stops an embed's description at 4096 characters.
const MAX_DESCRIPTION: usize = 4000;
/// Read a message the loop wrote (`loop_driver.rs`) into a card: its outcome
/// from the words it always uses, and the trailing "Elapsed: ..." as a field.
/// A message it does not know stays whole, as a plain card.
pub fn look(message: &str) -> Look {
// Elapsed ends every message; the last one is the real one, whatever a
// commit subject or an agent's line said before it.
let (description, elapsed) = match message.rsplit_once("Elapsed: ") {
Some((before, after)) => (
before.trim(),
Some(after.trim().trim_end_matches('.').to_string()).filter(|e| !e.is_empty()),
),
None => (message.trim(), None),
};
// The outcome is in the message's leading words, never in the free text
// after them (a commit subject, an agent's line).
let (tone, title) = if description.starts_with("Plan2Code loop is waiting on") {
(Tone::Waiting, "❓ Waiting for you")
} else if description.starts_with("Plan2Code loop stopped on") {
if description.ends_with("has a question for you to answer.") {
(Tone::Waiting, "❓ Stopped on a question")
} else {
(Tone::Stopped, "🛑 Loop stopped")
}
} else if description.starts_with("Plan2Code loop complete on") {
(Tone::Done, "✅ Loop complete")
} else if description.starts_with("Plan2Code loop on") && description.contains(" is complete.")
{
(Tone::Done, "✅ Phase complete")
} else {
(Tone::Plain, "📣 Plan2Code loop")
};
let mut fields = Vec::new();
if let Some((project, spec)) = label(message) {
if !project.is_empty() {
fields.push(("Project", project));
}
fields.push(("Spec", spec));
}
fields.extend(elapsed.map(|e| ("Elapsed", e)));
Look {
tone,
title: title.to_string(),
description: description.chars().take(MAX_DESCRIPTION).collect(),
fields,
}
}
/// The "project / spec" the loop's messages name after " on " (`Where::label`
/// in `loop_driver.rs`), as (project, spec); the project is empty when the
/// folder has no name. None for a message that does not name one.
fn label(message: &str) -> Option<(String, String)> {
let (_, after) = message.split_once(" on ")?;
let end = [": ", " at Phase "]
.iter()
.filter_map(|stop| after.find(stop))
.min()?;
let label = after[..end].trim();
if label.is_empty() {
return None;
}
Some(match label.split_once(" / ") {
Some((project, spec)) => (project.to_string(), spec.to_string()),
None => (String::new(), label.to_string()),
})
}
/// Slack treats these three as its own markup in message text.
fn slack_escaped(text: &str) -> String {
text.replace('&', "&amp;")
@@ -124,28 +243,108 @@ pub fn request_for(
let body = match kind {
NotifyKind::Query => return (target_url(url, param, message), None),
NotifyKind::Json => json!({ param: message }),
// No mentions, whatever a spec is called: this must never ping a channel.
NotifyKind::Discord => json!({ "content": message, "allowed_mentions": { "parse": [] } }),
NotifyKind::Slack => json!({ "text": slack_escaped(message) }),
NotifyKind::GoogleChat => json!({ "text": message }),
// A Teams workflow's "when a webhook request is received" trigger.
NotifyKind::Teams => json!({
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": null,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.4",
"body": [{ "type": "TextBlock", "text": message, "wrap": true }],
},
}],
}),
NotifyKind::Discord => discord_card(&look(message)),
NotifyKind::Slack => slack_card(&look(message)),
NotifyKind::GoogleChat => google_chat_card(&look(message)),
NotifyKind::Teams => teams_card(&look(message)),
};
(url.to_string(), Some(body))
}
/// An embed: a colored bar, a title, the message, an Elapsed field and a footer.
fn discord_card(look: &Look) -> Value {
let mut embed = json!({
"title": look.title,
"description": look.description,
"color": look.tone.discord_color(),
"footer": { "text": FOOTER },
});
if !look.fields.is_empty() {
embed["fields"] = look
.fields
.iter()
.map(|(name, value)| json!({ "name": name, "value": value, "inline": true }))
.collect();
}
// No mentions, whatever a spec is called: this must never ping a channel.
json!({ "embeds": [embed], "allowed_mentions": { "parse": [] } })
}
/// An attachment: the same parts, in Slack's own markup rules.
fn slack_card(look: &Look) -> Value {
let mut attachment = json!({
"fallback": slack_escaped(&look.description),
"color": look.tone.slack_color(),
"title": slack_escaped(&look.title),
"text": slack_escaped(&look.description),
"footer": FOOTER,
});
if !look.fields.is_empty() {
attachment["fields"] = look
.fields
.iter()
.map(|(title, value)| json!({ "title": title, "value": slack_escaped(value), "short": true }))
.collect();
}
json!({ "attachments": [attachment] })
}
/// A Google Chat card has no color bar, so the title's emoji carries the outcome.
/// Its text paragraphs read a little HTML, so the message is escaped as for Slack.
fn google_chat_card(look: &Look) -> Value {
let mut widgets =
vec![json!({ "textParagraph": { "text": slack_escaped(&look.description) } })];
for (label, value) in &look.fields {
widgets
.push(json!({ "decoratedText": { "topLabel": label, "text": slack_escaped(value) } }));
}
json!({
"cardsV2": [{
"cardId": "plan2code-loop",
"card": {
"header": { "title": look.title, "subtitle": FOOTER },
"sections": [{ "widgets": widgets }],
},
}],
})
}
/// A Teams workflow's "when a webhook request is received" trigger.
fn teams_card(look: &Look) -> Value {
let mut body = vec![
json!({
"type": "TextBlock",
"text": look.title,
"weight": "Bolder",
"size": "Medium",
"color": look.tone.teams_color(),
"wrap": true,
}),
json!({ "type": "TextBlock", "text": look.description, "wrap": true }),
];
if !look.fields.is_empty() {
let facts: Vec<Value> = look
.fields
.iter()
.map(|(title, value)| json!({ "title": title, "value": value }))
.collect();
body.push(json!({ "type": "FactSet", "facts": facts }));
}
json!({
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": null,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.4",
"body": body,
},
}],
})
}
/// The Start confirm's words for what the app will do.
pub fn describe(kind: NotifyKind, url: &str, param: &str) -> String {
match kind {
@@ -320,7 +519,135 @@ mod tests {
.contains("content-type: application/json"));
let (_, body) = request.split_once("\r\n\r\n").unwrap();
let body: Value = serde_json::from_str(body).unwrap();
assert_eq!(body["content"], "all done");
assert_eq!(body["embeds"][0]["description"], "all done");
}
const DONE: &str =
"Plan2Code loop complete on plan2code / lunch: all 4 phases built. Elapsed: 14m.";
const PHASE: &str = "Plan2Code loop on plan2code / lunch: Phase 2 of 4 (Setup) is complete. Done: 6 tasks. Next: Phase 3. Elapsed: phase 6m, run 14m.";
const ASKED: &str = "Plan2Code loop is waiting on plan2code / lunch: Phase 2 of 4 has a question for you to answer. Elapsed: phase 1m, run 3m.";
const ASKED_STOP: &str = "Plan2Code loop stopped on plan2code / lunch: Phase 2 of 4 has a question for you to answer. Elapsed: phase 1m, run 3m.";
const STOPPED: &str = "Plan2Code loop stopped on plan2code / lunch at Phase 2 of 4: the agent crashed (exit 1). Elapsed: phase 1m, run 3m.";
#[test]
fn a_message_reads_into_a_tone_a_title_and_an_elapsed_time() {
for (message, tone, title, elapsed) in [
(DONE, Tone::Done, "✅ Loop complete", "14m"),
(PHASE, Tone::Done, "✅ Phase complete", "phase 6m, run 14m"),
(
ASKED,
Tone::Waiting,
"❓ Waiting for you",
"phase 1m, run 3m",
),
(
ASKED_STOP,
Tone::Waiting,
"❓ Stopped on a question",
"phase 1m, run 3m",
),
(
STOPPED,
Tone::Stopped,
"🛑 Loop stopped",
"phase 1m, run 3m",
),
] {
let got = look(message);
assert_eq!(got.tone, tone, "{message}");
assert_eq!(got.title, title, "{message}");
assert_eq!(
got.fields,
vec![
("Project", "plan2code".to_string()),
("Spec", "lunch".to_string()),
("Elapsed", elapsed.to_string()),
],
"{message}"
);
assert!(!got.description.contains("Elapsed"), "{message}");
assert!(got.description.starts_with("Plan2Code loop"), "{message}");
}
let plain = look("A test message from Plan2Code");
assert_eq!(plain.tone, Tone::Plain);
assert_eq!(plain.title, "📣 Plan2Code loop");
assert_eq!(plain.description, "A test message from Plan2Code");
assert!(plain.fields.is_empty());
let bare = look("Plan2Code loop complete on lunch: 1 phase built. Elapsed: 2m.");
assert_eq!(
bare.fields,
vec![("Spec", "lunch".to_string()), ("Elapsed", "2m".to_string())],
"a spec with no project folder name shows only the spec"
);
}
#[test]
fn words_inside_the_message_do_not_change_what_it_is() {
// A phase's commit subject is free text: it may say anything.
let phase = look(
"Plan2Code loop on plan2code / lunch: Phase 1 of 2 is complete. Done: committed \"Fix loop stopped on error: has a question, Elapsed: 3\" (abc1234). Next: Phase 2. Elapsed: phase 1m, run 2m.",
);
assert_eq!(phase.tone, Tone::Done);
assert_eq!(phase.title, "✅ Phase complete");
assert!(
phase.description.contains("Elapsed: 3"),
"{}",
phase.description
);
assert!(phase.description.ends_with("Next: Phase 2."));
assert_eq!(
phase.fields.last(),
Some(&("Elapsed", "phase 1m, run 2m".to_string()))
);
let crash = look(
"Plan2Code loop stopped on plan2code / lunch at Phase 2 of 4: the work is complete. Elapsed: phase 1m, run 3m.",
);
assert_eq!(crash.tone, Tone::Stopped);
}
#[test]
fn discord_gets_an_embed_with_a_colored_bar_and_no_pings() {
let body = request_for(NotifyKind::Discord, "https://e.com/x", "n", DONE)
.1
.unwrap();
assert_eq!(body["allowed_mentions"], json!({ "parse": [] }));
let embed = &body["embeds"][0];
assert_eq!(embed["title"], "✅ Loop complete");
assert_eq!(embed["color"], 0x57F287);
assert_eq!(
embed["description"],
"Plan2Code loop complete on plan2code / lunch: all 4 phases built."
);
assert_eq!(
embed["fields"],
json!([
{ "name": "Project", "value": "plan2code", "inline": true },
{ "name": "Spec", "value": "lunch", "inline": true },
{ "name": "Elapsed", "value": "14m", "inline": true },
])
);
assert_eq!(embed["footer"]["text"], "Plan2Code loop");
let stopped = request_for(NotifyKind::Discord, "https://e.com/x", "n", STOPPED)
.1
.unwrap();
assert_eq!(stopped["embeds"][0]["color"], 0xED4245);
let mention = request_for(NotifyKind::Discord, "https://e.com/x", "n", "@everyone hi")
.1
.unwrap();
assert_eq!(mention["allowed_mentions"], json!({ "parse": [] }));
assert!(mention["embeds"][0].get("fields").is_none());
let long = "x".repeat(5000);
let body = request_for(NotifyKind::Discord, "https://e.com/x", "n", &long)
.1
.unwrap();
assert!(
body["embeds"][0]["description"]
.as_str()
.unwrap()
.chars()
.count()
<= 4000
);
}
#[test]
@@ -331,17 +658,49 @@ mod tests {
.unwrap()
};
assert_eq!(body(NotifyKind::Json, "hi"), json!({ "note": "hi" }));
let slack = body(NotifyKind::Slack, "a <b> & c");
assert!(slack.get("text").is_none());
let attachment = &slack["attachments"][0];
assert_eq!(attachment["text"], "a &lt;b&gt; &amp; c");
assert_eq!(attachment["fallback"], "a &lt;b&gt; &amp; c");
assert_eq!(attachment["title"], "📣 Plan2Code loop");
assert_eq!(attachment["color"], "#5865F2");
assert_eq!(attachment["footer"], "Plan2Code loop");
assert_eq!(
body(NotifyKind::Discord, "@everyone hi"),
json!({ "content": "@everyone hi", "allowed_mentions": { "parse": [] } }),
"a mention in a spec's name pings nobody"
body(NotifyKind::Slack, ASKED)["attachments"][0]["color"],
"#ECB22E"
);
assert_eq!(
body(NotifyKind::Slack, "a <b> & c"),
json!({ "text": "a &lt;b&gt; &amp; c" })
body(NotifyKind::Teams, ASKED)["attachments"][0]["content"]["body"][0]["color"],
"Warning"
);
assert_eq!(body(NotifyKind::GoogleChat, "hi"), json!({ "text": "hi" }));
let teams = body(NotifyKind::Teams, "hi");
assert_eq!(
body(NotifyKind::Discord, ASKED)["embeds"][0]["color"],
0xFEE75C
);
let slack = body(NotifyKind::Slack, STOPPED);
assert_eq!(slack["attachments"][0]["color"], "#E01E5A");
assert_eq!(
slack["attachments"][0]["fields"],
json!([
{ "title": "Project", "value": "plan2code", "short": true },
{ "title": "Spec", "value": "lunch", "short": true },
{ "title": "Elapsed", "value": "phase 1m, run 3m", "short": true },
])
);
let chat = body(NotifyKind::GoogleChat, PHASE);
let card = &chat["cardsV2"][0]["card"];
assert_eq!(card["header"]["title"], "✅ Phase complete");
let widgets = &card["sections"][0]["widgets"];
assert_eq!(
widgets[0]["textParagraph"]["text"],
"Plan2Code loop on plan2code / lunch: Phase 2 of 4 (Setup) is complete. Done: 6 tasks. Next: Phase 3."
);
assert_eq!(widgets[1]["decoratedText"]["topLabel"], "Project");
assert_eq!(widgets[1]["decoratedText"]["text"], "plan2code");
assert_eq!(widgets[3]["decoratedText"]["topLabel"], "Elapsed");
assert_eq!(widgets[3]["decoratedText"]["text"], "phase 6m, run 14m");
let teams = body(NotifyKind::Teams, DONE);
assert_eq!(teams["type"], "message");
let attachment = &teams["attachments"][0];
assert_eq!(
@@ -349,7 +708,22 @@ mod tests {
"application/vnd.microsoft.card.adaptive"
);
assert_eq!(attachment["content"]["type"], "AdaptiveCard");
assert_eq!(attachment["content"]["body"][0]["text"], "hi");
let card = &attachment["content"]["body"];
assert_eq!(card[0]["text"], "✅ Loop complete");
assert_eq!(card[0]["color"], "Good");
assert_eq!(card[0]["weight"], "Bolder");
assert_eq!(
card[1]["text"],
"Plan2Code loop complete on plan2code / lunch: all 4 phases built."
);
assert_eq!(
card[2]["facts"],
json!([
{ "title": "Project", "value": "plan2code" },
{ "title": "Spec", "value": "lunch" },
{ "title": "Elapsed", "value": "14m" },
])
);
assert_eq!(
request_for(NotifyKind::Slack, "https://e.com/x", "n", "m").0,
"https://e.com/x"