diff --git a/DESCRIPTION b/DESCRIPTION index 8016643..edd5cdf 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Package: chat.api Type: Package Title: Transport-Agnostic Chat Contract -Version: 0.2.0.3 -Date: 2026-11-18 +Version: 0.2.0.4 +Date: 2026-11-30 Authors@R: c( person("Troy", "Hernandez", role = c("aut", "cre"), email = "troy@cornball.ai", diff --git a/NEWS.md b/NEWS.md index 5f3aebf..310d66c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,12 @@ +# chat.api 0.2.0.4 + +* Matrix and loopback history can report page completeness and identify + the creator on the page containing the room creation event. Callers + can use this to verify an entire conversation before filing it. +* Matrix channel information can return the room type, join rule, + history visibility, membership and third-party invites from one + room state response. + # chat.api 0.2.0.3 * A Matrix client built without `e2ee` now says when an encrypted room's diff --git a/R/contract.R b/R/contract.R index bb23f35..dfecfd0 100644 --- a/R/contract.R +++ b/R/contract.R @@ -428,13 +428,15 @@ print.chat_invite <- function(x, ...) { #' Returns the channel's descriptive metadata: what it is called and what #' it is for. #' -#' Membership is deliberately not here, and \code{\link{chat_members}} is -#' a separate verb. The two look like one lookup and are not: a name and -#' a topic are two short strings that change rarely, while a member list -#' is unbounded and changes constantly. Bundling them makes every read of -#' a topic pay for a member list, which on a busy room is the expensive -#' part -- and a consumer caches the two on different schedules for -#' exactly that reason. +#' By default membership is fetched separately by \code{\link{chat_members}}. +#' On Matrix, pass \code{audience = TRUE} to fetch one full room-state +#' snapshot. The additional \code{audience} field holds \code{room_type} +#' (an empty string for an ordinary room), \code{join_rule}, +#' \code{history_visibility}, \code{membership} (a character vector of +#' membership states named by user ID), and \code{third_party_invites} +#' (active state keys). Missing creation, membership, join-rule or history +#' state, or a malformed response, raises an error. Other adapters may +#' omit \code{audience}. #' #' A NULL field means the channel has no such thing: a Matrix room with #' no \code{m.room.name} really has no name. An adapter that cannot @@ -960,6 +962,17 @@ chat_channels.default <- function(client, ...) { #' twice and the second page's messages all precede the first page's. #' A consumer assembling a full transcript prepends. #' +#' @section Complete history pages: +#' On Matrix and loopback, pass \code{require_complete = TRUE} to request +#' evidence that the adapter could read the messages on a page. Matrix +#' raises an error for an undecryptable event or unreadable message type. +#' Redacted messages carry no visible text and are omitted. The returned +#' page has \code{complete = TRUE} and a \code{creator} field naming the +#' sender of the room creation event on that page, or NULL. Other adapters +#' or older versions may omit these fields. A caller filing an entire +#' conversation must check \code{isTRUE(page$complete)} on every page, +#' follow the cursors to the end, and reach the room creation event. +#' #' @section Overlap with chat_poll: #' The same message can arrive from both, and adapters must return the #' same \code{id} for it either way. That id is the only thing a consumer diff --git a/R/loopback.R b/R/loopback.R index 70e29e0..8e65f68 100644 --- a/R/loopback.R +++ b/R/loopback.R @@ -201,7 +201,7 @@ chat_channels.chat_loopback <- function(client, ...) { #' @export chat_history.chat_loopback <- function(client, channel, limit = 50L, - cursor = NULL, ...) { + cursor = NULL, ..., require_complete = FALSE) { log <- client$env$log keep <- vapply(log, function(m) identical(m$channel, channel), logical(1)) log <- log[keep] @@ -230,7 +230,14 @@ chat_history.chat_loopback <- function(client, channel, limit = 50L, } else { nxt <- NULL } - list(messages = log, cursor = nxt) + page <- list(messages = log, cursor = nxt) + if (require_complete) { + creator <- if (is.null(nxt) && channel %in% client$env$channels) { + chat_whoami(client)$id + } + page <- c(page, list(complete = TRUE, creator = creator)) + } + page } #' @export diff --git a/R/matrix-audience.R b/R/matrix-audience.R new file mode 100644 index 0000000..303ace7 --- /dev/null +++ b/R/matrix-audience.R @@ -0,0 +1,59 @@ +# One complete /rooms/{roomId}/state response supplies both the metadata +# and audience. Separate membership and join-rule requests can disagree. +matrix_audience_info <- function(state, room) { + invalid <- function() stop("Incomplete or malformed Matrix room state.", call. = FALSE) + string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) + object <- function(x) { + is.list(x) && !is.data.frame(x) && (!length(x) || + (!is.null(names(x)) && !anyNA(names(x)) && all(nzchar(names(x))) && + !anyDuplicated(names(x)))) + } + if (!is.list(state) || !length(state) || !is.null(names(state))) invalid() + valid_event <- function(ev) { + object(ev) && string(ev[["type"]]) && + nzchar(ev[["type"]]) && string(ev[["state_key"]]) && + object(ev[["content"]]) && + (!("unsigned" %in% names(ev)) || object(ev[["unsigned"]])) && + (!("room_id" %in% names(ev)) || identical(ev[["room_id"]], room)) + } + if (!all(vapply(state, valid_event, logical(1)))) invalid() + types <- vapply(state, "[[", character(1), "type") + keys <- vapply(state, "[[", character(1), "state_key") + if (anyDuplicated(data.frame(types, keys))) invalid() + field <- function(type, name, required = TRUE) { + i <- which(types == type & keys == "") + if (length(i)) { + value <- state[[i]][["content"]][[name]] + if (string(value) && nzchar(value)) return(value) + } + if (required) invalid() + NULL + } + create <- which(types == "m.room.create" & keys == "") + if (length(create) != 1L) invalid() + # Redaction may remove the room type in older room versions. + if ("redacted_because" %in% names(state[[create]][["unsigned"]])) invalid() + creation <- state[[create]][["content"]] + room_type <- if ("type" %in% names(creation)) field("m.room.create", "type") else "" + members <- types == "m.room.member" + ids <- keys[members] + if (!length(ids) || any(!grepl("^@[^:[:space:]]+:[^[:space:]]+$", ids))) invalid() + membership <- vapply(state[members], function(ev) { + value <- ev[["content"]][["membership"]] + if (!string(value) || !value %in% c("join", "invite", "knock", "leave", "ban")) { + invalid() + } + value + }, character(1)) + names(membership) <- ids + # A third-party invite can authorize a future join before the server + # knows the invitee's Matrix ID. Redacted invites have empty content. + third_party <- types == "m.room.third_party_invite" + active <- vapply(state[third_party], function(ev) length(ev[["content"]]) > 0L, logical(1)) + audience <- list(room_type = room_type, + join_rule = field("m.room.join_rules", "join_rule"), + history_visibility = field("m.room.history_visibility", "history_visibility"), + membership = membership, third_party_invites = keys[third_party][active]) + list(id = room, name = field("m.room.name", "name", FALSE), + topic = field("m.room.topic", "topic", FALSE), audience = audience) +} diff --git a/R/matrix.R b/R/matrix.R index c211b9a..8e3dd81 100644 --- a/R/matrix.R +++ b/R/matrix.R @@ -120,9 +120,9 @@ #' Leave NULL in production. Resolved when \code{chat_react()} is #' called, not here, so a NULL seam costs nothing on installs without #' mx.api. -#' @param .info Testing seam: a list with \code{name} and \code{topic}, -#' replacing \code{mx.api::mx_room_name} and -#' \code{mx.api::mx_room_topic}. Leave NULL in production. +#' @param .info Testing seam for channel info. The \code{name}, +#' \code{topic}, and \code{state} functions replace \code{mx.api}'s +#' room name, topic, and full state readers. Leave NULL in production. #' @param .members Testing seam: replacement for #' \code{mx.api::mx_room_members}. Leave NULL in production. #' @param .join Testing seam: replacement for @@ -908,8 +908,12 @@ chat_react.chat_matrix <- function(client, channel, message_id, key, ...) { } #' @export -chat_channel_info.chat_matrix <- function(client, channel, ...) { +chat_channel_info.chat_matrix <- function(client, channel, ..., audience = FALSE) { s <- mx.client::mx_client_session(client$env$mx) + if (isTRUE(audience)) { + state_fn <- client$info_fn[["state"]] %||% mx.api::mx_room_state + return(matrix_audience_info(state_fn(s, channel), channel)) + } info <- client$info_fn %||% list(name = mx.api::mx_room_name, topic = mx.api::mx_room_topic) # A room with neither is the ordinary case for a direct message, and @@ -1221,7 +1225,7 @@ matrix_history_decrypt <- function(client, page) { #' @export chat_history.chat_matrix <- function(client, channel, limit = 50L, - cursor = NULL, ...) { + cursor = NULL, ..., require_complete = FALSE) { fn <- client$history_fn %||% mx.api::mx_messages sess <- mx.client::mx_client_session(client$env$mx) args <- list(sess, channel, dir = "b", limit = as.integer(limit)) @@ -1233,6 +1237,9 @@ chat_history.chat_matrix <- function(client, channel, limit = 50L, args$from <- cursor } res <- do.call(fn, args) + if (require_complete && !is.list(res$chunk)) { + stop("chat_history(): missing Matrix history page", call. = FALSE) + } chunk <- res$chunk %||% list() # Matrix pages backwards, so the chunk arrives newest-first. The # contract promises oldest-first, and this is the one place that @@ -1253,12 +1260,34 @@ chat_history.chat_matrix <- function(client, channel, limit = 50L, } contents <- matrix_event_contents(page) out <- list() + creator <- NULL for (ev in chunk) { id <- as.character(ev$event_id %||% "") + if (require_complete) { + if (!is.character(ev$type) || length(ev$type) != 1L || + is.na(ev$type) || !nzchar(ev$type)) { + stop("chat_history(): missing Matrix event type", call. = FALSE) + } + if (identical(ev$type, "m.room.create") && identical(ev$state_key, "")) { + creator <- ev$sender + } + # A redaction removes the original text and, for an encrypted + # event, its ciphertext. Both are absent from the visible history. + if (!is.null(ev$unsigned$redacted_because)) next + if (identical(ev$type, "m.room.encrypted") && is.null(decrypted[[id]])) { + stop("chat_history(): could not decrypt Matrix event ", id, call. = FALSE) + } + } if (nzchar(id) && !is.null(decrypted[[id]])) { d <- decrypted[[id]] m <- matrix_decrypted_message(d, d$ts %||% ev$origin_server_ts, self_id) + if (require_complete && + identical(d$type %||% "m.room.message", "m.room.message") && + (is.null(m) || is.na(m$body) || + (is.na(matrix_kind_strict(d$msgtype)) && !length(m$attachments)))) { + stop("chat_history(): unreadable Matrix message ", id, call. = FALSE) + } if (!is.null(m)) { out[[length(out) + 1L]] <- m } @@ -1275,6 +1304,10 @@ chat_history.chat_matrix <- function(client, channel, limit = 50L, } msgtype <- ev$content$msgtype %||% "" kind <- matrix_kind_strict(msgtype) + if (require_complete && (is.na(kind) || !is.character(ev$content$body) || + length(ev$content$body) != 1L || is.na(ev$content$body))) { + stop("chat_history(): unreadable Matrix message ", id, call. = FALSE) + } if (is.na(kind)) { # A msgtype the contract has no word for, with nothing to # fetch: a location, a picture with no address. Skipping @@ -1302,7 +1335,11 @@ chat_history.chat_matrix <- function(client, channel, limit = 50L, # nothing older, which is how a consumer paging to the start of a # room knows to stop -- an empty chunk is not the signal, because a # window can be all state events and still have history behind it. - list(messages = out, cursor = res$end) + page <- list(messages = out, cursor = res$end) + if (require_complete) { + page <- c(page, list(complete = TRUE, creator = creator)) + } + page } #' @export diff --git a/inst/tinytest/test_matrix.R b/inst/tinytest/test_matrix.R index 374b377..cc2e00f 100644 --- a/inst/tinytest/test_matrix.R +++ b/inst/tinytest/test_matrix.R @@ -2208,6 +2208,52 @@ local({ }) # ---- State: pending ---- +local({ + # A transcript consumer requires evidence for each page before filing it. + # An encrypted redaction has no ciphertext left. A reaction has no text. + # The creator is the room creation event's sender, including in room + # versions where its content has no creator property. + gone <- enc_ev("$gone") + gone$unsigned <- list(redacted_because = list(type = "m.room.redaction")) + make <- list(type = "m.room.create", state_key = "", sender = "@owner:ex", + content = list(room_version = "12"), event_id = "$create") + react <- list(event_id = "$reaction", type = "m.reaction", room_id = "!a:ex") + chunk <- list(enc_ev("$reaction"), gone, hev("$second"), enc_ev("$first"), make) + f <- fake_crypto(decrypted = list(dec_rec("$first", room_id = "!a:ex"), react)) + cl <- seam_client(mx = fake_mx(user_id = "@e2ee-recv:ex"), e2ee = TRUE, + .crypto = f$ops, .history = function(...) list(chunk = chunk), + .extract_media = function(...) list()) + strict <- function() chat_history(cl, "!a:ex", require_complete = TRUE) + page <- strict() + expect_identical(page$complete, TRUE) + expect_identical(page$creator, "@owner:ex") + expect_identical(vapply(page$messages, function(m) m$id, ""), c("$first", "$second")) + chunk <- list(enc_ev("$unread")) + expect_error(strict(), "could not decrypt Matrix event") + chunk <- list(hev("$unknown", msgtype = "m.location")) + expect_error(strict(), "unreadable Matrix message") + chunk <- list(hev("$plain", body = NULL)) + expect_error(strict(), "unreadable Matrix message") + chunk <- NULL + expect_error(strict(), "missing Matrix history page") + chunk <- list(hev("$visible")) + expect_null(strict()$creator) + expect_identical(names(chat_history(cl, "!a:ex")), c("messages", "cursor")) +}) + +local({ + cl <- chat_loopback() + channel <- chat_channel_create(cl, "topic") + chat_send(cl, channel, "first") + chat_send(cl, channel, "second") + page <- chat_history(cl, channel, limit = 1L, require_complete = TRUE) + expect_true(page$complete) + expect_null(page$creator) + older <- chat_history(cl, channel, cursor = page$cursor, require_complete = TRUE) + expect_identical(older$creator, chat_whoami(cl)$id) + expect_null(chat_history(cl, "unknown", require_complete = TRUE)$creator) +}) + if (requireNamespace("mx.client", quietly = TRUE)) local({ seen <- NULL diff --git a/inst/tinytest/test_matrix_audience.R b/inst/tinytest/test_matrix_audience.R new file mode 100644 index 0000000..a66b6c8 --- /dev/null +++ b/inst/tinytest/test_matrix_audience.R @@ -0,0 +1,80 @@ +if (!requireNamespace("mx.client", quietly = TRUE)) exit_file("needs mx.client") + +local({ + room <- "!room:example.org" + event <- function(type, content, key = "") { + list(type = type, state_key = key, content = content, room_id = room) + } + member <- function(id, state) event("m.room.member", list(membership = state), id) + all_state <- list( + event("m.room.create", list(room_version = "11")), + event("m.room.join_rules", list(join_rule = "invite")), + event("m.room.history_visibility", list(history_visibility = "shared")), + member("@bot:example.org", "join"), member("@owner:example.org", "join"), + event("m.room.name", list(name = "Private chat")), + event("m.room.topic", list(topic = "Test topic"))) + calls <- 0L + state <- all_state + read_state <- function(session, id) { + stopifnot(identical(id, room)) + calls <<- calls + 1L + state + } + client <- chat_matrix(mx = list(server = "https://example.invalid", token = "x", + user_id = "@bot:example.org", device_id = "DEV"), + .sync = function(...) NULL, .extract = function(...) list(), + .send = function(...) NULL, .media = function(...) NULL, + .info = list(name = function(...) "regular metadata", + topic = function(...) NULL, state = read_state)) + expect_identical(chat_channel_info(client, room)$name, "regular metadata") + expect_identical(calls, 0L) + get_info <- function() chat_channel_info(client, room, audience = TRUE) + info <- get_info() + expect_identical(calls, 1L) + expect_identical(info$id, room) + expect_identical(info$name, "Private chat") + expect_identical(info$topic, "Test topic") + expect_identical(info$audience, list(room_type = "", join_rule = "invite", + history_visibility = "shared", + membership = c("@bot:example.org" = "join", "@owner:example.org" = "join"), + third_party_invites = character())) + + state <- c(all_state, list(member("@guest:example.org", "knock"), + member("@invitee:example.org", "invite"), + event("m.room.third_party_invite", list(display_name = "guest"), "a"), + event("m.room.third_party_invite", list(), "withdrawn"))) + expect_identical(get_info()$audience$third_party_invites, "a") + expect_identical(unname(tail(get_info()$audience$membership, 2)), c("knock", "invite")) + state[[1]]$content$type <- "m.space" + expect_identical(get_info()$audience$room_type, "m.space") + + for (i in list(1L, 2L, 3L, 4:5)) { + state <- all_state[-i] + expect_error(get_info(), "Matrix room state") + } + for (bad in list(list(), c(all_state, all_state[4]), + list(events = all_state), c(all_state, list(NA)))) { + state <- bad + expect_error(get_info(), "Matrix room state") + } + for (bad in list(list(), list(membership = c("join", "leave")), + list(membership = "unrecognized"), list(membership_alias = "join"))) { + state <- all_state + state[[4]]$content <- bad + expect_error(get_info(), "Matrix room state") + } + state <- all_state + state[[1]]$content <- list("malformed creation") + expect_error(get_info(), "Matrix room state") + state <- all_state + state[[1]]$unsigned <- list(redacted_because = list()) + expect_error(get_info(), "Matrix room state") + state <- all_state + state[[4]]$room_id <- "!other:example.org" + expect_error(get_info(), "Matrix room state") + state <- all_state + state[[4]]$state_key <- "@bot" + expect_error(get_info(), "Matrix room state") + client$info_fn$state <- function(...) stop("state read failed") + expect_error(get_info(), "state read failed") +}) diff --git a/man/chat_channel_info.Rd b/man/chat_channel_info.Rd index 80be8dc..1b64942 100644 --- a/man/chat_channel_info.Rd +++ b/man/chat_channel_info.Rd @@ -22,13 +22,15 @@ Returns the channel's descriptive metadata: what it is called and what it is for. } \details{ -Membership is deliberately not here, and \code{\link{chat_members}} is -a separate verb. The two look like one lookup and are not: a name and -a topic are two short strings that change rarely, while a member list -is unbounded and changes constantly. Bundling them makes every read of -a topic pay for a member list, which on a busy room is the expensive -part -- and a consumer caches the two on different schedules for -exactly that reason. +By default membership is fetched separately by \code{\link{chat_members}}. +On Matrix, pass \code{audience = TRUE} to fetch one full room-state +snapshot. The additional \code{audience} field holds \code{room_type} +(an empty string for an ordinary room), \code{join_rule}, +\code{history_visibility}, \code{membership} (a character vector of +membership states named by user ID), and \code{third_party_invites} +(active state keys). Missing creation, membership, join-rule or history +state, or a malformed response, raises an error. Other adapters may +omit \code{audience}. A NULL field means the channel has no such thing: a Matrix room with no \code{m.room.name} really has no name. An adapter that cannot diff --git a/man/chat_history.Rd b/man/chat_history.Rd index 9107be1..6907534 100644 --- a/man/chat_history.Rd +++ b/man/chat_history.Rd @@ -51,6 +51,18 @@ Note that pages run backwards while each page runs forwards: call it twice and the second page's messages all precede the first page's. A consumer assembling a full transcript prepends. +} +\section{Complete history pages}{ +On Matrix and loopback, pass \code{require_complete = TRUE} to request +evidence that the adapter could read the messages on a page. Matrix +raises an error for an undecryptable event or unreadable message type. +Redacted messages carry no visible text and are omitted. The returned +page has \code{complete = TRUE} and a \code{creator} field naming the +sender of the room creation event on that page, or NULL. Other adapters +or older versions may omit these fields. A caller filing an entire +conversation must check \code{isTRUE(page$complete)} on every page, +follow the cursors to the end, and reach the room creation event. + } \section{Overlap with chat_poll}{ The same message can arrive from both, and adapters must return the diff --git a/man/chat_matrix.Rd b/man/chat_matrix.Rd index 0bacef9..c454b29 100644 --- a/man/chat_matrix.Rd +++ b/man/chat_matrix.Rd @@ -166,9 +166,9 @@ Leave NULL in production. Resolved when \code{chat_react()} is called, not here, so a NULL seam costs nothing on installs without mx.api.} -\item{.info}{Testing seam: a list with \code{name} and \code{topic}, -replacing \code{mx.api::mx_room_name} and -\code{mx.api::mx_room_topic}. Leave NULL in production.} +\item{.info}{Testing seam for channel info. The \code{name}, +\code{topic}, and \code{state} functions replace \code{mx.api}'s +room name, topic, and full state readers. Leave NULL in production.} \item{.members}{Testing seam: replacement for \code{mx.api::mx_room_members}. Leave NULL in production.}