@memberjunction/core-entities 6.2.0-edge.7 → 6.2.0-edge.8

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.
Files changed (47) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/AnchoredConversationSecurity.d.ts +103 -0
  3. package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -0
  4. package/dist/custom/AnchoredConversationSecurity.js +401 -0
  5. package/dist/custom/AnchoredConversationSecurity.js.map +1 -0
  6. package/dist/custom/ConversationWriteAccess.d.ts +11 -3
  7. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  8. package/dist/custom/ConversationWriteAccess.js +100 -9
  9. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  10. package/dist/custom/MJConversationDetailEntityExtended.d.ts.map +1 -1
  11. package/dist/custom/MJConversationDetailEntityExtended.js +18 -1
  12. package/dist/custom/MJConversationDetailEntityExtended.js.map +1 -1
  13. package/dist/custom/MJProjectEntityExtended.d.ts +12 -0
  14. package/dist/custom/MJProjectEntityExtended.d.ts.map +1 -0
  15. package/dist/custom/MJProjectEntityExtended.js +35 -0
  16. package/dist/custom/MJProjectEntityExtended.js.map +1 -0
  17. package/dist/custom/Permissions/index.d.ts +1 -0
  18. package/dist/custom/Permissions/index.d.ts.map +1 -1
  19. package/dist/custom/Permissions/index.js +1 -0
  20. package/dist/custom/Permissions/index.js.map +1 -1
  21. package/dist/custom/Permissions/mentionNotification.d.ts +64 -0
  22. package/dist/custom/Permissions/mentionNotification.d.ts.map +1 -0
  23. package/dist/custom/Permissions/mentionNotification.js +315 -0
  24. package/dist/custom/Permissions/mentionNotification.js.map +1 -0
  25. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
  26. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +12 -4
  27. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
  28. package/dist/custom/ResourcePermissions/ResourcePermissionEngine.d.ts.map +1 -1
  29. package/dist/custom/ResourcePermissions/ResourcePermissionEngine.js +9 -1
  30. package/dist/custom/ResourcePermissions/ResourcePermissionEngine.js.map +1 -1
  31. package/dist/engines/conversations.d.ts +294 -13
  32. package/dist/engines/conversations.d.ts.map +1 -1
  33. package/dist/engines/conversations.js +838 -40
  34. package/dist/engines/conversations.js.map +1 -1
  35. package/dist/generated/entities/__mj.d.ts +8364 -5414
  36. package/dist/generated/entities/__mj.d.ts.map +1 -1
  37. package/dist/generated/entities/__mj.js +12500 -8546
  38. package/dist/generated/entities/__mj.js.map +1 -1
  39. package/dist/generated/remote_operations.d.ts +294 -0
  40. package/dist/generated/remote_operations.d.ts.map +1 -1
  41. package/dist/generated/remote_operations.js +207 -0
  42. package/dist/generated/remote_operations.js.map +1 -1
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +2 -0
  46. package/dist/index.js.map +1 -1
  47. package/package.json +6 -6
