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
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"flag"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"slices"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	"github.com/rs/zerolog"
	"maunium.net/go/mautrix/event"
	"maunium.net/go/mautrix/id"

	"go.mau.fi/gomuks/pkg/hicli"
	"go.mau.fi/gomuks/pkg/hicli/database"
	"go.mau.fi/gomuks/pkg/hicli/jsoncmd"
)

// ---------------------------------------------------------------------------
// tuning
// ---------------------------------------------------------------------------

const (
	// backlogTarget is how many timeline rows a freshly loaded page walks back
	// to. Rows already in SQLite are essentially free; beyond that hicli
	// backfills from the homeserver, so the first walk of a long-lived room does
	// real /messages requests while later ones are local.
	backlogTarget = 1000

	// paginateBatch is the batch size for backfill requests to the homeserver.
	paginateBatch = 500

	// chunkSize is how many messages go into one SSE frame. Chunking (rather
	// than one frame per message) keeps framing overhead down on a large
	// backlog, while letting the browser paint the newest chunk immediately.
	chunkSize = 200

	// liveQueueSize bounds the per-subscriber queue for *live* events. Live
	// sends must never block, because they run on hicli's syncer goroutine.
	// Overflowing it means the client's view is missing events, which is
	// unrecoverable without a resync — see subscriber.overflow.
	liveQueueSize = 1024
)

// ---------------------------------------------------------------------------
// SSE fan-out hub
// ---------------------------------------------------------------------------

// subscriber is one connected browser tab, watching one room.
//
// Only *live* traffic goes through this channel. History is written straight to
// the HTTP response before the subscriber's drain loop starts (see
// handleEvents), so there is exactly one discipline here: never block, because
// these sends run on hicli's syncer goroutine and a stalled write would stall
// the whole sync loop.
//
// A full queue therefore cannot be papered over. Dropping a live event would
// leave a hole the client can never learn about — its cursor advances past the
// gap on the next event that *does* get through. So overflow is recorded and
// the stream is reset instead, which is the only honest recovery.
//
// Note there is no de-duplication here. A message committing between subscribe
// and the history snapshot is delivered twice, and that is deliberately fine:
// the client keys rows by event ID and updates in place, so a repeat delivery
// re-renders one row rather than adding a second. Suppressing it server-side
// would mean tracking a boundary per subscriber to fix something the client
// already handles.
type subscriber struct {
	ch chan []byte
	// overflow is set when a live event had to be dropped. The drain loop
	// notices and resets the client.
	overflow atomic.Bool

	// tabID identifies the browser tab this subscription belongs to, so the
	// tab can update its own visibility over a separate request. It is
	// generated by the client and only has to be unique among live streams.
	tabID string
	// visible is true while this tab is actually on screen showing this room.
	//
	// It exists so notifications can be suppressed for a conversation the user
	// is already looking at. Deciding that here rather than in the browser is
	// not an optimisation but a correctness requirement: the server sends each
	// notification to exactly one tab (see notifyHub), which is generally *not*
	// the tab displaying the room, so no single client has enough information
	// to make the call.
	//
	// Tying it to the subscription is what keeps it honest — a closed tab takes
	// its flag with it, so a crashed or navigated-away browser cannot leave a
	// room permanently muted.
	visible atomic.Bool
}

// hub is the set of tabs watching one room; there is one per roomView.
type hub struct {
	mu   sync.Mutex
	subs map[*subscriber]struct{}
}

func newHub() *hub {
	return &hub{subs: map[*subscriber]struct{}{}}
}

// subscribe registers a subscriber. Callers must subscribe *before* reading
// history, so that an event arriving mid-read is queued rather than lost.
//
// tabID lets the tab update its visibility later; visible is its state at
// connect time, which the client sends as a query parameter so a tab opened in
// the background never counts as on screen.
func (h *hub) subscribe(tabID string, visible bool) *subscriber {
	sub := &subscriber{ch: make(chan []byte, liveQueueSize), tabID: tabID}
	sub.visible.Store(visible)
	h.mu.Lock()
	h.subs[sub] = struct{}{}
	h.mu.Unlock()
	return sub
}

func (h *hub) unsubscribe(sub *subscriber) {
	h.mu.Lock()
	delete(h.subs, sub)
	h.mu.Unlock()
}

// anyVisible reports whether some tab currently has this room on screen.
func (h *hub) anyVisible() bool {
	h.mu.Lock()
	defer h.mu.Unlock()
	for sub := range h.subs {
		if sub.visible.Load() {
			return true
		}
	}
	return false
}

// setVisible updates the visibility of the subscription belonging to tabID.
//
// The tab is identified by an ID it made up rather than by its connection,
// because visibility arrives on a separate HTTP request from the SSE stream it
// applies to. An unknown ID is ignored: it means the stream has already gone,
// which is exactly when the flag no longer matters.
func (h *hub) setVisible(tabID string, visible bool) {
	h.mu.Lock()
	defer h.mu.Unlock()
	for sub := range h.subs {
		if sub.tabID == tabID {
			sub.visible.Store(visible)
		}
	}
}

// ---------------------------------------------------------------------------
// notification fan-out
// ---------------------------------------------------------------------------

// notifyHub delivers desktop notifications to exactly one open tab.
//
// Unlike hub, this is process-wide (notifications are not scoped to a room) and
// delivers to a *single* subscriber rather than all of them. Showing the same
// notification once per open tab is the obvious failure mode here, and the
// alternatives to fixing it server-side are all worse: a SharedWorker holding
// the one connection, or client-side coordination over BroadcastChannel /
// navigator.locks. Both put consensus in the browser to solve something the
// server already knows the answer to — it can simply write the frame once.
//
// Leadership is "longest connected", which is why subs is a slice and not a
// map: it needs an order. When the leader disconnects it is removed and the
// next tab inherits, so the feature keeps working as long as any tab is open
// and stops when the last one closes, with no lifecycle code anywhere.
//
// Caveat: a backgrounded tab is still a live subscriber even when the browser
// throttles it, so it can hold the lease while draining slowly. That is bounded
// by the same overflow path as hub — a full queue marks the subscriber, whose
// drain loop then resets and disconnects it, handing leadership on.
type notifyHub struct {
	mu   sync.Mutex
	subs []*subscriber
}

func newNotifyHub() *notifyHub {
	return &notifyHub{}
}

func (n *notifyHub) subscribe() *subscriber {
	sub := &subscriber{ch: make(chan []byte, liveQueueSize)}
	n.mu.Lock()
	n.subs = append(n.subs, sub)
	n.mu.Unlock()
	return sub
}

func (n *notifyHub) unsubscribe(sub *subscriber) {
	n.mu.Lock()
	defer n.mu.Unlock()
	n.subs = slices.DeleteFunc(n.subs, func(s *subscriber) bool { return s == sub })
}

// hasSubscribers reports whether any tab is listening for notifications.
//
// handleEvent checks this before doing any notification work at all, so an
// account with no webchat tab open pays nothing beyond this lock for the
// feature — which matters because that path runs on hicli's syncer goroutine
// for every room in every sync.
func (n *notifyHub) hasSubscribers() bool {
	n.mu.Lock()
	defer n.mu.Unlock()
	return len(n.subs) > 0
}

