package api
import (
"context"
"errors"
"sort"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// memChatSMS is the chat_sms, chat_seen and chat_sms_sent tables in memory.
type memChatSMS struct {
mu sync.Mutex
settings map[string]oltp.ChatSMS // repo\x00account
seen map[string]time.Time
sent map[string]time.Time // account\x00repo
records int // routes recorded: one per text that will leave
}
func (m *memChatSMS) SetChatSMS(repo, account string, s oltp.ChatSMS) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.settings == nil {
m.settings = map[string]oltp.ChatSMS{}
}
m.settings[repo+"\x00"+account] = s
return nil
}
func (m *memChatSMS) ChatSMS(repo, account string) oltp.ChatSMS {
m.mu.Lock()
defer m.mu.Unlock()
if s, ok := m.settings[repo+"\x00"+account]; ok {
return s
}
return oltp.ChatSMS{TZ: "UTC"}
}
func (m *memChatSMS) ChatSMSFollowers(repo string) ([]oltp.ChatSMSFollower, error) {
m.mu.Lock()
defer m.mu.Unlock()
var out []oltp.ChatSMSFollower
for k, s := range m.settings {
if r, a, _ := strings.Cut(k, "\x00"); r == repo && s.On {
out = append(out, oltp.ChatSMSFollower{Account: a, ChatSMS: s})
}
}
return out, nil
}
func (m *memChatSMS) TouchChatSeen(repo, account string, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.seen == nil {
m.seen = map[string]time.Time{}
}
if at.After(m.seen[repo+"\x00"+account]) {
m.seen[repo+"\x00"+account] = at
}
return nil
}
func (m *memChatSMS) ChatSeenSince(repo, account string, since time.Time) bool {
m.mu.Lock()
defer m.mu.Unlock()
at, ok := m.seen[repo+"\x00"+account]
return ok && !at.Before(since)
}
func (m *memChatSMS) RecordChatSMSSent(account, repo string, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.sent == nil {
m.sent = map[string]time.Time{}
}
m.sent[account+"\x00"+repo] = at
m.records++
return nil
}
func (m *memChatSMS) RecentChatSMSSent(account string, since time.Time) ([]oltp.ChatSMSSent, error) {
m.mu.Lock()
defer m.mu.Unlock()
var out []oltp.ChatSMSSent
for k, at := range m.sent {
if a, repo, _ := strings.Cut(k, "\x00"); a == account && !at.Before(since) {
out = append(out, oltp.ChatSMSSent{Repo: repo, At: at})
}
}
sort.Slice(out, func(i, j int) bool { return out[i].At.After(out[j].At) })
return out, nil
}
func (m *memChatSMS) routes() int {
m.mu.Lock()
defer m.mu.Unlock()
return m.records
}
// smsRig is a forge with a clock we move, and everybody holding the chat
// letter unless they are in lost.
type smsRig struct {
d Deps
fn *fakeNotify
store *memChatSMS
ids *memChatIdentity
now time.Time
lost map[string]bool
}
func newSMSRig(t *testing.T) *smsRig {
t.Helper()
g := &smsRig{fn: &fakeNotify{}, store: &memChatSMS{}, ids: &memChatIdentity{},
now: time.Date(2026, 11, 24, 15, 0, 0, 0, time.UTC), lost: map[string]bool{}}
g.d = Deps{Notify: g.fn, ChatSMS: g.store, ChatIdentities: g.ids, Now: func() time.Time { return g.now },
CapsFor: func(who, _ string) CapSet {
if g.lost[who] {
return fakeCaps("o")
}
return fakeCaps(anyCapLetters)
}}
return g
}
func (g *smsRig) follow(t *testing.T, who string, s oltp.ChatSMS) {
t.Helper()
s.On = true
if s.TZ == "" {
s.TZ = "UTC"
}
if err := g.store.SetChatSMS("alpha", who, s); err != nil {
t.Fatal(err)
}
}
// told runs one arrival and answers whom it was texted to. fireNotify
// hands off on a goroutine; every text that will leave records its route
// first, so the number of routes recorded is the number of events to
// wait for.
func (g *smsRig) told(from, text string, seq uint64) map[string]NotifyEvent {
before, routes := len(g.fn.snapshot()), g.store.routes()
g.d.chatSMSAt("alpha", text, from, seq)
want := before + g.store.routes() - routes
for deadline := time.Now().Add(5 * time.Second); len(g.fn.snapshot()) < want && time.Now().Before(deadline); {
time.Sleep(time.Millisecond)
}
out := map[string]NotifyEvent{}
for _, e := range g.fn.snapshot()[before:] {
if e.Workflow == "quarry-chat-sms" {
out[e.To] = e
}
}
return out
}
func names(m map[string]NotifyEvent) string {
var s []string
for k := range m {
s = append(s, k)
}
return strings.Join(s, ",")
}
// A person's line texts a follower who is away, with the repository,
// who said it, a short summary and a link, and notes the text for the
// reply that may follow.
func TestChatSMSTextsAFollowerWhoIsAway(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
got := g.told("eve", "the release is up", 7)
e, ok := got["dan"]
if len(got) != 1 || !ok {
t.Fatalf("FAIL: texted %q, want dan", names(got))
}
if e.TxnID != "chat-sms:alpha:7:dan" {
t.Errorf("FAIL: TxnID = %q", e.TxnID)
}
for _, k := range []string{"repo", "actor", "summary", "link"} {
if s, _ := e.Payload[k].(string); s == "" {
t.Errorf("FAIL: payload %q is empty: %v", k, e.Payload)
}
}
if e.Payload["repo"] != "alpha" || e.Payload["actor"] != "eve" || e.Payload["link"] != "/r/alpha/chat/7" {
t.Errorf("FAIL: payload = %v", e.Payload)
}
if recent, _ := g.store.RecentChatSMSSent("dan", g.now.Add(-time.Minute)); len(recent) != 1 || recent[0].Repo != "alpha" {
t.Errorf("FAIL: reply route = %+v, want alpha", recent)
}
if !t.Failed() {
t.Log("ok")
}
}
// Robot lines are never texted: not the forge's own, and not the
// upstream fossil's timeline announcements however its robot is named
// (fossil does not tell a bridge login the name, so the line's shape is
// the test, raw or as the bridge holds it).
func TestChatSMSNeverTextsARobot(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
for _, c := range []struct{ from, text string }{
{"robot", "pushed a thing"},
{"fossil:ci-announcer", "fix the parser (check-in: [abc123def4](https://up.example/info/abc123def4), user: bob)"},
{"fossil:nobody-you-know", "wiki edit (wiki: <a href='/info/abc'>abc</a>)"},
} {
if got := g.told(c.from, c.text, 3); len(got) != 0 {
t.Errorf("FAIL: a line by %q texted %q", c.from, names(got))
}
}
if got := g.told("fossil:alice", "a person on the other fossil", 4); len(got) != 1 {
t.Errorf("FAIL: a bridged person's line texted %q, want dan", names(got))
}
if !t.Failed() {
t.Log("ok")
}
}
// A muted repository fires nothing, and records no reply route for a
// text that never leaves.
func TestChatSMSRespectsAMute(t *testing.T) {
g := newSMSRig(t)
g.d.Prefs = &memPrefs{m: map[string]string{"dan|" + prefMute: "alpha"}}
g.follow(t, "dan", oltp.ChatSMS{})
if got := g.told("eve", "anyone there", 1); len(got) != 0 {
t.Errorf("FAIL: a muted repository texted %q", names(got))
}
if recent, _ := g.store.RecentChatSMSSent("dan", g.now.Add(-time.Hour)); len(recent) != 0 {
t.Errorf("FAIL: a route was recorded for a text that never left: %+v", recent)
}
if !t.Failed() {
t.Log("ok")
}
}
// Nobody is texted their own line: not as the account, not as the same
// login on the upstream fossil, not as a remote name an administrator
// linked to them.
func TestChatSMSNeverTextsTheAuthor(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
g.follow(t, "eve", oltp.ChatSMS{})
if err := g.ids.SetChatIdentity("alpha", "fossil:danm", "dan", "admin"); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ from, want string }{
{"eve", "dan"}, {"dan", "eve"}, {"fossil:dan", "eve"}, {"fossil:danm", "eve"},
} {
g.now = g.now.Add(time.Hour) // long enough that nobody is still there
got := g.told(c.from, "hello there", 5)
if len(got) != 1 || got[c.want].To != c.want {
t.Errorf("FAIL: a line by %q texted %q, want only %s", c.from, names(got), c.want)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// Only while away: a follower in the channel in the last 20 minutes is
// not texted, by having posted (as the account or as a linked remote
// name) or by having read it.
func TestChatSMSWaitsUntilTheFollowerIsAway(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
if err := g.ids.SetChatIdentity("alpha", "fossil:danm", "dan", "admin"); err != nil {
t.Fatal(err)
}
_ = g.store.TouchChatSeen("alpha", "dan", g.now.Add(-10*time.Minute))
if got := g.told("eve", "ten minutes after dan looked", 1); len(got) != 0 {
t.Errorf("FAIL: texted %q within 20 minutes of being there", names(got))
}
g.now = g.now.Add(15 * time.Minute) // dan was last there 25 minutes ago
if got := g.told("eve", "twenty five minutes after", 2); len(got) != 1 {
t.Errorf("FAIL: texted %q after 25 minutes away, want dan", names(got))
}
// dan posts upstream under a linked name: that is being there.
g.told("fossil:danm", "back for a moment", 3)
if got := g.told("eve", "right after dan posted", 4); len(got) != 0 {
t.Errorf("FAIL: texted %q right after a linked post", names(got))
}
// A line by an unlinked name proves nothing about dan.
g.now = g.now.Add(30 * time.Minute)
g.told("fossil:stranger", "hi", 5)
if got := g.told("eve", "later", 6); len(got) != 1 {
t.Errorf("FAIL: an unlinked name kept dan present: texted %q", names(got))
}
// The same login upstream is read as the same person, as the own-line
// skip reads it, for presence too.
g.now = g.now.Add(30 * time.Minute)
g.told("fossil:dan", "typing on the other fossil", 9)
if got := g.told("eve", "right after dan's other login", 10); len(got) != 0 {
t.Errorf("FAIL: texted %q right after the same login posted upstream", names(got))
}
g.now = g.now.Add(30 * time.Minute)
// Posting in the channel as the account is being there too.
g.told("dan", "me again", 7)
if got := g.told("eve", "after dan's own line", 8); len(got) != 0 {
t.Errorf("FAIL: texted %q right after dan posted", names(got))
}
if !t.Failed() {
t.Log("ok")
}
}
// Marking the channel read is being there: the read op touches presence.
func TestChatReadMarksTheReaderPresent(t *testing.T) {
g := newSMSRig(t)
g.d.Version, g.d.Chat = "v", &fakeChat{}
g.d.Repos = testRepos(wikiIndex(t))
mustRepo(t, g.d.Repos, "test").Chat = "c1"
r := ops.NewRegistry()
if err := RegisterAll(r, g.d); err != nil {
t.Fatal(err)
}
if _, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "chat.read", chatReadIn{Repo: "test"}); err != nil {
t.Fatal(err)
}
if !g.store.ChatSeenSince("test", "dan", g.now.Add(-time.Minute)) {
t.Errorf("FAIL: reading the channel left no sighting")
}
if !t.Failed() {
t.Log("ok")
}
}
// Quiet hours are the follower's wall clock in their zone, and may wrap
// midnight.
func TestChatSMSHonoursQuietHours(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{QuietStart: 22, QuietEnd: 7, TZ: "America/Chicago"})
g.follow(t, "eve", oltp.ChatSMS{QuietStart: 9, QuietEnd: 17}) // UTC office hours
// 15:00 UTC: 09:00 in Chicago, awake; inside eve's window.
if got := g.told("fay", "morning", 1); len(got) != 1 || got["dan"].To == "" {
t.Errorf("FAIL: at 15:00 UTC texted %q, want dan only", names(got))
}
g.now = time.Date(2026, 11, 25, 5, 0, 0, 0, time.UTC) // 23:00 Chicago, 05:00 UTC
if got := g.told("fay", "late", 2); len(got) != 1 || got["eve"].To == "" {
t.Errorf("FAIL: at 05:00 UTC texted %q, want eve only", names(got))
}
g.now = time.Date(2026, 11, 25, 18, 0, 0, 0, time.UTC) // noon in Chicago, past eve's window
if got := g.told("fay", "early", 3); len(got) != 2 {
t.Errorf("FAIL: at 18:00 UTC texted %q, want both", names(got))
}
if !t.Failed() {
t.Log("ok")
}
}
// Following is a choice made while the person could read the channel,
// not a grant: losing the chat letter ends the texts.
func TestChatSMSStopsWhenTheChatLetterIsLost(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
g.lost["dan"] = true
if got := g.told("eve", "anything", 1); len(got) != 0 {
t.Errorf("FAIL: texted %q without the chat letter", names(got))
}
if recent, _ := g.store.RecentChatSMSSent("dan", g.now.Add(-time.Hour)); len(recent) != 0 {
t.Error("FAIL: a reply route was recorded for a text never sent")
}
if !t.Failed() {
t.Log("ok")
}
}
// The summary is a plain line cut to fit a text.
func TestChatSMSSummaryIsShortAndPlain(t *testing.T) {
g := newSMSRig(t)
g.follow(t, "dan", oltp.ChatSMS{})
long := "see [the notes](https://example.invalid/notes) " + strings.Repeat("word ", 100)
e := g.told("eve", long, 1)["dan"]
s, _ := e.Payload["summary"].(string)
if n := utf8.RuneCountInString(s); n == 0 || n > chatSMSSummaryRunes+3 {
t.Errorf("FAIL: summary is %d runes", n)
}
if strings.Contains(s, "](") || strings.Contains(s, "https://") {
t.Errorf("FAIL: the summary kept link markup: %q", s)
}
if !t.Failed() {
t.Log("ok")
}
}
// The setting is the caller's own, behind the chat letter, and refuses a
// zone or an hour it could not honour.
func TestChatSMSSettingOps(t *testing.T) {
g := newSMSRig(t)
g.d.Version, g.d.Chat = "v", &fakeChat{}
g.d.Repos = testRepos(wikiIndex(t))
mustRepo(t, g.d.Repos, "test").Chat = "c1"
r := ops.NewRegistry()
if err := RegisterAll(r, g.d); err != nil {
t.Fatal(err)
}
for name, kind := range map[string]ops.Kind{"chat.sms": ops.Query, "chat.sms.set": ops.Command} {
d, ok := r.Lookup(name)
if !ok || d.Caps != "C" || d.Auth != ops.Token || d.Kind != kind {
t.Errorf("FAIL: %s = %+v, want a token op behind C", name, d)
}
}
dan := ops.WithUser(context.Background(), "dan")
got, err := r.Invoke(dan, "chat.sms", chatSMSIn{Repo: "test"})
if err != nil {
t.Fatal(err)
}
if o := got.(chatSMSOut); o.On || o.TZ != "UTC" || o.QuietStart != o.QuietEnd {
t.Errorf("FAIL: the default is %+v, want off, UTC, no quiet hours", o)
}
if _, err := r.Invoke(dan, "chat.sms.set", chatSMSSetIn{Repo: "test", On: true, QuietStart: 22, QuietEnd: 7, TZ: "America/Chicago"}); err != nil {
t.Fatal(err)
}
got, _ = r.Invoke(dan, "chat.sms", chatSMSIn{Repo: "test"})
if o := got.(chatSMSOut); !o.On || o.QuietStart != 22 || o.QuietEnd != 7 || o.TZ != "America/Chicago" {
t.Errorf("FAIL: read back %+v", o)
}
if got, _ := r.Invoke(ops.WithUser(context.Background(), "eve"), "chat.sms", chatSMSIn{Repo: "test"}); got.(chatSMSOut).On {
t.Error("FAIL: eve reads dan's setting")
}
for name, in := range map[string]chatSMSSetIn{
"zone": {Repo: "test", On: true, TZ: "Mars/Olympus"},
"hour": {Repo: "test", On: true, QuietStart: 24, TZ: "UTC"},
"negative": {Repo: "test", On: true, QuietEnd: -1, TZ: "UTC"},
} {
if _, err := r.Invoke(dan, "chat.sms.set", in); !errors.Is(err, ops.ErrInvalid) {
t.Errorf("FAIL: a bad %s answered %v, want invalid", name, err)
}
}
if _, err := r.Invoke(context.Background(), "chat.sms.set", chatSMSSetIn{Repo: "test", On: true}); err == nil {
t.Error("FAIL: an anonymous caller set a text setting")
}
if got, _ := r.Invoke(dan, "chat.sms", chatSMSIn{Repo: "test"}); got.(chatSMSOut).TZ != "America/Chicago" {
t.Error("FAIL: a refused setting replaced the stored one")
}
if !t.Failed() {
t.Log("ok")
}
}