[client] Polls: merge feature/polls — poll, vote and pollClose inside MLS; a poll is a message, only the asker closes, the close carries the final votes (review in PR #22)
ci / check (push) Has been cancelled

This commit is contained in:
2026-11-22 10:38:53 +01:00
6 changed files with 1025 additions and 10 deletions
+124
View File
@@ -0,0 +1,124 @@
# Polls — three payloads, and a poll the client keeps (`PROTOCOL.md` §4)
Amicitia F28, step 3 of its full-chat plan (`Amicitia/.agents/features/full-chat.md` §2). Everything
here is **inside MLS**: the relay's view (§5, §8) does not change. No new route, no new column.
## 1. Why and what
*Where shall we eat — the Italian place or the Thai one?* A chat people move to lets them ask a
question with a few answers, lets everyone vote and change their vote, and shows who chose what. The
person who asked closes it, and from then on the result is the same on every device.
So this change adds:
1. `poll`, a message (it has a `seq`, so it can be replied to and reacted to, and a receipt covers
it): a question, 2–10 options, single or multiple choice;
2. `vote`, a member's choices in a poll, replacing their earlier vote; no choices takes it back;
3. `pollClose`, sent by the asker only: the poll is closed, and **these are the final votes**.
## 2. Design
```mermaid
sequenceDiagram
participant A as Anna's app
participant C as Client (Anna)
participant R as Relay
participant D as Client (Ben)
participant B as Ben's app
A->>C: compose_poll(ben, "Where?", ["Italian","Thai"], false) → seq 8
C->>R: {"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
R->>D: fetch
D->>B: Poll{seq 8, …}; D remembers (Anna, 8): 2 options, single choice, open
B->>D: vote(anna, (Anna, 8), [1])
D->>R: {"kind":"vote","poll":{"author":"…","seq":8},"choices":[1]}
R->>C: fetch
C->>A: Vote{poll (Anna, 8), choices [1]}
A->>C: close_poll(ben, (Anna, 8))
C->>R: {"kind":"pollClose","poll":{…},"ballots":[{"author":"<Ben>","choices":[1]}]}
R->>D: fetch
D->>B: PollClosed{poll, ballots}: the final result
```
### 2.1 The payloads
```json
{"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[1]}
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[]}
{"kind":"pollClose","poll":{"author":"<22 chars>","seq":8},"ballots":[{"author":"<22 chars>","choices":[1]}]}
```
- **`poll`**: `question` 1–300 characters, `options` 2–10 of 1–100 characters each, all different;
none blank, none with a control character. `multiple` says whether a vote may hold several choices.
It shares the sender's one `seq` counter with `text`.
- **`vote`**: `choices` are indexes into `options`, ascending, each once; with `multiple` false, at
most one. `[]` takes the vote back. A vote replaces the sender's earlier one in that poll. No `seq`.
- **`pollClose`**: only the poll's author may send it. `ballots` are the votes the author's client
had accepted when it closed, one per member who has a vote (an empty vote is left out). No `seq`.
### 2.2 Why the close carries the votes
Without them two devices can disagree for ever: Ben votes while Anna closes; Anna's client receives
the vote after its close and drops it, Ben's app counted it. With `ballots`, the result after a close
is *what the asker's device saw*, and every device shows that. A vote that crossed the close is not
counted anywhere, and Ben's app sees that his vote is not in the result.
### 2.3 What the client keeps
For each conversation, the polls in it: who asked and the `seq`, how many options, `multiple`,
whether it is closed, and each member's current choices (at most two in a 1:1 chat). This goes into
the snapshot (`polls`, absent in older snapshots, so `SNAPSHOT_VERSION` stays 1). With it the client
— not each app — decides whether a vote or a close makes sense, and the close's `ballots` come from
what it accepted, not from the app.
### 2.4 What the receiving client checks
| Received | Dropped when | Otherwise |
|:--|:--|:--|
| `poll` | a field over its limit, fewer than 2 or more than 10 options, a blank or repeated option, a control character | `Event::Poll`; remembered; its `seq` counts like a text's |
| `vote` | the poll is not one it remembers in this conversation, or is closed; a choice out of range, repeated, not ascending; two choices in a single-choice poll | `Event::Vote`; replaces the sender's choices |
| `pollClose` | the sender is not the poll's author; the poll is unknown or already closed; a ballot by someone not in the conversation, twice for one person, empty, or invalid as a vote | `Event::PollClosed` with the ballots; the poll is closed, its votes are the ballots |
Blocked contacts' polls, votes and closes are dropped, as their texts are. Sending checks the same
rules and refuses with `ClientError::BadPoll` (a malformed poll or vote, a poll that is not ours to
close) or `ClientError::PollClosed`.
### 2.5 The client's API (Amicitia pins it)
- `compose_poll(contact, question, options: &[String], multiple) -> Outgoing`; `sent_seq` names it.
- `vote(contact, poll: MessageRef, choices: &[u8]) -> Outgoing`.
- `close_poll(contact, poll: MessageRef) -> Outgoing`; only our own poll.
- `Event::Poll { contact, seq, question, options, multiple }`, `Event::Vote { contact, poll, choices }`,
`Event::PollClosed { contact, poll, ballots: Vec<Ballot> }`; `Ballot { author, choices }`.
- Constants `MIN_POLL_OPTIONS` 2, `MAX_POLL_OPTIONS` 10, `MAX_OPTION_CHARS` 100,
`MAX_QUESTION_CHARS` 300.
### 2.6 An older client
A client from F27 does not know these kinds: a `poll` (it has a `seq`) shows as *Update Amicitia to
see this message*; a `vote` and a `pollClose` (no `seq`) are dropped. That is F27's rule working.
## 3. Risks
- **Privacy:** the two members learn the question, the options and who voted for what — **there is
no anonymous poll**: MLS authenticates every sender, so an anonymous vote could not be honest. The
app says *Everyone in this chat sees who voted for what* on the poll. The relay sees three more
kinds of blob, sized like short texts; the close's size grows with the number of votes (§5's note
on sizes; padding is G41's later work).
- **Integrity:** only a member can vote (MLS), only for themselves (a vote has no author field: it is
the sender's), only the asker can close, and the close can only name members.
- **Snapshot growth:** a few dozen bytes per poll, kept while the conversation exists.
- **Events (Amicitia):** none — votes and closes are not check-ins; a poll is a message like a text.
- **Offline:** staged as every payload; the app delivers them in order (F27's `deliver_older`).
## 4. Gaps and designed solutions
| Gap | Design |
|:--|:--|
| A vote and a close cross | The close carries the ballots (§2.2) |
| The app could invent a close's result | The client fills `ballots` from what it accepted (§2.3) |
| A poll from before the client kept polls (none exist: nobody sent one) | — |
| Polls in groups (F32): more members, more ballots | `Ballot` already names its author; F32 checks membership against the roster |
| The close's size reveals roughly how many voted | Up to two ballots in 1:1; G41's padding later |
| A peer reuses the `seq` of an earlier text for a poll, so one name means two messages (texts allow it too) | Later, for every kind with a `seq` at once: refuse a `seq` at or below the highest received, with care for a blob fetched again after a crash |
## 5. Verification
| Case | Test |
|:--|:--|
| A poll arrives with its seq, question, options and `multiple`; a receipt covers it | `client/tests/polls.rs` |
| A vote is set, replaced and taken back; both sides' own and their votes | same |
| A close carries the ballots the asker had, and the result is the same on both sides | same |
| A vote that crosses the close is not in the result anywhere | same |
| Only the asker closes; a vote or a second close after the close is refused and dropped | same + unit |
| Malformed polls, votes and closes are refused when sending and dropped when received | unit through `receive_payload` |
| A blocked contact's poll and vote are dropped | unit |
| The poll survives a snapshot and restore, closed or open, with its votes | `client/tests/polls.rs` |
| An F27 client shows a poll as Unsupported | F27's rule, its own test (`a_newer_apps_message_is_unsupported_and_counts_for_receipts`, now with `file` as the newer kind) |
| The relay's database holds no question and no option (canary; a choice is a small number, which no canary can find) | `real_relay.rs` |
| Planted bugs | the review |
+632 -8
View File
@@ -45,8 +45,24 @@ pub const MAX_NAME_CHARS: usize = 64;
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
/// The longest reaction, in bytes of UTF-8: the longest emoji ZWJ sequences are 28.
pub const MAX_EMOJI_BYTES: usize = 32;
/// The fewest and the most options a poll has.
pub const MIN_POLL_OPTIONS: usize = 2;
pub const MAX_POLL_OPTIONS: usize = 10;
/// The longest poll option, in characters.
pub const MAX_OPTION_CHARS: usize = 100;
/// The longest poll question, in characters.
pub const MAX_QUESTION_CHARS: usize = 300;
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
const KNOWN_KINDS: [&str; 5] = ["hello", "text", "receipt", "inbox", "reaction"];
const KNOWN_KINDS: [&str; 8] = [
"hello",
"text",
"receipt",
"inbox",
"reaction",
"poll",
"vote",
"pollClose",
];
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
@@ -66,6 +82,12 @@ pub enum ClientError {
/// A reply or reaction to a message that does not exist in this conversation, or an emoji
/// that is empty or has a control character.
BadReference,
/// A poll that is not well formed (an option blank or repeated, too few or too many), a vote
/// that is not (a choice out of range, repeated, or several in a single-choice poll), or a
/// close of a poll that is not ours or not in this conversation.
BadPoll,
/// A vote or a close for a poll that is already closed.
PollClosed,
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
State,
}
@@ -125,6 +147,28 @@ pub enum Event {
to: MessageRef,
emoji: Option<String>,
},
/// A poll (a message: `seq` names it with the contact's author, like a text's).
Poll {
contact: ContactId,
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
},
/// The contact's vote in a poll of this conversation, replacing their earlier one; no choices
/// takes it back. Indexes into the poll's options, ascending.
Vote {
contact: ContactId,
poll: MessageRef,
choices: Vec<u8>,
},
/// The contact closed their poll. `ballots` are the final votes, ours included: show these,
/// not what was counted before.
PollClosed {
contact: ContactId,
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// A message of a kind this client does not know (a newer app's). Show that something arrived
/// that needs an update; its `seq` counts like a text's.
Unsupported { contact: ContactId, seq: u64 },
@@ -211,6 +255,45 @@ pub struct MessageRef {
pub seq: u64,
}
/// One member's choices in a poll, as a close reports them.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Ballot {
pub author: Author,
pub choices: Vec<u8>,
}
/// A poll in a conversation, as this client accepted it (`.agents/features/polls.md` §2.3).
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct PollState {
pub(crate) poll: MessageRef,
pub(crate) options: u8,
pub(crate) multiple: bool,
pub(crate) closed: bool,
/// Each member's current, non-empty choices.
pub(crate) ballots: Vec<Ballot>,
}
impl PollState {
/// Indexes into the options, ascending, each once; at most one unless `multiple`.
fn choices_ok(&self, choices: &[u8]) -> bool {
choices.iter().all(|&i| i < self.options)
&& choices.windows(2).all(|w| w[0] < w[1])
&& (self.multiple || choices.len() <= 1)
}
fn set_ballot(&mut self, author: Author, choices: &[u8]) {
self.ballots.retain(|b| b.author != author);
if !choices.is_empty() {
self.ballots.push(Ballot {
author,
choices: choices.to_vec(),
});
}
}
}
/// The JSON inside an MLS application message. The relay never sees it.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
@@ -237,6 +320,22 @@ enum Payload {
#[serde(default, skip_serializing_if = "Option::is_none")]
emoji: Option<String>,
},
/// A question with options; a message, sharing the sender's `seq` with texts.
#[serde(rename_all = "camelCase")]
Poll {
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
},
/// The sender's choices in `poll`, replacing their earlier ones; `[]` takes the vote back.
Vote { poll: MessageRef, choices: Vec<u8> },
/// The poll's author closed it; `ballots` are the final votes.
#[serde(rename_all = "camelCase")]
PollClose {
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// The receiver has saved our texts up to `upto`.
Receipt { upto: u64 },
/// A new post token for the mailbox the receiver already knows (unblock).
@@ -273,6 +372,8 @@ struct Contact {
sent_seq: u64,
/// The highest `seq` of their texts we have received.
received_seq: u64,
/// The polls in this conversation, ours and theirs.
polls: Vec<PollState>,
}
pub struct Client<T: Transport> {
@@ -477,6 +578,7 @@ impl<T: Transport> Client<T> {
blocked: false,
sent_seq: 0,
received_seq: 0,
polls: Vec::new(),
});
id
}
@@ -573,6 +675,121 @@ impl<T: Transport> Client<T> {
Ok(Outgoing::post(out_to, post, blob))
}
/// A poll for a contact: a message, named by [`Client::sent_seq`] right after. `multiple`
/// lets a vote hold several choices. No network: save the snapshot, then deliver.
pub fn compose_poll(
&mut self,
contact: ContactId,
question: &str,
options: &[String],
multiple: bool,
) -> Result<Outgoing, ClientError> {
if question.chars().count() > MAX_QUESTION_CHARS
|| options.iter().any(|o| o.chars().count() > MAX_OPTION_CHARS)
{
return Err(ClientError::TooLong);
}
if !poll_ok(question, options) {
return Err(ClientError::BadPoll);
}
let index = self.index_of(contact)?;
let author = self.author();
let c = &mut self.contacts[index];
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let seq = c.sent_seq + 1;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::Poll {
seq,
question: question.to_string(),
options: options.to_vec(),
multiple,
},
)?;
c.sent_seq = seq;
c.polls.push(PollState {
poll: MessageRef { author, seq },
// At most MAX_POLL_OPTIONS (10), checked above.
options: options.len() as u8,
multiple,
closed: false,
ballots: Vec::new(),
});
Ok(Outgoing::post(to, post, blob))
}
/// Our vote in a poll of this conversation, ours or theirs, replacing our earlier one; `[]`
/// takes it back. No network: save the snapshot, then deliver.
pub fn vote(
&mut self,
contact: ContactId,
poll: MessageRef,
choices: &[u8],
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
let author = self.author();
let c = &mut self.contacts[index];
let p = c
.polls
.iter()
.position(|p| p.poll == poll)
.ok_or(ClientError::BadPoll)?;
if c.polls[p].closed {
return Err(ClientError::PollClosed);
}
if !c.polls[p].choices_ok(choices) {
return Err(ClientError::BadPoll);
}
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::Vote {
poll,
choices: choices.to_vec(),
},
)?;
c.polls[p].set_ballot(author, choices);
Ok(Outgoing::post(to, post, blob))
}
/// Closes our own poll. The close carries the votes this client has accepted, which become the
/// result on both sides. No network: save the snapshot, then deliver.
pub fn close_poll(
&mut self,
contact: ContactId,
poll: MessageRef,
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
if poll.author != self.author() {
return Err(ClientError::BadPoll);
}
let c = &mut self.contacts[index];
let p = c
.polls
.iter()
.position(|p| p.poll == poll)
.ok_or(ClientError::BadPoll)?;
if c.polls[p].closed {
return Err(ClientError::PollClosed);
}
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::PollClose {
poll,
ballots: c.polls[p].ballots.clone(),
},
)?;
c.polls[p].closed = true;
Ok(Outgoing::post(to, post, blob))
}
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
pub fn author(&self) -> Author {
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
@@ -1018,6 +1235,14 @@ impl<T: Transport> Client<T> {
emoji,
}))
}
Payload::Poll {
seq,
question,
options,
multiple,
} => self.receive_poll(index, seq, question, options, multiple),
Payload::Vote { poll, choices } => self.receive_vote(index, poll, choices),
Payload::PollClose { poll, ballots } => self.receive_close(index, poll, ballots),
Payload::Receipt { upto } => {
let c = &self.contacts[index];
if !self.receipts || c.name.is_none() || c.blocked {
@@ -1055,6 +1280,124 @@ impl<T: Transport> Client<T> {
c.received_seq = c.received_seq.max(seq);
Ok(Some(Event::Unsupported { contact: c.id, seq }))
}
/// The contact's poll: kept if well formed and not one we already have under that name.
fn receive_poll(
&mut self,
index: usize,
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(author) = self.peer_author(index) else {
return Ok(None);
};
let name = MessageRef { author, seq };
let c = &mut self.contacts[index];
let fits = question.chars().count() <= MAX_QUESTION_CHARS
&& options
.iter()
.all(|o| o.chars().count() <= MAX_OPTION_CHARS);
if c.blocked
|| seq == 0
|| !fits
|| !poll_ok(&question, &options)
|| c.polls.iter().any(|p| p.poll == name)
{
return Ok(None);
}
c.received_seq = c.received_seq.max(seq);
c.polls.push(PollState {
poll: name,
// At most MAX_POLL_OPTIONS (10): poll_ok.
options: options.len() as u8,
multiple,
closed: false,
ballots: Vec::new(),
});
Ok(Some(Event::Poll {
contact: c.id,
seq,
question,
options,
multiple,
}))
}
/// The contact's vote, in a poll of this conversation that is still open.
fn receive_vote(
&mut self,
index: usize,
poll: MessageRef,
choices: Vec<u8>,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(author) = self.peer_author(index) else {
return Ok(None);
};
let c = &mut self.contacts[index];
if c.blocked {
return Ok(None);
}
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
return Ok(None);
};
if p.closed || !p.choices_ok(&choices) {
return Ok(None);
}
p.set_ballot(author, &choices);
Ok(Some(Event::Vote {
contact: c.id,
poll,
choices,
}))
}
/// The contact closed their own poll: its votes become the close's ballots, if each is a
/// member's, once, and a valid vote.
fn receive_close(
&mut self,
index: usize,
poll: MessageRef,
ballots: Vec<Ballot>,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(peer) = self.peer_author(index) else {
return Ok(None);
};
let me = self.author();
let c = &mut self.contacts[index];
if c.blocked || poll.author != peer {
return Ok(None);
}
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
return Ok(None);
};
let valid = ballots.iter().enumerate().all(|(i, b)| {
(b.author == me || b.author == peer)
&& !ballots[..i].iter().any(|o| o.author == b.author)
&& !b.choices.is_empty()
&& p.choices_ok(&b.choices)
});
if p.closed || !valid {
return Ok(None);
}
p.closed = true;
p.ballots = ballots.clone();
Ok(Some(Event::PollClosed {
contact: c.id,
poll,
ballots,
}))
}
}
enum Parsed {
@@ -1081,6 +1424,19 @@ fn parse_payload(bytes: &[u8]) -> Result<Parsed, ClientError> {
}
}
/// A poll's question and options as the wire allows them (the lengths are checked apart): 2–10
/// options, none blank, none repeated, no control characters anywhere.
fn poll_ok(question: &str, options: &[String]) -> bool {
let fine = |s: &str| !s.trim().is_empty() && !s.chars().any(char::is_control);
(MIN_POLL_OPTIONS..=MAX_POLL_OPTIONS).contains(&options.len())
&& fine(question)
&& options.iter().all(|o| fine(o))
&& options
.iter()
.enumerate()
.all(|(i, o)| !options[..i].contains(o))
}
/// An emoji as the wire allows it: not empty, no control characters (the length is checked apart,
/// as [`ClientError::TooLong`]).
fn emoji_ok(emoji: &str) -> bool {
@@ -1226,14 +1582,18 @@ mod tests {
#[test]
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
assert!(matches!(
parse_payload(br#"{"kind":"poll","seq":4,"question":"?"}"#),
parse_payload(br#"{"kind":"file","seq":4,"name":"?"}"#),
Ok(Parsed::Unknown { seq: 4 })
));
for bad in [
&br#"{"kind":"poll","question":"?"}"#[..],
br#"{"kind":"poll","seq":0}"#,
br#"{"kind":"poll","seq":-1}"#,
br#"{"kind":"poll","seq":"4"}"#,
&br#"{"kind":"file","name":"?"}"#[..],
br#"{"kind":"file","seq":0}"#,
br#"{"kind":"file","seq":-1}"#,
br#"{"kind":"file","seq":"4"}"#,
br#"{"kind":"poll","seq":4,"question":"?"}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[256]}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[-1]}"#,
br#"{"kind":"pollClose","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"ballots":[{"author":"AAAAAAAAAAAAAAAAAAAAAA","choices":[0],"x":1}]}"#,
br#"{"seq":4}"#,
br#"{"kind":"text","body":"x","seq":1,"mentions":[]}"#,
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"emoji":"x","extra":1}"#,
@@ -1345,9 +1705,9 @@ mod tests {
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
let (mut eva, mut jan) = paired();
eva.set_receipts(true);
let out = seal_raw(&mut jan, r#"{"kind":"poll","seq":1,"question":"Pivo?"}"#);
let out = seal_raw(&mut jan, r#"{"kind":"file","seq":1,"name":"Pivo.jpg"}"#);
jan.deliver(&out).expect("deliver");
let out = seal_raw(&mut jan, r#"{"kind":"poll","question":"no seq"}"#);
let out = seal_raw(&mut jan, r#"{"kind":"file","name":"no seq"}"#);
jan.deliver(&out).expect("deliver");
let got = eva.receive().expect("receive");
assert_eq!(
@@ -1364,6 +1724,253 @@ mod tests {
assert_eq!(eva.receive_unknown(0, 2), Ok(None));
}
// Polls (`.agents/features/polls.md` §2.4).
fn strings(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
fn their_poll(seq: u64, options: &[&str], multiple: bool) -> Payload {
Payload::Poll {
seq,
question: "Kam?".into(),
options: strings(options),
multiple,
}
}
#[test]
fn a_malformed_poll_is_refused_when_sending_and_dropped_when_received() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let long = "x".repeat(MAX_OPTION_CHARS + 1);
let eleven: Vec<String> = (0..11).map(|i| i.to_string()).collect();
let bad: [(&str, Vec<String>); 7] = [
("Kam?", strings(&["jen jedna"])),
("Kam?", eleven),
("Kam?", strings(&["a", "a"])),
("Kam?", strings(&["a", " "])),
(" ", strings(&["a", "b"])),
("Kam?\u{7}", strings(&["a", "b"])),
("Kam?", strings(&["a", "b\n"])),
];
for (question, options) in &bad {
assert_eq!(
eva.compose_poll(id, question, options, false).err(),
Some(ClientError::BadPoll),
"{question:?} {options:?}"
);
let got = eva.receive_payload(
0,
Payload::Poll {
seq: 1,
question: question.to_string(),
options: options.clone(),
multiple: false,
},
);
assert_eq!(got, Ok(None), "{question:?} {options:?}");
}
assert_eq!(
eva.compose_poll(id, "Kam?", &[long.clone(), "b".into()], false)
.err(),
Some(ClientError::TooLong)
);
let long_question = "?".repeat(MAX_QUESTION_CHARS + 1);
assert_eq!(
eva.compose_poll(id, &long_question, &strings(&["a", "b"]), false)
.err(),
Some(ClientError::TooLong)
);
assert_eq!(
eva.receive_payload(
0,
Payload::Poll {
seq: 1,
question: "Kam?".into(),
options: vec![long, "b".into()],
multiple: false,
}
),
Ok(None)
);
assert_eq!(
eva.contacts[0].received_seq, 0,
"a dropped poll does not count"
);
assert!(eva.contacts[0].polls.is_empty());
// Ten options of exactly 100 characters, and 300 of question: fits.
let ten: Vec<String> = (0..10).map(|i| format!("{i}{}", "y".repeat(99))).collect();
let q = "?".repeat(MAX_QUESTION_CHARS);
assert!(eva.compose_poll(id, &q, &ten, true).is_ok());
assert!(matches!(
eva.receive_payload(0, their_poll(1, &["a", "b"], false)),
Ok(Some(Event::Poll { seq: 1, .. }))
));
assert_eq!(
eva.receive_payload(0, their_poll(1, &["c", "d"], false)),
Ok(None),
"a second poll under the same name"
);
}
#[test]
fn a_vote_that_does_not_fit_its_poll_is_refused_and_dropped() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let jan = eva.peer_author(0).expect("author");
eva.receive_payload(0, their_poll(1, &["a", "b", "c"], false))
.expect("poll");
eva.receive_payload(0, their_poll(2, &["a", "b", "c"], true))
.expect("poll");
let single = MessageRef {
author: jan,
seq: 1,
};
let multi = MessageRef {
author: jan,
seq: 2,
};
let unknown = MessageRef {
author: jan,
seq: 3,
};
let vote = |poll, choices: &[u8]| Payload::Vote {
poll,
choices: choices.to_vec(),
};
for (poll, choices) in [
(single, &[0u8, 1][..]),
(single, &[3][..]),
(multi, &[1, 0][..]),
(multi, &[1, 1][..]),
(multi, &[3][..]),
(unknown, &[0][..]),
] {
assert_eq!(
eva.vote(id, poll, choices).err(),
Some(ClientError::BadPoll),
"{poll:?} {choices:?}"
);
assert_eq!(eva.receive_payload(0, vote(poll, choices)), Ok(None));
}
assert!(eva.vote(id, multi, &[0, 2]).is_ok());
assert!(eva.vote(id, single, &[]).is_ok(), "taking back nothing");
assert!(matches!(
eva.receive_payload(0, vote(multi, &[0, 1, 2])),
Ok(Some(Event::Vote { .. }))
));
let p = &eva.contacts[0].polls[1];
assert_eq!(p.ballots.len(), 2);
// Taking it back removes the ballot.
eva.receive_payload(0, vote(multi, &[])).expect("vote");
assert_eq!(eva.contacts[0].polls[1].ballots.len(), 1);
}
#[test]
fn only_the_asker_closes_with_valid_ballots_and_then_nothing_changes_it() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let jan = eva.peer_author(0).expect("author");
let me = eva.author();
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
.expect("poll");
let theirs = MessageRef {
author: jan,
seq: 1,
};
let out = eva.compose_poll(id, "Kdy?", &strings(&["pá", "so"]), false);
assert!(out.is_ok());
let ours = MessageRef { author: me, seq: 1 };
assert_eq!(
eva.close_poll(id, theirs).err(),
Some(ClientError::BadPoll),
"not ours to close"
);
let close = |poll, ballots: Vec<Ballot>| Payload::PollClose { poll, ballots };
let ballot = |author, choices: &[u8]| Ballot {
author,
choices: choices.to_vec(),
};
let stranger = Author::from_bytes([7; 16]);
for payload in [
// Jan cannot close Eva's poll.
close(ours, vec![]),
close(theirs, vec![ballot(stranger, &[0])]),
close(theirs, vec![ballot(jan, &[0]), ballot(jan, &[1])]),
close(theirs, vec![ballot(jan, &[])]),
close(theirs, vec![ballot(me, &[0, 1])]),
close(theirs, vec![ballot(me, &[2])]),
close(
MessageRef {
author: jan,
seq: 2,
},
vec![],
),
] {
assert_eq!(eva.receive_payload(0, payload), Ok(None));
}
assert!(!eva.contacts[0].polls[0].closed);
let final_ = vec![ballot(jan, &[1]), ballot(me, &[0])];
assert_eq!(
eva.receive_payload(0, close(theirs, final_.clone())),
Ok(Some(Event::PollClosed {
contact: id,
poll: theirs,
ballots: final_.clone()
}))
);
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
// Closed: no vote, no second close, from either side.
assert_eq!(
eva.vote(id, theirs, &[1]).err(),
Some(ClientError::PollClosed)
);
let vote = Payload::Vote {
poll: theirs,
choices: vec![0],
};
assert_eq!(eva.receive_payload(0, vote), Ok(None));
assert_eq!(eva.receive_payload(0, close(theirs, vec![])), Ok(None));
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
// Our own: closed once.
assert!(eva.close_poll(id, ours).is_ok());
assert_eq!(
eva.close_poll(id, ours).err(),
Some(ClientError::PollClosed)
);
}
#[test]
fn a_blocked_contacts_poll_vote_and_close_are_dropped() {
let (mut eva, _jan) = paired();
let jan = eva.peer_author(0).expect("author");
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
.expect("poll");
let poll = MessageRef {
author: jan,
seq: 1,
};
eva.contacts[0].blocked = true;
assert_eq!(
eva.receive_payload(0, their_poll(2, &["a", "b"], false)),
Ok(None)
);
let vote = Payload::Vote {
poll,
choices: vec![0],
};
assert_eq!(eva.receive_payload(0, vote), Ok(None));
let close = Payload::PollClose {
poll,
ballots: vec![],
};
assert_eq!(eva.receive_payload(0, close), Ok(None));
assert_eq!(eva.contacts[0].polls.len(), 1);
assert!(!eva.contacts[0].polls[0].closed);
assert!(eva.contacts[0].polls[0].ballots.is_empty());
}
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
/// *Unsupported* at a client of the same version.
#[test]
@@ -1388,6 +1995,23 @@ mod tests {
post_token: Token::from_bytes([0; 32]),
},
Payload::Reaction { to, emoji: None },
Payload::Poll {
seq: 2,
question: "?".into(),
options: vec!["a".into(), "b".into()],
multiple: false,
},
Payload::Vote {
poll: to,
choices: vec![0],
},
Payload::PollClose {
poll: to,
ballots: vec![Ballot {
author: to.author,
choices: vec![1],
}],
},
];
assert_eq!(all.len(), KNOWN_KINDS.len());
for payload in all {
+7 -2
View File
@@ -3,8 +3,8 @@
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
use crate::{
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
CIPHERSUITE, MAX_NAME_CHARS,
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, PollState, Transport,
WelcomeBox, CIPHERSUITE, MAX_NAME_CHARS,
};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
@@ -54,6 +54,9 @@ struct ContactState {
sent_seq: u64,
#[serde(default)]
received_seq: u64,
// F28 (`.agents/features/polls.md` §2.3); absent in older snapshots.
#[serde(default)]
polls: Vec<PollState>,
}
fn yes() -> bool {
@@ -107,6 +110,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls.clone(),
})
.collect(),
welcome_boxes: self.welcome_boxes.clone(),
@@ -163,6 +167,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls,
});
}
Ok(Client {
+241
View File
@@ -0,0 +1,241 @@
//! Polls (`.agents/features/polls.md`). No I/O: runs on the Android emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(receipts);
jan.set_receipts(receipts);
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let Some(Event::Joined {
contact: eva_side, ..
}) = eva.poll().expect("poll").first().cloned()
else {
panic!("no join")
};
jan.poll().expect("poll");
(eva, eva_side, jan, jan_side)
}
fn strings(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
fn send(c: &mut C, out: Result<Outgoing, ClientError>) {
let out = out.expect("compose");
c.deliver(&out).expect("deliver");
}
#[test]
fn a_poll_arrives_votes_change_and_the_close_gives_both_sides_the_same_result() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
eva.send(eva_side, "Ahoj").expect("send");
let options = strings(&["Italská", "Thajská", "Doma"]);
let out = eva.compose_poll(eva_side, "Kam na večeři?", &options, true);
send(&mut eva, out);
assert_eq!(eva.sent_seq(eva_side), Some(2), "a poll is a message");
let poll = MessageRef {
author: eva.author(),
seq: 2,
};
let got = jan.poll().expect("poll");
assert_eq!(
got[1],
Event::Poll {
contact: jan_side,
seq: 2,
question: "Kam na večeři?".into(),
options: options.clone(),
multiple: true,
}
);
// Jan votes, changes his mind, takes it back, votes again; Eva votes in her own poll.
for choices in [&[0u8][..], &[0, 1], &[], &[1, 2]] {
let out = jan.vote(jan_side, poll, choices);
send(&mut jan, out);
}
let out = eva.vote(eva_side, poll, &[1]);
send(&mut eva, out);
let votes: Vec<Vec<u8>> = eva
.poll()
.expect("poll")
.into_iter()
.map(|e| match e {
Event::Vote {
contact,
poll: p,
choices,
} if contact == eva_side && p == poll => choices,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(votes, vec![vec![0], vec![0, 1], vec![], vec![1, 2]]);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::Vote {
contact: jan_side,
poll,
choices: vec![1]
}]
);
// A poll can be answered and reacted to like a text.
let out = jan.compose_text(jan_side, "Thajská!", Some(poll));
send(&mut jan, out);
let out = jan.react(jan_side, poll, Some("👍"));
send(&mut jan, out);
assert_eq!(eva.poll().expect("poll").len(), 2);
// Jan cannot close Eva's poll; Eva closes it.
assert_eq!(
jan.close_poll(jan_side, poll).err(),
Some(ClientError::BadPoll)
);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
let final_ = vec![
Ballot {
author: jan.author(),
choices: vec![1, 2],
},
Ballot {
author: eva.author(),
choices: vec![1],
},
];
let got = jan.poll().expect("poll");
let [Event::PollClosed {
contact,
poll: p,
ballots,
}] = got.as_slice()
else {
panic!("{got:?}")
};
assert_eq!((*contact, *p), (jan_side, poll));
let mut sorted = ballots.clone();
sorted.sort_by_key(|b| b.author.as_bytes().to_vec());
let mut expected = final_.clone();
expected.sort_by_key(|b| b.author.as_bytes().to_vec());
assert_eq!(sorted, expected);
assert_eq!(
jan.vote(jan_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.vote(eva_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
}
#[test]
fn a_vote_that_crosses_the_close_is_counted_nowhere() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Pátek?", &strings(&["ano", "ne"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let poll = MessageRef {
author: eva.author(),
seq: 1,
};
let out = jan.vote(jan_side, poll, &[0]);
send(&mut jan, out);
eva.poll().expect("poll");
// Both at once: Jan changes his vote while Eva closes.
let out = jan.vote(jan_side, poll, &[1]);
send(&mut jan, out);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
assert_eq!(
eva.poll().expect("poll"),
vec![],
"the late vote is dropped"
);
let got = jan.poll().expect("poll");
assert_eq!(
got,
vec![Event::PollClosed {
contact: jan_side,
poll,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0]
}],
}],
"Jan's result is Eva's: his first vote, not the one that crossed"
);
}
#[test]
fn a_receipt_covers_a_poll() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, true);
let out = eva.compose_poll(eva_side, "Pivo?", &strings(&["ano", "jasně"]), false);
send(&mut eva, out);
let got = jan.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Poll { seq: 1, .. }]),
"{got:?}"
);
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
contact: eva_side,
upto: 1
}));
}
#[test]
fn a_poll_survives_a_restart_open_or_closed_with_its_votes() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Kdy?", &strings(&["pá", "so", "ne"]), true);
send(&mut eva, out);
let out = eva.compose_poll(eva_side, "Kde?", &strings(&["u nás", "u vás"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let when = MessageRef {
author: eva.author(),
seq: 1,
};
let where_ = MessageRef {
author: eva.author(),
seq: 2,
};
let out = jan.vote(jan_side, when, &[0, 2]);
send(&mut jan, out);
eva.poll().expect("poll");
let out = eva.close_poll(eva_side, where_);
send(&mut eva, out);
jan.poll().expect("poll");
let mut eva = C::restore(&eva.snapshot().expect("snapshot"), relay.clone()).expect("eva");
let mut jan = C::restore(&jan.snapshot().expect("snapshot"), relay.clone()).expect("jan");
// Closed stays closed, on both sides.
assert_eq!(
jan.vote(jan_side, where_, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.close_poll(eva_side, where_).err(),
Some(ClientError::PollClosed)
);
// The open one keeps Jan's vote: Eva's close after the restart carries it.
let out = eva.close_poll(eva_side, when);
send(&mut eva, out);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::PollClosed {
contact: jan_side,
poll: when,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0, 2]
}],
}]
);
}
+17
View File
@@ -214,6 +214,13 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
};
let out = jan.react(jan_side, mine, Some(emoji)).expect("react");
jan.deliver(&out).expect("deliver");
// And a poll (F28): its question and options neither.
let question = "POLL-QUESTION-CANARY";
let options = vec!["OPTION-CANARY-A".to_string(), "OPTION-CANARY-B".to_string()];
let out = jan
.compose_poll(jan_side, question, &options, false)
.expect("poll");
jan.deliver(&out).expect("deliver");
// Snapshot the database while both messages wait, before anyone fetches.
let waiting = std::fs::read(&db).expect("db");
@@ -240,6 +247,13 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
to: mine,
emoji: Some(emoji.into()),
},
Event::Poll {
contact: eva_side,
seq: 2,
question: question.into(),
options: options.clone(),
multiple: false,
},
]
);
let after = std::fs::read(&db).expect("db");
@@ -248,6 +262,9 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
for (what, needle) in [
("canary", canary.as_bytes()),
("reaction", emoji.as_bytes()),
("poll question", question.as_bytes()),
("poll option", options[0].as_bytes()),
("poll option", options[1].as_bytes()),
("inviter's name", "Eva Nováková".as_bytes()),
("invitee's name", "Jan Dvořák".as_bytes()),
("invite secret", invite.secret.as_bytes().as_slice()),
+4
View File
@@ -53,6 +53,9 @@ Every MLS application message carries one JSON object. The relay sees none of it
| `hello` | `mailbox`, `postToken`, `name` | where and how to post to the sender; once per conversation |
| `text` | `body`, `seq`, `replyTo`? | a message; `seq` counts the sender's messages to this contact from 1. `replyTo` *(2026-11-21)*, when there, names the message it answers |
| `reaction` *(2026-11-21)* | `to`, `emoji`? | the sender's reaction to the message `to`: `emoji` (1–32 bytes of UTF-8, no control characters) sets it, replacing their earlier one; absent removes it. No `seq` |
| `poll` *(2026-11-22)* | `seq`, `question`, `options`, `multiple` | a message (it shares `seq` with `text`): a question of 1–300 characters and 2–10 different options of 1–100, none blank, no control characters; `multiple` allows several choices in a vote |
| `vote` *(2026-11-22)* | `poll`, `choices` | the sender's choices in the poll `poll` names, replacing their earlier ones: indexes into `options`, ascending, each once, at most one unless `multiple`; `[]` takes the vote back. Refused once the poll is closed. No `seq` |
| `pollClose` *(2026-11-22)* | `poll`, `ballots` | sent by the poll's author only: the poll is closed, and `ballots` (`{author, choices}`, one per member with a non-empty vote) are **the final votes**, as the author's client had accepted them, so a vote that crossed the close counts nowhere. No `seq` |
| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them |
| `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox |
@@ -111,6 +114,7 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
## 7. Tests that prove this document
- A canary string sent in a message never appears anywhere in the relay's database or logs.
- A reaction's emoji and a reply's text never appear in the relay's database (`client/tests/real_relay.rs`, `client/tests/reactions.rs`); a reaction or reply to a message that does not exist in the conversation is refused (`client/tests/reactions.rs`, the client's unit tests).
- A poll's question and options never appear in the relay's database (`client/tests/real_relay.rs`); a vote or close that does not fit its poll, a close by anyone but the poll's author, and anything after the close are refused and dropped (`client/tests/polls.rs`, the client's unit tests).
- A post without a valid token is refused; after rotation the old token is refused.
- A delivered blob is gone; an undelivered blob is gone after the TTL (clock injected).
- A wake carries the constant body and nothing of the mailbox, its tokens or the blob; a mailbox is