// send delivers a notification to the leader (the longest-connected tab) only.
//
// Like hub.broadcastLive this must never block: it runs on hicli's syncer
// goroutine. A full queue means that tab has stopped reading, so the
// notification is dropped for it — and unlike a timeline event, it is not
// retried against another subscriber. A notification is a transient alert; the
// message itself is still in the timeline either way, and re-routing a stale
// alert to a different tab is worse than not showing it.
func (n *notifyHub) send(logger zerolog.Logger, payload any) {
	frame, err := sseFrame(sseNotify, payload, "")
	if err != nil {
		logger.Err(err).Msg("marshal notification")
		return
	}
	n.mu.Lock()
	defer n.mu.Unlock()
	if len(n.subs) == 0 {
		return
	}
	leader := n.subs[0]
	select {
	case leader.ch <- frame:
	default:
		leader.overflow.Store(true)
		logger.Warn().Msg("notification subscriber queue full, dropping notification")
	}
}

// SSE event names. Each one maps to exactly one O(1) DOM operation in the
// frontend, which is the whole point of the protocol: the server always knows
// whether a batch belongs above or below what the client holds, so the client
// never has to sort or compare anything.
const (
	// sseAppend adds messages to the bottom (live events, gap replay).
	sseAppend = "append"
	// ssePrepend adds messages to the top (walking back through history).
	ssePrepend = "prepend"
	// sseUpdate re-renders existing messages in place, keyed by event ID.
	// Unknown IDs are dropped by the client — an update for a message outside
	// its window is not an insert.
	sseUpdate = "update"
	// sseReset tells the client to throw away everything and reload.
	sseReset = "reset"
	// sseTyping carries typing notifications; not a message operation.
	sseTyping = "typing"
	// sseNotify carries a desktop notification. It is the only event name that
	// travels on /notifications rather than a room's stream.
	sseNotify = "notify"
)

// sseFrame renders one SSE frame. A non-empty id sets the stream's Last-Event-ID,
// which the browser echoes back on reconnect.
//
// The id is always an event ID, never a timeline row ID: see resolveCursorSQL
// for why row IDs cannot survive a round trip through the client.
func sseFrame(eventName string, payload any, lastEventID string) ([]byte, error) {
	b, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}
	frame := make([]byte, 0, len(b)+64)
	if lastEventID != "" {
		frame = append(frame, "id: "...)
		frame = append(frame, lastEventID...)
		frame = append(frame, '\n')
	}
	frame = append(frame, "event: "...)
	frame = append(frame, eventName...)
	frame = append(frame, "\ndata: "...)
	frame = append(frame, b...)
	frame = append(frame, '\n', '\n')
	return frame, nil
}

// broadcastLive fans a live event out to every subscriber without blocking.
func (h *hub) broadcastLive(logger zerolog.Logger, eventName string, payload any, lastEventID string) {
	frame, err := sseFrame(eventName, payload, lastEventID)
	if err != nil {
		logger.Err(err).Str("event", eventName).Msg("marshal sse event")
		return
	}
	h.mu.Lock()
	defer h.mu.Unlock()
	for sub := range h.subs {
		select {
		case sub.ch <- frame:
		default:
			// Only a browser that has stopped reading entirely can get here.
			// The event is genuinely lost for this subscriber, so mark it and
			// let the drain loop reset the client rather than leave a silent
			// hole in its log.
			sub.overflow.Store(true)
			logger.Warn().Msg("subscriber queue full, resetting client")
		}
	}
}

// ---------------------------------------------------------------------------
// wire format
// ---------------------------------------------------------------------------

// mediaInfo describes an attachment for the frontend. The URL points at
// webchat's own media proxy, never at the homeserver.
type mediaInfo struct {
	URL      string `json:"url"`
	MimeType string `json:"mimetype,omitempty"`
	Size     int    `json:"size,omitempty"`
	// Width/Height let the frontend reserve layout space, which is what makes
	// lazy loading usable: without them every not-yet-loaded image has zero
	// height and the scroll position jumps around as images arrive.
	Width    int    `json:"w,omitempty"`
	Height   int    `json:"h,omitempty"`
	FileName string `json:"filename,omitempty"`
	// Duration is in milliseconds, for audio/video.
	Duration int `json:"duration,omitempty"`
}

// edit is one revision of a message, in the order the revisions were made.
type edit struct {
	Body      string `json:"body"`
	Timestamp int64  `json:"timestamp"`
}

// message is the trimmed-down view of a Matrix event that the frontend needs.
//
// It carries no sort key. Ordering is decided entirely by which frame a message
// arrives in (prepend/append), so the frontend never compares two messages —
// see the SSE event name constants above.
//
// Edits and redaction state are *fields of the message they affect*, not
// separate entries. That is what keeps the protocol to four operations: an edit
// is not a new row to be positioned, it is a changed rendering of an existing
// one, delivered as an `update`.
type message struct {
	// EventID is the identity, the dedup key and the SSE resume cursor. It is
	// UNIQUE in hicli's schema, server-assigned and never reused.
	EventID id.EventID `json:"event_id"`
	Sender  id.UserID  `json:"sender"`
	// Display is the sender's room display name, falling back to the MXID
	// localpart. The full MXID stays in Sender for the hover title.
	Display   string `json:"display"`
	Body      string `json:"body"`
	Timestamp int64  `json:"timestamp"`
	IsOwn     bool   `json:"is_own"`
	// MsgType distinguishes m.text/m.image/m.video/m.audio/m.file so the
	// frontend can pick an element.
	MsgType string     `json:"msgtype,omitempty"`
	Media   *mediaInfo `json:"media,omitempty"`
	// Redacted marks a deleted message. The body is kept when we still have it
	// cached (hicli never deletes event rows, so a redaction seen live leaves
	// the original text in place) and the frontend shows it behind a marker.
	// After a database rebuild the homeserver only serves the stripped event,
	// so the same message then renders as the marker alone.
	Redacted bool `json:"redacted,omitempty"`
	// Edits are the successive revisions of this message, oldest first.
	Edits []edit `json:"edits,omitempty"`
	// Set when the event could not be decrypted; Body is then a placeholder.
	Error string `json:"error,omitempty"`
}

// notification is one desktop notification for the frontend.
//
// Crucially, webchat decides *nothing* about which messages get one. hicli
// evaluates the account's Matrix push rules on every sync
// (hicli/pushrules.go, evaluatePushRules) and reports the result as
// SyncRoom.Notifications; this type is just that decision on the wire.
//
// That is not laziness, it is the only way to get it right: those rules are
// what already express "notify for direct messages and mentions, stay quiet in
// busy public rooms", they are edited from any Matrix client, and they include
// per-room mutes. Reimplementing the policy here would duplicate spec-defined
// logic and silently drift from every other client on the account.
type notification struct {
	RoomID   id.RoomID `json:"room_id"`
	RoomName string    `json:"room_name"`
	// Path is where the frontend should navigate when the notification is
	// clicked.
	Path   string    `json:"path"`
	Sender id.UserID `json:"sender"`
	// Display is the sender's room display name, as in message.Display.
	Display string `json:"display"`
	Body    string `json:"body"`
	// Highlight marks a mention (or anything else the push rules highlight, in
	// practice mostly the user's name); the frontend renders these more loudly.
	Highlight bool `json:"highlight"`
	// Sound is the push rules' sound tweak. The frontend maps it to the
	// Notification `silent` option rather than playing audio itself.
	Sound bool `json:"sound"`
}

// messageContent is the subset of m.room.message content webchat understands.
type messageContent struct {
	Body       string                   `json:"body"`
	MsgType    event.MessageType        `json:"msgtype"`
	FileName   string                   `json:"filename"`
	URL        id.ContentURIString      `json:"url"`
	File       *event.EncryptedFileInfo `json:"file"`
	Info       *event.FileInfo          `json:"info"`
	NewContent *struct {
		Body string `json:"body"`
	} `json:"m.new_content"`
}

