1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package main

// Whether the listings say how fresh the mirror is.
//
// mailweb serves every page out of SQLite and touches IMAP for none of them, so
// a connection that died on Tuesday produces exactly the interface a quiet
// account does. The footer is the only thing separating the two, which makes
// "the footer is missing from a page" a silent failure of the sort this file
// exists to catch — nothing about a listing that lacks it looks wrong.

import (
	"log"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

// withLastIMAP runs f with the process's last-successful-command mark set to
// now-ago, restoring it afterwards. The mark is package state because it is a
// property of the process; the tests that move it must put it back.
func withLastIMAP(t *testing.T, ago time.Duration, f func()) {
	t.Helper()
	saved := lastIMAP.Load()
	t.Cleanup(func() { lastIMAP.Store(saved) })
	lastIMAP.Store(time.Now().Add(-ago).Unix())
	f()
}

// listingRoutes are the four pages that carry the freshness footer: the ones
// read to answer "is there anything new", which is the question a stale mirror
// answers wrong without saying so. A message page is deliberately not among
// them — see templates/mirror.html.
var listingRoutes = []string{"/", "/contacts", "/forge", "/drafts"}

// TestListingsStateMirrorFreshness: each listing says when the server last
// answered, in both renderings.
func TestListingsStateMirrorFreshness(t *testing.T) {
	accountName = "test"
	myAddress = "me@example.org"
	myAddresses = map[string]bool{myAddress: true}
	mux := newTestServer(t).routes()

	withLastIMAP(t, 4*time.Minute, func() {
		for _, route := range listingRoutes {
			for _, view := range []string{"html", "llm"} {
				t.Run(route+" "+view, func(t *testing.T) {
					req := httptest.NewRequest("GET", route, nil)
					if view == "llm" {
						req.Header.Set("Accept", "text/llm")
					}
					rec := httptest.NewRecorder()
					mux.ServeHTTP(rec, req)
					if rec.Code != 200 {
						t.Fatalf("status %d", rec.Code)
					}
					body := rec.Body.String()
					if !strings.Contains(body, "4 minutes ago") {
						t.Errorf("no freshness statement in %s %s", route, view)
					}
					// The distance is not enough on its own: it says how long
					// ago something happened without saying what, and the one
					// thing this must not be read as is when mail last
					// arrived.
					if !strings.Contains(body, "synced") {
						t.Errorf("%s %s states a distance but does not say it is a sync", route, view)
					}
				})
			}
		}
	})
}

// TestStaleMirrorSaysSo: past the IDLE period a round-trip that was due has not
// happened, and the listing above the footer may be missing mail rather than
// there being none. That is a different statement from "synced 40 minutes ago"
// and has to read as one.
func TestStaleMirrorSaysSo(t *testing.T) {
	accountName = "test"
	mux := newTestServer(t).routes()

	withLastIMAP(t, staleAfter+10*time.Minute, func() {
		for _, view := range []string{"html", "llm"} {
			req := httptest.NewRequest("GET", "/", nil)
			if view == "llm" {
				req.Header.Set("Accept", "text/llm")
			}
			rec := httptest.NewRecorder()
			mux.ServeHTTP(rec, req)
			body := rec.Body.String()

			marked := strings.Contains(body, "mirror-stale") || strings.Contains(body, "STALE")
			if !marked {
				t.Errorf("%s: a stale mirror is not marked as one", view)
			}
			if !strings.Contains(body, "behind") {
				t.Errorf("%s: staleness is marked but not explained", view)
			}
		}
	})
}

// TestUnsyncedMirrorIsNotDatedFrom1970: before any IMAP command has succeeded
// there is no answer, and the footer must say so rather than render the zero
// time — which would date the mirror to 1970 and call it 56 years stale.
func TestUnsyncedMirrorIsNotDatedFrom1970(t *testing.T) {
	accountName = "test"
	mux := newTestServer(t).routes()

	withLastIMAP(t, 0, func() {
		lastIMAP.Store(0)
		for _, view := range []string{"html", "llm"} {
			req := httptest.NewRequest("GET", "/", nil)
			if view == "llm" {
				req.Header.Set("Accept", "text/llm")
			}
			rec := httptest.NewRecorder()
			mux.ServeHTTP(rec, req)
			body := rec.Body.String()

			if strings.Contains(body, "1970") {
				t.Errorf("%s: renders the zero time as a sync date", view)
			}
			if !strings.Contains(body, "not yet") && !strings.Contains(body, "NOT YET") {
				t.Errorf("%s: says nothing about never having synced", view)
			}
		}
	})
}

// TestFreshnessRecordsSuccessNotAttempts: imapSeen is called where commands
// complete, never where they are issued. A hung connection is the condition the
// footer exists to make visible, and marking an attempt would paper over it
// with a fresh timestamp.
func TestFreshness(t *testing.T) {
	now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC)

	saved := lastIMAP.Load()
	t.Cleanup(func() { lastIMAP.Store(saved) })

	lastIMAP.Store(0)
	if f := freshness(now); !f.At.IsZero() || f.Ago != "" || !f.Stale {
		t.Errorf("an unsynced mirror is %+v, want zero-valued and stale", f)
	}

	lastIMAP.Store(now.Add(-2 * time.Minute).Unix())
	if f := freshness(now); f.Stale || f.Ago != "2 minutes ago" {
		t.Errorf("a two-minute-old sync is %+v, want fresh", f)
	}

	// A connection in IDLE says nothing for 25 minutes at a stretch (see
	// idleRestartInterval), so the threshold has to sit above that or every
	// healthy account reads as broken. Asserted a little past the period
	// itself, since that is where a threshold set too low would first bite.
	lastIMAP.Store(now.Add(-29 * time.Minute).Unix())
	if f := freshness(now); f.Stale {
		t.Error("a connection one IDLE period old is healthy, not stale")
	}

	lastIMAP.Store(now.Add(-3 * time.Hour).Unix())
	if f := freshness(now); !f.Stale {
		t.Error("three hours without an answer is stale")
	}
}

