Announce incoming messages on the node's terminal

The node now checks for new messages every 10 s in the background (before,
only when the web UI asked), and Inbox.Collect reports newly filed visible
messages through OnArrivals. The CLI logs one line per conversation with the
listing title and a link to it, never the buyer's text. Hidden messages are not
announced, a backlog is capped at 5 lines, and a lock stops a background check
and a UI request from filing the same message twice.

The e2e checks that node A announces the message before its API is called.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 21:29:49 +01:00
co-authored by Claude Sonnet 5.5
parent 20ea9b32f7
commit a81595e9ee
8 changed files with 316 additions and 16 deletions
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"context"
"fmt"
"log/slog"
"sort"
"time"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
// inboxCheckEvery is how often the node looks for new messages when the
// web UI is not open. (The UI triggers a check itself whenever it asks.)
inboxCheckEvery = 10 * time.Second
// maxNotices caps the lines one check writes, so a backlog after a long
// time offline does not flood the terminal.
maxNotices = 5
)
// watchInbox files incoming messages in the background, so the owner is told
// about them on the terminal even with no browser open. The notices come from
// the Inbox's OnArrivals callback, which also fires for checks made by the UI.
func watchInbox(ctx context.Context, log *slog.Logger, in *inbox.Inbox) {
tick := time.NewTicker(inboxCheckEvery)
defer tick.Stop()
failing := false
for {
if _, err := in.Collect(ctx); err != nil && ctx.Err() == nil {
if !failing { // say it once, not every ten seconds
log.Warn("could not check for new messages", "err", err)
}
failing = true
} else {
failing = false
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// arrivalNotice returns the callback that tells the owner about new messages.
// It names the listing and links to the conversation but never prints what
// the buyer wrote: that is untrusted text and belongs in the browser.
func arrivalNotice(ctx context.Context, log *slog.Logger, st *store.Store, httpAddr string) func([]inbox.Arrival) {
type conv struct {
listing, thread string
author string
count int
started bool
}
return func(arrivals []inbox.Arrival) {
byConv := map[string]*conv{}
var order []string
for _, a := range arrivals {
key := a.Listing.ID + "/" + a.Thread
c := byConv[key]
if c == nil {
c = &conv{listing: a.Listing.ID, thread: a.Thread, author: a.Listing.Author}
byConv[key] = c
order = append(order, key)
}
c.count++
c.started = c.started || a.New
}
sort.Strings(order)
for n, key := range order {
if n == maxNotices {
log.Info("more conversations have new messages", "more", len(order)-maxNotices,
"open", uiURL(httpAddr, "/mine"))
break
}
c := byConv[key]
title := ""
if l, err := st.Get(ctx, c.author, c.listing); err == nil && l != nil {
title = l.Title
}
msg := "new message"
if c.started {
msg = "new conversation"
}
attrs := []any{"listing", title}
if c.count > 1 {
attrs = append(attrs, "messages", c.count)
}
attrs = append(attrs,
"conversation", shortID(c.thread),
"open", uiURL(httpAddr, fmt.Sprintf("/mine/%s/%s", c.listing, c.thread)))
log.Info(msg, attrs...)
}
}
}
func shortID(hex string) string {
if len(hex) > 8 {
return hex[:8]
}
return hex
}
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"bytes"
"context"
"fmt"
"log/slog"
"strings"
"testing"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
func notice(t *testing.T) (func([]inbox.Arrival), *bytes.Buffer) {
t.Helper()
st, err := store.Open(":memory:", store.Options{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
var out bytes.Buffer
log := slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // keep the lines comparable
}
return a
}}))
return arrivalNotice(context.Background(), log, st, "0.0.0.0:8080"), &out
}
func TestNoticeNamesTheConversationAndLinksToIt(t *testing.T) {
say, out := notice(t)
ref := message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)}
thread := strings.Repeat("ab", 32)
say([]inbox.Arrival{{Listing: ref, Thread: thread, New: true}})
got := out.String()
for _, want := range []string{
"level=INFO", `msg="new conversation"`, "conversation=abababab",
"open=http://127.0.0.1:8080/#/mine/" + ref.ID + "/" + thread, // a wildcard bind opens on loopback
} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in:\n%s", want, got)
}
}
if strings.Contains(got, "token") || strings.Contains(got, "login") {
t.Errorf("the notice must not carry the sign-in token:\n%s", got)
}
}
func TestNoticeGroupsMessagesOfOneConversation(t *testing.T) {
say, out := notice(t)
ref := message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)}
thread := strings.Repeat("cd", 32)
say([]inbox.Arrival{{Listing: ref, Thread: thread}, {Listing: ref, Thread: thread}, {Listing: ref, Thread: thread}})
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
if len(lines) != 1 {
t.Fatalf("one conversation, want one line, got %d:\n%s", len(lines), out.String())
}
if !strings.Contains(lines[0], `msg="new message"`) || !strings.Contains(lines[0], "messages=3") {
t.Errorf("want a plain new message with a count of 3: %s", lines[0])
}
}
func TestNoticeCapsALongBacklog(t *testing.T) {
say, out := notice(t)
var arrivals []inbox.Arrival
for i := 0; i < 12; i++ {
arrivals = append(arrivals, inbox.Arrival{
Listing: message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)},
Thread: fmt.Sprintf("%064x", i), New: true,
})
}
say(arrivals)
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
if len(lines) != maxNotices+1 {
t.Fatalf("want %d conversation lines and one summary, got %d:\n%s", maxNotices, len(lines), out.String())
}
last := lines[len(lines)-1]
if !strings.Contains(last, "more=7") || !strings.Contains(last, "#/mine") {
t.Errorf("the summary should say how many more and where to look: %s", last)
}
}
+16 -6
View File
@@ -99,19 +99,22 @@ func cmdRun(args []string) error {
if token == "" {
log.Warn("no admin token found; publishing through the API is disabled")
}
in := &inbox.Inbox{
Store: st, Device: dev, Publisher: node,
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
}
handler := api.New(api.Config{
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
MessageDifficulty: *msgDifficulty,
Inbox: &inbox.Inbox{
Store: st, Device: dev, Publisher: node,
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
},
Inbox: in,
})
ln, err := net.Listen("tcp", *httpAddr)
if err != nil {
return err
}
// Set before anything can call Collect (the server and the watcher below).
in.OnArrivals = arrivalNotice(ctx, log, st, ln.Addr().String())
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
@@ -144,6 +147,7 @@ func cmdRun(args []string) error {
}
go announce(ctx, log, node, st, dev.Cert.Author)
go watchInbox(ctx, log, in)
<-ctx.Done()
log.Info("shutting down")
@@ -186,14 +190,20 @@ func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.S
// loginURL is the link that signs the owner in to the web UI.
func loginURL(listenAddr, token string) string {
return uiURL(listenAddr, "/login/"+token)
}
// uiURL is the address of a page of the web UI (route is the part after "#")
// as a browser on this machine can open it.
func uiURL(listenAddr, route string) string {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "http://" + listenAddr + "/#/login/" + token
return "http://" + listenAddr + "/#" + route
}
// A wildcard address (0.0.0.0, ::) is not something a browser can open.
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
host = "127.0.0.1"
}
// JoinHostPort brackets IPv6 addresses.
return "http://" + net.JoinHostPort(host, port) + "/#/login/" + token
return "http://" + net.JoinHostPort(host, port) + "/#" + route
}