// displayName picks the nicest available name for a sender: the room display
// name if the member event has one, otherwise the MXID localpart.
//
// Dropping the server name can in principle make two users from different
// homeservers look alike. The full MXID is kept in the message's Sender field
// and shown on hover, so the ambiguity is always resolvable; a nick column full
// of @user:server.tld is the worse trade.
func displayName(sender id.UserID, roomDisplayName string) string {
	if roomDisplayName != "" {
		return roomDisplayName
	}
	if lp := sender.Localpart(); lp != "" {
		return lp
	}
	return string(sender)
}

// toMessage converts a joined timeline row into a wire message, returning false
// for events the UI does not display.
//
// Dropped here: state events, reactions, and edits. Edits are dropped as
// *timeline rows* because they are re-attached to the message they replace by
// loadEdits — showing them standalone is what made an edit appear as a
// duplicate message at the bottom of the log.
//
// Redacted events are deliberately kept: they render with a marker instead of
// vanishing, so a deletion is visible without a reload.
func (s *server) toMessage(row timelineRow) (message, bool) {
	if row.StateKey.Valid {
		return message{}, false
	}
	// Edits are folded into their target, never shown on their own.
	if row.RelationType.String == string(event.RelReplace) {
		return message{}, false
	}

	msg := message{
		EventID:   row.EventID,
		Sender:    row.Sender,
		Display:   displayName(row.Sender, row.Displayname.String),
		Timestamp: row.Timestamp,
		IsOwn:     row.Sender == s.userID,
		Redacted:  row.RedactedBy.Valid,
	}

	// An encrypted event that hicli could not decrypt (yet) still deserves a
	// placeholder, otherwise messages would silently vanish from the log. A
	// later `decrypted` event replaces it in place, keyed by event ID.
	if row.DecryptionError != "" {
		msg.Error = row.DecryptionError
		msg.Body = "[unable to decrypt]"
		return msg, true
	}

	if row.Type != event.EventMessage.Type && row.Type != event.EventSticker.Type {
		return message{}, false
	}

	var content messageContent
	if err := json.Unmarshal(row.Content, &content); err != nil {
		return message{}, false
	}
	// Edits carry the replacement text in m.new_content.
	if content.NewContent != nil && content.NewContent.Body != "" {
		msg.Body = content.NewContent.Body
	} else {
		msg.Body = content.Body
	}
	msg.MsgType = string(content.MsgType)

	// Attachments: the URL lives in `file` for encrypted rooms and `url` for
	// plaintext ones.
	uri := content.URL
	if content.File != nil {
		uri = content.File.URL
	}
	if url := mediaURL(uri); url != "" {
		msg.Media = &mediaInfo{
			URL:      url,
			FileName: content.FileName,
		}
		if msg.Media.FileName == "" {
			msg.Media.FileName = content.Body
		}
		if info := content.Info; info != nil {
			msg.Media.MimeType = info.MimeType
			msg.Media.Size = info.Size
			msg.Media.Width = info.Width
			msg.Media.Height = info.Height
			msg.Media.Duration = info.Duration
		}
	}

	// A message with neither text nor an attachment has nothing to render —
	// except a redacted one, whose emptiness is exactly what we want to show
	// (the homeserver strips content on redaction, so a redacted event fetched
	// after a database rebuild arrives with an empty body).
	if msg.Body == "" && msg.Media == nil && !msg.Redacted {
		return message{}, false
	}
	return msg, true
}

// toMessages converts timeline rows to wire messages and attaches each one's
// edits, in one batched query rather than one per message.
//
// order is preserved: callers rely on it to decide prepend vs append.
func (v *roomView) toMessages(ctx context.Context, rows []timelineRow) []message {
	msgs := make([]message, 0, len(rows))
	for _, row := range rows {
		if msg, ok := v.s.toMessage(row); ok {
			msgs = append(msgs, msg)
		}
	}
	if len(msgs) == 0 {
		return msgs
	}
	ids := make([]id.EventID, len(msgs))
	for i, msg := range msgs {
		ids[i] = msg.EventID
	}
	edits, err := v.loadEdits(ctx, ids)
	if err != nil {
		// Edits are an enhancement; failing to load them should not cost us the
		// messages themselves.
		v.s.log.Err(err).Msg("load edits")
		return msgs
	}
	for i := range msgs {
		for _, e := range edits[msgs[i].EventID] {
			msgs[i].Edits = append(msgs[i].Edits, edit{Body: e.Body, Timestamp: e.Timestamp})
		}
	}
	return msgs
}

// ---------------------------------------------------------------------------
// server
// ---------------------------------------------------------------------------

// server is the process-wide state: one Matrix client, one account, and the
// set of rooms that currently have a browser attached.
//
// Everything room-specific lives in a roomView instead. The split exists
// because hicli already syncs *every* joined room — its sync filter has no
// room restriction (hicli/syncwrap.go, GetFilterJSON) — so serving more rooms
// is purely a matter of routing, not of fetching more.
type server struct {
	cli    *hicli.HiClient
	userID id.UserID
	log    zerolog.Logger

	// uploadLimit is the homeserver's m.upload.size, i.e. the largest
	// attachment it will accept. The browser shrinks oversized images down to
	// this before uploading, and handleUpload enforces it server-side too.
	uploadLimit int64

	// notify fans desktop notifications out to a single tab, for every room
	// rather than just the open ones — see notifyHub.
	notify *notifyHub

	// views holds one roomView per room that has been opened since startup.
	// Created lazily rather than upfront: an account can be in hundreds of
	// rooms and all but a couple of them will never be looked at.
	//
	// Entries are never removed. A view holds a hub with no subscribers and a
	// mutex — a few dozen bytes — so reclaiming them would buy nothing but a
	// lifetime problem, since the syncer goroutine and HTTP handlers both reach
	// for them concurrently.
	viewsMu sync.RWMutex
	views   map[id.RoomID]*roomView
}

// roomView is the per-room state: one SSE fan-out hub and one pagination lock.
//
// Both are per-room by necessity, not by preference. Subscribers must be
// per-room because a browser tab is showing exactly one room's timeline, and
// hicli's paginator refuses concurrent pagination *for the same room*
// (ErrPaginationAlreadyInProgress, hicli/paginate.go) — a single global lock
// would serialise unrelated rooms' backfills for no reason.
type roomView struct {
	s      *server
	roomID id.RoomID
	hub    *hub

	// backfillMu serializes calls into hicli's paginator for this room. It is
	// held for the duration of that call only — see backfill.
	backfillMu sync.Mutex
}

// view returns the roomView for a room, creating it if this is the first time
// the room has been opened.
func (s *server) view(roomID id.RoomID) *roomView {
	s.viewsMu.RLock()
	v, ok := s.views[roomID]
	s.viewsMu.RUnlock()
	if ok {
		return v
	}
	s.viewsMu.Lock()
	defer s.viewsMu.Unlock()
	// Re-check: another request may have created it while we were upgrading.
	if v, ok := s.views[roomID]; ok {
		return v
	}
	v = &roomView{s: s, roomID: roomID, hub: newHub()}
	s.views[roomID] = v
	return v
}

// viewIfOpen returns the roomView for a room only if one already exists.
//
// This is what the sync event handler uses, and it is the reason serving every
// joined room costs no more than serving one: a sync touching a room nobody is
// looking at does no work beyond this map lookup. Creating views here instead
// would allocate a hub for every room in the account on the first sync.
func (s *server) viewIfOpen(roomID id.RoomID) *roomView {
	s.viewsMu.RLock()
	defer s.viewsMu.RUnlock()
	return s.views[roomID]
}

