@rtsee/messenger 0.0.140 → 0.0.141

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.
@@ -7,6 +7,8 @@ import { blobToDataUrl, RTSeeImageCropper } from "@rtsee/utilities-ui";
7
7
  const DEFAULT_CHATS_FETCH_STEP = 20;
8
8
  const READ_TOGETHER_AUTO_CALL_STORAGE_KEY = "rtsee-read-together-auto-video-call";
9
9
  const READ_TOGETHER_AUTO_CALL_TTL_MS = 30 * 60 * 1000;
10
+ const PENDING_INVITE_TOKEN_STORAGE_KEY = "rtsee-pending-invite-token";
11
+ const PENDING_INVITE_TOKEN_TTL_MS = 30 * 60 * 1000;
10
12
  export class RTSeeMessenger extends RTSeeCore {
11
13
  chats = [];
12
14
  standaloneChats = [];
@@ -28,13 +30,17 @@ export class RTSeeMessenger extends RTSeeCore {
28
30
  manageChatInfo = null;
29
31
  chatInfo = null;
30
32
  inviteUserOpened = false;
33
+ headerAddDropdownOpen = false;
31
34
  autoVideoCallOnInviteAccept = false;
32
35
  preserveInviteOnRouteEnter = false;
33
36
  chatsLoadedOnce = false;
34
37
  openInviteWhenChatsEmpty = false;
38
+ toggleAddDropdownWhenChatsExist = false;
35
39
  pendingInviteToken = null;
36
40
  pendingInviteInfo = null;
37
41
  inviteJoinInProgress = false;
42
+ suppressMessengerNavigation = false;
43
+ lastContentRoute = null;
38
44
  isPaymentPageOpened = false;
39
45
  isPaymentValidationPageOpened = false;
40
46
  isManagePlanPageOpened = false;
@@ -51,8 +57,16 @@ export class RTSeeMessenger extends RTSeeCore {
51
57
  draftWorkflowDisposers = new Map();
52
58
  trackedCreatedChatIds = new Set();
53
59
  pendingRemoteChats = new Map();
60
+ autoJoinedInviteRooms = new Set();
61
+ pendingInviteInfoRequest = null;
54
62
  constructor(options) {
55
63
  super(options);
64
+ this.captureCurrentContentRoute();
65
+ const initialInviteToken = this.checkForChatInviteToken();
66
+ if (initialInviteToken) {
67
+ this.pendingInviteToken = initialInviteToken;
68
+ this.persistPendingInviteToken(initialInviteToken);
69
+ }
56
70
  this.search = new RTSeeMessengerSearch({
57
71
  signalingClient: this.signalingClient,
58
72
  });
@@ -212,6 +226,7 @@ export class RTSeeMessenger extends RTSeeCore {
212
226
  return;
213
227
  }
214
228
  this.closeInviteUser();
229
+ this.closeHeaderAddDropdown();
215
230
  this.manageChatInfo = new RTSeeManageChatInfo({
216
231
  chat: chat ? chat : undefined,
217
232
  companionUrl: this.companionUrl,
@@ -247,9 +262,12 @@ export class RTSeeMessenger extends RTSeeCore {
247
262
  this.manageChatInfo = null;
248
263
  }
249
264
  openInviteUser() {
265
+ this.captureCurrentContentRoute();
250
266
  this.preserveInviteOnRouteEnter = false;
267
+ this.closeHeaderAddDropdown();
251
268
  this.collapseInfo();
252
269
  this.closeManageChatInfo();
270
+ this.armAutoVideoCallOnInviteAccept();
253
271
  this.inviteUserOpened = true;
254
272
  }
255
273
  closeInviteUser() {
@@ -257,27 +275,165 @@ export class RTSeeMessenger extends RTSeeCore {
257
275
  this.preserveInviteOnRouteEnter = false;
258
276
  this.openInviteWhenChatsEmpty = false;
259
277
  }
278
+ toggleHeaderAddDropdown(force) {
279
+ this.headerAddDropdownOpen =
280
+ typeof force === "boolean" ? force : !this.headerAddDropdownOpen;
281
+ return this.headerAddDropdownOpen;
282
+ }
283
+ closeHeaderAddDropdown() {
284
+ this.headerAddDropdownOpen = false;
285
+ }
286
+ extractContentRoute(rawUrl) {
287
+ let candidate = rawUrl;
288
+ if (!candidate) {
289
+ if (typeof window === "undefined" || !window.location) {
290
+ return null;
291
+ }
292
+ candidate = `${window.location.pathname || "/"}${window.location.search || ""}`;
293
+ }
294
+ try {
295
+ const parsed = new URL(candidate, "https://rtsee.local");
296
+ const pathname = parsed.pathname || "/";
297
+ const lowerPath = pathname.toLowerCase();
298
+ const nonContentPrefixes = [
299
+ "/messenger",
300
+ "/auth",
301
+ "/profile",
302
+ "/events-dashboard",
303
+ "/dashboard",
304
+ ];
305
+ if (nonContentPrefixes.some((prefix) => lowerPath === prefix || lowerPath.startsWith(`${prefix}/`))) {
306
+ return null;
307
+ }
308
+ parsed.searchParams.delete(JOIN_CHAT_TOKEN_URL_PARAM);
309
+ parsed.searchParams.delete("eraseAnonimousIdentity");
310
+ parsed.searchParams.delete("eraseAnonymousIdentity");
311
+ const query = parsed.searchParams.toString();
312
+ return query ? `${pathname}?${query}` : pathname;
313
+ }
314
+ catch {
315
+ return null;
316
+ }
317
+ }
318
+ captureCurrentContentRoute(rawUrl) {
319
+ const contentRoute = this.extractContentRoute(rawUrl);
320
+ if (contentRoute) {
321
+ this.lastContentRoute = contentRoute;
322
+ }
323
+ }
324
+ getCurrentInviteRedirectPath() {
325
+ const liveRoute = this.extractContentRoute();
326
+ const chosen = liveRoute || this.lastContentRoute;
327
+ if (!chosen || chosen === "/") {
328
+ return undefined;
329
+ }
330
+ return chosen;
331
+ }
332
+ getCurrentBrowserOrigin() {
333
+ if (typeof window === "undefined" || !window.location?.origin) {
334
+ return undefined;
335
+ }
336
+ const rawOrigin = window.location.origin.trim();
337
+ if (!/^https?:\/\//i.test(rawOrigin)) {
338
+ return undefined;
339
+ }
340
+ // Canonicalize www.dnipio.com -> dnipio.com to prevent 301 redirects that can drop query params
341
+ return rawOrigin
342
+ .replace(/^http:\/\/(www\.)?dnipio\.com$/i, "https://dnipio.com")
343
+ .replace(/^https:\/\/www\.dnipio\.com$/i, "https://dnipio.com")
344
+ .replace(/\/+$/, "");
345
+ }
346
+ applyCurrentRouteToInvitationLink(invitationLink, explicitRedirectPath, explicitOrigin) {
347
+ if (!invitationLink) {
348
+ return invitationLink;
349
+ }
350
+ const redirectPath = explicitRedirectPath ?? this.getCurrentInviteRedirectPath();
351
+ const preferredOrigin = explicitOrigin ?? this.getCurrentBrowserOrigin();
352
+ try {
353
+ const linkUrl = new URL(invitationLink);
354
+ if (preferredOrigin) {
355
+ const parsedOrigin = new URL(preferredOrigin);
356
+ linkUrl.protocol = parsedOrigin.protocol;
357
+ linkUrl.host = parsedOrigin.host;
358
+ }
359
+ if (redirectPath && redirectPath !== "/") {
360
+ const routeUrl = new URL(redirectPath, linkUrl.origin);
361
+ const targetPathname = (routeUrl.pathname || "/").replace(/\/+$/, "") || "/";
362
+ if (targetPathname !== "/") {
363
+ const basePath = linkUrl.pathname.replace(/\/+$/, "");
364
+ if (!basePath) {
365
+ linkUrl.pathname = targetPathname;
366
+ }
367
+ else if (!basePath.endsWith(targetPathname)) {
368
+ linkUrl.pathname = `${basePath}${targetPathname.startsWith("/") ? targetPathname : `/${targetPathname}`}`;
369
+ }
370
+ else {
371
+ linkUrl.pathname = basePath;
372
+ }
373
+ }
374
+ routeUrl.searchParams.forEach((value, key) => {
375
+ if (key !== JOIN_CHAT_TOKEN_URL_PARAM &&
376
+ !linkUrl.searchParams.has(key)) {
377
+ linkUrl.searchParams.set(key, value);
378
+ }
379
+ });
380
+ }
381
+ return linkUrl.toString();
382
+ }
383
+ catch {
384
+ return invitationLink;
385
+ }
386
+ }
387
+ async getChatInvitationLink(chatId) {
388
+ this.armAutoVideoCallOnInviteAccept();
389
+ const redirectPath = this.getCurrentInviteRedirectPath();
390
+ const origin = this.getCurrentBrowserOrigin();
391
+ const result = await this.remoteActions.getChatInvitationLink.send({
392
+ chatId,
393
+ redirectPath,
394
+ origin,
395
+ });
396
+ if (result?.invitationLink) {
397
+ result.invitationLink = this.applyCurrentRouteToInvitationLink(result.invitationLink, redirectPath, origin);
398
+ }
399
+ return result;
400
+ }
260
401
  /**
261
402
  * Prepares the Messenger screen for the "Read Together on Video Call" flow:
262
403
  * - Arms automatic video-call initiation once the invited user accepts.
263
404
  * - Opens `.rts-messenger-header-invite-user-container` when the current user has no chats.
405
+ * - Optionally toggles `.rts-messenger-header-add-button` dropdown when existing chats are present.
264
406
  * - Notifies host containers (`NAVIGATE_TO_MESSENGER`) to focus the Messenger view.
265
407
  */
266
- prepareReadTogetherVideoCall() {
408
+ prepareReadTogetherVideoCall(options) {
409
+ this.captureCurrentContentRoute();
267
410
  this.folded = false;
268
411
  this.closeManageChatInfo();
269
412
  this.closeProfile();
270
413
  this.closeChatInfo();
271
414
  this.armAutoVideoCallOnInviteAccept();
272
415
  if (!this.chats.length) {
416
+ this.headerAddDropdownOpen = false;
273
417
  this.openInviteWhenChatsEmpty = !this.chatsLoadedOnce;
418
+ this.toggleAddDropdownWhenChatsExist =
419
+ Boolean(options?.toggleAddMenuWhenChatsExist) && !this.chatsLoadedOnce;
274
420
  this.preserveInviteOnRouteEnter = true;
275
421
  this.inviteUserOpened = true;
276
422
  }
277
423
  else {
278
424
  this.openInviteWhenChatsEmpty = false;
279
- this.preserveInviteOnRouteEnter = false;
425
+ this.toggleAddDropdownWhenChatsExist = false;
280
426
  this.inviteUserOpened = false;
427
+ if (options?.toggleAddMenuWhenChatsExist) {
428
+ if (this.openedChat) {
429
+ this.closeChat();
430
+ }
431
+ const isOpen = this.toggleHeaderAddDropdown();
432
+ this.preserveInviteOnRouteEnter = isOpen;
433
+ }
434
+ else {
435
+ this.preserveInviteOnRouteEnter = false;
436
+ }
281
437
  }
282
438
  this.emit(MessengerClientEvents.NAVIGATE_TO_MESSENGER);
283
439
  }
@@ -401,6 +557,7 @@ export class RTSeeMessenger extends RTSeeCore {
401
557
  this.preserveInviteOnRouteEnter = false;
402
558
  return;
403
559
  }
560
+ this.closeHeaderAddDropdown();
404
561
  this.closeInviteUser();
405
562
  }
406
563
  closeProfile() {
@@ -423,6 +580,7 @@ export class RTSeeMessenger extends RTSeeCore {
423
580
  remoteActions: this.remoteActions,
424
581
  myClientId: this.clientId,
425
582
  evCollector: this.evCollector,
583
+ getInvitationLink: (targetChatId) => this.getChatInvitationLink(targetChatId || this.openedChat?.id),
426
584
  });
427
585
  this.chatInfo.on("edit-chat-info", () => {
428
586
  this.openManageChatInfo(this.openedChat);
@@ -469,6 +627,9 @@ export class RTSeeMessenger extends RTSeeCore {
469
627
  this.folded = state;
470
628
  }
471
629
  attachWindowEvents() {
630
+ if (typeof window === "undefined") {
631
+ return;
632
+ }
472
633
  window.addEventListener("focus", () => {
473
634
  this.onFocus();
474
635
  });
@@ -525,31 +686,154 @@ export class RTSeeMessenger extends RTSeeCore {
525
686
  void this.prepareChatInvitation(chatInviteToken);
526
687
  }
527
688
  }
528
- checkForChatInviteToken() {
689
+ persistPendingInviteToken(token) {
690
+ if (!token || typeof sessionStorage === "undefined") {
691
+ return;
692
+ }
529
693
  try {
530
- const params = new URLSearchParams(window.location.search);
694
+ sessionStorage.setItem(PENDING_INVITE_TOKEN_STORAGE_KEY, JSON.stringify({ token, ts: Date.now() }));
695
+ }
696
+ catch {
697
+ // Ignore storage restrictions
698
+ }
699
+ }
700
+ readPersistedInviteToken() {
701
+ if (typeof sessionStorage === "undefined") {
702
+ return null;
703
+ }
704
+ try {
705
+ const raw = sessionStorage.getItem(PENDING_INVITE_TOKEN_STORAGE_KEY);
706
+ if (!raw) {
707
+ return null;
708
+ }
709
+ if (raw.startsWith("{")) {
710
+ const parsed = JSON.parse(raw);
711
+ if (parsed?.token &&
712
+ (!parsed.ts || Date.now() - parsed.ts < PENDING_INVITE_TOKEN_TTL_MS)) {
713
+ return parsed.token;
714
+ }
715
+ sessionStorage.removeItem(PENDING_INVITE_TOKEN_STORAGE_KEY);
716
+ return null;
717
+ }
718
+ // Plain token string written by early inline <head> SSR script
719
+ return raw.trim() || null;
720
+ }
721
+ catch {
722
+ return null;
723
+ }
724
+ }
725
+ clearPersistedInviteToken() {
726
+ if (typeof sessionStorage === "undefined") {
727
+ return;
728
+ }
729
+ try {
730
+ sessionStorage.removeItem(PENDING_INVITE_TOKEN_STORAGE_KEY);
731
+ }
732
+ catch {
733
+ // Ignore storage restrictions
734
+ }
735
+ }
736
+ extractTokenFromHash(rawHash) {
737
+ if (!rawHash) {
738
+ return null;
739
+ }
740
+ const stripped = rawHash.replace(/^#+/, "");
741
+ if (!stripped) {
742
+ return null;
743
+ }
744
+ try {
745
+ const queryPart = stripped.includes("?")
746
+ ? stripped.slice(stripped.indexOf("?") + 1)
747
+ : stripped;
748
+ const params = new URLSearchParams(queryPart);
531
749
  return params.get(JOIN_CHAT_TOKEN_URL_PARAM) || null;
532
750
  }
533
- catch (e) {
534
- console.log("Failed to check for chat invite token", e);
751
+ catch {
535
752
  return null;
536
753
  }
537
754
  }
538
- async prepareChatInvitation(token) {
539
- this.pendingInviteToken = token;
540
- this.pendingInviteInfo = null;
755
+ checkForChatInviteToken(explicitUrl) {
756
+ if (explicitUrl) {
757
+ try {
758
+ const parsed = new URL(explicitUrl, "https://rtsee.local");
759
+ const fromExplicit = parsed.searchParams.get(JOIN_CHAT_TOKEN_URL_PARAM) ||
760
+ this.extractTokenFromHash(parsed.hash);
761
+ if (fromExplicit) {
762
+ this.persistPendingInviteToken(fromExplicit);
763
+ return fromExplicit;
764
+ }
765
+ }
766
+ catch {
767
+ // Fall through to window / sessionStorage checks
768
+ }
769
+ }
770
+ if (typeof window === "undefined") {
771
+ return null;
772
+ }
541
773
  try {
542
- const info = await this.remoteActions.getChatInvitationInfo.send(token);
543
- if (this.pendingInviteToken === token) {
544
- this.pendingInviteInfo = info;
774
+ if (window.location?.search) {
775
+ const params = new URLSearchParams(window.location.search);
776
+ const fromSearch = params.get(JOIN_CHAT_TOKEN_URL_PARAM);
777
+ if (fromSearch) {
778
+ this.persistPendingInviteToken(fromSearch);
779
+ return fromSearch;
780
+ }
781
+ }
782
+ const fromHash = this.extractTokenFromHash(window.location?.hash);
783
+ if (fromHash) {
784
+ this.persistPendingInviteToken(fromHash);
785
+ return fromHash;
545
786
  }
787
+ return this.readPersistedInviteToken();
546
788
  }
547
789
  catch (e) {
548
- console.log("Failed to fetch chat invitation info", e);
549
- this.pendingInviteToken = null;
790
+ console.log("Failed to check for chat invite token", e);
791
+ return null;
792
+ }
793
+ }
794
+ async prepareChatInvitation(token) {
795
+ if (!token) {
796
+ return;
797
+ }
798
+ this.persistPendingInviteToken(token);
799
+ if (this.pendingInviteToken === token &&
800
+ this.pendingInviteInfo?.token === token) {
801
+ return;
802
+ }
803
+ if (this.pendingInviteInfoRequest?.token === token) {
804
+ return this.pendingInviteInfoRequest.promise;
805
+ }
806
+ this.pendingInviteToken = token;
807
+ if (this.pendingInviteInfo?.token !== token) {
550
808
  this.pendingInviteInfo = null;
551
- this.cleanChatInviteTokenFromUrl();
552
809
  }
810
+ const requestPromise = (async () => {
811
+ try {
812
+ const info = await this.remoteActions.getChatInvitationInfo.send(token);
813
+ if (this.pendingInviteToken === token) {
814
+ this.pendingInviteInfo = info;
815
+ }
816
+ }
817
+ catch (e) {
818
+ console.log("Failed to fetch chat invitation info", e);
819
+ if (this.pendingInviteToken !== token) {
820
+ return;
821
+ }
822
+ const isTransientError = e?.code === "TIMEOUT" || e?.code === "DISCONNECTED";
823
+ if (!isTransientError) {
824
+ this.pendingInviteToken = null;
825
+ this.pendingInviteInfo = null;
826
+ this.cleanChatInviteTokenFromUrl();
827
+ }
828
+ }
829
+ finally {
830
+ if (this.pendingInviteInfoRequest?.token === token) {
831
+ this.pendingInviteInfoRequest = null;
832
+ }
833
+ }
834
+ })();
835
+ this.pendingInviteInfoRequest = { token, promise: requestPromise };
836
+ return requestPromise;
553
837
  }
554
838
  async acceptChatInvitation() {
555
839
  if (!this.pendingInviteToken || this.inviteJoinInProgress) {
@@ -564,6 +848,7 @@ export class RTSeeMessenger extends RTSeeCore {
564
848
  this.inviteJoinInProgress = false;
565
849
  this.pendingInviteToken = null;
566
850
  this.pendingInviteInfo = null;
851
+ this.clearPersistedInviteToken();
567
852
  }
568
853
  }
569
854
  ignoreChatInvitation() {
@@ -572,10 +857,31 @@ export class RTSeeMessenger extends RTSeeCore {
572
857
  this.cleanChatInviteTokenFromUrl();
573
858
  }
574
859
  cleanChatInviteTokenFromUrl() {
860
+ this.clearPersistedInviteToken();
861
+ if (typeof window === "undefined" || !window.location?.href) {
862
+ return;
863
+ }
575
864
  try {
576
865
  const url = new URL(window.location.href);
577
866
  url.searchParams.delete(JOIN_CHAT_TOKEN_URL_PARAM);
578
- window.history.replaceState({}, '', url.toString());
867
+ if (url.hash && url.hash.includes(JOIN_CHAT_TOKEN_URL_PARAM)) {
868
+ const rawHash = url.hash.replace(/^#+/, "");
869
+ if (rawHash.includes("?")) {
870
+ const qIdx = rawHash.indexOf("?");
871
+ const prefix = rawHash.slice(0, qIdx);
872
+ const hashParams = new URLSearchParams(rawHash.slice(qIdx + 1));
873
+ hashParams.delete(JOIN_CHAT_TOKEN_URL_PARAM);
874
+ const nextHashQuery = hashParams.toString();
875
+ url.hash = nextHashQuery ? `${prefix}?${nextHashQuery}` : prefix;
876
+ }
877
+ else {
878
+ const hashParams = new URLSearchParams(rawHash);
879
+ hashParams.delete(JOIN_CHAT_TOKEN_URL_PARAM);
880
+ const nextHash = hashParams.toString();
881
+ url.hash = nextHash ? `#${nextHash}` : "";
882
+ }
883
+ }
884
+ window.history.replaceState({}, "", url.toString());
579
885
  }
580
886
  catch (e) {
581
887
  console.log("Failed to clean invite token from URL", e);
@@ -594,11 +900,19 @@ export class RTSeeMessenger extends RTSeeCore {
594
900
  chat = this.addChat(chatData);
595
901
  }
596
902
  this.syncPresentationRoom(chat, true);
597
- this.openChat(chat);
903
+ this.suppressMessengerNavigation = true;
904
+ try {
905
+ this.openChat(chat);
906
+ }
907
+ finally {
908
+ this.suppressMessengerNavigation = false;
909
+ }
598
910
  if (chat.type !== RTSeeChatTypes.INDIVIDUAL) {
599
911
  chat.sendMessage('Joining the room!');
600
912
  }
601
913
  this.cleanChatInviteTokenFromUrl();
914
+ this.emit(MessengerClientEvents.INVITE_ACCEPTED, chat);
915
+ await this.joinOrStartVideoCallForInvite(chat, false);
602
916
  }
603
917
  catch (e) {
604
918
  console.log("Failed to join chat via token", e);
@@ -662,6 +976,7 @@ export class RTSeeMessenger extends RTSeeCore {
662
976
  },
663
977
  });
664
978
  this.folded = false;
979
+ this.closeHeaderAddDropdown();
665
980
  this.closeInviteUser();
666
981
  this.closeManageChatInfo();
667
982
  this.closeProfile();
@@ -796,8 +1111,16 @@ export class RTSeeMessenger extends RTSeeCore {
796
1111
  if (!chat) {
797
1112
  return null;
798
1113
  }
1114
+ const lastMsgText = chat.lastMessage?.text ||
1115
+ chat.messages?.[chat.messages.length - 1]?.text ||
1116
+ "";
1117
+ const isInviteAcceptanceChat = typeof lastMsgText === "string" &&
1118
+ lastMsgText.endsWith("has accepted the invitation");
799
1119
  const inviteStillOpened = wasInviteOpened || this.inviteUserOpened;
800
- const shouldAutoStartVideoCall = inviteStillOpened || hadPendingAutoCall || this.hasPendingAutoVideoCall();
1120
+ const shouldAutoStartVideoCall = isInviteAcceptanceChat ||
1121
+ inviteStillOpened ||
1122
+ hadPendingAutoCall ||
1123
+ this.hasPendingAutoVideoCall();
801
1124
  let targetChat = this.getChatById(chat.id);
802
1125
  if (targetChat) {
803
1126
  targetChat.init(chat);
@@ -810,7 +1133,13 @@ export class RTSeeMessenger extends RTSeeCore {
810
1133
  this.closeInviteUser();
811
1134
  }
812
1135
  if (!this.openedChat || inviteStillOpened || shouldAutoStartVideoCall) {
813
- this.openChat(targetChat);
1136
+ this.suppressMessengerNavigation = shouldAutoStartVideoCall;
1137
+ try {
1138
+ this.openChat(targetChat);
1139
+ }
1140
+ finally {
1141
+ this.suppressMessengerNavigation = false;
1142
+ }
814
1143
  }
815
1144
  this.recalculateUnreadMessagesCount();
816
1145
  if (inviteStillOpened || shouldAutoStartVideoCall) {
@@ -818,13 +1147,8 @@ export class RTSeeMessenger extends RTSeeCore {
818
1147
  }
819
1148
  if (shouldAutoStartVideoCall) {
820
1149
  this.clearPendingAutoVideoCall();
821
- // Wait one tick so Angular hides `.rts-messenger-header-invite-user-container`
822
- // and renders the opened chat before initiating the video call (`getUserMedia`).
823
1150
  setTimeout(() => {
824
- const activeVideoChat = this.videoChat;
825
- if (!activeVideoChat?.isInActiveCall) {
826
- void this.initializeVideoCall(targetChat);
827
- }
1151
+ void this.joinOrStartVideoCallForInvite(targetChat, true);
828
1152
  }, 0);
829
1153
  }
830
1154
  return targetChat;
@@ -856,8 +1180,16 @@ export class RTSeeMessenger extends RTSeeCore {
856
1180
  return chat;
857
1181
  }
858
1182
  populateChats(chats) {
859
- chats.forEach((elem) => {
860
- this.addChat(elem, true);
1183
+ (chats || []).forEach((elem) => {
1184
+ if (!elem?.id) {
1185
+ return;
1186
+ }
1187
+ try {
1188
+ this.addChat(elem, true);
1189
+ }
1190
+ catch (e) {
1191
+ console.warn(`Skipping malformed chat ${elem.id}:`, e);
1192
+ }
861
1193
  });
862
1194
  }
863
1195
  addChat(chatData, append, standalone = false) {
@@ -959,9 +1291,16 @@ export class RTSeeMessenger extends RTSeeCore {
959
1291
  this.openInviteWhenChatsEmpty = false;
960
1292
  if (this.chats.length > 0 && !this.openedChat) {
961
1293
  this.inviteUserOpened = false;
962
- this.preserveInviteOnRouteEnter = false;
1294
+ if (this.toggleAddDropdownWhenChatsExist) {
1295
+ this.toggleAddDropdownWhenChatsExist = false;
1296
+ this.headerAddDropdownOpen = true;
1297
+ }
1298
+ else {
1299
+ this.preserveInviteOnRouteEnter = false;
1300
+ }
963
1301
  }
964
1302
  else if (this.chats.length === 0) {
1303
+ this.toggleAddDropdownWhenChatsExist = false;
965
1304
  this.inviteUserOpened = true;
966
1305
  }
967
1306
  }
@@ -1032,7 +1371,48 @@ export class RTSeeMessenger extends RTSeeCore {
1032
1371
  console.log("ERROR! Signaling Client is not initialized or Video Chat is not connected!");
1033
1372
  return;
1034
1373
  }
1035
- await this.videoChat.connect(roomId, this.signalingClient.getMyPeer());
1374
+ const peer = this.signalingClient.getMyPeer() || this.myPeer;
1375
+ await this.videoChat.connect(roomId, peer);
1376
+ }
1377
+ async joinOrStartVideoCallForInvite(chat, isInviter) {
1378
+ if (!chat) {
1379
+ return;
1380
+ }
1381
+ this.clearPendingAutoVideoCall();
1382
+ if (!chat.conferenceRoom?.id) {
1383
+ try {
1384
+ const refreshedChat = await this.remoteActions.getChat.send({
1385
+ id: chat.id,
1386
+ });
1387
+ if (refreshedChat?.conferenceRoom?.id) {
1388
+ chat.setConferenceRoom(refreshedChat.conferenceRoom);
1389
+ }
1390
+ }
1391
+ catch {
1392
+ // Fall back to deterministic room id if chat fetch fails
1393
+ }
1394
+ }
1395
+ const roomId = chat.conferenceRoom?.id || `room-${chat.id}`;
1396
+ if (!chat.conferenceRoom?.id) {
1397
+ chat.setConferenceRoom({ id: roomId, chatId: chat.id });
1398
+ }
1399
+ if (this.videoChat?.isInActiveCall &&
1400
+ this.videoChat?.roomId === roomId) {
1401
+ return;
1402
+ }
1403
+ if (this.autoJoinedInviteRooms.has(roomId)) {
1404
+ return;
1405
+ }
1406
+ this.autoJoinedInviteRooms.add(roomId);
1407
+ setTimeout(() => {
1408
+ this.autoJoinedInviteRooms.delete(roomId);
1409
+ }, 15000);
1410
+ if (isInviter) {
1411
+ await this.initializeVideoCall(chat);
1412
+ }
1413
+ else {
1414
+ await this.joinCall(roomId);
1415
+ }
1036
1416
  }
1037
1417
  async initializeVideoCall(chat) {
1038
1418
  this.clearPendingAutoVideoCall();
@@ -1104,28 +1484,69 @@ export class RTSeeMessenger extends RTSeeCore {
1104
1484
  if (localChat) {
1105
1485
  localChat.addMember(memberData);
1106
1486
  const myId = this.myPeer?.clientId || this.clientId;
1107
- if (memberData.id && memberData.id !== myId) {
1487
+ if (memberData.id && memberData.id !== myId && !memberData.isAgent) {
1108
1488
  const wasInviteOpened = this.inviteUserOpened;
1109
1489
  const shouldAutoStartVideoCall = wasInviteOpened || this.hasPendingAutoVideoCall();
1110
1490
  if (wasInviteOpened) {
1111
1491
  this.closeInviteUser();
1112
1492
  }
1113
1493
  if (wasInviteOpened || shouldAutoStartVideoCall) {
1114
- this.openChat(localChat);
1494
+ this.suppressMessengerNavigation = true;
1495
+ try {
1496
+ this.openChat(localChat);
1497
+ }
1498
+ finally {
1499
+ this.suppressMessengerNavigation = false;
1500
+ }
1115
1501
  this.emit(MessengerClientEvents.INVITE_ACCEPTED, localChat);
1116
1502
  }
1117
1503
  if (shouldAutoStartVideoCall) {
1118
1504
  this.clearPendingAutoVideoCall();
1119
1505
  setTimeout(() => {
1120
- const activeVideoChat = this.videoChat;
1121
- if (!activeVideoChat?.isInActiveCall) {
1122
- void this.initializeVideoCall(localChat);
1123
- }
1506
+ void this.joinOrStartVideoCallForInvite(localChat, true);
1124
1507
  }, 0);
1125
1508
  }
1126
1509
  }
1127
1510
  }
1128
1511
  });
1512
+ socket.on(RTSeeMessengerEvents.CHAT_INVITE_ACCEPTED, (eventData) => {
1513
+ if (!eventData?.chatId) {
1514
+ return;
1515
+ }
1516
+ const myId = this.myPeer?.clientId ||
1517
+ this.signalingClient?.getMyPeerId?.() ||
1518
+ this.clientId;
1519
+ if (eventData.acceptedById && eventData.acceptedById === myId) {
1520
+ return;
1521
+ }
1522
+ void (async () => {
1523
+ let targetChat = this.getChatById(eventData.chatId);
1524
+ if (!targetChat) {
1525
+ targetChat = await this.getRemoteChat(eventData.chatId);
1526
+ }
1527
+ if (!targetChat) {
1528
+ return;
1529
+ }
1530
+ if (eventData.roomId) {
1531
+ targetChat.setConferenceRoom({
1532
+ id: eventData.roomId,
1533
+ chatId: targetChat.id,
1534
+ });
1535
+ }
1536
+ if (this.inviteUserOpened) {
1537
+ this.closeInviteUser();
1538
+ }
1539
+ this.suppressMessengerNavigation = true;
1540
+ try {
1541
+ this.openChat(targetChat);
1542
+ }
1543
+ finally {
1544
+ this.suppressMessengerNavigation = false;
1545
+ }
1546
+ this.emit(MessengerClientEvents.INVITE_ACCEPTED, targetChat);
1547
+ await this.joinOrStartVideoCallForInvite(targetChat, true);
1548
+ })();
1549
+ });
1129
1550
  socket.on(RTSeeMessengerEvents.CHAT_MEMBER_UPDATED, (memberData) => {
1130
1551
  const localChat = this.getChatById(memberData.chatId);
1131
1552
  if (localChat) {