@@ -3,12 +3,214 @@ import { EscapeSQLString, IndexByUUID, NormalizeUUID, ToEpochMs, UUIDMap, UUIDSe
3
3
  import { BehaviorSubject } from "rxjs";
4
4
  import { ArtifactMetadataEngine } from "./artifacts.js";
5
5
  import { ResourcePermissionEngine } from "../custom/ResourcePermissions/ResourcePermissionEngine.js";
6
+ import { FilterAnchoredConversationsForUser, IsConversationHiddenByFieldSecurity, ParseConversationAnchorMetadata } from "../custom/AnchoredConversationSecurity.js";
6
7
  /**
7
8
  * `MJ: Resource Types.ID` for Conversations. Conversations that the current
8
9
  * user doesn't own but has been granted access to (via `MJ: Resource Permissions`)
9
10
  * are folded into the list by `LoadConversations` using this ID.
10
11
  */
11
12
  const CONVERSATIONS_RESOURCE_TYPE_ID = '81D4BC3D-9FEB-EF11-B01A-286B35C04427';
13
+ /**
14
+ * `MJ: Resource Types.ID` for Projects (Conversation Folders). Used for Google Drive-style
15
+ * folder ACL sharing (`MJ: Resource Permissions`) where users/roles granted access to a
16
+ * folder inherit access to conversations inside it.
17
+ */
18
+ export const PROJECTS_RESOURCE_TYPE_ID = '88D0DF27-AF8F-43AC-9EC4-2AC314F49355';
19
+ /**
20
+ * The spellings of `"inheritFolderAccess": true` the SQL filter recognises: the compact one every MJ writer
21
+ * produces (`JSON.stringify` and the server's save, which rewrites `AdditionalData` compactly) and the
22
+ * one-space one. {@link INHERIT_FOLDER_ACCESS_SQL_CLAUSE} and {@link IsInheritingFolderAccessInSQL} are both
23
+ * built from this list, so they cannot drift apart.
24
+ */
25
+ export const INHERIT_FOLDER_ACCESS_TRUE_SPELLINGS = ['"inheritFolderAccess":true', '"inheritFolderAccess": true'];
26
+ /**
27
+ * SQL predicate matching conversations that inherit access from their folder. Inheritance is opt-in: turning
28
+ * it on writes `"inheritFolderAccess":true` into `Conversation.AdditionalData`.
29
+ *
30
+ * `LIKE`, not `JSON_VALUE`: this filter runs on PostgreSQL too, which translates no SQL Server JSON
31
+ * functions in a runtime filter. A `LIKE` also matches the key nested inside another object, which the parser
32
+ * does not count; `MJConversationEntityServer` refuses to save a value the two read differently, so they agree on
33
+ * every row the entity layer writes.
34
+ */
35
+ export const INHERIT_FOLDER_ACCESS_SQL_CLAUSE = `(${INHERIT_FOLDER_ACCESS_TRUE_SPELLINGS.map((s) => `AdditionalData LIKE '%${s}%'`).join(' OR ')})`;
36
+ /**
37
+ * What {@link INHERIT_FOLDER_ACCESS_SQL_CLAUSE} decides for this `AdditionalData`: true when the SQL filter
38
+ * treats the conversation as inheriting its folder's access. Case-insensitive, like SQL Server's default
39
+ * collation. The server compares this as well as {@link IsInheritingFolderAccess}, so a rewrite that one of
40
+ * them reads differently is caught.
41
+ */
42
+ export function IsInheritingFolderAccessInSQL(additionalData) {
43
+ if (!additionalData) {
44
+ return false;
45
+ }
46
+ const lower = additionalData.toLowerCase();
47
+ return INHERIT_FOLDER_ACCESS_TRUE_SPELLINGS.some((s) => lower.includes(s.toLowerCase()));
48
+ }
49
+ /**
50
+ * `AdditionalData` rewritten as compact JSON when it holds a JSON object, so the stored text always uses the
51
+ * spelling {@link INHERIT_FOLDER_ACCESS_SQL_CLAUSE} matches. Anything else (null, an array, text that is not
52
+ * JSON) comes back unchanged. The round trip through `JSON.parse` rounds an integer beyond 2^53, so such a
53
+ * number in the object is stored rounded.
54
+ */
55
+ export function CanonicalizeConversationAdditionalData(additionalData) {
56
+ if (!additionalData) {
57
+ return additionalData;
58
+ }
59
+ try {
60
+ const parsed = JSON.parse(additionalData);
61
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
62
+ return JSON.stringify(parsed);
63
+ }
64
+ }
65
+ catch {
66
+ // Not JSON: leave it as written.
67
+ }
68
+ return additionalData;
69
+ }
70
+ /** Spots `"inheritFolderAccess": true` in AdditionalData that is not valid JSON. */
71
+ const INHERIT_TRUE_PATTERN = /"inheritFolderAccess"\s*:\s*true/;
72
+ /**
73
+ * Returns true when `conversation` inherits permissions from its parent folder (`ProjectID`).
74
+ * Inheritance is opt-in: it is on only when `conversation.AdditionalData` stores
75
+ * `"inheritFolderAccess": true`.
76
+ */
77
+ export function IsInheritingFolderAccess(conversation) {
78
+ const raw = conversation?.AdditionalData;
79
+ if (!raw || raw.trim().length === 0) {
80
+ return false;
81
+ }
82
+ try {
83
+ const parsed = JSON.parse(raw);
84
+ return !!parsed && typeof parsed === 'object' && parsed['inheritFolderAccess'] === true;
85
+ }
86
+ catch {
87
+ return INHERIT_TRUE_PATTERN.test(raw);
88
+ }
89
+ }
90
+ /**
91
+ * Returns the updated `AdditionalData` JSON string after setting or clearing `inheritFolderAccess`.
92
+ * Preserves any other keys already present in `existingAdditionalData`. When `inheritFolderAccess`
93
+ * is `false` (the default) and no other keys exist, returns `null`.
94
+ */
95
+ export function BuildUpdatedAdditionalDataForFolderInheritance(existingAdditionalData, inheritFolderAccess) {
96
+ let dataObj = {};
97
+ if (existingAdditionalData && existingAdditionalData.trim().length > 0) {
98
+ try {
99
+ const parsed = JSON.parse(existingAdditionalData);
100
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
101
+ dataObj = { ...parsed };
102
+ }
103
+ }
104
+ catch {
105
+ // If existing AdditionalData is non-JSON, replace with clean object
106
+ }
107
+ }
108
+ if (inheritFolderAccess) {
109
+ dataObj['inheritFolderAccess'] = true;
110
+ }
111
+ else {
112
+ delete dataObj['inheritFolderAccess'];
113
+ }
114
+ return Object.keys(dataObj).length === 0 ? null : JSON.stringify(dataObj);
115
+ }
116
+ /**
117
+ * Returns the higher of two `MJ: Resource Permissions` levels (`'Owner' > 'Edit' > 'View' > null`).
118
+ */
119
+ export function ComparePermissionLevels(a, b) {
120
+ const rank = (lvl) => {
121
+ if (lvl === 'Owner')
122
+ return 3;
123
+ if (lvl === 'Edit')
124
+ return 2;
125
+ if (lvl === 'View')
126
+ return 1;
127
+ return 0;
128
+ };
129
+ const rA = rank(a);
130
+ const rB = rank(b);
131
+ if (rA === 0 && rB === 0)
132
+ return null;
133
+ return rA >= rB ? (a ?? null) : (b ?? null);
134
+ }
135
+ /**
136
+ * Pure rollup helper that computes open and resolved anchored comment counts across
137
+ * fields, sections, groups, and contributions, while enforcing FLS visibility when
138
+ * `entityInfo` and `currentUser` are provided.
139
+ */
140
+ export function ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo) {
141
+ let totalOpenCount = 0;
142
+ let totalResolvedCount = 0;
143
+ let recordLevelOpenCount = 0;
144
+ const byField = new Map();
145
+ const bySection = new Map();
146
+ const byGroup = new Map();
147
+ const byContribution = new Map();
148
+ for (const conv of conversations) {
149
+ if (!conv.AnchorType) {
150
+ continue;
151
+ }
152
+ if (currentUser &&
153
+ entityInfo &&
154
+ IsConversationHiddenByFieldSecurity(entityInfo, currentUser, conv.AnchorType, conv.AnchorKey, conv.AnchorMetadataObject ?? conv.AnchorMetadata)) {
155
+ continue;
156
+ }
157
+ if (conv.IsResolved) {
158
+ totalResolvedCount++;
159
+ continue;
160
+ }
161
+ totalOpenCount++;
162
+ const meta = ParseConversationAnchorMetadata(conv.AnchorMetadataObject ?? conv.AnchorMetadata);
163
+ const rawKey = conv.AnchorKey?.trim() ?? '';
164
+ if (conv.AnchorType === 'Record') {
165
+ recordLevelOpenCount++;
166
+ }
167
+ else if (conv.AnchorType === 'Field') {
168
+ const fieldKey = (rawKey || meta?.fieldName?.trim() || '').toLowerCase();
169
+ if (fieldKey) {
170
+ byField.set(fieldKey, (byField.get(fieldKey) ?? 0) + 1);
171
+ }
172
+ }
173
+ else if (conv.AnchorType === 'Section') {
174
+ const sectionKey = rawKey || meta?.sectionKey?.trim() || '';
175
+ if (sectionKey) {
176
+ bySection.set(sectionKey, (bySection.get(sectionKey) ?? 0) + 1);
177
+ }
178
+ }
179
+ else if (conv.AnchorType === 'Group') {
180
+ const groupKey = rawKey || meta?.groupKey?.trim() || '';
181
+ if (groupKey) {
182
+ byGroup.set(groupKey, (byGroup.get(groupKey) ?? 0) + 1);
183
+ }
184
+ }
185
+ else if (conv.AnchorType === 'Contribution') {
186
+ if (rawKey) {
187
+ byContribution.set(rawKey, (byContribution.get(rawKey) ?? 0) + 1);
188
+ }
189
+ }
190
+ // Roll up Field threads into their parent Section and Group when metadata provides them
191
+ if (conv.AnchorType !== 'Section' && meta?.sectionKey) {
192
+ const secKey = meta.sectionKey.trim();
193
+ if (secKey) {
194
+ bySection.set(secKey, (bySection.get(secKey) ?? 0) + 1);
195
+ }
196
+ }
197
+ if (conv.AnchorType !== 'Group' && meta?.groupKey) {
198
+ const grpKey = meta.groupKey.trim();
199
+ if (grpKey) {
200
+ byGroup.set(grpKey, (byGroup.get(grpKey) ?? 0) + 1);
201
+ }
202
+ }
203
+ }
204
+ return {
205
+ TotalOpenCount: totalOpenCount,
206
+ TotalResolvedCount: totalResolvedCount,
207
+ RecordLevelOpenCount: recordLevelOpenCount,
208
+ ByField: byField,
209
+ BySection: bySection,
210
+ ByGroup: byGroup,
211
+ ByContribution: byContribution
212
+ };
213
+ }
12
214
  /**
13
215
  * The Fields list a fresh per-request load must select to satisfy
14
216
  * {@link ConversationWindowSourceRow} — single-sourced so server callers cannot drift
@@ -266,10 +468,19 @@ function mergeArtifactJSON(junction, version, artifact) {
266
468
  * without an identity there is nobody to be the owner of, and widening on absent input
267
469
  * is how a personal folder reaches a stranger's list.
268
470
  */