// senderDisplayName looks up a sender's current room display name. Used for
// typing notifications and desktop notifications, which carry user IDs rather
// than joined event rows; timeline display names are resolved by the SQL join
// in eventColumns instead.
// A name is never worth failing over: every lookup problem — no client, no
// member event, a database error — falls back to the MXID localpart, which is
// always available and always recognisable.
func (s *server) senderDisplayName(ctx context.Context, roomID id.RoomID, sender id.UserID) string {
	if s.cli == nil {
		return displayName(sender, "")
	}
	memberEvt, err := s.cli.DB.CurrentState.Get(ctx, roomID, event.StateMember, string(sender))
	if err != nil || memberEvt == nil {
		return displayName(sender, "")
	}
	var content struct {
		Displayname string `json:"displayname"`
	}
	_ = json.Unmarshal(memberEvt.Content, &content)
	return displayName(sender, content.Displayname)
}

// nullString converts an optional string to the sql.NullString that
// timelineRow uses, so events pushed by hicli can be fed through the same
// conversion as rows read back from SQLite.
func nullString(s *string) sql.NullString {
	if s == nil {
		return sql.NullString{}
	}
	return sql.NullString{String: *s, Valid: true}
}

// ptrIfSet returns a pointer to s, or nil if s is empty. hicli uses "" for
// absent in several event fields where the database column is NULL.
func ptrIfSet(s string) *string {
	if s == "" {
		return nil
	}
	return &s
}

// handleEvent is hicli's EventHandler: it runs on the syncer's goroutine for
// every push event, and classifies each one into the four-operation protocol.
//
// The classification is the heart of the design: a timeline row is either a new
// message (append), or a modification of an existing one (update). Edits and
// redactions are the latter, which is why they never need a position.
//
// Timeline handling dispatches through viewIfOpen, so a sync for a room no
// browser has open is dropped after one map lookup. That is what keeps syncing
// the whole account as cheap as syncing a single room.
//
// Notifications are the one thing that deliberately does *not* work that way:
// the whole point is to hear about rooms you are not looking at, so they are
// handled for every room in the sync. That extra pass is skipped entirely when
// no tab is listening.
func (s *server) handleEvent(rawEvt any) {
	ctx := context.Background()
	switch evt := rawEvt.(type) {
	case *jsoncmd.SyncComplete:
		notifying := s.notify.hasSubscribers()
		for roomID, room := range evt.Rooms {
			if notifying {
				s.handleNotifications(ctx, room)
			}
			v := s.viewIfOpen(roomID)
			if v == nil {
				continue
			}
			// A limited sync makes hicli wipe the room's timeline and restart
			// row IDs (see resolveCursorSQL). Every connected client is now
			// holding a view that cannot be reconciled, so tell them to start
			// over. hicli reports this and webchat used to ignore it, which
			// left connected tabs silently stitching pre- and post-reset
			// history together.
			if room.Reset {
				v.s.log.Info().Stringer("room", roomID).
					Msg("timeline reset, telling clients to reload")
				v.hub.broadcastLive(v.s.log, sseReset, map[string]any{}, "")
				continue
			}
			v.handleTimeline(ctx, room)
		}

	case *jsoncmd.EventsDecrypted:
		v := s.viewIfOpen(evt.RoomID)
		if v == nil {
			return
		}
		// Late decryption replaces the "[unable to decrypt]" placeholder. This
		// is an update keyed by event ID, so — unlike before — it needs no
		// timeline row ID, which is just as well: the query hicli uses to find
		// these events does not join the timeline table, so the row IDs it
		// reports are always zero.
		ids := make([]id.EventID, 0, len(evt.Events))
		for _, e := range evt.Events {
			ids = append(ids, e.ID)
		}
		v.broadcastUpdate(ctx, ids)

	case *jsoncmd.Typing:
		v := s.viewIfOpen(evt.RoomID)
		if v == nil {
			return
		}
		others := make([]string, 0, len(evt.UserIDs))
		for _, u := range evt.UserIDs {
			if u != s.userID {
				others = append(others, s.senderDisplayName(ctx, evt.RoomID, u))
			}
		}
		v.hub.broadcastLive(s.log, sseTyping, map[string]any{"users": others}, "")
	}
}

// handleTimeline turns one sync's worth of new timeline rows into append and
// update frames.
func (v *roomView) handleTimeline(ctx context.Context, room *jsoncmd.SyncRoom) {
	// The timeline lists row IDs; the actual event bodies are in .Events.
	byRowID := make(map[database.EventRowID]*database.Event, len(room.Events))
	for _, e := range room.Events {
		byRowID[e.RowID] = e
	}

	var appendIDs []id.EventID
	var updateIDs []id.EventID

	for _, tuple := range room.Timeline {
		evtData, ok := byRowID[tuple.Event]
		if !ok {
			// Not included in this payload (e.g. already known); fetch it.
			var err error
			evtData, err = v.s.cli.DB.Event.GetByRowID(ctx, tuple.Event)
			if err != nil || evtData == nil {
				continue
			}
		}

		switch {
		case evtData.RelationType == event.RelReplace:
			// An edit: re-render the message it replaces, not the edit itself.
			if evtData.RelatesTo != "" {
				updateIDs = append(updateIDs, evtData.RelatesTo)
			}
		case evtData.Type == event.EventRedaction.Type:
			// A redaction: re-render its target. hicli's schema has an AFTER
			// INSERT trigger that sets redacted_by on the target row, and it
			// runs inside the sync transaction, which has already committed by
			// the time we get here — so re-reading the target now sees it.
			if target := redactionTarget(evtData); target != "" {
				updateIDs = append(updateIDs, target)
			}
		default:
			appendIDs = append(appendIDs, evtData.ID)
		}
	}

	if len(appendIDs) > 0 {
		v.broadcastMessages(ctx, sseAppend, appendIDs)
	}
	if len(updateIDs) > 0 {
		v.broadcastUpdate(ctx, updateIDs)
	}
}

// handleNotifications turns one room's push-rule matches into notify frames.
//
// room.Notifications is hicli's output, not ours: it has already run the
// account's push rules over each new event (evaluatePushRules) and listed only
// those that should notify. So there is no policy here — no DM check, no
// mention matching, no mute list — just formatting.
//
// hicli also suppresses these until the first sync has completed
// (firstSyncReceived, hicli/sync.go), so starting webchat after a week away
// does not produce a week of notifications.
func (s *server) handleNotifications(ctx context.Context, room *jsoncmd.SyncRoom) {
	if len(room.Notifications) == 0 {
		return
	}
	// Suppress notifications for a room the user is already watching. This is
	// decided here, not in the browser, because the notification goes to
	// exactly one tab (notifyHub) and that tab is usually not the one showing
	// the room — it cannot know whether some other tab has it on screen. A tab
	// only counts while it is actually visible, so a room left open in a
	// background window still notifies.
	if v := s.viewIfOpen(room.Meta.ID); v != nil && v.hub.anyVisible() {
		return
	}
	for _, notif := range room.Notifications {
		if notif.Event == nil {
			continue
		}
		// Never notify for our own messages. hicli's push rules normally take
		// care of this, but a rule set edited by hand could let one through,
		// and being pinged by your own message is pure noise.
		if notif.Event.Sender == s.userID {
			continue
		}
		// Reuse the timeline's own conversion so a notification says exactly
		// what the message row will say — same body, same attachment handling,
		// same "not something we render" rejections (state events, reactions,
		// edits). Content/type mirror eventColumns' COALESCE: the cleartext
		// when the event was encrypted, the raw content when it was not.
		evt := notif.Event
		content, evtType := evt.Content, evt.Type
		if evt.Decrypted != nil {
			content, evtType = evt.Decrypted, evt.DecryptedType
		}
		msg, ok := s.toMessage(timelineRow{
			EventID:      evt.ID,
			Sender:       evt.Sender,
			Timestamp:    evt.Timestamp.UnixMilli(),
			Content:      content,
			Type:         evtType,
			StateKey:     nullString(evt.StateKey),
			RedactedBy:   nullString(ptrIfSet(string(evt.RedactedBy))),
			RelationType: nullString(ptrIfSet(string(evt.RelationType))),
		})
		if !ok {
			continue
		}
		// A message that was redacted before we got here is not worth an alert.
		if msg.Redacted {
			continue
		}
		s.notify.send(s.log, notification{
			RoomID:    room.Meta.ID,
			RoomName:  roomDisplayName(room.Meta),
			Path:      roomPath(room.Meta.ID),
			Sender:    msg.Sender,
			Display:   s.senderDisplayName(ctx, room.Meta.ID, msg.Sender),
			Body:      notificationBody(msg),
			Highlight: notif.Highlight,
			Sound:     notif.Sound,
		})
	}
}

