alice-and-bot 1.0.78 → 1.0.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/components.js CHANGED
@@ -11,8 +11,10 @@ import {
11
11
  getCachedConversationKey,
12
12
  getOrCreateConversation,
13
13
  importIdentity,
14
+ isAttachmentExpiredError,
14
15
  isSilentMessage,
15
16
  isStoredPushMessage,
17
+ isTimestampExpired,
16
18
  isTouchOnlyDevice,
17
19
  loadCredentials,
18
20
  loadOrCreateCredentials,
@@ -21,6 +23,7 @@ import {
21
23
  renameConversation,
22
24
  reportError,
23
25
  resolveHandle,
26
+ retentionDays,
24
27
  saveCredentials,
25
28
  sendCanvasEvent,
26
29
  sendMessage,
@@ -41,7 +44,7 @@ import {
41
44
  subscribeUserName,
42
45
  typingTtl,
43
46
  uploadAttachment
44
- } from "./chunk-GTVFIQQN.js";
47
+ } from "./chunk-UYJMSQZX.js";
45
48
  import {
46
49
  actOnCanvas,
47
50
  canvasFromRow,
@@ -479,7 +482,7 @@ var formatMessagePreview = (message) => {
479
482
 
480
483
  // lit/core/conversation-previews.ts
481
484
  var conversationPreviewsCacheKey = "alicebot_conversation_previews_cache";
482
- var previewMessagesLimit = 5;
485
+ var previewMessagesLimit = 25;
483
486
  var maxPriorityConversations = 40;
484
487
  var maxConcurrentFetches = 6;
485
488
  var fetchTimeoutMs = 15e3;
@@ -487,15 +490,69 @@ var typingRefreshIntervalMs = 5e3;
487
490
  var firstOf = (value) => Array.isArray(value) ? value[0] : value;
488
491
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
489
492
  var isEncryptedKeyStr = (value) => typeof value === "string";
493
+ var isValidRecentMessage = (value) => isRecord(value) && typeof value.id === "string" && typeof value.timestamp === "number" && typeof value.authorPublicSignKey === "string";
490
494
  var isValidPreview = (value) => isRecord(value) && typeof value.text === "string" && typeof value.timestamp === "number" && typeof value.authorPublicSignKey === "string" && typeof value.updatedAt === "number";
495
+ var sanitizeCachedPreview = (preview, nowMs) => {
496
+ const recentMessages = Array.isArray(preview.recentMessages) ? preview.recentMessages.filter((item) => isValidRecentMessage(item) && !isTimestampExpired(item.timestamp, nowMs)) : void 0;
497
+ return {
498
+ text: preview.text,
499
+ timestamp: preview.timestamp,
500
+ authorPublicSignKey: preview.authorPublicSignKey,
501
+ updatedAt: preview.updatedAt,
502
+ ...preview.empty ? {
503
+ empty: true
504
+ } : {},
505
+ ...recentMessages ? {
506
+ recentMessages
507
+ } : {},
508
+ ...typeof preview.oldestFetchedTimestamp === "number" ? {
509
+ oldestFetchedTimestamp: preview.oldestFetchedTimestamp
510
+ } : {},
511
+ ...typeof preview.fetchedFullPage === "boolean" ? {
512
+ fetchedFullPage: preview.fetchedFullPage
513
+ } : {}
514
+ };
515
+ };
491
516
  var formatPreviewText = (message) => {
492
517
  if (isSilentMessage(message)) return null;
493
518
  if (message.type === "call") return "\u{1F4DE} Voice call";
494
519
  return formatMessagePreview(message);
495
520
  };
521
+ var isCountableUnreadMessage = (message) => !isSilentMessage(message) && message.type !== "edit";
496
522
  var sortMessagesDesc = (messages) => [
497
523
  ...messages
498
524
  ].sort((a, b) => b.timestamp - a.timestamp);
525
+ var extractRecentMessages = (messages, limit = previewMessagesLimit) => {
526
+ const seen = /* @__PURE__ */ new Set();
527
+ return sortMessagesDesc(messages).filter((m) => {
528
+ if (!isCountableUnreadMessage(m) || seen.has(m.id)) return false;
529
+ seen.add(m.id);
530
+ return true;
531
+ }).slice(0, limit).map((m) => ({
532
+ id: m.id,
533
+ timestamp: m.timestamp,
534
+ authorPublicSignKey: m.publicSignKey
535
+ }));
536
+ };
537
+ var mergeRecentMessages = (existing, incoming, limit = previewMessagesLimit) => {
538
+ const byId = /* @__PURE__ */ new Map();
539
+ (existing ?? []).forEach((m) => byId.set(m.id, m));
540
+ incoming.forEach((m) => byId.set(m.id, m));
541
+ return Array.from(byId.values()).sort((a, b) => b.timestamp - a.timestamp).slice(0, limit);
542
+ };
543
+ var minMessageTimestamp = (messages) => messages.reduce((min, m) => m.timestamp < min ? m.timestamp : min, messages[0]?.timestamp ?? 0);
544
+ var withRecentMetadata = ({ preview, recentMessages, oldestFetchedTimestamp, fetchedFullPage }) => ({
545
+ ...preview,
546
+ ...nonempty(recentMessages) ? {
547
+ recentMessages
548
+ } : {},
549
+ ...oldestFetchedTimestamp !== void 0 && oldestFetchedTimestamp > 0 ? {
550
+ oldestFetchedTimestamp
551
+ } : {},
552
+ ...fetchedFullPage !== void 0 ? {
553
+ fetchedFullPage
554
+ } : {}
555
+ });
499
556
  var extractLatestPreview = (messages, updatedAt) => {
500
557
  const match = sortMessagesDesc(messages).find((m) => formatPreviewText(m) !== null);
501
558
  if (!match) {
@@ -665,7 +722,7 @@ var notifyConversationMessages = (conversationId, messages, updatedAt) => {
665
722
  if (!conversationId) return;
666
723
  liveMessagesListeners.forEach((listener) => listener(conversationId, messages, updatedAt));
667
724
  };
668
- var readCachedConversationPreviews = (publicSignKey) => {
725
+ var readCachedConversationPreviews = (publicSignKey, nowMs = Date.now()) => {
669
726
  try {
670
727
  const raw = globalThis.localStorage?.getItem(conversationPreviewsCacheKey);
671
728
  if (!raw) return {};
@@ -673,7 +730,10 @@ var readCachedConversationPreviews = (publicSignKey) => {
673
730
  if (!isRecord(parsed) || parsed.publicSignKey !== publicSignKey || !isRecord(parsed.previews)) {
674
731
  return {};
675
732
  }
676
- return Object.fromEntries(Object.entries(parsed.previews).filter((entry) => isValidPreview(entry[1])));
733
+ return Object.fromEntries(Object.entries(parsed.previews).filter((entry) => isValidPreview(entry[1]) && (entry[1].empty === true || !isTimestampExpired(entry[1].timestamp, nowMs))).map(([convId, preview]) => [
734
+ convId,
735
+ sanitizeCachedPreview(preview, nowMs)
736
+ ]));
677
737
  } catch {
678
738
  return {};
679
739
  }
@@ -732,7 +792,13 @@ var decryptMessagesList = (conversationId, conversationKey, rawMessages) => {
732
792
  });
733
793
  return Promise.all(rawMessages.map(decryptOne)).then((results) => results.filter((m) => m !== void 0));
734
794
  };
735
- var samePreview = (a, b) => a !== void 0 && a.text === b.text && a.timestamp === b.timestamp && a.authorPublicSignKey === b.authorPublicSignKey && a.updatedAt === b.updatedAt && Boolean(a.empty) === Boolean(b.empty);
795
+ var sameRecentMessages = (a, b) => {
796
+ const listA = a ?? [];
797
+ const listB = b ?? [];
798
+ if (listA.length !== listB.length) return false;
799
+ return listA.every((item, idx) => item.id === listB[idx].id && item.timestamp === listB[idx].timestamp && item.authorPublicSignKey === listB[idx].authorPublicSignKey);
800
+ };
801
+ var samePreview = (a, b) => a !== void 0 && a.text === b.text && a.timestamp === b.timestamp && a.authorPublicSignKey === b.authorPublicSignKey && a.updatedAt === b.updatedAt && Boolean(a.empty) === Boolean(b.empty) && Boolean(a.fetchedFullPage) === Boolean(b.fetchedFullPage) && a.oldestFetchedTimestamp === b.oldestFetchedTimestamp && sameRecentMessages(a.recentMessages, b.recentMessages);
736
802
  var makeCreateConversationPreviewsManager = ({ subscribeKeys, fetchLatestMessages, keyStore = defaultPushKeyStore, readCache = readCachedConversationPreviews, writeCache = writeCachedConversationPreviews, maxConcurrency = maxConcurrentFetches, maxConversations = maxPriorityConversations }) => (credentials, onChange) => {
737
803
  const { publicSignKey, privateEncryptKey } = credentials;
738
804
  const previews = {
@@ -806,7 +872,12 @@ var makeCreateConversationPreviewsManager = ({ subscribeKeys, fetchLatestMessage
806
872
  if (state.cancelled) return;
807
873
  const prev = previews[conversationId];
808
874
  if (prev && prev.updatedAt > current.updatedAt) return;
809
- applyPreview(conversationId, extractLatestPreview(decrypted, current.updatedAt));
875
+ applyPreview(conversationId, withRecentMetadata({
876
+ preview: extractLatestPreview(decrypted, current.updatedAt),
877
+ recentMessages: extractRecentMessages(decrypted),
878
+ oldestFetchedTimestamp: minMessageTimestamp(current.messages),
879
+ fetchedFullPage: current.messages.length >= previewMessagesLimit
880
+ }));
810
881
  });
811
882
  });
812
883
  };
@@ -858,12 +929,16 @@ var makeCreateConversationPreviewsManager = ({ subscribeKeys, fetchLatestMessage
858
929
  if (state.cancelled) return;
859
930
  checkedInSession.add(conversationId);
860
931
  const effectiveUpdatedAt = Math.max(updatedAt ?? 0, knownUpdatedAt.get(conversationId) ?? 0, messages[0]?.timestamp ?? 0, previews[conversationId]?.updatedAt ?? 0);
861
- const nextPreview = extractLatestPreview(messages, effectiveUpdatedAt);
932
+ const basePreview = extractLatestPreview(messages, effectiveUpdatedAt);
862
933
  const existing = previews[conversationId];
863
- if (nextPreview.empty && existing && !existing.empty) return;
864
- if (!nextPreview.empty && existing && !existing.empty && existing.timestamp > nextPreview.timestamp) {
934
+ if (basePreview.empty && existing && !existing.empty) return;
935
+ if (!basePreview.empty && existing && !existing.empty && existing.timestamp > basePreview.timestamp) {
865
936
  return;
866
937
  }
938
+ const nextPreview = withRecentMetadata({
939
+ preview: basePreview,
940
+ recentMessages: extractRecentMessages(messages)
941
+ });
867
942
  applyPreview(conversationId, nextPreview);
868
943
  };
869
944
  liveMessagesListeners.add(onLiveMessages);
@@ -880,10 +955,16 @@ var makeCreateConversationPreviewsManager = ({ subscribeKeys, fetchLatestMessage
880
955
  dbMsg
881
956
  ]).then((decrypted) => {
882
957
  if (state.cancelled || empty(decrypted)) return;
883
- const nextPreview = extractLatestPreview(decrypted, Math.max(message.timestamp, knownUpdatedAt.get(conversationId) ?? 0));
884
- if (nextPreview.empty) return;
958
+ const basePreview = extractLatestPreview(decrypted, Math.max(message.timestamp, knownUpdatedAt.get(conversationId) ?? 0));
959
+ if (basePreview.empty) return;
885
960
  const existing = previews[conversationId];
886
- if (existing && existing.timestamp > nextPreview.timestamp) return;
961
+ if (existing && existing.timestamp > basePreview.timestamp) return;
962
+ const nextPreview = withRecentMetadata({
963
+ preview: basePreview,
964
+ recentMessages: mergeRecentMessages(existing?.recentMessages, extractRecentMessages(decrypted)),
965
+ oldestFetchedTimestamp: existing?.oldestFetchedTimestamp,
966
+ fetchedFullPage: existing?.fetchedFullPage
967
+ });
887
968
  applyPreview(conversationId, nextPreview);
888
969
  });
889
970
  });
@@ -927,6 +1008,160 @@ var createConversationPreviewsManager = makeCreateConversationPreviewsManager({
927
1008
  fetchLatestMessages: queryLatestMessagesOnce
928
1009
  });
929
1010
 
1011
+ // lit/core/unread-state.ts
1012
+ var unreadStateStorageKey = "alicebot_unread_state";
1013
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1014
+ var parseNumberRecord = (value) => isRecord2(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1]))) : {};
1015
+ var parseTrueRecord = (value) => isRecord2(value) ? Object.fromEntries(Object.entries(value).filter((entry) => entry[1] === true).map(([k]) => [
1016
+ k,
1017
+ true
1018
+ ])) : {};
1019
+ var parseStoredUnreadState = (raw, publicSignKey) => {
1020
+ if (!raw) return null;
1021
+ try {
1022
+ const parsed = JSON.parse(raw);
1023
+ if (!isRecord2(parsed) || parsed.publicSignKey !== publicSignKey || typeof parsed.initializedAt !== "number" || !Number.isFinite(parsed.initializedAt)) {
1024
+ return null;
1025
+ }
1026
+ return {
1027
+ publicSignKey,
1028
+ initializedAt: parsed.initializedAt,
1029
+ lastReadAt: parseNumberRecord(parsed.lastReadAt),
1030
+ markedUnread: parseTrueRecord(parsed.markedUnread)
1031
+ };
1032
+ } catch {
1033
+ return null;
1034
+ }
1035
+ };
1036
+ var readUnreadState = (publicSignKey) => {
1037
+ try {
1038
+ return parseStoredUnreadState(globalThis.localStorage?.getItem(unreadStateStorageKey), publicSignKey);
1039
+ } catch {
1040
+ return null;
1041
+ }
1042
+ };
1043
+ var writeUnreadState = (state) => {
1044
+ try {
1045
+ if (!globalThis.localStorage?.getItem("alicebot_credentials")) return;
1046
+ globalThis.localStorage.setItem(unreadStateStorageKey, JSON.stringify(state));
1047
+ } catch {
1048
+ }
1049
+ };
1050
+ var seedUnreadState = (state, publicSignKey, conversations, nowMs = Date.now()) => {
1051
+ if (state && state.publicSignKey === publicSignKey) return state;
1052
+ const lastReadAt = Object.fromEntries(conversations.map((conv) => [
1053
+ conv.id,
1054
+ conv.updatedAt && conv.updatedAt > 0 ? conv.updatedAt : nowMs
1055
+ ]));
1056
+ return {
1057
+ publicSignKey,
1058
+ initializedAt: nowMs,
1059
+ lastReadAt,
1060
+ markedUnread: {}
1061
+ };
1062
+ };
1063
+ var latestKnownConversationTimestamp = (conversation, preview) => Math.max(conversation?.updatedAt ?? 0, preview?.timestamp ?? 0, preview?.updatedAt ?? 0, preview?.recentMessages?.[0]?.timestamp ?? 0);
1064
+ var markConversationRead = (state, conversationId, readUpToTimestamp) => {
1065
+ const prevReadAt = state.lastReadAt[conversationId];
1066
+ const nextReadAt = Math.max(prevReadAt ?? 0, readUpToTimestamp);
1067
+ const wasMarked = Boolean(state.markedUnread[conversationId]);
1068
+ if (prevReadAt === nextReadAt && !wasMarked) return state;
1069
+ const { [conversationId]: _removed, ...restMarked } = state.markedUnread;
1070
+ return {
1071
+ ...state,
1072
+ lastReadAt: {
1073
+ ...state.lastReadAt,
1074
+ [conversationId]: nextReadAt
1075
+ },
1076
+ markedUnread: restMarked
1077
+ };
1078
+ };
1079
+ var computeConversationUnread = ({ conversationId, preview, selfPublicSignKey, state, isActivelyViewing }) => {
1080
+ const manuallyMarked = Boolean(state?.markedUnread[conversationId]);
1081
+ const baseReadAt = state && conversationId in state.lastReadAt ? state.lastReadAt[conversationId] : state?.initializedAt ?? 0;
1082
+ if (isActivelyViewing) {
1083
+ return {
1084
+ isUnread: manuallyMarked,
1085
+ count: 0,
1086
+ overflow: false,
1087
+ markedUnread: manuallyMarked,
1088
+ effectiveReadAt: baseReadAt
1089
+ };
1090
+ }
1091
+ if (!preview || preview.empty) {
1092
+ return {
1093
+ isUnread: manuallyMarked,
1094
+ count: 0,
1095
+ overflow: false,
1096
+ markedUnread: manuallyMarked,
1097
+ effectiveReadAt: baseReadAt
1098
+ };
1099
+ }
1100
+ if (preview.recentMessages && nonempty(preview.recentMessages)) {
1101
+ const latestSelfTs = preview.recentMessages.reduce((max2, msg) => msg.authorPublicSignKey === selfPublicSignKey && msg.timestamp > max2 ? msg.timestamp : max2, 0);
1102
+ const effectiveReadAt = Math.max(baseReadAt, latestSelfTs);
1103
+ const count2 = preview.recentMessages.filter((msg) => msg.authorPublicSignKey !== selfPublicSignKey && msg.timestamp > effectiveReadAt).length;
1104
+ const overflow = count2 > 0 && Boolean(preview.fetchedFullPage) && (preview.oldestFetchedTimestamp ?? 0) > effectiveReadAt;
1105
+ return {
1106
+ isUnread: count2 > 0 || manuallyMarked,
1107
+ count: count2,
1108
+ overflow,
1109
+ markedUnread: manuallyMarked,
1110
+ effectiveReadAt
1111
+ };
1112
+ }
1113
+ if (preview.authorPublicSignKey === selfPublicSignKey) {
1114
+ return {
1115
+ isUnread: manuallyMarked,
1116
+ count: 0,
1117
+ overflow: false,
1118
+ markedUnread: manuallyMarked,
1119
+ effectiveReadAt: Math.max(baseReadAt, preview.timestamp)
1120
+ };
1121
+ }
1122
+ if (preview.timestamp > baseReadAt) {
1123
+ return {
1124
+ isUnread: true,
1125
+ count: 1,
1126
+ overflow: false,
1127
+ markedUnread: manuallyMarked,
1128
+ effectiveReadAt: baseReadAt
1129
+ };
1130
+ }
1131
+ return {
1132
+ isUnread: manuallyMarked,
1133
+ count: 0,
1134
+ overflow: false,
1135
+ markedUnread: manuallyMarked,
1136
+ effectiveReadAt: baseReadAt
1137
+ };
1138
+ };
1139
+ var formatUnreadBadgeLabel = (count2, overflow = false) => {
1140
+ if (count2 <= 0) return "";
1141
+ if (count2 > 99) return "99+";
1142
+ return overflow ? `${count2}+` : String(count2);
1143
+ };
1144
+ var findUnreadDividerInfo = (messages, userId, unreadDividerAfterTimestamp) => {
1145
+ if (unreadDividerAfterTimestamp === void 0) return null;
1146
+ const unread = messages.filter((m) => m.authorId !== userId && m.timestamp > unreadDividerAfterTimestamp);
1147
+ if (!nonempty(unread)) return null;
1148
+ return {
1149
+ firstUnreadMessageId: unread[0].id,
1150
+ count: unread.length
1151
+ };
1152
+ };
1153
+ var subscribeUnreadStateStorage = (publicSignKey, onChange) => {
1154
+ if (typeof globalThis.addEventListener !== "function") return () => {
1155
+ };
1156
+ const handler = (event) => {
1157
+ if (event.key !== unreadStateStorageKey) return;
1158
+ const next = parseStoredUnreadState(event.newValue, publicSignKey);
1159
+ if (next) onChange(next);
1160
+ };
1161
+ globalThis.addEventListener("storage", handler);
1162
+ return () => globalThis.removeEventListener("storage", handler);
1163
+ };
1164
+
930
1165
  // lit/core/voice-call.ts
931
1166
  var defaultStunServers = [
932
1167
  {
@@ -2417,6 +2652,31 @@ var audioBars = Array.from({
2417
2652
  var fileStyle = (isDark) => `display:flex;align-items:center;gap:8px;padding:8px 12px;border-radius:8px;background:${isDark ? "#ffffff15" : "#00000010"};text-decoration:none;color:inherit`;
2418
2653
  var imagePlaceholderStyle = (isDark) => `width:200px;height:150px;border-radius:8px;background:${isDark ? "#ffffff10" : "#00000008"};display:flex;align-items:center;justify-content:center`;
2419
2654
  var videoPlaceholderStyle = (isDark) => `display:flex;align-items:center;justify-content:center;max-width:100%;width:480px;aspect-ratio:16/9;border-radius:8px;margin-top:6px;background:${isDark ? "#1a1a1a" : "#e5e7eb"}`;
2655
+ var expiredAttachmentStyle = (isDark) => `display:flex;align-items:center;gap:8px;padding:10px 12px;border-radius:10px;border:1px dashed ${isDark ? "rgba(255,255,255,0.2)" : "rgba(0,0,0,0.18)"};background:${isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.04)"};color:${isDark ? "#d1d5db" : "#4b5563"};font-size:13px;max-width:280px`;
2656
+ var expiredSubtitleStyle = (isDark) => `font-size:11px;color:${isDark ? "#9ca3af" : "#6b7280"};margin-top:2px`;
2657
+ var expiredAttachmentLabel = (type) => type === "image" ? "Image expired" : type === "video" ? "Video expired" : type === "audio" ? "Voice note expired" : "File expired";
2658
+ var expiredAttachmentHtml = (attachment, isDark) => html5`
2659
+ <div
2660
+ data-testid="expired-attachment"
2661
+ style="${expiredAttachmentStyle(isDark)}"
2662
+ >
2663
+ <span style="opacity:0.75">${faPaperclip}</span>
2664
+ <div style="min-width:0;flex:1">
2665
+ <div style="font-weight:500">${expiredAttachmentLabel(attachment.type)}</div>
2666
+ <div style="${expiredSubtitleStyle(isDark)}">
2667
+ ${attachment.type === "file" ? `${attachment.name} \xB7 ` : ""}Files auto-delete after ${retentionDays} days
2668
+ </div>
2669
+ </div>
2670
+ </div>
2671
+ `;
2672
+ var unavailableAttachmentHtml = (isDark) => html5`
2673
+ <div
2674
+ data-testid="unavailable-attachment"
2675
+ style="${expiredAttachmentStyle(isDark)}"
2676
+ >
2677
+ Unable to load media
2678
+ </div>
2679
+ `;
2420
2680
  var isSafeAttachmentSourceUrl = (rawUrl) => {
2421
2681
  if (!rawUrl || /[\p{Cc}\\]/u.test(rawUrl)) return false;
2422
2682
  try {
@@ -2440,10 +2700,22 @@ var sanitizeDownloadFilename = (name) => {
2440
2700
  const nonEmpty = base || "attachment";
2441
2701
  return /\.(?:html?|xhtml|svg|js|mjs|xml)$/i.test(nonEmpty) ? `${nonEmpty}.bin` : nonEmpty;
2442
2702
  };
2443
- var decryptAttachmentSafely = (decrypt, report) => decrypt().then((url) => isSafeDecryptedMediaUrl(url) ? url : null).catch((error) => {
2703
+ var decryptAttachmentOutcome = (decrypt, report) => decrypt().then((url) => isSafeDecryptedMediaUrl(url) ? {
2704
+ status: "ok",
2705
+ url
2706
+ } : {
2707
+ status: "failed"
2708
+ }).catch((error) => {
2709
+ if (isAttachmentExpiredError(error)) {
2710
+ return {
2711
+ status: "expired"
2712
+ };
2713
+ }
2444
2714
  console.error("Failed to decrypt attachment:", error);
2445
2715
  report("attachment_decrypt_failed");
2446
- return null;
2716
+ return {
2717
+ status: "failed"
2718
+ };
2447
2719
  });
2448
2720
  var ChatAttachment = class extends LitElement4 {
2449
2721
  static properties = {
@@ -2476,6 +2748,12 @@ var ChatAttachment = class extends LitElement4 {
2476
2748
  },
2477
2749
  _loading: {
2478
2750
  state: true
2751
+ },
2752
+ _expired: {
2753
+ state: true
2754
+ },
2755
+ _failed: {
2756
+ state: true
2479
2757
  }
2480
2758
  };
2481
2759
  constructor() {
@@ -2490,18 +2768,26 @@ var ChatAttachment = class extends LitElement4 {
2490
2768
  this.longPressActive = false;
2491
2769
  this._decryptedUrl = null;
2492
2770
  this._loading = false;
2771
+ this._expired = false;
2772
+ this._failed = false;
2493
2773
  }
2494
2774
  createRenderRoot() {
2495
2775
  return this;
2496
2776
  }
2497
2777
  _handleDecrypt = async () => {
2498
- if (!this.onDecrypt || this._decryptedUrl || this.attachment.type === "location" || !isSafeAttachmentSourceUrl(this.attachment.url)) return;
2778
+ if (!this.onDecrypt || this._decryptedUrl || this._expired || this._loading || this.attachment.type === "location" || !isSafeAttachmentSourceUrl(this.attachment.url)) return;
2499
2779
  const { onDecrypt, attachment } = this;
2500
2780
  this._loading = true;
2781
+ this._failed = false;
2501
2782
  try {
2502
- this._decryptedUrl = await decryptAttachmentSafely(() => onDecrypt(attachment.url), reportError);
2503
- } catch (err) {
2504
- console.error("Failed to decrypt attachment", err);
2783
+ const outcome = await decryptAttachmentOutcome(() => onDecrypt(attachment.url), reportError);
2784
+ if (outcome.status === "ok") {
2785
+ this._decryptedUrl = outcome.url;
2786
+ } else if (outcome.status === "expired") {
2787
+ this._expired = true;
2788
+ } else {
2789
+ this._failed = true;
2790
+ }
2505
2791
  } finally {
2506
2792
  this._loading = false;
2507
2793
  }
@@ -2518,7 +2804,9 @@ var ChatAttachment = class extends LitElement4 {
2518
2804
  }
2519
2805
  }
2520
2806
  _maybeAutoDecrypt() {
2521
- if (!this.onDecrypt || this._decryptedUrl) return;
2807
+ if (!this.onDecrypt || this._decryptedUrl || this._expired || this._failed) {
2808
+ return;
2809
+ }
2522
2810
  const { type } = this.attachment;
2523
2811
  if (type === "image" || type === "video") {
2524
2812
  this._handleDecrypt();
@@ -2540,6 +2828,9 @@ var ChatAttachment = class extends LitElement4 {
2540
2828
  ></chat-location-card>
2541
2829
  `;
2542
2830
  }
2831
+ if (this._expired) {
2832
+ return expiredAttachmentHtml(attachment, isDark);
2833
+ }
2543
2834
  if (attachment.type === "audio") {
2544
2835
  return this._decryptedUrl ? html5`
2545
2836
  <chat-audio-player
@@ -2581,7 +2872,7 @@ var ChatAttachment = class extends LitElement4 {
2581
2872
  alt="${attachment.name}"
2582
2873
  style="max-width:100%;border-radius:8px;cursor:pointer;transition:transform .15s,box-shadow .15s${isSelected ? ";transform:scale(1.02);box-shadow:0 0 16px rgba(100,100,255,0.4)" : ""}${this.longPressActive && isSelected ? ";animation:msg-highlight .3s ease forwards" : ""}"
2583
2874
  />
2584
- ` : html5`
2875
+ ` : this._failed ? unavailableAttachmentHtml(isDark) : html5`
2585
2876
  <div style="${imagePlaceholderStyle(isDark)}">${spinnerHtml(isDark)}</div>
2586
2877
  `;
2587
2878
  }
@@ -2592,7 +2883,7 @@ var ChatAttachment = class extends LitElement4 {
2592
2883
  .isDark="${isDark}"
2593
2884
  .name="${attachment.name}"
2594
2885
  ></chat-video-player>
2595
- ` : html5`
2886
+ ` : this._failed ? unavailableAttachmentHtml(isDark) : html5`
2596
2887
  <div style="${videoPlaceholderStyle(isDark)}">${spinnerHtml(isDark)}</div>
2597
2888
  `;
2598
2889
  }
@@ -7451,6 +7742,22 @@ var pruneOptimistic = (messages, optimistic, userId) => {
7451
7742
  const remaining = optimistic.filter((o) => !realTexts.has(o.text));
7452
7743
  return remaining.length === optimistic.length ? optimistic : remaining;
7453
7744
  };
7745
+ var unreadDividerRowStyle = "display:flex;align-items:center;gap:10px;margin:8px 0 4px;width:100%";
7746
+ var unreadDividerLineStyle = (isDark) => `flex:1;height:1px;background:${isDark ? "rgba(255,255,255,0.12)" : "rgba(24,23,21,0.11)"}`;
7747
+ var unreadDividerPillStyle = (isDark) => `font-size:11px;font-weight:600;letter-spacing:0.01em;padding:3px 10px;border-radius:9999px;white-space:nowrap;background:${isDark ? "rgba(125,162,207,0.16)" : "rgba(57,88,127,0.10)"};color:${isDark ? "#9cc0eb" : "#39587f"};border:1px solid ${isDark ? "rgba(125,162,207,0.28)" : "rgba(57,88,127,0.18)"}`;
7748
+ var backUnreadBadgeStyle = (isDark) => `display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;margin-left:-4px;margin-right:4px;border-radius:9999px;border:none;cursor:pointer;font-size:11px;font-weight:700;line-height:1;font-variant-numeric:tabular-nums;background:${isDark ? "#7da2cf" : "#39587f"};color:${isDark ? "#111110" : "#ffffff"};flex-shrink:0`;
7749
+ var renderUnreadMessagesDivider = (count2, isDark) => html9`
7750
+ <div
7751
+ data-testid="unread-messages-divider"
7752
+ role="separator"
7753
+ aria-label="${count2 === 1 ? "1 unread message" : `${count2} unread messages`}"
7754
+ style="${unreadDividerRowStyle}"
7755
+ >
7756
+ <span style="${unreadDividerLineStyle(isDark)}"></span>
7757
+ <span style="${unreadDividerPillStyle(isDark)}">${count2 === 1 ? "1 unread message" : `${count2} unread messages`}</span>
7758
+ <span style="${unreadDividerLineStyle(isDark)}"></span>
7759
+ </div>
7760
+ `;
7454
7761
  var ChatBox = class extends LitElement8 {
7455
7762
  static properties = {
7456
7763
  messages: {
@@ -7576,6 +7883,12 @@ var ChatBox = class extends LitElement8 {
7576
7883
  participants: {
7577
7884
  type: Array
7578
7885
  },
7886
+ unreadDividerAfterTimestamp: {
7887
+ attribute: false
7888
+ },
7889
+ otherUnreadCount: {
7890
+ type: Number
7891
+ },
7579
7892
  _input: {
7580
7893
  state: true
7581
7894
  },
@@ -7657,6 +7970,7 @@ var ChatBox = class extends LitElement8 {
7657
7970
  this.voiceCallState = "idle";
7658
7971
  this.voiceCallDuration = 0;
7659
7972
  this.voiceCallMuted = false;
7973
+ this.otherUnreadCount = 0;
7660
7974
  this.activeSpinners = [];
7661
7975
  this.activeProgress = [];
7662
7976
  this.activeStreams = [];
@@ -8713,6 +9027,7 @@ var ChatBox = class extends LitElement8 {
8713
9027
  const allMsgs = allMessagesFrom(this.messages, this._optimisticMessages, this.userId);
8714
9028
  const timeline = timelineWithTransientEvents(allMsgs, this.activeSpinners, this.activeProgress, this.activeStreams, this.typingUsers);
8715
9029
  const quickReplyEntryId = activeQuickReplyEntryId(timeline, this._isSending);
9030
+ const unreadDivider = findUnreadDividerInfo(allMsgs, this.userId, this.unreadDividerAfterTimestamp);
8716
9031
  const hasContent = !!this._input.trim() || this._pendingFiles.length > 0;
8717
9032
  const showMic = this.enableAudioRecording && !hasContent && !this._isRecording;
8718
9033
  const showStop = this._isRecording && !this._isRecordingLocked;
@@ -8906,6 +9221,17 @@ var ChatBox = class extends LitElement8 {
8906
9221
  >
8907
9222
  ${faArrowLeft}
8908
9223
  </button>
9224
+ ${this.otherUnreadCount > 0 ? html9`
9225
+ <button
9226
+ type="button"
9227
+ data-testid="back-unread-badge"
9228
+ @click="${this.onBack}"
9229
+ aria-label="${this.otherUnreadCount === 1 ? "1 unread chat" : `${this.otherUnreadCount} unread chats`}"
9230
+ style="${backUnreadBadgeStyle(isDark)}"
9231
+ >
9232
+ ${this.otherUnreadCount > 99 ? "99+" : this.otherUnreadCount}
9233
+ </button>
9234
+ ` : nothing4}
8909
9235
  ` : nothing4}
8910
9236
  <div style="flex:1;display:flex;justify-content:center;min-width:0;overflow:hidden">
8911
9237
  ${this._isEditingTitle ? html9`
@@ -9041,7 +9367,7 @@ var ChatBox = class extends LitElement8 {
9041
9367
  }
9042
9368
  if (entry.kind === "stream") return entry.stream.elementId;
9043
9369
  return "typing";
9044
- }, (entry) => this._renderTimelineEntry(entry, customColors, isDark, quickReplyEntryId))} ${this._isSending ? sendingIndicator(sendingStatusText(this._sendingType), customColors?.primary ?? defaultPrimary(isDark), isDark) : nothing4}
9370
+ }, (entry) => this._renderTimelineEntry(entry, customColors, isDark, quickReplyEntryId, unreadDivider))} ${this._isSending ? sendingIndicator(sendingStatusText(this._sendingType), customColors?.primary ?? defaultPrimary(isDark), isDark) : nothing4}
9045
9371
  `}
9046
9372
  </div>
9047
9373
  </div>
@@ -9335,10 +9661,12 @@ var ChatBox = class extends LitElement8 {
9335
9661
  </div>
9336
9662
  `;
9337
9663
  }
9338
- _renderMessageEntry(entry, quickReplyEntryId) {
9664
+ _renderMessageEntry(entry, quickReplyEntryId, unreadDivider) {
9339
9665
  const isDark = this._effectiveDark;
9340
9666
  const { customColors } = this;
9667
+ const showUnreadDivider = unreadDivider !== null && entry.msg.id === unreadDivider.firstUnreadMessageId;
9341
9668
  return html9`
9669
+ ${showUnreadDivider ? renderUnreadMessagesDivider(unreadDivider.count, isDark) : nothing4}
9342
9670
  <chat-message
9343
9671
  .msg="${entry.msg}"
9344
9672
  .prev="${entry.prevMsg}"
@@ -9361,9 +9689,9 @@ var ChatBox = class extends LitElement8 {
9361
9689
  ></chat-message>
9362
9690
  `;
9363
9691
  }
9364
- _renderTimelineEntry(entry, customColors, isDark, quickReplyEntryId) {
9692
+ _renderTimelineEntry(entry, customColors, isDark, quickReplyEntryId, unreadDivider) {
9365
9693
  if (entry.kind === "message") {
9366
- return this._renderMessageEntry(entry, quickReplyEntryId);
9694
+ return this._renderMessageEntry(entry, quickReplyEntryId, unreadDivider);
9367
9695
  }
9368
9696
  if (entry.kind === "spinner") {
9369
9697
  return renderSpinnerIndicator(entry.spinner, isDark, customColors?.hideNames, this.isGroupChat, customColors?.text);
@@ -9611,10 +9939,13 @@ var sidebarInlineRenameInputStyle = (isDark) => `width:100%;box-sizing:border-bo
9611
9939
  var sidebarRenameButtonStyle = (isDark, customColors) => `background:transparent;border:none;cursor:pointer;padding:6px;border-radius:6px;color:${customColors?.text ?? (isDark ? "#9ca3af" : "#6b7280")};display:flex;align-items:center;justify-content:center;font-size:12px;transition:opacity 0.15s,background 0.15s;flex-shrink:0`;
9612
9940
  var sidebarItemBodyStyle = "flex:1;min-width:0;display:flex;flex-direction:column;gap:2px";
9613
9941
  var sidebarItemTopRowStyle = "display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0;min-height:18px";
9614
- var sidebarItemTimeStyle = (isDark) => `font-size:11px;line-height:18px;flex-shrink:0;color:${isDark ? "#78736a" : "#8c867c"}`;
9615
- var sidebarItemPreviewRowStyle = "font-size:12px;line-height:15px;min-height:15px;height:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis";
9616
- var sidebarItemPreviewStyle = (isDark) => `${sidebarItemPreviewRowStyle};color:${isDark ? "#9c968c" : "#66625b"}`;
9942
+ var sidebarItemTimeStyle = (isDark, isUnread = false) => `font-size:11px;line-height:18px;flex-shrink:0;font-variant-numeric:tabular-nums;font-weight:${isUnread ? "600" : "400"};color:${isUnread ? isDark ? "#7da2cf" : "#39587f" : isDark ? "#78736a" : "#8c867c"}`;
9943
+ var sidebarItemBottomRowStyle = "display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0";
9944
+ var sidebarItemPreviewRowStyle = "font-size:12px;line-height:15px;min-height:15px;height:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0";
9945
+ var sidebarItemPreviewStyle = (isDark, isUnread = false) => `${sidebarItemPreviewRowStyle};font-weight:${isUnread ? "500" : "400"};color:${isUnread ? isDark ? "#e7e5df" : "#2c2a26" : isDark ? "#9c968c" : "#66625b"}`;
9617
9946
  var sidebarItemTypingStyle = (isDark) => `${sidebarItemPreviewRowStyle};font-weight:500;color:${isDark ? "#7da2cf" : "#39587f"}`;
9947
+ var sidebarUnreadBadgeStyle = (isDark) => `display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:9999px;font-size:11px;font-weight:700;line-height:1;font-variant-numeric:tabular-nums;flex-shrink:0;background:${isDark ? "#7da2cf" : "#39587f"};color:${isDark ? "#111110" : "#ffffff"}`;
9948
+ var sidebarUnreadDotStyle = (isDark) => `display:inline-block;width:9px;height:9px;border-radius:9999px;flex-shrink:0;background:${isDark ? "#7da2cf" : "#39587f"}`;
9618
9949
  var sidebarHoverStyles = `
9619
9950
  .alice-sidebar-rename-btn { opacity: 0.6; }
9620
9951
  .alice-sidebar-desktop .alice-sidebar-item .alice-sidebar-rename-btn { opacity: 0; pointer-events: none; }
@@ -9748,7 +10079,7 @@ var sidebarHeaderStyle = (isDark) => `padding:12px 14px;border-bottom:1px solid
9748
10079
  var sidebarSearchInputStyle = (isDark, customColors) => `width:100%;padding:8px 12px;border-radius:8px;font-size:13px;outline:none;border:1px solid ${inputBorderColor(isDark, customColors)};background:${customColors?.inputBackground ?? defaultInputBackground(isDark)};color:${customColors?.inputBackground ? inputTextColor(isDark, customColors) : customColors?.text ?? (isDark ? "#f4f4f4" : "#111827")};box-sizing:border-box`;
9749
10080
  var sidebarListStyle = (scrollbarColor) => `flex:1;min-height:0;overflow-y:auto;padding:6px 8px;display:flex;flex-direction:column;gap:2px;${scrollbarColor ? `scrollbar-color:${scrollbarColor};` : ""}`;
9750
10081
  var sidebarItemStyle = (isSelected, isDark, customColors) => `display:flex;align-items:center;gap:10px;padding:8px 10px;width:100%;text-align:left;background:${isSelected ? isDark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)" : "transparent"};border:none;border-left:3px solid ${isSelected ? customColors?.primary ?? defaultPrimary(isDark) : "transparent"};border-radius:8px;cursor:pointer;transition:background 0.15s;box-sizing:border-box;outline:none`;
9751
- var sidebarItemTitleStyle = (isDark, isSelected, customColors) => `font-size:13px;line-height:18px;font-weight:${isSelected ? "600" : "500"};color:${customColors?.text ?? (isDark ? "#f4f4f4" : "#111827")};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0`;
10082
+ var sidebarItemTitleStyle = (isDark, isSelected, customColors, isUnread = false) => `font-size:13px;line-height:18px;font-weight:${isSelected || isUnread ? "600" : "500"};color:${customColors?.text ?? (isDark ? "#f4f4f4" : "#111827")};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0`;
9752
10083
  var mobileBackButtonStyle = (isDark, customColors) => `position:absolute;top:10px;left:10px;z-index:90;display:flex;align-items:center;gap:6px;padding:6px 12px;border-radius:18px;background:${isDark ? "rgba(30,30,30,0.9)" : "rgba(255,255,255,0.9)"};color:${customColors?.text ?? (isDark ? "#f4f4f4" : "#111827")};border:1px solid ${isDark ? "#444" : "#e5e7eb"};box-shadow:0 2px 8px rgba(0,0,0,0.15);cursor:pointer;font-size:12px;font-weight:600;backdrop-filter:blur(4px)`;
9753
10084
  var mobileFullListStyle = (isDark, customColors) => `display:flex;flex-direction:column;width:100%;height:100%;min-height:0;background:${customColors?.background ?? (isDark ? "#111110" : "#f6f4ee")};font-family:sans-serif;box-sizing:border-box`;
9754
10085
  var mainChatContainerStyle = "display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden;position:relative";
@@ -9899,6 +10230,12 @@ var ConnectedChat = class extends LitElement10 {
9899
10230
  },
9900
10231
  onConversationChange: {
9901
10232
  attribute: false
10233
+ },
10234
+ unreadDividerAfterTimestamp: {
10235
+ attribute: false
10236
+ },
10237
+ otherUnreadCount: {
10238
+ type: Number
9902
10239
  }
9903
10240
  };
9904
10241
  constructor() {
@@ -9911,6 +10248,7 @@ var ConnectedChat = class extends LitElement10 {
9911
10248
  this.enableChatSwitching = false;
9912
10249
  this.disableAutoFocus = false;
9913
10250
  this.isDark = false;
10251
+ this.otherUnreadCount = 0;
9914
10252
  }
9915
10253
  _activeConversationId = "";
9916
10254
  _subscribedConversationId = "";
@@ -9919,6 +10257,9 @@ var ConnectedChat = class extends LitElement10 {
9919
10257
  _conversations = null;
9920
10258
  _conversationPreviews = {};
9921
10259
  _typingByConversation = {};
10260
+ _unreadState = null;
10261
+ _unreadStorageUnsub = null;
10262
+ _internalUnreadDividerAfterTimestamp = void 0;
9922
10263
  _searchQuery = "";
9923
10264
  _nameCache = /* @__PURE__ */ new Map();
9924
10265
  _nameUnsubs = /* @__PURE__ */ new Map();
@@ -9983,6 +10324,8 @@ var ConnectedChat = class extends LitElement10 {
9983
10324
  this._activeConversationId = this.conversationId;
9984
10325
  this.addEventListener("click", this._handleClick);
9985
10326
  globalThis.addEventListener("keydown", this._handleGlobalKeydown);
10327
+ globalThis.addEventListener("focus", this._handleVisibilityOrFocus);
10328
+ globalThis.document?.addEventListener("visibilitychange", this._handleVisibilityOrFocus);
9986
10329
  if (this.enableChatSwitching) {
9987
10330
  this._responsiveUnsub = subscribeIsMobile((m) => {
9988
10331
  this._isMobile = m;
@@ -9995,6 +10338,8 @@ var ConnectedChat = class extends LitElement10 {
9995
10338
  super.disconnectedCallback();
9996
10339
  this.removeEventListener("click", this._handleClick);
9997
10340
  globalThis.removeEventListener("keydown", this._handleGlobalKeydown);
10341
+ globalThis.removeEventListener("focus", this._handleVisibilityOrFocus);
10342
+ globalThis.document?.removeEventListener("visibilitychange", this._handleVisibilityOrFocus);
9998
10343
  this._teardown();
9999
10344
  }
10000
10345
  get _effectiveDark() {
@@ -10085,6 +10430,10 @@ var ConnectedChat = class extends LitElement10 {
10085
10430
  this._previewsManager = null;
10086
10431
  this._allTypingUnsub?.();
10087
10432
  this._allTypingUnsub = null;
10433
+ this._unreadStorageUnsub?.();
10434
+ this._unreadStorageUnsub = null;
10435
+ this._unreadState = null;
10436
+ this._internalUnreadDividerAfterTimestamp = void 0;
10088
10437
  this._conversationPreviews = {};
10089
10438
  this._typingByConversation = {};
10090
10439
  this._chatListCredentials = null;
@@ -10111,6 +10460,31 @@ var ConnectedChat = class extends LitElement10 {
10111
10460
  }
10112
10461
  this._setupConversationSubscriptions();
10113
10462
  }
10463
+ _isConversationVisiblyOpen(conversationId) {
10464
+ if (!this.enableChatSwitching) return false;
10465
+ if (this._isMobile && this._mobileShowList) return false;
10466
+ if (globalThis.document?.visibilityState === "hidden") return false;
10467
+ const currentId = this._activeConversationId || this.conversationId;
10468
+ return currentId === conversationId;
10469
+ }
10470
+ _markConversationReadIfNeeded(conversationId) {
10471
+ if (!this._unreadState || !conversationId) return;
10472
+ const conv = this._conversations?.find((c) => c.id === conversationId);
10473
+ const preview = this._conversationPreviews[conversationId];
10474
+ const readTs = latestKnownConversationTimestamp(conv, preview);
10475
+ const next = markConversationRead(this._unreadState, conversationId, readTs);
10476
+ if (next === this._unreadState) return;
10477
+ this._unreadState = next;
10478
+ writeUnreadState(next);
10479
+ }
10480
+ _handleVisibilityOrFocus = () => {
10481
+ if (globalThis.document?.visibilityState === "hidden") return;
10482
+ const currentId = this._activeConversationId || this.conversationId;
10483
+ if (currentId && this._isConversationVisiblyOpen(currentId)) {
10484
+ this._markConversationReadIfNeeded(currentId);
10485
+ this.requestUpdate();
10486
+ }
10487
+ };
10114
10488
  _setupChatListSubscriptions() {
10115
10489
  if (!this.credentials) return;
10116
10490
  if (this._conversationsUnsub && sameCredentials(this._chatListCredentials, this.credentials)) {
@@ -10118,8 +10492,18 @@ var ConnectedChat = class extends LitElement10 {
10118
10492
  }
10119
10493
  this._teardownChatListSubscriptions();
10120
10494
  this._chatListCredentials = this.credentials;
10495
+ const { publicSignKey } = this.credentials;
10496
+ this._unreadState = readUnreadState(publicSignKey);
10497
+ this._unreadStorageUnsub = subscribeUnreadStateStorage(publicSignKey, (next) => {
10498
+ this._unreadState = next;
10499
+ this.requestUpdate();
10500
+ });
10121
10501
  this._previewsManager = createConversationPreviewsManager(this.credentials, (map3) => {
10122
10502
  this._conversationPreviews = map3;
10503
+ const currentId = this._activeConversationId || this.conversationId;
10504
+ if (currentId && this._isConversationVisiblyOpen(currentId)) {
10505
+ this._markConversationReadIfNeeded(currentId);
10506
+ }
10123
10507
  this.requestUpdate();
10124
10508
  });
10125
10509
  this._allTypingUnsub = subscribeAllTypingStates(this.credentials, (map3) => {
@@ -10128,7 +10512,13 @@ var ConnectedChat = class extends LitElement10 {
10128
10512
  });
10129
10513
  this._conversationsUnsub = subscribeConversations(this.credentials, (convs) => {
10130
10514
  this._conversations = convs;
10131
- if (convs) this._previewsManager?.setConversations(convs);
10515
+ if (convs) {
10516
+ if (!this._unreadState) {
10517
+ this._unreadState = seedUnreadState(null, publicSignKey, convs);
10518
+ writeUnreadState(this._unreadState);
10519
+ }
10520
+ this._previewsManager?.setConversations(convs);
10521
+ }
10132
10522
  convs?.forEach((conv) => {
10133
10523
  const other = conv.participants.find((p) => p.publicSignKey !== this.credentials.publicSignKey);
10134
10524
  if (other && !conv.title && !other.name) {
@@ -10137,6 +10527,10 @@ var ConnectedChat = class extends LitElement10 {
10137
10527
  });
10138
10528
  this._identityDetails = mergeIdentityDetails(this._identityDetails, extractInlineIdentityDetails(this._participants, convs));
10139
10529
  this._resubscribeIdentities();
10530
+ const currentId = this._activeConversationId || this.conversationId;
10531
+ if (currentId && this._isConversationVisiblyOpen(currentId)) {
10532
+ this._markConversationReadIfNeeded(currentId);
10533
+ }
10140
10534
  if (!this._activeConversationId && convs && convs.length > 0 && this.enableChatSwitching) {
10141
10535
  this._selectConversation(convs[0].id);
10142
10536
  }
@@ -10153,6 +10547,19 @@ var ConnectedChat = class extends LitElement10 {
10153
10547
  }
10154
10548
  _selectConversation(id) {
10155
10549
  if (this._activeConversationId === id && !this._mobileShowList) return;
10550
+ if (this.enableChatSwitching && this.credentials && this._unreadState) {
10551
+ const status = computeConversationUnread({
10552
+ conversationId: id,
10553
+ preview: this._conversationPreviews[id],
10554
+ selfPublicSignKey: this.credentials.publicSignKey,
10555
+ state: this._unreadState,
10556
+ isActivelyViewing: false
10557
+ });
10558
+ this._internalUnreadDividerAfterTimestamp = status.count > 0 ? status.effectiveReadAt : void 0;
10559
+ this._markConversationReadIfNeeded(id);
10560
+ } else {
10561
+ this._internalUnreadDividerAfterTimestamp = void 0;
10562
+ }
10156
10563
  this._activeConversationId = id;
10157
10564
  this._mobileShowList = false;
10158
10565
  if (this._subscribedConversationId !== id || !sameCredentials(this._subscribedCredentials, this.credentials)) {
@@ -10326,6 +10733,8 @@ var ConnectedChat = class extends LitElement10 {
10326
10733
  _handleSend = (text, replyTo) => {
10327
10734
  const targetId = this._activeConversationId || this.conversationId;
10328
10735
  if (!this.credentials || !targetId) return;
10736
+ this._internalUnreadDividerAfterTimestamp = void 0;
10737
+ this._markConversationReadIfNeeded(targetId);
10329
10738
  this.dispatchEvent(new CustomEvent("message-sent", {
10330
10739
  bubbles: true,
10331
10740
  composed: true
@@ -10860,6 +11269,14 @@ var ConnectedChat = class extends LitElement10 {
10860
11269
  const baseColor = avatarColor(otherKey, isDark);
10861
11270
  const avatar = otherParticipant ? resolveParticipantAvatar(otherParticipant, this._identityDetails) : void 0;
10862
11271
  const preview = this._conversationPreviews[conv.id];
11272
+ const unread = computeConversationUnread({
11273
+ conversationId: conv.id,
11274
+ preview,
11275
+ selfPublicSignKey: myKey,
11276
+ state: this._unreadState,
11277
+ isActivelyViewing: this._isConversationVisiblyOpen(conv.id)
11278
+ });
11279
+ const unreadLabel = formatUnreadBadgeLabel(unread.count, unread.overflow);
10863
11280
  const typingNames = activeTypingNamesForConversation(this._typingByConversation[conv.id], preview);
10864
11281
  const typingLabel2 = formatConversationTypingLabel(typingNames, conv.participants.length > 2);
10865
11282
  const previewLine = preview ? formatConversationPreviewLine({
@@ -10872,6 +11289,7 @@ var ConnectedChat = class extends LitElement10 {
10872
11289
  return html11`
10873
11290
  <div
10874
11291
  class="alice-sidebar-item"
11292
+ data-conversation-id="${conv.id}"
10875
11293
  style="${sidebarItemStyle(isSelected, isDark, this.customColors)}"
10876
11294
  @click="${() => this._selectConversation(conv.id)}"
10877
11295
  >
@@ -10897,18 +11315,34 @@ var ConnectedChat = class extends LitElement10 {
10897
11315
  @blur="${this._commitSidebarRename}"
10898
11316
  />
10899
11317
  ` : html11`
10900
- <div style="${sidebarItemTitleStyle(isDark, isSelected, this.customColors)}">
11318
+ <div style="${sidebarItemTitleStyle(isDark, isSelected, this.customColors, unread.isUnread)}">
10901
11319
  ${displayName}
10902
11320
  </div>
10903
11321
  `} ${timeLabel && this._editingSidebarConvId !== conv.id ? html11`
10904
- <span style="${sidebarItemTimeStyle(isDark)}">${timeLabel}</span>
11322
+ <span style="${sidebarItemTimeStyle(isDark, unread.isUnread)}">${timeLabel}</span>
10905
11323
  ` : nothing6}
10906
11324
  </div>
10907
- <div
10908
- data-testid="conversation-preview-slot"
10909
- style="${typingLabel2 ? sidebarItemTypingStyle(isDark) : sidebarItemPreviewStyle(isDark)}"
10910
- >
10911
- ${typingLabel2 || previewLine || nothing6}
11325
+ <div style="${sidebarItemBottomRowStyle}">
11326
+ <div
11327
+ data-testid="conversation-preview-slot"
11328
+ style="${typingLabel2 ? sidebarItemTypingStyle(isDark) : sidebarItemPreviewStyle(isDark, unread.isUnread)}"
11329
+ >
11330
+ ${typingLabel2 || previewLine || nothing6}
11331
+ </div>
11332
+ ${unread.isUnread ? unreadLabel ? html11`
11333
+ <span
11334
+ data-testid="conversation-unread-badge"
11335
+ aria-label="${unread.count === 1 ? "1 unread message" : `${unreadLabel} unread messages`}"
11336
+ style="${sidebarUnreadBadgeStyle(isDark)}"
11337
+ >${unreadLabel}</span>
11338
+ ` : html11`
11339
+ <span
11340
+ data-testid="conversation-unread-badge"
11341
+ data-unread-dot
11342
+ aria-label="Unread"
11343
+ style="${sidebarUnreadDotStyle(isDark)}"
11344
+ ></span>
11345
+ ` : nothing6}
10912
11346
  </div>
10913
11347
  </div>
10914
11348
  <button
@@ -10992,6 +11426,8 @@ var ConnectedChat = class extends LitElement10 {
10992
11426
  .isDark="${isDark}"
10993
11427
  .emptyMessage="${this.emptyMessage}"
10994
11428
  .suggestedMessages="${this.suggestedMessages}"
11429
+ .unreadDividerAfterTimestamp="${this.unreadDividerAfterTimestamp ?? this._internalUnreadDividerAfterTimestamp}"
11430
+ .otherUnreadCount="${this.otherUnreadCount}"
10995
11431
  @new-thread="${this._handleNewThread}"
10996
11432
  @rename-conversation="${this._handleRenameConversation}"
10997
11433
  @show-participants="${this._handleShowParticipants}"