269
- export function BuildProjectVisibilityFilter(userId) {
471
+ export function BuildProjectVisibilityFilter(userId, sharedProjectIds = []) {
270
472
  const id = String(userId ?? '').trim();
271
- return id.length > 0
272
- ? `(OwnerUserID IS NULL OR OwnerUserID='${EscapeSQLString(id)}')`
473
+ const cleanedSharedIds = sharedProjectIds
474
+ .map((pid) => String(pid ?? '').trim())
475
+ .filter((pid) => pid.length > 0);
476
+ const sharedClause = cleanedSharedIds.length > 0
477
+ ? ` OR ID IN (${cleanedSharedIds.map((pid) => `'${EscapeSQLString(pid)}'`).join(',')})`
478
+ : '';
479
+ if (id.length > 0) {
480
+ return `(OwnerUserID IS NULL OR OwnerUserID='${EscapeSQLString(id)}'${sharedClause})`;
481
+ }
482
+ return cleanedSharedIds.length > 0
483
+ ? `(OwnerUserID IS NULL${sharedClause})`
273
484
  : `OwnerUserID IS NULL`;
274
485
  }
275
486
  /**
@@ -345,6 +556,10 @@ export class ConversationEngine extends BaseEngine {
345
556
  this._detailCache = new Map();
346
557
  /** Track the environment ID used for the last load */
347
558
  this._lastEnvironmentId = null;
559
+ /** Track the user ID used for the last conversations load */
560
+ this._lastConversationsUserId = null;
561
+ /** Conversation IDs shared with the current user via explicit MJ: Resource Permissions grants */
562
+ this._explicitSharedConversationIds = new Set();
348
563
  /** Track the environment ID used for the last projects (folders) load */
349
564
  this._lastProjectsEnvironmentId = null;
350
565
  /**
@@ -355,6 +570,11 @@ export class ConversationEngine extends BaseEngine {
355
570
  * from cache and never issue a read of their own.
356
571
  */
357
572
  this._lastProjectsUserId = null;
573
+ /**
574
+ * The user the last folder or conversation load ran for. Kept whole, not just the ID, so event handlers can
575
+ * match that user's Role grants as well as their User grants (see {@link getUserSharedProjectPermissions}).
576
+ */
577
+ this._lastViewer = null;
358
578
  /**
359
579
  * Monotonic ticket for conversation loads, to keep the newest ANSWER rather than the
360
580
  * newest REQUEST.
@@ -370,7 +590,8 @@ export class ConversationEngine extends BaseEngine {
370
590
  * For conversations the current user *received* via sharing, this map goes
371
591
  * from `conversationId` to the grantor's display info. Populated by
372
592
  * {@link LoadConversations} using the `SharedByUserID` column on the
373
- * `MJ: Resource Permissions` row. Used by the chat UI to render
593
+ * `MJ: Resource Permissions` row or the conversation owner for conversations
594
+ * inside a shared folder. Used by the chat UI to render
374
595
  * "Shared by {email}" next to the title and a share icon in the sidebar.
375
596
  */
376
597
  this._sharedByByConversationId = new Map();
@@ -436,8 +657,16 @@ export class ConversationEngine extends BaseEngine {
436
657
  return this.GetSharedByInfo(conversation.ID)?.Level === 'Owner';
437
658
  }
438
659
  /**
439
- * True when the user may change the conversation's folder and pin: they own
440
- * it, or hold an Edit or Owner grant on it. A View grant is read-only.
660
+ * True when the user may move the conversation to another folder or change whether it inherits its
661
+ * folder's access: only its owner. Both decide who else sees it, so an Edit or Owner grant is not
662
+ * enough. Mirrors the server's rule in `MJConversationEntityServer`.
663
+ */
664
+ CanMoveConversation(conversation, userId) {
665
+ return !!conversation.UserID && UUIDsEqual(conversation.UserID, userId);
666
+ }
667
+ /**
668
+ * True when the user may pin the conversation: they own it, or hold an Edit or Owner grant on it.
669
+ * A View grant is read-only. Moving it is owner-only: see {@link CanMoveConversation}.
441
670
  */
442
671
  CanEditConversation(conversation, userId) {
443
672
  if (conversation.UserID && UUIDsEqual(conversation.UserID, userId)) {
@@ -486,13 +715,16 @@ export class ConversationEngine extends BaseEngine {
486
715
  return;
487
716
  }
488
717
  this._lastEnvironmentId = environmentId;
718
+ this._lastConversationsUserId = contextUser?.ID ?? null;
719
+ this._lastViewer = contextUser ?? null;
489
720
  // Claim a ticket for this load. Anything published below is gated on still holding
490
721
  // the newest one — see _conversationsLoadGeneration.
491
722
  const generation = ++this._conversationsLoadGeneration;
492
723
  const sharedPermissions = await this.getSharedConversationPermissions(contextUser);
493
- const filter = this.buildVisibleConversationsFilter(environmentId, contextUser.ID, sharedPermissions.map((p) => p.ResourceRecordID), options);
724
+ const initialSharedProjectIds = this.getSharedProjectIds(environmentId);
725
+ const filter = this.buildVisibleConversationsFilter(environmentId, contextUser.ID, sharedPermissions.map((p) => p.ResourceRecordID), options, initialSharedProjectIds);
494
726
  const rv = new RunView();
495
- const result = await rv.RunView({
727
+ let result = await rv.RunView({
496
728
  EntityName: 'MJ: Conversations',
497
729
  ExtraFilter: filter,
498
730
  OrderBy: 'IsPinned DESC, __mj_UpdatedAt DESC',
@@ -519,28 +751,118 @@ export class ConversationEngine extends BaseEngine {
519
751
  console.error('[ConversationEngine] Failed to load conversations:', result.ErrorMessage);
520
752
  this._conversations$.next([]);
521
753
  }
522
- // Build the "shared by" map AFTER fetching conversations so we can
523
- // exclude permissions on conversations the user owns. A role-inherited
754
+ await this.applyConversationSharingMetadata(rv, result.Results ?? [], sharedPermissions, initialSharedProjectIds, contextUser);
755
+ // Load the folder (project) list so the sidebar can group conversations
756
+ // under their folder. Done after the conversation query (so it isn't
757
+ // delayed) and after the early-return guard above; LoadProjects has its
758
+ // own per-environment guard to avoid redundant reloads.
759
+ await this.LoadProjects(environmentId, contextUser, forceRefresh);
760
+ if (generation !== this._conversationsLoadGeneration) {
761
+ return;
762
+ }
763
+ // If LoadProjects discovered shared folders that were not yet in _projects$ when
764
+ // the initial conversation query ran, re-query MJ: Conversations so conversations
765
+ // inside those shared folders are automatically included and marked View-only.
766
+ const currentSharedProjectIds = this.getSharedProjectIds(environmentId);
767
+ if (!this.sameIdSet(initialSharedProjectIds, currentSharedProjectIds)) {
768
+ const updatedFilter = this.buildVisibleConversationsFilter(environmentId, contextUser.ID, sharedPermissions.map((p) => p.ResourceRecordID), options, currentSharedProjectIds);
769
+ result = await rv.RunView({
770
+ EntityName: 'MJ: Conversations',
771
+ ExtraFilter: updatedFilter,
772
+ OrderBy: 'IsPinned DESC, __mj_UpdatedAt DESC',
773
+ MaxRows: 1000,
774
+ ResultType: 'entity_object',
775
+ BypassCache: forceRefresh
776
+ }, contextUser);
777
+ if (generation !== this._conversationsLoadGeneration) {
778
+ return;
779
+ }
780
+ if (result.Success) {
781
+ this._conversations$.next(result.Results || []);
782
+ }
783
+ else {
784
+ console.error('[ConversationEngine] Failed to load conversations:', result.ErrorMessage);
785
+ this._conversations$.next([]);
786
+ }
787
+ await this.applyConversationSharingMetadata(rv, result.Results ?? [], sharedPermissions, currentSharedProjectIds, contextUser);
788
+ }
789
+ }
790
+ /**
791
+ * Populates {@link _explicitSharedConversationIds} and {@link _sharedByByConversationId}
792
+ * from both explicit `MJ: Resource Permissions` grants and folder-inherited permissions
793
+ * on conversations inside Shared or Public folders (when {@link IsInheritingFolderAccess}
794
+ * is true).
795
+ *
796
+ * Explicit grants and folder-inherited grants combine via {@link ComparePermissionLevels}
797
+ * (`Owner > Edit > View`), while conversations whose owner has not turned on `inheritFolderAccess`
798
+ * do not inherit folder access and are only visible to their owner or explicit conversation grantees.
799
+ *
800
+ * Side effect: when any loaded conversation turns out not to be visible to the user, it is
801
+ * dropped and the remaining list is re-emitted on {@link _conversations$}.
802
+ */
803
+ async applyConversationSharingMetadata(rv, conversations, sharedPermissions, sharedProjectIds, contextUser) {
804
+ // Exclude permissions on conversations the user owns. A role-inherited
524
805
  // grant on the user's own conversation (e.g. they're in a role that
525
806
  // got View access via a feedback workflow) must NOT appear as
526
807
  // "shared with me at View level" — otherwise the chat UI would treat
527
808
  // their own conversation as read-only. See isReadOnlyView in
528
809
  // conversation-chat-area.component.
529
- const ownedConversationIds = new Set((result.Results ?? [])
810
+ const ownedConversationIds = new Set(conversations
530
811
  .filter((c) => c.UserID && UUIDsEqual(c.UserID, contextUser.ID))
531
812
  .map((c) => NormalizeUUID(c.ID)));
532
813
  const trulySharedPermissions = sharedPermissions.filter((p) => !ownedConversationIds.has(NormalizeUUID(p.ResourceRecordID)));
533
- await this.rebuildSharedByMap(rv, trulySharedPermissions, contextUser);
534
- // Load the folder (project) list so the sidebar can group conversations
535
- // under their folder. Done after the conversation query (so it isn't
536
- // delayed) and after the early-return guard above; LoadProjects has its
537
- // own per-environment guard to avoid redundant reloads.
538
- await this.LoadProjects(environmentId, contextUser, forceRefresh);
814
+ this._explicitSharedConversationIds = new Set(trulySharedPermissions.map((p) => NormalizeUUID(p.ResourceRecordID)));
815
+ const sharedProjectIdSet = new Set(sharedProjectIds.map((id) => NormalizeUUID(id)));
816
+ const convById = new Map(conversations.map((c) => [NormalizeUUID(c.ID), c]));
817
+ const effectiveExplicitPermissions = trulySharedPermissions.map((p) => {
818
+ const conv = convById.get(NormalizeUUID(p.ResourceRecordID));
819
+ const inherited = conv && conv.ProjectID && IsInheritingFolderAccess(conv) && sharedProjectIdSet.has(NormalizeUUID(conv.ProjectID))
820
+ ? this.GetEffectiveProjectPermission(conv.ProjectID, contextUser)
821
+ : null;
822
+ return {
823
+ ResourceRecordID: p.ResourceRecordID,
824
+ SharedByUserID: p.SharedByUserID ?? null,
825
+ SharedByUser: p.SharedByUser ?? null,
826
+ PermissionLevel: ComparePermissionLevels(p.PermissionLevel ?? 'View', inherited?.Level) ?? 'View'
827
+ };
828
+ });
829
+ const folderSharedPermissions = [];
830
+ const visibleConversations = [];
831
+ let filteredAny = false;
832
+ for (const conv of conversations) {
833
+ const normId = NormalizeUUID(conv.ID);
834
+ const isOwned = !conv.UserID || ownedConversationIds.has(normId);
835
+ if (isOwned || this._explicitSharedConversationIds.has(normId)) {
836
+ visibleConversations.push(conv);
837
+ continue;
838
+ }
839
+ if (conv.ProjectID &&
840
+ IsInheritingFolderAccess(conv) &&
841
+ sharedProjectIdSet.has(NormalizeUUID(conv.ProjectID))) {
842
+ visibleConversations.push(conv);
843
+ const inherited = this.GetEffectiveProjectPermission(conv.ProjectID, contextUser);
844
+ const convWithUser = conv;
845
+ folderSharedPermissions.push({
846
+ ResourceRecordID: conv.ID,
847
+ SharedByUserID: conv.UserID ?? inherited?.SharedByUserID ?? null,
848
+ SharedByUser: convWithUser.User ?? inherited?.SharedByUser ?? null,
849
+ PermissionLevel: inherited?.Level ?? 'View'
850
+ });
851
+ }
852
+ else {
853
+ filteredAny = true;
854
+ }
855
+ }
856
+ if (filteredAny) {
857
+ this._conversations$.next(visibleConversations);
858
+ }
859
+ await this.rebuildSharedByMap(rv, [...effectiveExplicitPermissions, ...folderSharedPermissions], contextUser);
539
860
  }
540
861
  /**
541
862
  * Returns an `ExtraFilter` for `MJ: Conversations` that matches exactly the conversations
542
- * {@link LoadConversations} shows the user: owned by the user or shared with them, not
543
- * archived, and (unless `includeApplicationScoped`) Global or Both scope.
863
+ * {@link LoadConversations} shows the user: owned by the user, explicitly shared with them,
864
+ * or inside a visible Shared/Public folder (with folder inheritance enabled), not archived,
865
+ * and (unless `includeApplicationScoped`) Global or Both scope.
544
866
  *
545
867
  * Use it anywhere that reads conversations for display (search, pickers) so those reads
546
868
  * cannot show more than the conversation list does. It is not capped, unlike the list load.
@@ -551,7 +873,162 @@ export class ConversationEngine extends BaseEngine {
551
873
  */
552
874
  async GetVisibleConversationsFilter(environmentId, contextUser, options) {
553
875
  const sharedPermissions = await this.getSharedConversationPermissions(contextUser);
554
- return this.buildVisibleConversationsFilter(environmentId, contextUser.ID, sharedPermissions.map((p) => p.ResourceRecordID), options);
876
+ const sharedProjectIds = this.getSharedProjectIds(environmentId);
877
+ return this.buildVisibleConversationsFilter(environmentId, contextUser.ID, sharedPermissions.map((p) => p.ResourceRecordID), options, sharedProjectIds);
878
+ }
879
+ /**
880
+ * Approved `MJ: Resource Permissions` rows targeting `MJ: Projects` (`PROJECTS_RESOURCE_TYPE_ID`).
881
+ */
882
+ getApprovedProjectPermissions() {
883
+ const allPerms = ResourcePermissionEngine.Instance.Permissions ?? [];
884
+ return allPerms.filter((p) => p.Status === 'Approved' &&
885
+ UUIDsEqual(p.ResourceTypeID, PROJECTS_RESOURCE_TYPE_ID));
886
+ }
887
+ /**
888
+ * Approved `MJ: Projects` permission grants that apply to `user` (direct User grant or Role grant),
889
+ * reduced to the highest `PermissionLevel` per project ID.
890
+ */
891
+ getUserSharedProjectPermissions(user) {
892
+ if (!user?.ID)
893
+ return [];
894
+ const approved = this.getApprovedProjectPermissions();
895
+ const roleIdSet = new Set((user.UserRoles ?? [])
896
+ .map((ur) => ur.RoleID)
897
+ .filter((id) => !!id)
898
+ .map((id) => NormalizeUUID(id)));
899
+ const matching = approved.filter((p) => (p.Type === 'User' && !!p.UserID && UUIDsEqual(p.UserID, user.ID)) ||
900
+ (p.Type === 'Role' && !!p.RoleID && roleIdSet.has(NormalizeUUID(p.RoleID))));
901
+ const byProjectId = new Map();
902
+ for (const perm of matching) {
903
+ const key = NormalizeUUID(perm.ResourceRecordID);
904
+ const existing = byProjectId.get(key);
905
+ if (!existing) {
906
+ byProjectId.set(key, perm);
907
+ }
908
+ else {
909
+ const winner = ComparePermissionLevels(existing.PermissionLevel ?? 'View', perm.PermissionLevel ?? 'View');
910
+ if (winner !== (existing.PermissionLevel ?? 'View')) {
911
+ byProjectId.set(key, perm);
912
+ }
913
+ }
914
+ }
915
+ return [...byProjectId.values()];
916
+ }
917
+ /**
918
+ * Returns the three-tier visibility mode (`'Private' | 'Shared' | 'Public'`) for a folder:
919
+ * - `'Public'`: `OwnerUserID == null` (environment-wide)
920
+ * - `'Shared'`: `OwnerUserID != null` and the folder itself has approved `MJ: Resource Permissions` grants
921
+ * - `'Private'`: `OwnerUserID != null` with no active folder shares
922
+ *
923
+ * A subfolder is shared on its own: the server's read filter and write check look at a folder's own
924
+ * grants only, so this does too, and the tier shown is the access the server enforces.
925
+ */
926
+ GetProjectVisibilityTier(projectOrId) {
927
+ const project = typeof projectOrId === 'string'
928
+ ? this._projects$.value.find((p) => !!p.ID && UUIDsEqual(p.ID, projectOrId))
929
+ : projectOrId;
930
+ if (!project) {
931
+ return 'Private';
932
+ }
933
+ if (!project.OwnerUserID) {
934
+ return 'Public';
935
+ }
936
+ const shared = !!project.ID && this.getApprovedProjectPermissions().some((p) => UUIDsEqual(p.ResourceRecordID, project.ID));
937
+ return shared ? 'Shared' : 'Private';
938
+ }
939
+ /**
940
+ * Resolves the effective permission level (`'View' | 'Edit' | 'Owner'`) a user inherits from a folder.
941
+ * The folder's own grants only, not its ancestors', matching the server (see {@link GetProjectVisibilityTier}):
942
+ * - Public folders (`OwnerUserID == null`) grant at least `'View'` to everyone in the environment.
943
+ * - Shared folders grant the user's highest direct/role `MJ: Resource Permissions` level (`View`/`Edit`/`Owner`).
944
+ * - Folder owners also receive at least `'View'` on other users' inherited conversations placed in their Shared folder.
945
+ *
946
+ * Without a `contextUser`, it answers for the user the last folder or conversation load ran for, Role grants included.
947
+ */
948
+ GetEffectiveProjectPermission(projectId, contextUser) {
949
+ if (!projectId)
950
+ return null;
951
+ const viewer = contextUser ?? this._lastViewer;
952
+ const userId = viewer?.ID ?? this._lastConversationsUserId ?? this._lastProjectsUserId;
953
+ const normUserId = userId ? NormalizeUUID(userId) : null;
954
+ const userProjectPerms = this.getUserSharedProjectPermissions(viewer);
955
+ const userPermByProjectId = new Map(userProjectPerms.map((p) => [NormalizeUUID(p.ResourceRecordID), p]));
956
+ if (normUserId) {
957
+ for (const p of this.getApprovedProjectPermissions()) {
958
+ if (p.Type === 'User' && p.UserID && NormalizeUUID(p.UserID) === normUserId) {
959
+ const key = NormalizeUUID(p.ResourceRecordID);
960
+ const existing = userPermByProjectId.get(key);
961
+ if (!existing ||
962
+ ComparePermissionLevels(existing.PermissionLevel ?? 'View', p.PermissionLevel ?? 'View') !==
963
+ (existing.PermissionLevel ?? 'View')) {
964
+ userPermByProjectId.set(key, p);
965
+ }
966
+ }
967
+ }
968
+ }
969
+ const normProjectId = NormalizeUUID(projectId);
970
+ const proj = this._projects$.value.find((p) => !!p.ID && NormalizeUUID(p.ID) === normProjectId);
971
+ const directGrant = userPermByProjectId.get(normProjectId);
972
+ let bestLevel = null;
973
+ let sharedByUserId = null;
974
+ let sharedByUser = null;
975
+ if (directGrant) {
976
+ bestLevel = directGrant.PermissionLevel ?? 'View';
977
+ sharedByUserId = directGrant.SharedByUserID ?? proj?.OwnerUserID ?? null;
978
+ sharedByUser = directGrant.SharedByUser ?? proj?.OwnerUser ?? null;
979
+ }
980
+ if (proj) {
981
+ if (!proj.OwnerUserID) {
982
+ bestLevel = ComparePermissionLevels(bestLevel, 'View');
983
+ }
984
+ else if (userId && !UUIDsEqual(proj.OwnerUserID, userId)) {
985
+ // Folder owned by another user that is in our visible project list (shared with us)
986
+ bestLevel = ComparePermissionLevels(bestLevel, 'View');
987
+ sharedByUserId = sharedByUserId ?? proj.OwnerUserID;
988
+ sharedByUser = sharedByUser ?? proj.OwnerUser ?? null;
989
+ }
990
+ else if (userId && this.GetProjectVisibilityTier(proj) !== 'Private') {
991
+ // Folder owner viewing collaborators' conversations inside their Shared folder
992
+ bestLevel = ComparePermissionLevels(bestLevel, 'View');
993
+ }
994
+ }
995
+ if (!bestLevel) {
996
+ return null;
997
+ }
998
+ return {
999
+ Level: bestLevel,
1000
+ SharedByUserID: sharedByUserId,
1001
+ SharedByUser: sharedByUser
1002
+ };
1003
+ }
1004
+ /**
1005
+ * IDs of loaded folders in `environmentId` that share their conversations with participants:
1006
+ * - `'Public'` folders (`OwnerUserID IS NULL`)
1007
+ * - `'Shared'` folders (have approved `MJ: Resource Permissions` grants on the folder itself,
1008
+ * or are owned by another user and visible to the current viewer).
1009
+ */
1010
+ getSharedProjectIds(environmentId) {
1011
+ const viewerId = this._lastConversationsUserId ?? this._lastProjectsUserId;
1012
+ return this._projects$.value
1013
+ .filter((p) => {
1014
+ if (p.IsArchived)
1015
+ return false;
1016
+ if (p.EnvironmentID && !UUIDsEqual(p.EnvironmentID, environmentId))
1017
+ return false;
1018
+ if (!p.OwnerUserID)
1019
+ return true; // Public tier
1020
+ if (viewerId && !UUIDsEqual(p.OwnerUserID, viewerId))
1021
+ return true; // Shared with viewer by another owner
1022
+ return this.GetProjectVisibilityTier(p) !== 'Private';
1023
+ })
1024
+ .map((p) => p.ID)
1025
+ .filter((id) => !!id);
1026
+ }
1027
+ sameIdSet(a, b) {
1028
+ if (a.length !== b.length)
1029
+ return false;
1030
+ const setA = new Set(a.map((id) => NormalizeUUID(id)));
1031
+ return b.every((id) => setA.has(NormalizeUUID(id)));
555
1032
  }
556
1033
  /**
557
1034
  * Approved conversation grants (direct and role-inherited) for the user, from
@@ -561,17 +1038,30 @@ export class ConversationEngine extends BaseEngine {
561
1038
  await ResourcePermissionEngine.Instance.Config(false, contextUser);
562
1039
  return ResourcePermissionEngine.Instance.GetUserAvailableResources(contextUser, CONVERSATIONS_RESOURCE_TYPE_ID);
563
1040
  }
564
- buildVisibleConversationsFilter(environmentId, userId, sharedConversationIds, options) {
1041
+ buildVisibleConversationsFilter(environmentId, userId, sharedConversationIds, options, sharedProjectIds = []) {
565
1042
  const ownershipClause = `UserID='${userId}'`;
566
1043
  const sharedClause = sharedConversationIds.length > 0
567
- ? ` OR ID IN (${sharedConversationIds.map((id) => `'${id}'`).join(',')})`
1044
+ ? ` OR ID IN (${sharedConversationIds.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`
1045
+ : '';
1046
+ const sharedFolderClause = sharedProjectIds.length > 0
1047
+ ? ` OR (ProjectID IN (${sharedProjectIds.map((id) => `'${EscapeSQLString(id)}'`).join(',')}) AND ${INHERIT_FOLDER_ACCESS_SQL_CLAUSE})`
568
1048
  : '';
569
1049
  // The main chat view shows Global and Both. App-scoped conversations live inside
570
1050
  // their owning Application's embedded surface.
571
1051
  const scopeClause = options?.includeApplicationScoped
572
1052
  ? ''
573
1053
  : ` AND ApplicationScope IN ('Global', 'Both')`;
574
- return `EnvironmentID='${environmentId}' AND (${ownershipClause}${sharedClause}) AND (IsArchived IS NULL OR IsArchived=0)${scopeClause}`;
1054
+ // Anchored record/document comment threads live inside the target record's
1055
+ // comment drawer/popover and should not clutter the main Chat sidebar list.
1056
+ const anchorClause = options?.includeAnchored
1057
+ ? ''
1058
+ : ` AND AnchorType IS NULL`;
1059
+ // Record-bound AI conversations (e.g. "Ask AI" on an entity record form) stay
1060
+ // attached to their owning record and do not pollute the general-purpose Chat sidebar.
1061
+ const recordLinkedClause = options?.includeRecordLinked
1062
+ ? ''
1063
+ : ` AND LinkedEntityID IS NULL`;
1064
+ return `EnvironmentID='${environmentId}' AND (${ownershipClause}${sharedClause}${sharedFolderClause}) AND (IsArchived IS NULL OR IsArchived=0)${scopeClause}${anchorClause}${recordLinkedClause}`;
575
1065
  }
576
1066
  /**
577
1067
  * Populates {@link _sharedByByConversationId}. Resolves grantor emails via
@@ -616,14 +1106,13 @@ export class ConversationEngine extends BaseEngine {
616
1106
  * Loads the projects (conversation folders) visible to a user in an environment and
617
1107
  * emits via Projects$.
618
1108
  *
619
- * Visible means SHARED (OwnerUserID IS NULL — every folder that existed before
620
- * ownership was expressible) plus the user's OWN personal folders. A personal folder
621
- * never reaches anyone else's sidebar. The set is small, so it is cached whole;
622
- * reloading is skipped only when both the environment AND the user match, because the
623
- * read now depends on both.
1109
+ * Visible means:
1110
+ * - PUBLIC (`OwnerUserID IS NULL`),
1111
+ * - SHARED with the user or their roles via `MJ: Resource Permissions` (`PROJECTS_RESOURCE_TYPE_ID`), or
1112
+ * - PRIVATE/OWNED by the user (`OwnerUserID = contextUser.ID`).
624
1113
  *
625
1114
  * @param environmentId - The environment to filter projects by
626
- * @param contextUser - The current user context; also decides which personal folders load
1115
+ * @param contextUser - The current user context; also decides which personal/shared folders load
627
1116
  * @param forceRefresh - If true, reloads even if already cached for this environment/user
628
1117
  */
629
1118
  async LoadProjects(environmentId, contextUser, forceRefresh = false) {
@@ -633,9 +1122,10 @@ export class ConversationEngine extends BaseEngine {
633
1122
  && this._lastProjectsUserId === userId) {
634
1123
  return;
635
1124
  }
636
- // Shared folders, plus this user's own. One definition, shared with every other
637
- // list read of this entity — see BuildProjectVisibilityFilter.
638
- const ownership = BuildProjectVisibilityFilter(userId);
1125
+ await ResourcePermissionEngine.Instance.Config(false, contextUser);
1126
+ const sharedProjectIds = this.getUserSharedProjectPermissions(contextUser).map((p) => p.ResourceRecordID);
1127
+ // Public folders, folders shared with this user/role, plus this user's own.
1128
+ const ownership = BuildProjectVisibilityFilter(userId, sharedProjectIds);
639
1129
  const rv = new RunView();
640
1130
  const result = await rv.RunView({
641
1131
  EntityName: 'MJ: Projects',
@@ -654,6 +1144,7 @@ export class ConversationEngine extends BaseEngine {
654
1144
  if (result.Success) {
655
1145
  this._lastProjectsEnvironmentId = environmentId;
656
1146
  this._lastProjectsUserId = userId;
1147
+ this._lastViewer = contextUser ?? null;
657
1148
  this._projects$.next(result.Results || []);
658
1149
  }
659
1150
  else {
@@ -674,6 +1165,21 @@ export class ConversationEngine extends BaseEngine {
674
1165
  async MoveConversationToProject(conversationId, projectId, contextUser) {
675
1166
  return this.SaveConversation(conversationId, { ProjectID: projectId }, contextUser);
676
1167
  }
1168
+ /**
1169
+ * Enables or disables folder permission inheritance for a conversation (`inheritFolderAccess`
1170
+ * in `Conversation.AdditionalData`). It is off by default; while off, the conversation is restricted
1171
+ * to its owner and explicit conversation-level `MJ: Resource Permissions` grantees even when
1172
+ * placed inside a Shared or Public folder.
1173
+ */
1174
+ async SetConversationFolderInheritance(conversationId, inheritFolderAccess, contextUser) {
1175
+ const existing = this.GetConversation(conversationId);
1176
+ const updatedAdditionalData = BuildUpdatedAdditionalDataForFolderInheritance(existing?.AdditionalData, inheritFolderAccess);
1177
+ const saved = await this.SaveConversation(conversationId, { AdditionalData: updatedAdditionalData }, contextUser);
1178
+ if (saved) {
1179
+ this.reconcileFolderSharedConversations();
1180
+ }
1181
+ return saved;
1182
+ }
677
1183
  /**
678
1184
  * Creates a fork (an `MJ: Conversation Branches` row) started by `contextUser`. A fork before the
679
1185
  * first message shares nothing, so its parent is always Main. Never reads or writes the
@@ -762,10 +1268,15 @@ export class ConversationEngine extends BaseEngine {
762
1268
  }
763
1269
  }
764
1270
  const newParentId = project.ParentID ?? null;
765
- // 1. Unassign conversations directly in this folder
1271
+ // 1. Unassign conversations directly in this folder that the caller can edit.
1272
+ // View-only conversations owned by other users in a shared folder cannot be edited
1273
+ // by this caller; if any still exist in the DB, the delete below will surface
1274
+ // FK_Conversation_Project via ExplainProjectDeleteFailure.
766
1275
  const directConversations = this._conversations$.value.filter(c => c.ProjectID && UUIDsEqual(c.ProjectID, id));
767
1276
  for (const conv of directConversations) {
768
- await this.SaveConversation(conv.ID, { ProjectID: null }, contextUser);
1277
+ if (!contextUser?.ID || !conv.UserID || this.CanEditConversation(conv, contextUser.ID)) {
1278
+ await this.SaveConversation(conv.ID, { ProjectID: null }, contextUser);
1279
+ }
769
1280
  }
770
1281
  // 2. Reparent direct child folders one level up.
771
1282
  //
@@ -826,6 +1337,7 @@ export class ConversationEngine extends BaseEngine {
826
1337
  this._projects$.next(projectsBeforeDelete);
827
1338
  throw new Error(ExplainProjectDeleteFailure(project.LatestResult?.CompleteMessage));
828
1339
  }
1340
+ this.reconcileFolderSharedConversations();
829
1341
  return true;
830
1342
  }
831
1343
  /**
@@ -909,6 +1421,15 @@ export class ConversationEngine extends BaseEngine {
909
1421
  if (options?.linkedRecordId !== undefined) {
910
1422
  conversation.LinkedRecordID = options.linkedRecordId;
911
1423
  }
1424
+ if (options?.anchorType !== undefined) {
1425
+ conversation.AnchorType = options.anchorType;
1426
+ }
1427
+ if (options?.anchorKey !== undefined) {
1428
+ conversation.AnchorKey = options.anchorKey;
1429
+ }
1430
+ if (options?.anchorMetadata !== undefined) {
1431
+ conversation.AnchorMetadataObject = options.anchorMetadata;
1432
+ }
912
1433
  // Guard our own save event: the engine's BaseEntity event handler
913
1434
  // (handleConversationEntityEvent) ALSO prepends a conversation it doesn't yet
914
1435
  // hold. When the save event is dispatched synchronously during Save(), that
@@ -936,12 +1457,210 @@ export class ConversationEngine extends BaseEngine {
936
1457
  // out on next refresh.
937
1458
  // The GetConversation() check is belt-and-suspenders against a save event that
938
1459
  // slips past _selfMutating (e.g. async dispatch) — never add the same ID twice.
939
- if (conversation.ApplicationScope !== 'Application' && !this.GetConversation(conversation.ID)) {
1460
+ if (conversation.ApplicationScope !== 'Application' &&
1461
+ conversation.AnchorType == null &&
1462
+ conversation.LinkedEntityID == null &&
1463
+ !this.GetConversation(conversation.ID)) {
940
1464
  const updated = [conversation, ...this._conversations$.value];
941
1465
  this._conversations$.next(updated);
942
1466
  }
943
1467
  return conversation;
944
1468
  }
1469
+ /**
1470
+ * Loads non-anchored AI conversations (`AnchorType IS NULL`) bound to a specific
1471
+ * `(linkedEntityId, linkedRecordId)` for `contextUser`, ordered by most-recently updated.
1472
+ * Used by `<mj-chat-agents-overlay>` ("Ask AI") when a user opens an entity record form.
1473
+ */
1474
+ async LoadRecordConversations(linkedEntityId, linkedRecordId, contextUser, environmentId, provider) {
1475
+ const cleanEntityId = linkedEntityId?.trim();
1476
+ const cleanRecordId = linkedRecordId?.trim();
1477
+ if (!cleanEntityId || !cleanRecordId || !contextUser?.ID) {
1478
+ return [];
1479
+ }
1480
+ const md = provider ?? this.ProviderToUse;
1481
+ const rv = RunView.FromMetadataProvider(md);
1482
+ const safeEntityId = EscapeSQLString(cleanEntityId);
1483
+ const safeRecordId = EscapeSQLString(cleanRecordId);
1484
+ const safeUserId = EscapeSQLString(contextUser.ID);
1485
+ const envClause = environmentId?.trim()
1486
+ ? ` AND EnvironmentID='${EscapeSQLString(environmentId.trim())}'`
1487
+ : '';
1488
+ const result = await rv.RunView({
1489
+ EntityName: 'MJ: Conversations',
1490
+ ExtraFilter: `LinkedEntityID='${safeEntityId}'` +
1491
+ ` AND (LinkedRecordID='${safeRecordId}' OR LinkedRecordID='ID|${safeRecordId}')` +
1492
+ ` AND AnchorType IS NULL` +
1493
+ ` AND UserID='${safeUserId}'` +
1494
+ ` AND (IsArchived IS NULL OR IsArchived=0)` +
1495
+ envClause,
1496
+ OrderBy: '__mj_UpdatedAt DESC',
1497
+ MaxRows: 50,
1498
+ ResultType: 'entity_object'
1499
+ }, contextUser);
1500
+ return result.Success && result.Results ? result.Results : [];
1501
+ }
1502
+ // ========================================================================
1503
+ // ANCHORED RECORD CONVERSATIONS & COMMENT THREADS
1504
+ // ========================================================================
1505
+ /**
1506
+ * Loads all anchored conversations (`AnchorType IS NOT NULL`) attached to a specific
1507
+ * `(linkedEntityId, linkedRecordId)` that `contextUser` is authorized to see under both
1508
+ * row-level security (RLS on the linked record) and field-level security (FLS on the
1509
+ * anchored field or any `restrictedFields` stamped in `AnchorMetadataObject`).
1510
+ */
1511
+ async LoadAnchoredConversations(linkedEntityId, linkedRecordId, contextUser, options) {
1512
+ const provider = options?.provider ?? this.ProviderToUse;
1513
+ const clauses = [
1514
+ `LinkedEntityID='${EscapeSQLString(linkedEntityId)}'`,
1515
+ `LinkedRecordID='${EscapeSQLString(linkedRecordId)}'`,
1516
+ `AnchorType IS NOT NULL`,
1517
+ `(IsArchived IS NULL OR IsArchived=0)`
1518
+ ];
1519
+ if (options?.includeResolved === false) {
1520
+ clauses.push(`IsResolved=0`);
1521
+ }
1522
+ if (options?.anchorType) {
1523
+ clauses.push(`AnchorType='${EscapeSQLString(options.anchorType)}'`);
1524
+ }
1525
+ if (options?.anchorKey !== undefined) {
1526
+ clauses.push(`AnchorKey='${EscapeSQLString(options.anchorKey)}'`);
1527
+ }
1528
+ const rv = RunView.FromMetadataProvider(provider);
1529
+ const result = await rv.RunView({
1530
+ EntityName: 'MJ: Conversations',
1531
+ ExtraFilter: clauses.join(' AND '),
1532
+ OrderBy: 'IsResolved ASC, __mj_UpdatedAt DESC',
1533
+ ResultType: 'entity_object',
1534
+ BypassCache: options?.bypassCache ?? false
1535
+ }, contextUser);
1536
+ if (!result.Success || !result.Results) {
1537
+ return [];
1538
+ }
1539
+ return FilterAnchoredConversationsForUser(provider, contextUser, result.Results);
1540
+ }
1541
+ /**
1542
+ * Loads all `MJ: Conversation Details` rows for the given anchored conversation IDs,
1543
+ * grouped by normalized `ConversationID` in chronological `Sequence ASC, __mj_CreatedAt ASC` order.
1544
+ */
1545
+ async LoadAnchoredConversationDetails(conversationIds, contextUser, provider, bypassCache = false) {
1546
+ const byConversationId = new Map();
1547
+ const cleanIds = conversationIds.map(id => id?.trim()).filter((id) => !!id);
1548
+ if (cleanIds.length === 0) {
1549
+ return byConversationId;
1550
+ }
1551
+ for (const id of cleanIds) {
1552
+ byConversationId.set(NormalizeUUID(id), []);
1553
+ }
1554
+ const md = provider ?? this.ProviderToUse;
1555
+ const rv = RunView.FromMetadataProvider(md);
1556
+ const inList = cleanIds.map(id => `'${EscapeSQLString(id)}'`).join(',');
1557
+ const result = await rv.RunView({
1558
+ EntityName: 'MJ: Conversation Details',
1559
+ ExtraFilter: `ConversationID IN (${inList}) AND (HiddenToUser IS NULL OR HiddenToUser=0) AND ReplacedAt IS NULL`,
1560
+ OrderBy: 'Sequence ASC, __mj_CreatedAt ASC',
1561
+ ResultType: 'entity_object',
1562
+ BypassCache: bypassCache
1563
+ }, contextUser);
1564
+ if (result.Success && result.Results) {
1565
+ for (const detail of result.Results) {
1566
+ const key = NormalizeUUID(detail.ConversationID);
1567
+ const list = byConversationId.get(key) ?? [];
1568
+ list.push(detail);
1569
+ byConversationId.set(key, list);
1570
+ }
1571
+ }
1572
+ return byConversationId;
1573
+ }
1574
+ /**
1575
+ * Creates a new anchored comment thread (`MJ: Conversations` with `AnchorType`, `AnchorKey`,
1576
+ * and `AnchorMetadataObject`) bound to `(linkedEntityId, linkedRecordId)`, and optionally
1577
+ * posts the opening `MJ: Conversation Details` message.
1578
+ */
1579
+ async CreateAnchoredConversation(params, contextUser) {
1580
+ const md = params.provider ?? this.ProviderToUse;
1581
+ const conversation = await md.GetEntityObject('MJ: Conversations', contextUser);
1582
+ conversation.NewRecord();
1583
+ const fallbackName = params.anchorMetadata?.anchorDisplayName
1584
+ || params.anchorMetadata?.sectionDisplayName
1585
+ || params.anchorMetadata?.groupDisplayName
1586
+ || params.anchorKey
1587
+ || `${params.anchorType} Comment`;
1588
+ conversation.Name = (params.name?.trim() || fallbackName).slice(0, 255);
1589
+ if (params.environmentId) {
1590
+ conversation.EnvironmentID = params.environmentId;
1591
+ }
1592
+ else if (this._lastEnvironmentId) {
1593
+ conversation.EnvironmentID = this._lastEnvironmentId;
1594
+ }
1595
+ conversation.UserID = contextUser.ID;
1596
+ conversation.ApplicationScope = 'Global';
1597
+ conversation.LinkedEntityID = params.linkedEntityId;
1598
+ conversation.LinkedRecordID = params.linkedRecordId;
1599
+ conversation.AnchorType = params.anchorType;
1600
+ conversation.AnchorKey = params.anchorKey ?? null;
1601
+ conversation.AnchorMetadataObject = params.anchorMetadata ?? null;
1602
+ if (params.defaultAgentId !== undefined) {
1603
+ conversation.DefaultAgentID = params.defaultAgentId;
1604
+ }
1605
+ this._selfMutating = true;
1606
+ try {
1607
+ const saved = await conversation.Save();
1608
+ if (!saved) {
1609
+ throw new Error(conversation.LatestResult?.CompleteMessage || conversation.LatestResult?.Message || 'Failed to create anchored conversation');
1610
+ }
1611
+ }
1612
+ finally {
1613
+ this._selfMutating = false;
1614
+ }
1615
+ let initialDetail = null;
1616
+ const messageText = params.initialMessage?.trim();
1617
+ if (messageText) {
1618
+ initialDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
1619
+ initialDetail.NewRecord();
1620
+ initialDetail.ConversationID = conversation.ID;
1621
+ initialDetail.UserID = contextUser.ID;
1622
+ initialDetail.Role = 'User';
1623
+ initialDetail.Message = messageText;
1624
+ const detailSaved = await initialDetail.Save();
1625
+ if (!detailSaved) {
1626
+ throw new Error(initialDetail.LatestResult?.CompleteMessage || initialDetail.LatestResult?.Message || 'Failed to save initial comment message');
1627
+ }
1628
+ }
1629
+ return { Conversation: conversation, InitialDetail: initialDetail };
1630
+ }
1631
+ /**
1632
+ * Marks an anchored conversation thread as resolved or re-opened (`IsResolved`,
1633
+ * `ResolvedByUserID`, `ResolvedAt`).
1634
+ */
1635
+ async SetConversationResolved(conversationId, isResolved, contextUser, provider) {
1636
+ const md = provider ?? this.ProviderToUse;
1637
+ const conversation = await md.GetEntityObject('MJ: Conversations', contextUser);
1638
+ const loaded = await conversation.Load(conversationId);
1639
+ if (!loaded) {
1640
+ throw new Error(`Conversation ${conversationId} not found`);
1641
+ }
1642
+ conversation.IsResolved = isResolved;
1643
+ conversation.ResolvedByUserID = isResolved ? contextUser.ID : null;
1644
+ conversation.ResolvedAt = isResolved ? new Date() : null;
1645
+ this._selfMutating = true;
1646
+ try {
1647
+ const saved = await conversation.Save();
1648
+ if (!saved) {
1649
+ throw new Error(conversation.LatestResult?.CompleteMessage || conversation.LatestResult?.Message || 'Failed to update conversation resolution status');
1650
+ }
1651
+ }
1652
+ finally {
1653
+ this._selfMutating = false;
1654
+ }
1655
+ return conversation;
1656
+ }
1657
+ /**
1658
+ * Computes open and resolved anchored comment counts across fields, sections, groups,
1659
+ * and contributions for a record, respecting FLS for `currentUser`.
1660
+ */
1661
+ ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo) {
1662
+ return ComputeAnchoredCommentCounts(conversations, currentUser, entityInfo);
1663
+ }
945
1664
  /**
946
1665
  * Folds a conversation that was created OUTSIDE this engine (e.g. server-side by a
947
1666
  * realtime-session mint, which never fires a client BaseEntity event) into the cached
@@ -971,9 +1690,11 @@ export class ConversationEngine extends BaseEngine {
971
1690
  if (!loaded) {
972
1691
  return null;
973
1692
  }
974
- // App-scoped conversations live inside their owning Application's embedded surface,
975
- // not the main-chat list this engine caches — mirror CreateConversation and skip them.
976
- if (conversation.ApplicationScope === 'Application') {
1693
+ // App-scoped, anchored, and record-bound conversations live inside their owning
1694
+ // surface, not the main-chat list this engine caches — mirror CreateConversation and skip them.
1695
+ if (conversation.ApplicationScope === 'Application' ||
1696
+ conversation.AnchorType != null ||
1697
+ conversation.LinkedEntityID != null) {
977
1698
  return conversation;
978
1699
  }
979
1700
  // Re-check under the loaded row in case a concurrent emit added it meanwhile.
@@ -2728,9 +3449,13 @@ export class ConversationEngine extends BaseEngine {
2728
3449
  this._conversations$.next([]);
2729
3450
  this._projects$.next([]);
2730
3451
  this._detailCache.clear();
3452
+ this._sharedByByConversationId.clear();
3453
+ this._explicitSharedConversationIds.clear();
2731
3454
  this._lastEnvironmentId = null;
3455
+ this._lastConversationsUserId = null;
2732
3456
  this._lastProjectsEnvironmentId = null;
2733
3457
  this._lastProjectsUserId = null;
3458
+ this._lastViewer = null;
2734
3459
  }
2735
3460
  // ========================================================================
2736
3461
  // CONVERSATION DETAIL CRUD
@@ -3015,6 +3740,7 @@ export class ConversationEngine extends BaseEngine {
3015
3740
  if (existing) {
3016
3741
  this.mergeDataOntoRecord(existing, data);
3017
3742
  this._conversations$.next([...this._conversations$.value]);
3743
+ this.reconcileFolderSharedConversations();
3018
3744
  }
3019
3745
  else if (event.baseEntity) {
3020
3746
  // A conversation created OUTSIDE this engine (local save event) that we don't
@@ -3023,18 +3749,26 @@ export class ConversationEngine extends BaseEngine {
3023
3749
  // app-scoped rows live in their owning surface (see CreateConversation), and
3024
3750
  // archived rows don't belong in the active list.
3025
3751
  const scope = data['ApplicationScope'];
3752
+ const anchorType = data['AnchorType'];
3753
+ const linkedEntityId = data['LinkedEntityID'];
3026
3754
  const environmentId = data['EnvironmentID'];
3027
3755
  const isArchived = data['IsArchived'] === true;
3028
3756
  const inLoadedEnvironment = !this._lastEnvironmentId ||
3029
3757
  (environmentId != null && UUIDsEqual(environmentId, this._lastEnvironmentId));
3030
- if (scope !== 'Application' && !isArchived && inLoadedEnvironment) {
3758
+ if (scope !== 'Application' &&
3759
+ anchorType == null &&
3760
+ linkedEntityId == null &&
3761
+ !isArchived &&
3762
+ inLoadedEnvironment) {
3031
3763
  this._conversations$.next([event.baseEntity, ...this._conversations$.value]);
3764
+ this.reconcileFolderSharedConversations();
3032
3765
  }
3033
3766
  }
3034
3767
  }
3035
3768
  else if (action === 'delete') {
3036
3769
  const existing = this.GetConversation(id);
3037
3770
  if (existing) {
3771
+ this._sharedByByConversationId.delete(NormalizeUUID(id));
3038
3772
  this.removeFromList(id);
3039
3773
  this.removeDetailCache(id);
3040
3774
  }
@@ -3099,6 +3833,7 @@ export class ConversationEngine extends BaseEngine {
3099
3833
  if (action === 'delete') {
3100
3834
  if (existingIdx >= 0) {
3101
3835
  this._projects$.next(current.filter(p => !UUIDsEqual(p.ID, id)));
3836
+ this.reconcileFolderSharedConversations();
3102
3837
  }
3103
3838
  return true;
3104
3839
  }
@@ -3141,9 +3876,11 @@ export class ConversationEngine extends BaseEngine {
3141
3876
  // folder in the environment — widening on absent input is the failure mode worth
3142
3877
  // avoiding, and it is the same rule the read path applies.
3143
3878
  const ownerUserId = data['OwnerUserID'];
3879
+ const viewerId = this._lastProjectsUserId ?? this._lastConversationsUserId;
3880
+ const hasProjectGrant = this.getUserSharedProjectPermissions(this._lastViewer).some((p) => UUIDsEqual(p.ResourceRecordID, id));
3144
3881
  const isVisibleToViewer = ownerUserId == null || ownerUserId === ''
3145
3882
  ? true
3146
- : !!this._lastProjectsUserId && UUIDsEqual(ownerUserId, this._lastProjectsUserId);
3883
+ : (!!viewerId && UUIDsEqual(ownerUserId, viewerId)) || hasProjectGrant;
3147
3884
  const belongsInList = !isArchived && inLoadedEnvironment && isVisibleToViewer;
3148
3885
  if (existingIdx >= 0) {
3149
3886
  if (!belongsInList) {
@@ -3153,13 +3890,74 @@ export class ConversationEngine extends BaseEngine {
3153
3890
  this.mergeDataOntoRecord(current[existingIdx], data);
3154
3891
  this._projects$.next([...current]);
3155
3892
  }
3893
+ this.reconcileFolderSharedConversations();
3156
3894
  }
3157
3895
  else if (event.baseEntity && belongsInList) {
3158
3896
  // New folder from a local event — append the entity object
3159
3897
  this._projects$.next([...current, event.baseEntity]);
3898
+ this.reconcileFolderSharedConversations();
3160
3899
  }
3161
3900
  return true;
3162
3901
  }
3902
+ /**
3903
+ * Keeps folder-shared conversations in `_conversations$` and `_sharedByByConversationId`
3904
+ * aligned with the currently loaded Shared/Public folders and each conversation's
3905
+ * {@link IsInheritingFolderAccess} setting:
3906
+ * - Non-owned conversations without an explicit `MJ: Resource Permissions` grant that sit
3907
+ * inside a visible Shared/Public folder (and have folder inheritance enabled) get a
3908
+ * `SharedByInfo` entry with the viewer's inherited folder permission level.
3909
+ * - Non-owned conversations without an explicit grant whose folder is no longer a visible
3910
+ * Shared/Public folder or whose `inheritFolderAccess` was turned off are dropped from
3911
+ * `_conversations$` and `_sharedByByConversationId`.
3912
+ */
3913
+ reconcileFolderSharedConversations() {
3914
+ const viewerUserId = this._lastConversationsUserId ?? this._lastProjectsUserId;
3915
+ if (!viewerUserId) {
3916
+ return;
3917
+ }
3918
+ const envId = this._lastEnvironmentId ?? this._lastProjectsEnvironmentId ?? '';
3919
+ const sharedProjectIdSet = new Set(this.getSharedProjectIds(envId).map((id) => NormalizeUUID(id)));
3920
+ const currentConversations = this._conversations$.value;
3921
+ const keptConversations = [];
3922
+ let listChanged = false;
3923
+ for (const conv of currentConversations) {
3924
+ const normId = NormalizeUUID(conv.ID);
3925
+ const isOwned = !conv.UserID || UUIDsEqual(conv.UserID, viewerUserId);
3926
+ const isExplicitlyShared = this._explicitSharedConversationIds.has(normId);
3927
+ if (isOwned || isExplicitlyShared) {
3928
+ keptConversations.push(conv);
3929
+ continue;
3930
+ }
3931
+ const inSharedFolder = !!conv.ProjectID &&
3932
+ IsInheritingFolderAccess(conv) &&
3933
+ sharedProjectIdSet.has(NormalizeUUID(conv.ProjectID));
3934
+ if (inSharedFolder) {
3935
+ keptConversations.push(conv);
3936
+ const inherited = this.GetEffectiveProjectPermission(conv.ProjectID, this._lastViewer);
3937
+ const existingShare = this._sharedByByConversationId.get(normId);
3938
+ if (!existingShare) {
3939
+ const convWithUser = conv;
3940
+ this._sharedByByConversationId.set(normId, {
3941
+ UserID: conv.UserID ?? inherited?.SharedByUserID ?? null,
3942
+ Name: convWithUser.User ?? inherited?.SharedByUser ?? null,
3943
+ Email: null,
3944
+ Level: inherited?.Level ?? 'View'
3945
+ });
3946
+ }
3947
+ else if (inherited?.Level) {
3948
+ existingShare.Level = ComparePermissionLevels(existingShare.Level, inherited.Level) ?? 'View';
3949
+ }
3950
+ }
3951
+ else {
3952
+ listChanged = true;
3953
+ this._sharedByByConversationId.delete(normId);
3954
+ this.removeDetailCache(conv.ID);
3955
+ }
3956
+ }
3957
+ if (listChanged) {
3958
+ this._conversations$.next(keptConversations);
3959
+ }
3960
+ }
3163
3961
  /**
3164
3962
  * Handles save/delete events on AI Agent Run entities from local or remote code.
3165
3963
  * Updates the AgentRunsByDetailId map so timers and status reflect reality.