// notificationBody is the one-line summary shown in the notification.
//
// An attachment has no useful text body (for an image it is just the filename),
// so it gets a placeholder instead. Long messages are truncated: notification
// daemons cut them off anyway, and doing it here keeps the frame small.
func notificationBody(msg message) string {
	body := msg.Body
	if msg.Media != nil && msg.MsgType != "m.text" {
		switch msg.MsgType {
		case "m.image":
			body = "[image]"
		case "m.video":
			body = "[video]"
		case "m.audio":
			body = "[audio]"
		default:
			body = "[file]"
		}
	}
	const maxBody = 200
	if len(body) > maxBody {
		// Trim on a rune boundary so the snippet cannot end mid-character.
		body = strings.ToValidUTF8(body[:maxBody], "") + "…"
	}
	return body
}

// roomDisplayName is the room's name, falling back to its ID. Rooms that hicli
// has not named yet (no m.room.name, no canonical alias, member list not
// loaded) would otherwise show an empty title.
func roomDisplayName(room *database.Room) string {
	if room == nil {
		return ""
	}
	if room.Name != nil && *room.Name != "" {
		return *room.Name
	}
	return string(room.ID)
}

// redactionTarget extracts the event a redaction applies to.
//
// Matrix moved `redacts` from the top level of the event into its content in
// room version 11. hicli normalises this while processing the event, copying
// the top-level field into content when only the former is present (see
// processEvent in hicli/sync.go), so reading content alone covers both.
func redactionTarget(evt *database.Event) id.EventID {
	var content struct {
		Redacts id.EventID `json:"redacts"`
	}
	if err := json.Unmarshal(evt.Content, &content); err != nil {
		return ""
	}
	return content.Redacts
}

// broadcastMessages re-reads the given events from SQLite and sends them as one
// frame under the given operation.
//
// Re-reading rather than converting the pushed database.Event structs directly
// is what collapses the two conversion paths into one: display names, edits and
// redaction state all come from the same joined query the history path uses, so
// a message renders identically no matter which path delivered it.
func (v *roomView) broadcastMessages(ctx context.Context, op string, ids []id.EventID) {
	rows, err := v.queryByEventIDs(ctx, ids)
	if err != nil {
		v.s.log.Err(err).Str("op", op).Msg("read events for broadcast")
		return
	}
	msgs := v.toMessages(ctx, rows)
	if len(msgs) == 0 {
		return
	}
	// The resume cursor is the newest event in the frame. Only append frames
	// set it: they are the only ones that extend the client's newest-known
	// message. (Frames are built oldest-first, so that is the last element.)
	cursor := ""
	if op == sseAppend {
		cursor = string(msgs[len(msgs)-1].EventID)
	}
	v.hub.broadcastLive(v.s.log, op, map[string]any{"messages": msgs}, cursor)
}

// broadcastUpdate re-renders existing messages in place. Updates never carry a
// resume cursor (they do not extend the timeline) and are never positional, so
// they go to every subscriber regardless of its history boundary.
func (v *roomView) broadcastUpdate(ctx context.Context, ids []id.EventID) {
	v.broadcastMessages(ctx, sseUpdate, ids)
}

