Files
mesh-catalog/modules/desk-channel/cmd/desk-channel/desk_test.go
T

447 lines
19 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
)
type memShown map[string]Shown
func (m memShown) Get(h string) (*Shown, error) {
s, ok := m[h]
if !ok {
return nil, nil
}
return &s, nil
}
func (m memShown) Put(h string, s Shown) error { m[h] = s; return nil }
func (m memShown) Handles() ([]string, error) {
var out []string
for h := range m {
out = append(out, h)
}
return out, nil
}
type notified struct {
machine string
args map[string]any
}
func newDesk(t *testing.T, machines ...string) (*Desk, *[]notified, map[string][]json.RawMessage, memShown) {
t.Helper()
var shown []notified
said := map[string][]json.RawMessage{}
store := memShown{}
n := 0
d := &Desk{Machines: func() []string { return machines }, Store: store, Logf: t.Logf,
Now: func() time.Time { return time.Date(2026, 10, 8, 14, 0, 0, 0, time.UTC) },
Notify: func(machine string, args map[string]any) (json.RawMessage, error) {
if machine == "away-machine" {
return nil, errors.New("no session answers")
}
n++
shown = append(shown, notified{machine, args})
raw, _ := json.Marshal(map[string]int{"id": n})
return raw, nil
},
Publish: func(subject string, body any, id string) error {
raw, _ := json.Marshal(body)
said[subject] = append(said[subject], raw)
return nil
}}
d.init()
return d, &shown, said, store
}
func take(t *testing.T, d *Desk, verb string, m oc.Message) {
t.Helper()
raw, _ := json.Marshal(m)
if err := d.Take(occ.ChannelSubject(verb, Kind), raw); err != nil {
t.Fatal(err)
}
}
// novox/hq ADR 0259: the desk shows the router's message with its tickets as the notifier's actions, and
// says a click as a choice the router judges — only on a machine the message was shown on.
func TestAClickOnAMachineTheMessageWasShownOnIsSaidToTheRouter(t *testing.T) {
d, shown, said, _ := newDesk(t, "laptop", "away-machine")
take(t, d, occ.Show, oc.Message{Handle: "m1", Title: "3 failed services", Body: "Needs you: <mend> them.",
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t1"}}})
if len(*shown) != 1 || (*shown)[0].machine != "laptop" || (*shown)[0].args["expire_ms"] != 0 ||
(*shown)[0].args["body"] != "Needs you: &lt;mend&gt; them." {
t.Fatalf("shown %+v", *shown)
}
d.Chosen("e1", "laptop", "t1")
d.Chosen("e1", "laptop", "t1") // a redelivery
got := said[occ.IntakeSubject(occ.Chosen, Kind)]
var c oc.Choice
if len(got) != 1 || json.Unmarshal(got[0], &c) != nil || c.Ticket != "t1" || c.Handle != "m1" ||
c.Sender.Identity != "laptop" || c.Sender.Authenticated {
t.Fatalf("said %s", got)
}
// Elsewhere it is refused, there, and nothing is said to the router.
d.Chosen("e2", "workstation", "t1")
d.Chosen("e3", "laptop", "forged")
if len(said[occ.IntakeSubject(occ.Chosen, Kind)]) != 1 {
t.Error("a click not shown there was said")
}
if last := (*shown)[len(*shown)-1]; last.machine != "laptop" || last.args["summary"] != "That answer was not taken" {
t.Errorf("the refusal was not shown where it was chosen: %+v", last)
}
// The router's reply to the click is shown on the machine it was made on.
take(t, d, occ.Send, oc.Message{Handle: "r1", Title: "Details: 3 failed services", Reply: c.ID})
if last := (*shown)[len(*shown)-1]; last.machine != "laptop" || last.args["summary"] != "Details: 3 failed services" {
t.Errorf("%+v", last)
}
}
// The note follows the body after a blank line: the desk has no smaller text, and leaves nothing out (issue 639).
func TestTheNoteFollowsTheBody(t *testing.T) {
d, shown, _, _ := newDesk(t, "laptop")
take(t, d, occ.Show, oc.Message{Handle: "m1", Title: "q", Body: "The summary.", Note: "Asked by mesh-knowledge at 16:05.",
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t1"}}})
if last := (*shown)[len(*shown)-1]; last.args["body"] != "The summary.\n\nAsked by mesh-knowledge at 16:05." {
t.Errorf("the body: %q", last.args["body"])
}
}
func TestAnEditReplacesTheNotification(t *testing.T) {
d, shown, _, _ := newDesk(t, "laptop")
take(t, d, occ.Show, oc.Message{Handle: "m1", Title: "q", Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t1"}}})
take(t, d, occ.Edit, oc.Message{Handle: "m1", Title: "Silence for a week: chosen"})
if last := (*shown)[len(*shown)-1]; last.args["replace_id"] != 1 || last.args["actions"] != nil {
t.Errorf("the edit: %+v", last.args)
}
}
// Issue 384: a notifier that started again (nine old popups, resolved and silenced ones among them, shown from
// the desk's own memory on 2026-10-10). Its bundle started again, so the notifications are still on screen and
// the answers they waited for are lost. With three messages remembered on the machine — one open with answers,
// one silenced, one resolved — nothing is shown, the notification ids are kept, and the standing says when the
// answers were lost. The router then says the open one again under its handle: it replaces its notification in
// place (one popup, its buttons alive again), and a click on it is said to the router. The same start event
// is acted on once.
func TestANotifierThatStartedAgainIsShownNothingFromMemory(t *testing.T) {
d, shown, said, store := newDesk(t, "laptop")
d.Paused("laptop", false)
d.SayStanding()
take(t, d, occ.Show, oc.Message{Handle: "open", Title: "2 failed services on shanks",
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t-open"}}})
take(t, d, occ.Show, oc.Message{Handle: "silenced", Title: "Agent-home shrank",
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t-silenced"}}})
take(t, d, occ.Edit, oc.Message{Handle: "silenced", Title: "Silenced until Saturday: Agent-home shrank", Silent: true})
take(t, d, occ.Show, oc.Message{Handle: "resolved", Title: "Questions for you not delivered",
Buttons: []oc.Button{{Label: "Details", Ticket: "t-resolved"}}})
take(t, d, occ.Edit, oc.Message{Handle: "resolved", Title: "Resolved: questions for you are delivered", Silent: true})
openID := store["open"].On["laptop"]
before := len(*shown)
standings := len(said[occ.IntakeSubject(occ.StandingWhat, Kind)])
later := d.Now().Add(time.Hour)
d.Now = func() time.Time { return later }
d.Paused("laptop", false)
if n := d.Started("e-start", "laptop"); n != 1 {
t.Fatalf("messages with buttons on the machine: %d, want 1 (the open one)", n)
}
if len(*shown) != before {
t.Fatalf("shown from memory after the notifier started again: %+v", (*shown)[before:])
}
if store["open"].On["laptop"] != openID {
t.Fatalf("the open message's notification was forgotten: %+v", store["open"].On)
}
got := said[occ.IntakeSubject(occ.StandingWhat, Kind)]
var s Standing
if len(got) != standings+1 || json.Unmarshal(got[len(got)-1], &s) != nil || !s.Ready || !s.AnswersLostAt.Equal(later) {
t.Fatalf("the standing after the start: %d said, last %s", len(got)-standings, got[len(got)-1])
}
// The router says the open one again under its handle: in place of its notification, with its answers.
take(t, d, occ.Show, oc.Message{Handle: "open", Title: "2 failed services on shanks",
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t-open"}}})
last := (*shown)[len(*shown)-1]
if len(*shown) != before+1 || last.args["replace_id"] != openID || last.args["actions"] == nil {
t.Fatalf("the open message said again: %+v", last.args)
}
d.Chosen("e2", "laptop", "t-open")
if len(said[occ.IntakeSubject(occ.Chosen, Kind)]) != 1 {
t.Error("a click on the message said again was not said to the router")
}
// The same start event again (a redelivery) does nothing more.
standings = len(said[occ.IntakeSubject(occ.StandingWhat, Kind)])
if n := d.Started("e-start", "laptop"); n != 0 || len(said[occ.IntakeSubject(occ.StandingWhat, Kind)]) != standings {
t.Errorf("a redelivered start was acted on again: %d", n)
}
// A desk none of whose notifiers started again says a zero time, which the router reads as none.
fresh, _, _, _ := newDesk(t, "laptop")
if !fresh.Standing().AnswersLostAt.IsZero() {
t.Error("a desk whose notifier never started again says a time")
}
}
func TestNoMachineThatShowsItIsAFailureSaidToTheRouter(t *testing.T) {
d, _, said, _ := newDesk(t, "away-machine")
take(t, d, occ.Send, oc.Message{Handle: "m1", Title: "x"})
if f := said[occ.IntakeSubject(occ.FailedWhat, Kind)]; len(f) != 1 || !strings.Contains(string(f[0]), "no session answers") ||
strings.Contains(string(f[0]), `"permanent":true`) {
t.Errorf("%s", f)
}
none, _, _, _ := newDesk(t)
if s := none.Standing(); s.Ready || !strings.Contains(s.Why, "desktop-machines names none") {
t.Errorf("%+v", s)
}
}
// It claims the desk's kind, and promises nothing that would let it approve.
func TestItPromisesNoVerifiedSender(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
var m struct {
Claims []struct {
Name, Kind string
Capabilities []string
}
Consumes []string
}
_ = json.Unmarshal(raw, &m)
if len(m.Claims) != 2 || m.Claims[0].Kind != Kind || m.Claims[1].Kind != Kind {
t.Fatalf("%+v", m.Claims)
}
for _, c := range m.Claims[0].Capabilities {
if c == "verified-sender" || c == "reaches-away" {
t.Errorf("the desk promises %s", c)
}
}
if strings.Join(m.Consumes, ",") != AnswerEvent+","+StartedEvent+","+PausedEvent {
t.Errorf("consumes %v", m.Consumes)
}
}
// A message the router marks secret (a link's code) is shown and kept nowhere of this module's.
func TestASecretMessageIsShownAndNotKept(t *testing.T) {
d, shown, _, store := newDesk(t, "laptop")
d.Paused("laptop", false)
take(t, d, occ.Send, oc.Message{Handle: "code", Title: "Link a Telegram account as you", Body: "123 456", Secret: true})
if len(*shown) != 1 {
t.Fatal("not shown")
}
if _, kept := store["code"]; kept {
t.Error("the code was kept")
}
}
// The review of 2026-10-09 (H4, C4): a link's code is shown only on a machine whose notifier said lately that
// it is not paused — a code held back by a paused notifier appears later, to whoever is at the screen then —
// and is sent secret, so the notifier keeps it out of the history every caller of the verbs reads. While no
// named machine is heard unpaused, the desk says it cannot send.
func TestASecretIsShownOnlyWhereTheNotifierIsHeardUnpausedAndNeverKept(t *testing.T) {
d, shown, said, store := newDesk(t, "laptop", "desk2")
now := d.Now()
if s := d.Standing(); s.Ready || !strings.Contains(s.Why, "not heard") {
t.Fatalf("ready before any notifier said whether it is paused: %+v", s)
}
d.Paused("laptop", false)
if s := d.Standing(); !s.Ready {
t.Fatalf("not ready with laptop heard unpaused: %+v", s)
}
code := oc.Message{Handle: "code", Title: "Link a Telegram account as you", Body: "123 456", Secret: true}
take(t, d, occ.Send, code)
if len(*shown) != 1 || (*shown)[0].machine != "laptop" || (*shown)[0].args["secret"] != true {
t.Fatalf("the code was shown as %+v", *shown)
}
if _, kept := store["code"]; kept {
t.Error("the code was kept")
}
// Paused: not shown anywhere, said as failed, and the desk is not ready.
d.Paused("laptop", true)
take(t, d, occ.Send, code)
if len(*shown) != 1 {
t.Fatalf("the code was shown on a paused notifier: %+v", *shown)
}
if f := said[occ.IntakeSubject(occ.FailedWhat, Kind)]; len(f) != 1 || !strings.Contains(string(f[0]), "paused") {
t.Errorf("not said as failed: %s", f)
}
if s := d.Standing(); s.Ready || !strings.Contains(s.Why, "paused") {
t.Errorf("ready while paused: %+v", s)
}
// Heard unpaused, but longer ago than PausedFresh: not known now.
d.Paused("laptop", false)
d.Now = func() time.Time { return now.Add(PausedFresh + time.Second) }
if s := d.Standing(); s.Ready {
t.Errorf("ready on a word older than %s: %+v", PausedFresh, s)
}
// A machine not named is never one to show on, whatever it says.
d.Paused("stranger", false)
if s := d.Standing(); s.Ready {
t.Error("a machine not named made the desk ready")
}
// A message that is not secret still goes to every named machine, paused or not.
take(t, d, occ.Send, oc.Message{Handle: "m9", Title: "x"})
if len(*shown) != 3 {
t.Errorf("an ordinary message was held back: %+v", *shown)
}
}
// It runs as its own account (the review of 2026-10-09, H4): what it shows and the answers it says are its
// own, out of every agent's reach, as telegram's are.
func TestItRunsAsItsOwnAccount(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
var m struct {
RunsAs string `json:"runs-as"`
Own map[string]string `json:"own-secrets"`
Owner string `json:"secrets-owner"`
Resources []map[string]any
}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
if m.RunsAs != Account || m.Owner != Account || m.Own["broker"] == "" {
t.Fatalf("runs as %q, owner %q, secrets %v", m.RunsAs, m.Owner, m.Own)
}
var account, state, settings bool
for _, r := range m.Resources {
switch r["id"] {
case "account":
account = r["type"] == "user" && r["name"] == Account && r["shell"] == "/usr/bin/nologin"
case "state":
state = r["owner"] == Account && r["mode"] == "0700"
case "settings":
settings = r["owner"] == Account && r["mode"] == "0600"
}
}
if !account || !state || !settings {
t.Errorf("the account %v, its state %v, its settings %v", account, state, settings)
}
}
// Issue 373: a message said again under its handle (a reminder, an escalation) replaces its notification on
// each machine — the notifier is called with that notification's replace id — and is shown anew only where it
// was not shown; a message under a new handle replaces nothing.
func TestAMessageSaidAgainUnderItsHandleReplacesItsNotification(t *testing.T) {
d, shown, _, store := newDesk(t, "laptop", "desktop")
take(t, d, occ.Send, oc.Message{Handle: "m1", Title: "2 failed services on shanks"})
take(t, d, occ.Send, oc.Message{Handle: "m2", Title: "another problem"})
if len(*shown) != 4 {
t.Fatalf("shown %d", len(*shown))
}
for _, n := range *shown {
if _, has := n.args["replace_id"]; has {
t.Fatalf("a new message replaced a notification: %+v", n)
}
}
first := store["m1"].On
// The desk now names a third machine as well.
d.Machines = func() []string { return []string{"laptop", "desktop", "third"} }
take(t, d, occ.Show, oc.Message{Handle: "m1", Title: "Still open: 2 failed services on shanks", Urgent: true,
Buttons: []oc.Button{{Label: "Silence for a week", Ticket: "t1"}}})
again := (*shown)[4:]
if len(again) != 3 {
t.Fatalf("said again on %d machines", len(again))
}
for _, n := range again {
want, was := first[n.machine]
got, replaces := n.args["replace_id"]
switch {
case was && (!replaces || got != want):
t.Errorf("on %s the reminder did not replace notification %d: %v", n.machine, want, n.args)
case !was && replaces:
t.Errorf("on %s, where it was not shown, it replaced %v", n.machine, got)
}
}
if s := store["m1"]; len(s.On) != 3 || len(s.Message.Buttons) != 1 {
t.Fatalf("what is shown was not kept: %+v", s)
}
}
// downStore is a store that does not answer while down: the bus reloading its accounts (2026-10-26 09:18).
type downStore struct {
memShown
down *bool
}
func (s downStore) Get(h string) (*Shown, error) {
if *s.down {
return nil, errors.New("nats: no responders available for request")
}
return s.memShown.Get(h)
}
func (s downStore) Put(h string, v Shown) error {
if *s.down {
return errors.New("nats: no responders available for request")
}
return s.memShown.Put(h, v)
}
// The review of PR 176: a replace that fails on a machine keeps that machine's notification on record, so a
// later edit or clearing still reaches it; failing everywhere, it is said to the router as failed. And
// (2026-10-26 09:18, an urgent "A new build of mesh-controller cannot be delivered" left on screen for hours
// after its clearing): a message shown while the store does not answer keeps where it is shown in memory, its
// work is taken, its clearing replaces it in place, and it is kept once the store answers.
func TestAFailedReplaceKeepsTheNotificationItWasToReplace(t *testing.T) {
// The raise, then its clearing, taken while the store does not answer; the store then stays down or comes
// back. Each is taken (never offered again, where a redelivered raise would follow its clearing), the
// clearing replaces the urgent notification in place, and the screen and the store end on the clearing.
for _, back := range []bool{false, true} {
t.Run(fmt.Sprintf("the store does not answer, back %v", back), func(t *testing.T) {
d, shown, _, store := newDesk(t, "laptop")
down := true
d.Store = downStore{store, &down}
raised, _ := json.Marshal(oc.Message{Handle: "m9", Title: "A new build cannot be delivered", Urgent: true})
if err := d.Take(occ.ChannelSubject(occ.Send, Kind), raised); err != nil {
t.Fatalf("the raise was not taken: %v", err)
}
cleared, _ := json.Marshal(oc.Message{Handle: "m9", Title: "Cleared: a new build can be delivered"})
if err := d.Take(occ.ChannelSubject(occ.Edit, Kind), cleared); err != nil {
t.Fatalf("the clearing was not taken: %v", err)
}
d.KeepUnkept() // the minute's standing, store still down
down = !back
d.KeepUnkept()
take(t, d, occ.Send, oc.Message{Handle: "m10", Title: "another"})
if len(*shown) != 3 || (*shown)[1].args["replace_id"] != 1 || (*shown)[1].args["summary"] != "Cleared: a new build can be delivered" {
t.Fatalf("the clearing did not replace the urgent notification: %+v", *shown)
}
s, kept := store["m9"]
if back != kept || (kept && s.Message.Title != "Cleared: a new build can be delivered") {
t.Fatalf("store back %v, kept %v: %+v", back, kept, store)
}
if got, _ := d.recall("m9"); got == nil || got.Message.Title != "Cleared: a new build can be delivered" {
t.Fatalf("recalled %+v", got)
}
})
}
d, shown, said, store := newDesk(t, "laptop", "desktop")
take(t, d, occ.Send, oc.Message{Handle: "m1", Title: "2 failed services on shanks"})
first := store["m1"].On
notify := d.Notify
d.Notify = func(machine string, args map[string]any) (json.RawMessage, error) {
if machine == "desktop" {
return nil, errors.New("no session answers")
}
return notify(machine, args)
}
take(t, d, occ.Send, oc.Message{Handle: "m1", Title: "Still open: 2 failed services on shanks"})
if got := store["m1"].On["desktop"]; got != first["desktop"] {
t.Fatalf("the desktop's notification %d was forgotten: %v", first["desktop"], store["m1"].On)
}
d.Notify = func(string, map[string]any) (json.RawMessage, error) { return nil, errors.New("away") }
take(t, d, occ.Send, oc.Message{Handle: "m1", Title: "Now urgent: 2 failed services on shanks"})
if len(said[occ.IntakeSubject(occ.FailedWhat, Kind)]) != 1 {
t.Fatalf("shown nowhere, and not said as failed")
}
_ = shown
}