Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 5 additions & 2 deletions docs/OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -975,8 +975,11 @@ agent may:
reason) and `answer` is the reason; the reason is optional, at most
2000 characters, cleaned like the text. Nobody decided within 7
days, the status becomes `expired` and the webhook gets "The proposal
expired after 7 days without a decision." once. An agent has at most
10 undecided proposals, so a loop can't run up the planner's bill.
expired after 7 days without a decision." once. The agent can take
back an undecided proposal with `POST /api/proposals/<id>/withdraw`
(status `withdrawn`, the mail links stop working, no webhook). An
agent has at most 10 undecided proposals, withdrawn ones count for a
day, so a loop can't run up the planner's bill.

Each admin's mail has their own link (`https://<panel>/proposal/…`)
that decides without logging in, handy on a phone: it shows the plan
Expand Down
1 change: 1 addition & 0 deletions docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ terminal.
plan's `Delete:` lines are confirmed with it, once each
- [x] A rejection can have a reason for the proposing agent, an expired
proposal tells it once
- [x] The proposing agent can withdraw an undecided proposal

### 11e. Quarantine and signs of a hack (operator 2026-11-12)
- [x] quarantine a group (panel, CLI, genco's agent): services stopped,
Expand Down
1 change: 1 addition & 0 deletions server/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ fn describe(method: &Method, path: &str) -> Option<String> {
("POST", "/groups/*/quarantine", "Quarantine group"),
("DELETE", "/groups/*/quarantine", "Lift quarantine"),
("POST", "/proposals/*/reject", "Reject proposal"),
("POST", "/proposals/*/withdraw", "Withdraw proposal"),
("POST", "/update/check", "Check for updates"),
("POST", "/update/install", "Start update"),
("POST", "/update/auto", "Change automatic updates"),
Expand Down
99 changes: 89 additions & 10 deletions server/src/proposals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
//! its last answer goes back to the proposing agent's webhook; the agent
//! can also poll the proposal (without the plans). A rejection (with the
//! admin's reason, if any) and the expiry after `VALID_DAYS` go to the
//! webhook too. The mail (mail.rs) has a personal link for each admin, it
//! decides without a login (links.rs).
//! webhook too. The proposing agent can withdraw it while it is undecided.
//! The mail (mail.rs) has a personal link for each admin, it decides
//! without a login (links.rs).

mod links;
mod mail;
Expand Down Expand Up @@ -54,6 +55,9 @@ const MAX_NOTE: usize = 2000;
/// More undecided proposals of one agent are refused, a loop mustn't mail
/// the admins or pay the planner without end.
const MAX_PENDING: i64 = 10;
/// Withdrawn proposals count towards `MAX_PENDING` this long: a withdrawal
/// doesn't stop a planner that already works on it.
const WITHDRAWN_MS: i64 = 24 * 60 * 60 * 1000;

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -82,7 +86,8 @@ pub struct Proposal {
pub approver: Option<String>,
pub approver_email: Option<String>,
/// planning, pending (the plan waits for an admin), approved (genco's
/// agent works on it), answered, rejected, expired
/// agent works on it), answered, rejected, expired, withdrawn (by the
/// proposing agent)
pub status: String,
pub decided_by: Option<String>,
pub conversation_id: Option<i64>,
Expand Down Expand Up @@ -296,7 +301,7 @@ fn proposal_text(text: &str) -> Result<(String, usize)> {
}

/// Stores a new proposal for the planner; more than `MAX_PENDING`
/// undecided ones of the agent are refused.
/// undecided or recently withdrawn ones of the agent are refused.
fn insert(
conn: &Connection,
peer_id: i64,
Expand All @@ -306,13 +311,15 @@ fn insert(
let (text, removed) = proposal_text(text)?;
let undecided: i64 = conn.query_row(
"SELECT count(*) FROM proposals WHERE peer_id = ?1
AND status IN ('planning', 'pending') AND created_at > ?2",
params![peer_id, now() - VALID_MS],
AND (status IN ('planning', 'pending') AND created_at > ?2
OR status = 'withdrawn' AND decided_at > ?3)",
params![peer_id, now() - VALID_MS, now() - WITHDRAWN_MS],
|r| r.get(0),
)?;
if undecided >= MAX_PENDING {
return Err(Error::Invalid(format!(
"{MAX_PENDING} proposals wait for a decision already"
"{MAX_PENDING} proposals wait for a decision or were withdrawn \
today already"
)));
}
conn.execute(
Expand All @@ -331,7 +338,16 @@ fn decide(
status: &str,
by: &crate::users::User,
) -> Result<()> {
let p = get_one(conn, id)?;
close(conn, &get_one(conn, id)?, status, Some(&by.name))
}

/// Ends an undecided proposal with `status`, only once.
fn close(
conn: &Connection,
p: &Proposal,
status: &str,
by: Option<&str>,
) -> Result<()> {
if !open(&p.status) {
return Err(Error::Invalid(format!(
"the proposal is {} already",
Expand All @@ -341,12 +357,12 @@ fn decide(
let changed = conn.execute(
"UPDATE proposals SET status = ?1, decided_by = ?2, decided_at = ?3,
mail_at = NULL WHERE id = ?4 AND status IN ('planning', 'pending')",
params![status, by.name, now(), id],
params![status, by, now(), p.id],
)?;
if changed != 1 {
return Err(Error::Invalid("the proposal is decided already".into()));
}
end_links(conn, id)?;
end_links(conn, p.id)?;
Ok(())
}

Expand Down Expand Up @@ -805,6 +821,29 @@ async fn reject(
Ok(Json(()))
}

/// The proposing agent takes back an undecided proposal: a planner still
/// at work throws its plan away and the mail links stop working.
fn withdrawn(conn: &Connection, id: i64, peer_id: i64) -> Result<()> {
let p = get_one(conn, id)?;
if p.peer_id != peer_id {
return Err(Error::NotFound);
}
close(conn, &p, "withdrawn", None)
}

async fn withdraw(
token: ApiToken,
State(db): State<Db>,
State(events): State<Events>,
Path(id): Path<i64>,
) -> Result<Json<()>> {
token.require(tokens::PROPOSE)?;
let peer = token.peer.ok_or(Error::Forbidden)?;
withdrawn(&db.conn(), id, peer)?;
events.send(Event::Approvals);
Ok(Json(()))
}

/// Marks the proposals nobody decided on in time as expired, once;
/// returns the ones it marked.
fn expire(conn: &Connection) -> Result<Vec<Proposal>> {
Expand Down Expand Up @@ -863,6 +902,7 @@ pub fn routes() -> Router<AppState> {
.route("/proposals/{id}/approve", post(approve))
.route("/proposals/{id}/change", post(change))
.route("/proposals/{id}/reject", post(reject))
.route("/proposals/{id}/withdraw", post(withdraw))
.merge(links::routes())
}

Expand Down Expand Up @@ -1054,6 +1094,25 @@ mod tests {
assert!(insert(&conn, p, "Update Craft", None).is_err());
}

#[test]
fn withdrawn_proposals_count_for_a_day() {
let db = Db::memory();
let conn = db.conn();
let p = peer(&conn);
for _ in 0..MAX_PENDING {
let id = insert(&conn, p, "Update Craft", None).unwrap();
withdrawn(&conn, id, p).unwrap();
}
assert!(insert(&conn, p, "Update Craft", None).is_err());

conn.execute(
"UPDATE proposals SET decided_at = ?1",
[now() - WITHDRAWN_MS - 1],
)
.unwrap();
insert(&conn, p, "Update Craft", None).unwrap();
}

#[test]
fn only_one_decision() {
let db = Db::memory();
Expand All @@ -1070,6 +1129,26 @@ mod tests {
assert_eq!(p.from, "Corleone");
}

#[test]
fn only_the_proposing_agent_withdraws_undecided_ones() {
let db = Db::memory();
let conn = db.conn();
let p = peer(&conn);
let id = add(&conn, p, "Update Craft", None).unwrap();
assert!(withdrawn(&conn, id, p + 1).is_err());

withdrawn(&conn, id, p).unwrap();
assert_eq!(get_one(&conn, id).unwrap().status, "withdrawn");
assert!(withdrawn(&conn, id, p).is_err());
assert!(decide(&conn, id, "approved", &admin(&conn, "a")).is_err());

let planning = insert(&conn, p, "Update Node", None).unwrap();
withdrawn(&conn, planning, p).unwrap();
let other = add(&conn, p, "Update PHP", None).unwrap();
decide(&conn, other, "rejected", &admin(&conn, "b")).unwrap();
assert!(withdrawn(&conn, other, p).is_err());
}

#[test]
fn old_proposals_expire() {
let db = Db::memory();
Expand Down
5 changes: 5 additions & 0 deletions server/src/proposals/mail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ pub(super) async fn mail(cfg: &Config, db: &Db, id: i64) {

let subject = subject(&p, plan);
for (user_id, email) in to {
// decided or withdrawn meanwhile: the others get no dead link
if !get_one(&db.conn(), id).is_ok_and(|p| p.status == "pending") {
return;
}

// without a domain there is no link to send
let link = cfg.panel_url("/proposal/").and_then(|base| {
match links::create(&db.conn(), id, user_id) {
Expand Down
3 changes: 3 additions & 0 deletions webui/src/components/ProposalDetail.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
Nobody decided within 7 days, {proposal.from} was told.
</p>
{/if}
{#if proposal.status === 'withdrawn'}
<p class="hint">{proposal.from} withdrew it before a decision.</p>
{/if}
{#if proposal.answer}
<p>
{proposal.status === 'rejected'
Expand Down
4 changes: 4 additions & 0 deletions webui/src/components/dialogs/AgentsDialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@
text: 'Its status and answer, or the reason of a rejection (the webhook gets them too, and a message when it expires after 7 days):',
code: `${auth} ${location.origin}/api/proposals/<id>`,
},
{
text: 'Take back a proposal nobody decided yet, e.g. one you replaced (no webhook):',
code: `${auth} -X POST ${location.origin}/api/proposals/<id>/withdraw`,
},
]);
</script>

Expand Down
2 changes: 1 addition & 1 deletion webui/src/components/dialogs/ApprovalsDialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
<td>{formatTime(expiresAt(a), true)}</td>
{/snippet}
</ListView>
<p>Decided and expired, last 30 days:</p>
<p>Decided, expired and withdrawn, last 30 days:</p>
<ListView
items={history}
key={approvalKey}
Expand Down
3 changes: 2 additions & 1 deletion webui/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,8 @@ export type Proposal = {
| 'approved'
| 'answered'
| 'rejected'
| 'expired';
| 'expired'
| 'withdrawn';
decidedBy: string | null;
conversationId: number | null;
/** what went back: the agent's answer, or the reason of a rejection */
Expand Down
11 changes: 9 additions & 2 deletions webui/src/lib/approvals.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { get, type Approval, type PendingAction, type Plan } from './api';
import {
get,
type Approval,
type PendingAction,
type Plan,
type Proposal,
} from './api';

// Start → Approvals: the AI agents' proposals and the pending actions
// (deletions, the agent's remote backup changes); the taskbar shows the
Expand Down Expand Up @@ -64,13 +70,14 @@ export function newestPlan(a: Approval): Plan | null {
return a.kind === 'proposal' ? (a.proposal.plans.at(-1) ?? null) : null;
}

const PROPOSAL_STATUS: Record<string, string> = {
const PROPOSAL_STATUS: Record<Proposal['status'], string> = {
planning: 'being planned',
pending: 'waiting',
approved: 'the agent works on it',
answered: 'answered',
rejected: 'rejected',
expired: 'expired',
withdrawn: 'withdrawn',
};

const ACTION_STATUS: Record<PendingAction['status'], string> = {
Expand Down
4 changes: 2 additions & 2 deletions webui/src/pages/ProposalLink.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@
<div class="content">
{#if gone || !link || !proposal}
<p>
This link no longer works (the proposal was decided or
expired). Open the panel to see it.
This link no longer works (the proposal was decided, expired
or withdrawn). Open the panel to see it.
</p>
{:else if done}
<p>{done}</p>
Expand Down