// handleRooms serves the room list, which is the landing page.
//
// Deliberately a plain rendered page rather than another live stream: keeping
// it static is what lets handleEvent early-out on rooms nobody has open. The
// list is re-sorted on every load, which is as fresh as it needs to be for
// something you look at for a second before clicking through.
func (s *server) handleRooms(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	rooms, err := listRooms(r.Context(), s.cli)
	if err != nil {
		s.log.Err(err).Msg("list rooms")
		http.Error(w, "could not list rooms", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := roomsTmpl.Execute(w, map[string]any{
		"UserID": s.userID,
		"Rooms":  rooms,
	}); err != nil {
		s.log.Err(err).Msg("render room list")
	}
}

// handleIndex serves the single-page UI for one room, with the backlog already
// in it.
//
// Embedding the backlog rather than streaming it is what makes the scrolling
// sane. When the log starts empty, every message arrives as a prepend into a
// container whose scrollTop is 0 — and scroll anchoring is specified not to
// engage there (css-scroll-anchoring §2.1: no anchor node is selected for a
// scrolling box that is not scrolled away from its origin; §2.2.2 lists a zero
// scroll offset as a suppression trigger). So the view could only be held still
// by measuring and re-applying scroll offsets by hand, which is what used to be
// here and what jumped. With the rows already present at first paint there is
// nothing to hold still: the page is simply scrolled to the bottom once.
//
// The messages are embedded as JSON and rendered by the same mk() the live
// stream uses, rather than as server-rendered <li>s. Update frames re-render
// arbitrary rows in place (edits, redactions, late decryption), so that
// renderer has to exist in the browser regardless; a second server-side one
// would have to produce byte-identical markup forever or an edited message
// would visibly change shape as it was revised.
func (v *roomView) handleIndex(w http.ResponseWriter, r *http.Request) {
	// The room name is read per request rather than cached on the view: it can
	// change at any time (an m.room.name event, or a DM whose name is derived
	// from its members), and a page load is not a hot path.
	roomName := ""
	if room, err := v.s.cli.DB.Room.Get(r.Context(), v.roomID); err == nil && room != nil && room.Name != nil {
		roomName = *room.Name
	}

	msgs, newest, oldest, have := v.pageBacklog(r.Context())
	// json.Marshal escapes <, > and & as \u003c, \u003e and \u0026, so the
	// payload cannot terminate the <script> element it is embedded in.
	backlog, err := json.Marshal(msgs)
	if err != nil {
		v.s.log.Err(err).Msg("marshal page backlog")
		backlog = []byte("[]")
		newest, oldest, have = "", "", 0
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := tmpl.Execute(w, map[string]any{
		"RoomID": v.roomID,
		// Base is the prefix every API call in the page is built from, so the
		// frontend needs no knowledge of the routing scheme beyond "prepend
		// this". Escaped once here rather than in JS.
		"Base":        roomPath(v.roomID),
		"UserID":      v.s.userID,
		"RoomName":    roomName,
		"UploadLimit": v.s.uploadLimit,
		"Backlog":     template.JS(backlog),
		// The stream resumes forward from Newest and continues backwards from
		// Oldest, so it neither replays nor skips what is already on the page.
		"Newest": newest,
		"Oldest": oldest,
		"Have":   have,
	}); err != nil {
		v.s.log.Err(err).Msg("render index")
	}
}

// handleEvents is the SSE stream. It is the *only* way messages reach the
// browser: backlog, gap replay after a reconnect, and live events all arrive
// here, so the frontend has a single idempotent rendering path.
//
// History is written directly to the response *before* the live drain loop
// starts. That ordering is what lets the protocol drop its sort key: history
// and live events can no longer interleave, so every frame is either strictly
// above or strictly below what the client already holds, and the server always
// knows which.
func (v *roomView) handleEvents(w http.ResponseWriter, r *http.Request) {
	flusher, ok := startSSE(w)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}

	ctx := r.Context()

	// Subscribe *before* reading history, so an event committing while we read
	// is queued rather than lost. It may then also appear in the history we are
	// about to send; the client renders by event ID, so the repeat collapses
	// onto the row it already has.
	// The tab reports whether it is on screen right now, so a room opened in a
	// background tab does not start out suppressing its own notifications.
	sub := v.hub.subscribe(r.URL.Query().Get("tab"), r.URL.Query().Get("visible") == "1")
	defer v.hub.unsubscribe(sub)

	// The cursor comes from Last-Event-ID on a reconnect and from ?since on the
	// first connect, where the page rendered its own backlog and the browser
	// has no header to send yet. The header wins when both are present: it is
	// necessarily the newer of the two, since ?since is fixed at page load.
	cursor := r.Header.Get("Last-Event-ID")
	if cursor == "" {
		cursor = r.URL.Query().Get("since")
	}
	have, _ := strconv.Atoi(r.URL.Query().Get("have"))
	if !v.sendHistory(ctx, w, flusher, cursor, r.URL.Query().Get("before"), have) {
		return
	}

	// Keepalive comments stop intermediaries from dropping an idle stream.
	ticker := time.NewTicker(25 * time.Second)
	defer ticker.Stop()

	for {
		// A dropped live event leaves a hole this client cannot discover on its
		// own, so the only correct recovery is to make it start over.
		if sub.overflow.Load() {
			frame, err := sseFrame(sseReset, map[string]any{}, "")
			if err == nil {
				_, _ = w.Write(frame)
				flusher.Flush()
			}
			return
		}
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			if _, err := w.Write([]byte(": keepalive\n\n")); err != nil {
				return
			}
			flusher.Flush()
		case frame := <-sub.ch:
			if _, err := w.Write(frame); err != nil {
				return
			}
			flusher.Flush()
		}
	}
}

// startSSE writes the event-stream headers and flushes them, so the browser
// treats the response as open rather than waiting for a complete body.
func startSSE(w http.ResponseWriter) (http.Flusher, bool) {
	flusher, ok := w.(http.Flusher)
	if !ok {
		return nil, false
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	// nginx buffers proxied responses by default, which would hold frames back
	// until the buffer fills — fatal for a stream that is mostly idle.
	w.Header().Set("X-Accel-Buffering", "no")
	w.WriteHeader(http.StatusOK)
	flusher.Flush()
	return flusher, true
}

// handleNotifications is the notification stream, subscribed by every page.
//
// Unlike a room's /events stream this has no history and no resume cursor. A
// notification is a transient alert about something that happened while you
// were not looking; replaying a missed one after a reconnect would announce
// old news, and the message itself is in the timeline regardless. So there is
// nothing to send on connect and nothing to catch up on — only live frames.
//
// Note the stream is opened by every tab even though only one of them will be
// sent anything: subscribing is what makes a tab eligible to become the leader
// when the current one closes (see notifyHub).
func (s *server) handleNotificationStream(w http.ResponseWriter, r *http.Request) {
	flusher, ok := startSSE(w)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}

	sub := s.notify.subscribe()
	defer s.notify.unsubscribe(sub)

	ctx := r.Context()
	ticker := time.NewTicker(25 * time.Second)
	defer ticker.Stop()

	for {
		// Overflow means this tab stopped reading. There is no "reset" for a
		// stream with no state, so just drop the connection: the tab is
		// removed from the subscriber list and leadership passes to the next.
		if sub.overflow.Load() {
			return
		}
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			if _, err := w.Write([]byte(": keepalive\n\n")); err != nil {
				return
			}
			flusher.Flush()
		case frame := <-sub.ch:
			if _, err := w.Write(frame); err != nil {
				return
			}
			flusher.Flush()
		}
	}
}

// sendHistory delivers everything the client is missing, returning false if the
// connection died partway.
//
// There are three cases, distinguished by what the client already holds:
//
//   - Nothing (no cursor): walk backwards to backlogTarget rows, backfilling
//     from the homeserver when the local cache runs out. This is now the cold
//     path — a fresh page load arrives with its backlog already rendered.
//   - A cursor and a pre-rendered backlog (`since`+`before`+`have`): send the
//     gap above it, then top the backlog up to backlogTarget from `before`.
//   - A cursor alone (a reconnect, via Last-Event-ID): send only the gap.
//
// oldest/have describe the *bottom* of what the page rendered: the oldest
// timeline row it covered, and how many rows that was. They are what let the
// backfill continue from where the page stopped instead of duplicating it.
func (v *roomView) sendHistory(ctx context.Context, w io.Writer, flusher http.Flusher, lastEventID, oldest string, have int) bool {
	if lastEventID == "" {
		return v.sendBacklog(ctx, w, flusher, 0, backlogTarget, true)
	}
	// Event IDs are resolved against the *current* timeline on every reconnect,
	// so a recycled or renumbered row ID can never be misread — see
	// resolveCursorSQL.
	cursor, found, err := v.resolveCursor(ctx, id.EventID(lastEventID))
	if err != nil {
		v.s.log.Err(err).Str("last_event_id", lastEventID).Msg("resolve cursor")
		return v.sendBacklog(ctx, w, flusher, 0, backlogTarget, true)
	}
	if !found {
		// The event is no longer on the timeline: it was cleared by a limited
		// sync. The client's view cannot be extended, only replaced.
		v.s.log.Info().Str("last_event_id", lastEventID).
			Msg("cursor no longer on timeline, resetting client")
		if !writeFrame(w, flusher, sseReset, map[string]any{}, "") {
			return false
		}
		return v.sendBacklog(ctx, w, flusher, 0, backlogTarget, true)
	}
	if !v.sendGap(ctx, w, flusher, cursor) {
		return false
	}
	if oldest == "" || have >= backlogTarget {
		return true
	}
	// The page rendered a short backlog (the local cache ran out), so continue
	// below it. The client already holds a newer cursor from the gap above, so
	// these prepends must not carry one of their own.
	bottom, found, err := v.resolveCursor(ctx, id.EventID(oldest))
	if err != nil || !found {
		return true // the boundary is gone; the client keeps what it has
	}
	return v.sendBacklog(ctx, w, flusher, bottom, backlogTarget-have, false)
}

// sendGap replays everything newer than the client's cursor. Deliberately
// uncapped: after a long disconnect we would rather push a large gap than
// silently skip messages.
func (v *roomView) sendGap(ctx context.Context, w io.Writer, flusher http.Flusher, cursor database.TimelineRowID) bool {
	rows, err := v.queryForward(ctx, cursor)
	if err != nil {
		v.s.log.Err(err).Msg("query timeline gap")
		return false
	}
	if len(rows) == 0 {
		return true
	}
	// Oldest-first and all newer than what the client holds: an append.
	return v.sendChunks(ctx, w, flusher, sseAppend, rows, "")
}