// What the log says when the connection stops answering.
//
// The footer states staleness on a page, which only helps somebody already
// looking at one. watchFreshness says the same thing in the journal, and these
// cover the part that decides when: the edges, and only the edges.

// Going stale is reported once, and names when the server was last heard from.
func TestFreshnessLogLineOnGoingStale(t *testing.T) {
	at := time.Date(2026, 9, 12, 16, 42, 0, 0, time.UTC)
	stale := mirrorFreshness{At: at, Ago: "40 minutes ago", Stale: true}

	line := freshnessLogLine(stale, false)
	if line == "" {
		t.Fatal("going stale logged nothing")
	}
	if !strings.Contains(line, "STALE") {
		t.Errorf("line does not say STALE: %q", line)
	}
	if !strings.Contains(line, "16:42:00") {
		t.Errorf("line does not name when the server last answered: %q", line)
	}

	// Still stale on the next tick: already said, so say nothing. A line every
	// tick for a machine offline overnight is how a log stops being read.
	if repeat := freshnessLogLine(stale, true); repeat != "" {
		t.Errorf("repeated the same complaint: %q", repeat)
	}
}

// Recovery is worth a line too: it is what says the outage ended, and without
// it the last word on the subject is a complaint that is no longer true.
func TestFreshnessLogLineOnRecovery(t *testing.T) {
	fresh := mirrorFreshness{
		At:  time.Date(2026, 9, 12, 17, 20, 0, 0, time.UTC),
		Ago: "a moment ago",
	}

	line := freshnessLogLine(fresh, true)
	if !strings.Contains(line, "recovered") {
		t.Errorf("recovery not reported: %q", line)
	}

	// Healthy and was healthy — nothing to say.
	if quiet := freshnessLogLine(fresh, false); quiet != "" {
		t.Errorf("a healthy mirror logged %q", quiet)
	}
}

// A mailweb that has never reached its server has no timestamp to name, and
// must not render one from the zero time.
func TestFreshnessLogLineNeverConnected(t *testing.T) {
	line := freshnessLogLine(mirrorFreshness{Stale: true}, false)

	if !strings.Contains(line, "since startup") {
		t.Errorf("line does not say it never connected: %q", line)
	}
	if strings.Contains(line, "1970") || strings.Contains(line, "0001") {
		t.Errorf("line renders the zero time: %q", line)
	}
}

// The loop reports each transition exactly once as the state moves.
func TestWatchFreshnessLoopReportsEdges(t *testing.T) {
	var buf strings.Builder
	saved := log.Writer()
	log.SetOutput(&buf)
	log.SetFlags(0)
	t.Cleanup(func() { log.SetOutput(saved) })

	states := []mirrorFreshness{
		{At: time.Now(), Ago: "a moment ago"},                // healthy
		{At: time.Now(), Ago: "a moment ago"},                // still healthy
		{At: time.Now(), Ago: "40 minutes ago", Stale: true}, // → stale
		{At: time.Now(), Ago: "50 minutes ago", Stale: true}, // still stale
		{At: time.Now(), Ago: "a moment ago"},                // → recovered
	}
	tick := make(chan time.Time, len(states))
	for range states {
		tick <- time.Now()
	}
	close(tick)

	i := 0
	watchFreshnessLoop(tick, func() mirrorFreshness {
		f := states[i]
		i++
		return f
	})

	out := buf.String()
	if got := strings.Count(out, "STALE"); got != 1 {
		t.Errorf("STALE logged %d times, want 1:\n%s", got, out)
	}
	if got := strings.Count(out, "recovered"); got != 1 {
		t.Errorf("recovery logged %d times, want 1:\n%s", got, out)
	}
}