// pageBacklog reads the backlog that handleIndex embeds directly into the HTML,
// returning messages oldest-first along with the newest and oldest timeline row
// event IDs it covered.
//
// Unlike sendBacklog this reads *only what SQLite already has*: it never calls
// backfill. That is the whole point of pre-rendering. A cold room's backfill
// does real /messages round trips against the homeserver, and doing that inline
// would hold the page load — and therefore a blank screen — for as long as it
// takes. Whatever is missing is streamed in afterwards as prepends, which by
// then land in a log that is scrolled away from the origin, the one case where
// scroll anchoring is specified to hold the view still.
//
// The returned event IDs are timeline row IDs, not message IDs: they are only
// ever resolved back to a timeline position (see resolveCursorSQL), never
// displayed, so a state event serves as a boundary just as well as a message.
func (v *roomView) pageBacklog(ctx context.Context) (msgs []message, newest, oldest id.EventID, rowCount int) {
	var cursor database.TimelineRowID // 0 = start from the newest row
	var all []timelineRow
	for rowCount < backlogTarget {
		batch, err := v.queryBackward(ctx, cursor, paginateBatch)
		if err != nil {
			v.s.log.Err(err).Msg("query timeline for page backlog")
			break
		}
		if len(batch) == 0 {
			break // nothing more cached; the stream backfills the rest
		}
		// The cursor advances over every row read, not just displayable ones —
		// see queryBackward.
		cursor = batch[len(batch)-1].RowID
		rowCount += len(batch)
		all = append(all, batch...) // accumulated newest-first
	}
	if len(all) == 0 {
		return nil, "", "", 0
	}
	newest, oldest = all[0].EventID, all[len(all)-1].EventID
	slices.Reverse(all) // flip to oldest-first for rendering
	return v.toMessages(ctx, all), newest, oldest, rowCount
}

// sendBacklog walks backwards from cursor (0 = the newest message), emitting
// chunks as it goes so the bottom of the log paints immediately, and
// backfilling from the homeserver once the local cache is exhausted.
//
// setCursor says whether the first frame carries the SSE resume cursor. It is
// false when continuing below a backlog the page already rendered: the client
// then already holds a *newer* cursor, and overwriting it with an older one
// would make the next reconnect replay everything in between.
func (v *roomView) sendBacklog(ctx context.Context, w io.Writer, flusher http.Flusher, cursor database.TimelineRowID, target int, setCursor bool) bool {
	// The resume cursor is established from the *first* batch, which is the
	// newest one. So a client that disconnects halfway through the walk still
	// has a valid cursor and resumes forward correctly — how much history it
	// managed to load has no bearing on staying up to date.
	cursorSent := !setCursor

	sent := 0
	for sent < target {
		rows, err := v.queryBackward(ctx, cursor, paginateBatch)
		if err != nil {
			v.s.log.Err(err).Msg("query timeline backlog")
			return false
		}
		if len(rows) == 0 {
			// Nothing cached below the cursor: ask hicli to backfill from the
			// homeserver, then re-read. Paginate writes the fetched events into
			// SQLite, so the next queryBackward picks them up.
			more, err := v.backfill(ctx, cursor)
			if err != nil {
				v.s.log.Err(err).Msg("backfill from homeserver")
				return false
			}
			if !more {
				return true // start of the room
			}
			rows, err = v.queryBackward(ctx, cursor, paginateBatch)
			if err != nil {
				v.s.log.Err(err).Msg("query timeline after backfill")
				return false
			}
			if len(rows) == 0 {
				return true
			}
		}

		// The cursor advances over *every* row read, not just the displayable
		// ones. Advancing only past rendered messages would let a window of
		// nothing but state events leave the cursor unchanged and spin forever.
		cursor = rows[len(rows)-1].RowID

		// Rows come back newest-first; flip to oldest-first for rendering.
		slices.Reverse(rows)

		// The newest row of the first batch is the resume point. It need not be
		// a row the client renders — a state event works just as well — because
		// the cursor is only ever resolved back to a timeline position, never
		// displayed.
		resumeFrom := id.EventID("")
		if !cursorSent {
			resumeFrom = rows[len(rows)-1].EventID
			cursorSent = true
		}
		if !v.sendChunks(ctx, w, flusher, ssePrepend, rows, resumeFrom) {
			return false
		}
		sent += len(rows)

		if ctx.Err() != nil {
			return false
		}
	}
	return true
}

// backfill asks hicli to fetch older events from the homeserver. It reports
// whether more history may exist.
//
// The lock covers only this call, not the surrounding walk: hicli refuses
// concurrent pagination for one room, but holding it across the SSE writes
// would let one stalled browser block every other tab's first paint.
func (v *roomView) backfill(ctx context.Context, cursor database.TimelineRowID) (bool, error) {
	v.backfillMu.Lock()
	defer v.backfillMu.Unlock()
	resp, err := v.s.cli.API.Paginate(ctx, &jsoncmd.PaginateParams{
		RoomID:        v.roomID,
		MaxTimelineID: cursor,
		Limit:         paginateBatch,
	})
	if err != nil {
		return false, err
	}
	return resp.HasMore, nil
}

// writeFrame writes one SSE frame straight to the response.
func writeFrame(w io.Writer, flusher http.Flusher, eventName string, payload any, lastEventID string) bool {
	frame, err := sseFrame(eventName, payload, lastEventID)
	if err != nil {
		return false
	}
	if _, err := w.Write(frame); err != nil {
		return false
	}
	flusher.Flush()
	return true
}

// sendChunks converts rows (oldest-first) to messages and writes them out in
// chunks under the given operation.
//
// Chunking preserves order in both directions. For a prepend the caller walks
// backwards batch by batch, so batches arrive newest-first while each batch is
// internally oldest-first; chunks within a batch must therefore be emitted
// newest-chunk-first so that successive prepends stack up correctly. Worked
// example, rows [a,b,c,d] (oldest to newest) with chunkSize 2: this sends [c,d]
// then [a,b], and prepending each in turn yields [c,d] -> [a,b,c,d].
//
// resumeFrom, when set, is attached to the first frame written. It is emitted
// even for a batch that renders nothing, so that a window of state events does
// not cost the client its resume point.
func (v *roomView) sendChunks(ctx context.Context, w io.Writer, flusher http.Flusher, op string, rows []timelineRow, resumeFrom id.EventID) bool {
	msgs := v.toMessages(ctx, rows)
	if len(msgs) == 0 {
		if resumeFrom != "" {
			return writeFrame(w, flusher, op, map[string]any{"messages": []message{}}, string(resumeFrom))
		}
		return true
	}

	type chunk struct{ start, end int }
	var chunks []chunk
	for start := 0; start < len(msgs); start += chunkSize {
		chunks = append(chunks, chunk{start, min(start+chunkSize, len(msgs))})
	}
	// Prepends paint from the bottom up, so the newest chunk goes first.
	if op == ssePrepend {
		slices.Reverse(chunks)
	}

	for i, c := range chunks {
		cursor := ""
		if i == 0 {
			cursor = string(resumeFrom)
		}
		if !writeFrame(w, flusher, op, map[string]any{"messages": msgs[c.start:c.end]}, cursor) {
			return false
		}
		if ctx.Err() != nil {
			return false
		}
	}
	return true
}

// handleSend sends a text message to this room. hicli takes care of encrypting
// it and sharing the megolm session as needed.
func (v *roomView) handleSend(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Text string `json:"text"`
	}
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if req.Text == "" {
		http.Error(w, "text required", http.StatusBadRequest)
		return
	}
	evt, err := v.s.cli.API.SendMessage(r.Context(), &jsoncmd.SendMessageParams{
		RoomID: v.roomID,
		Text:   req.Text,
	})
	if err != nil {
		v.s.log.Err(err).Msg("send message")
		http.Error(w, "send failed", http.StatusInternalServerError)
		return
	}
	// The echo back through /events is what actually renders the message, so
	// here we only confirm acceptance.
	writeJSON(w, map[string]any{"ok": true, "event_id": evt.ID})
}

// handleTyping forwards typing notifications so the other side sees them.
// handleVisibility records whether a tab currently has this room on screen, so
// the server can skip notifications for a conversation the user is watching.
//
// This is a separate request rather than a message on the SSE stream because
// SSE is one-directional; the alternative would be a WebSocket, which is a lot
// of machinery for one boolean.
//
// Kept deliberately forgiving: an unknown tab ID is a no-op rather than an
// error, since the natural race — the stream dropping just as the tab reports
// going hidden — is harmless and would otherwise log noise on every reconnect.
func (v *roomView) handleVisibility(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Tab     string `json:"tab"`
		Visible bool   `json:"visible"`
	}
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if req.Tab == "" {
		http.Error(w, "tab required", http.StatusBadRequest)
		return
	}
	v.hub.setVisible(req.Tab, req.Visible)
	w.WriteHeader(http.StatusNoContent)
}

func (v *roomView) handleTyping(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Typing bool `json:"typing"`
	}
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	timeout := 0
	if req.Typing {
		timeout = 10000
	}
	if err := v.s.cli.API.SetTyping(r.Context(), &jsoncmd.SetTypingParams{
		RoomID:  v.roomID,
		Timeout: timeout,
	}); err != nil {
		v.s.log.Debug().Err(err).Msg("set typing")
	}
	w.WriteHeader(http.StatusNoContent)
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(v); err != nil {
		log.Printf("encode json: %v", err)
	}
}

// roomInfo is a minimal room listing entry, used both by the `rooms` command
// and by the room list page.
type roomInfo struct {
	ID   id.RoomID
	Name string
	// Path is the URL of this room's chat page.
	Path string
	// Activity is the timestamp of the room's last activity, in milliseconds,
	// as hicli's sorting_timestamp. Rendered as a relative time by the page.
	Activity int64
}

// listRooms returns joined rooms, most recently active first.
//
// hicli's GetBySortTS excludes spaces (`room_type<>'m.space'`) and rooms that
// have never had activity (`sorting_timestamp > 0`), which is exactly the set
// worth listing — so no filtering is needed here.
func listRooms(ctx context.Context, cli *hicli.HiClient) ([]roomInfo, error) {
	rooms, err := cli.DB.Room.GetBySortTS(ctx, time.Now().Add(1*time.Hour), 500)
	if err != nil {
		return nil, err
	}
	out := make([]roomInfo, 0, len(rooms))
	for _, r := range rooms {
		name := "(unnamed)"
		if r.Name != nil && *r.Name != "" {
			name = *r.Name
		}
		out = append(out, roomInfo{
			ID:       r.ID,
			Name:     name,
			Path:     roomPath(r.ID),
			Activity: r.SortingTimestamp.UnixMilli(),
		})
	}
	return out, nil
}

// roomPath is the URL prefix for a room's page and its API endpoints.
//
// Room IDs contain no characters that are special in a path segment
// (`!localpart:server`), but they are escaped anyway: the ID comes from the
// homeserver, and constructing URLs from remote data without escaping is a
// habit worth not having.
func roomPath(roomID id.RoomID) string {
	return "/room/" + url.PathEscape(string(roomID))
}

// withRoom resolves the {roomID} path parameter to a roomView before handing
// off to a room-scoped handler.
//
// The database lookup is the access control for every room route, and it is
// the same shape the media proxy uses (see handleMedia): hicli only has a room
// row for rooms this account is actually in, so "is it in the DB" answers "may
// this be served". Without it, any room ID typed into the URL bar would create
// a view and start paginating a room we may not be in.
func (s *server) withRoom(h func(*roomView, http.ResponseWriter, *http.Request)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		roomID := id.RoomID(r.PathValue("roomID"))
		room, err := s.cli.DB.Room.Get(r.Context(), roomID)
		if err != nil {
			s.log.Err(err).Stringer("room", roomID).Msg("look up room")
			http.Error(w, "room lookup failed", http.StatusInternalServerError)
			return
		}
		if room == nil {
			http.NotFound(w, r)
			return
		}
		h(s.view(roomID), w, r)
	}
}

// ---------------------------------------------------------------------------
// serve command
// ---------------------------------------------------------------------------

func cmdServe(args []string) {
	fs := flag.NewFlagSet("serve", flag.ExitOnError)
	addr := fs.String("addr", "127.0.0.1:8775", "listen address")
	dbPath := fs.String("db", defaultDBPath(), "path to the webchat database")
	debug := fs.Bool("debug", false, "verbose logging")
	fs.Parse(args)

	logger := newLogger(*debug)
	ctx := logger.WithContext(context.Background())

	s := &server{
		views:  map[id.RoomID]*roomView{},
		notify: newNotifyHub(),
		log:    logger,
	}
	cli, err := startClient(ctx, *dbPath, logger, s.handleEvent)
	if err != nil {
		fatalf("%v", err)
	}
	s.cli = cli
	s.userID = cli.Account.UserID
	if !cli.VerificationState.IsVerified {
		logger.Warn().Msg("device is not cross-signing verified; encrypted history may not decrypt — re-run `webchat login`")
	}
	s.uploadLimit = fetchUploadLimit(ctx, cli, logger)

	mux := http.NewServeMux()
	// The room list is the landing page; every room lives under /room/{id}, so
	// each one gets its own SSE stream and its own Last-Event-ID cursor. That
	// is what lets the single-timeline protocol carry over unchanged.
	mux.HandleFunc("GET /{$}", s.handleRooms)
	// Notifications are process-wide, not per room: the point is to hear about
	// rooms you do *not* have open. Every page subscribes; only one is sent to.
	mux.HandleFunc("GET /notifications", s.handleNotificationStream)
	mux.HandleFunc("GET /room/{roomID}", s.withRoom((*roomView).handleIndex))
	mux.HandleFunc("GET /room/{roomID}/events", s.withRoom((*roomView).handleEvents))
	mux.HandleFunc("POST /room/{roomID}/send", s.withRoom((*roomView).handleSend))
	mux.HandleFunc("POST /room/{roomID}/typing", s.withRoom((*roomView).handleTyping))
	mux.HandleFunc("POST /room/{roomID}/visibility", s.withRoom((*roomView).handleVisibility))
	mux.HandleFunc("POST /room/{roomID}/upload", s.withRoom((*roomView).handleUpload))
	// Media stays global: it is keyed by mxc URI and access-controlled against
	// hicli's media table, which is already room-agnostic.
	mux.HandleFunc("GET /media/{server}/{fileID}", s.handleMedia)

	srv := &http.Server{Addr: *addr, Handler: mux}

	// Shut down cleanly so the sqlite WAL is checkpointed and olm state flushed.
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-stop
		logger.Info().Msg("shutting down")
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = srv.Shutdown(shutdownCtx)
		cli.Stop()
	}()

	logger.Info().
		Str("addr", *addr).
		Stringer("user", s.userID).
		Msg("webchat listening")
	if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		logPanic("listen: %v", err)
	}
}