@memberjunction/core-entities 6.2.0-edge.6 → 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.
- package/dist/.tsbuildinfo +1 -1
- package/dist/custom/AnchoredConversationSecurity.d.ts +103 -0
- package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -0
- package/dist/custom/AnchoredConversationSecurity.js +401 -0
- package/dist/custom/AnchoredConversationSecurity.js.map +1 -0
- package/dist/custom/ConversationWriteAccess.d.ts +11 -3
- package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
- package/dist/custom/ConversationWriteAccess.js +100 -9
- package/dist/custom/ConversationWriteAccess.js.map +1 -1
- package/dist/custom/MJConversationDetailEntityExtended.d.ts.map +1 -1
- package/dist/custom/MJConversationDetailEntityExtended.js +18 -1
- package/dist/custom/MJConversationDetailEntityExtended.js.map +1 -1
- package/dist/custom/MJProjectEntityExtended.d.ts +12 -0
- package/dist/custom/MJProjectEntityExtended.d.ts.map +1 -0
- package/dist/custom/MJProjectEntityExtended.js +35 -0
- package/dist/custom/MJProjectEntityExtended.js.map +1 -0
- package/dist/custom/MJQueryEntityExtended.d.ts +56 -14
- package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
- package/dist/custom/MJQueryEntityExtended.js +99 -15
- package/dist/custom/MJQueryEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +3 -0
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +2 -0
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/index.d.ts +1 -0
- package/dist/custom/Permissions/index.d.ts.map +1 -1
- package/dist/custom/Permissions/index.js +1 -0
- package/dist/custom/Permissions/index.js.map +1 -1
- package/dist/custom/Permissions/mentionNotification.d.ts +64 -0
- package/dist/custom/Permissions/mentionNotification.d.ts.map +1 -0
- package/dist/custom/Permissions/mentionNotification.js +315 -0
- package/dist/custom/Permissions/mentionNotification.js.map +1 -0
- package/dist/custom/QueryDiagnostics.d.ts +66 -0
- package/dist/custom/QueryDiagnostics.d.ts.map +1 -0
- package/dist/custom/QueryDiagnostics.js +84 -0
- package/dist/custom/QueryDiagnostics.js.map +1 -0
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +12 -4
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
- package/dist/custom/ResourcePermissions/ResourcePermissionEngine.d.ts.map +1 -1
- package/dist/custom/ResourcePermissions/ResourcePermissionEngine.js +11 -2
- package/dist/custom/ResourcePermissions/ResourcePermissionEngine.js.map +1 -1
- package/dist/engines/BrandKitEngine.d.ts +77 -0
- package/dist/engines/BrandKitEngine.d.ts.map +1 -0
- package/dist/engines/BrandKitEngine.js +199 -0
- package/dist/engines/BrandKitEngine.js.map +1 -0
- package/dist/engines/QueryEngine.d.ts +22 -4
- package/dist/engines/QueryEngine.d.ts.map +1 -1
- package/dist/engines/QueryEngine.js +61 -8
- package/dist/engines/QueryEngine.js.map +1 -1
- package/dist/engines/RemoteOperationEngineBase.d.ts +5 -0
- package/dist/engines/RemoteOperationEngineBase.d.ts.map +1 -1
- package/dist/engines/RemoteOperationEngineBase.js +21 -1
- package/dist/engines/RemoteOperationEngineBase.js.map +1 -1
- package/dist/engines/VideoStudioEngine.d.ts +28 -0
- package/dist/engines/VideoStudioEngine.d.ts.map +1 -0
- package/dist/engines/VideoStudioEngine.js +75 -0
- package/dist/engines/VideoStudioEngine.js.map +1 -0
- package/dist/engines/component-metadata.d.ts.map +1 -1
- package/dist/engines/component-metadata.js +1 -0
- package/dist/engines/component-metadata.js.map +1 -1
- package/dist/engines/conversations.d.ts +327 -14
- package/dist/engines/conversations.d.ts.map +1 -1
- package/dist/engines/conversations.js +919 -52
- package/dist/engines/conversations.js.map +1 -1
- package/dist/engines/interactive-forms.d.ts.map +1 -1
- package/dist/engines/interactive-forms.js +1 -0
- package/dist/engines/interactive-forms.js.map +1 -1
- package/dist/generated/entities/__mj.d.ts +11147 -7017
- package/dist/generated/entities/__mj.d.ts.map +1 -1
- package/dist/generated/entities/__mj.js +5792 -555
- package/dist/generated/entities/__mj.js.map +1 -1
- package/dist/generated/remote_operations.d.ts +450 -0
- package/dist/generated/remote_operations.d.ts.map +1 -1
- package/dist/generated/remote_operations.js +288 -0
- package/dist/generated/remote_operations.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,20 +1,222 @@
|
|
|
1
1
|
import { BaseEngine, EntityEventRowIsFree, ResolveEntityEventKey, ResolveEntityEventRow, RunQuery, RunView, TransformSimpleObjectToEntityObject } from "@memberjunction/core";
|
|
2
|
-
import { EscapeSQLString, NormalizeUUID, ToEpochMs, UUIDsEqual } from "@memberjunction/global";
|
|
2
|
+
import { EscapeSQLString, IndexByUUID, NormalizeUUID, ToEpochMs, UUIDMap, UUIDSet, UUIDsEqual } from "@memberjunction/global";
|
|
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
|
|
15
217
|
* from the assembler's requirements.
|
|
16
218
|
*/
|
|
17
|
-
export const ConversationWindowFields = ['ID', 'Sequence', 'Role', 'Message', 'SummaryOfEarlierConversation', '__mj_CreatedAt', 'ReplacedAt'];
|
|
219
|
+
export const ConversationWindowFields = ['ID', 'Sequence', 'Role', 'Message', 'SummaryOfEarlierConversation', '__mj_CreatedAt', 'ReplacedAt', 'UserID', 'User', 'AgentID', 'Agent', 'ParentID'];
|
|
18
220
|
/** The fork kinds, keyed by {@link ForkKind} so a value CodeGen adds to the union fails to compile until it is listed. */
|
|
19
221
|
const FORK_KIND_KEYS = { Fork: true, Edit: true, Regenerate: true };
|
|
20
222
|
/** True when `value` is a key of {@link FORK_KIND_KEYS}. */
|
|
@@ -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
|
-
|
|
272
|
-
|
|
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
|
|
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
|
|
440
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
523
|
-
//
|
|
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(
|
|
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
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
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
|
|
543
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
620
|
-
*
|
|
621
|
-
*
|
|
622
|
-
*
|
|
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
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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
|
-
|
|
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' &&
|
|
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
|
|
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.
|
|
@@ -1576,6 +2297,7 @@ export class ConversationEngine extends BaseEngine {
|
|
|
1576
2297
|
ExtraFilter: `${pathFilter} AND Sequence < ${oldestSequence}`,
|
|
1577
2298
|
OrderBy: 'Sequence DESC',
|
|
1578
2299
|
MaxRows: 1,
|
|
2300
|
+
SkipTotalRowCount: true,
|
|
1579
2301
|
Fields: ['ID'],
|
|
1580
2302
|
ResultType: 'simple'
|
|
1581
2303
|
}, contextUser);
|
|
@@ -2057,12 +2779,13 @@ export class ConversationEngine extends BaseEngine {
|
|
|
2057
2779
|
.filter(d => !excluded.has(NormalizeUUID(d.ID)) && !ConversationEngine.IsReplacedRow(d))
|
|
2058
2780
|
.filter(d => !floor || ConversationEngine.isAtOrAfter(d.__mj_CreatedAt, floor))
|
|
2059
2781
|
.sort((a, b) => a.Sequence - b.Sequence);
|
|
2782
|
+
const attribution = ConversationEngine.buildSpeakerAttribution(ordered, options);
|
|
2060
2783
|
const boundary = floor ? undefined : ConversationEngine.findSummaryBoundary(ordered);
|
|
2061
2784
|
if (boundary) {
|
|
2062
2785
|
const tail = ordered.filter(d => d.Sequence >= boundary.Sequence);
|
|
2063
|
-
return [ConversationEngine.buildSummaryMessage(boundary), ...tail.map(d => ConversationEngine.detailToContextMessage(d))];
|
|
2786
|
+
return [ConversationEngine.buildSummaryMessage(boundary), ...tail.map(d => ConversationEngine.detailToContextMessage(d, attribution))];
|
|
2064
2787
|
}
|
|
2065
|
-
const all = ordered.map(d => ConversationEngine.detailToContextMessage(d));
|
|
2788
|
+
const all = ordered.map(d => ConversationEngine.detailToContextMessage(d, attribution));
|
|
2066
2789
|
const cap = options?.maxTailMessages;
|
|
2067
2790
|
return cap && all.length > cap ? all.slice(-cap) : all;
|
|
2068
2791
|
}
|
|
@@ -2519,17 +3242,84 @@ export class ConversationEngine extends BaseEngine {
|
|
|
2519
3242
|
}
|
|
2520
3243
|
};
|
|
2521
3244
|
}
|
|
2522
|
-
/** Converts a raw ConversationDetail row into a context message with sequence metadata. */
|
|
2523
|
-
static detailToContextMessage(detail) {
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
3245
|
+
/** Converts a raw ConversationDetail row into a context message with sequence and speaker metadata. */
|
|
3246
|
+
static detailToContextMessage(detail, attribution) {
|
|
3247
|
+
const role = ConversationEngine.mapDetailRoleToChatRole(detail.Role);
|
|
3248
|
+
const raw = detail.Message || '';
|
|
3249
|
+
const content = ConversationEngine.formatAttributedMessageContent(detail, role, attribution);
|
|
3250
|
+
const metadata = {
|
|
3251
|
+
sequence: detail.Sequence,
|
|
3252
|
+
conversationDetailId: detail.ID,
|
|
3253
|
+
...(content !== raw ? { rawContent: raw } : {}),
|
|
3254
|
+
...(detail.UserID !== undefined ? { userId: detail.UserID } : {}),
|
|
3255
|
+
...(detail.User !== undefined ? { userName: detail.User } : {}),
|
|
3256
|
+
...(detail.AgentID !== undefined ? { agentId: detail.AgentID } : {}),
|
|
3257
|
+
...(detail.Agent !== undefined ? { agentName: detail.Agent } : {}),
|
|
3258
|
+
...(detail.ParentID !== undefined ? { parentId: detail.ParentID } : {}),
|
|
3259
|
+
};
|
|
3260
|
+
return { role, content, metadata };
|
|
3261
|
+
}
|
|
3262
|
+
/** Builds speaker attribution state for a context window assembly pass. */
|
|
3263
|
+
static buildSpeakerAttribution(ordered, options) {
|
|
3264
|
+
const mode = options?.speakerAttribution ?? 'auto';
|
|
3265
|
+
const labelsById = new UUIDMap();
|
|
3266
|
+
for (const [key, value] of options?.speakerLabels ?? []) {
|
|
3267
|
+
if (key && value?.trim()) {
|
|
3268
|
+
labelsById.Set(key, value.trim());
|
|
2530
3269
|
}
|
|
3270
|
+
}
|
|
3271
|
+
const distinctUsers = new UUIDSet();
|
|
3272
|
+
const distinctAgents = new UUIDSet();
|
|
3273
|
+
for (const d of ordered) {
|
|
3274
|
+
const role = ConversationEngine.mapDetailRoleToChatRole(d.Role);
|
|
3275
|
+
if (role === 'user' && d.UserID) {
|
|
3276
|
+
distinctUsers.Add(d.UserID);
|
|
3277
|
+
}
|
|
3278
|
+
else if (role === 'assistant' && d.AgentID) {
|
|
3279
|
+
distinctAgents.Add(d.AgentID);
|
|
3280
|
+
}
|
|
3281
|
+
}
|
|
3282
|
+
const rowsById = IndexByUUID(ordered);
|
|
3283
|
+
const hasMultipleHumans = distinctUsers.Size > 1 || labelsById.Size > 0;
|
|
3284
|
+
return {
|
|
3285
|
+
attributeUsers: mode === 'always' || (mode === 'auto' && hasMultipleHumans),
|
|
3286
|
+
attributeAgents: mode === 'always' || (mode === 'auto' && hasMultipleHumans && distinctAgents.Size > 1),
|
|
3287
|
+
labelsById,
|
|
3288
|
+
rowsById,
|
|
2531
3289
|
};
|
|
2532
3290
|
}
|
|
3291
|
+
/** Formats message content with `[Speaker]: ` or `[Speaker -> replying to Target]: ` when speaker attribution applies. */
|
|
3292
|
+
static formatAttributedMessageContent(detail, role, attribution) {
|
|
3293
|
+
const raw = detail.Message || '';
|
|
3294
|
+
if (!attribution) {
|
|
3295
|
+
return raw;
|
|
3296
|
+
}
|
|
3297
|
+
const speaker = role === 'user' && attribution.attributeUsers
|
|
3298
|
+
? ConversationEngine.speakerLabelForRow(detail, attribution.labelsById)
|
|
3299
|
+
: role === 'assistant' && attribution.attributeAgents
|
|
3300
|
+
? ConversationEngine.speakerLabelForRow(detail, attribution.labelsById)
|
|
3301
|
+
: null;
|
|
3302
|
+
if (!speaker) {
|
|
3303
|
+
return raw;
|
|
3304
|
+
}
|
|
3305
|
+
const parentRow = detail.ParentID ? attribution.rowsById.Get(detail.ParentID) : undefined;
|
|
3306
|
+
const parentSpeaker = parentRow ? ConversationEngine.speakerLabelForRow(parentRow, attribution.labelsById) : null;
|
|
3307
|
+
const header = parentSpeaker ? `[${speaker} -> replying to ${parentSpeaker}]` : `[${speaker}]`;
|
|
3308
|
+
return `${header}: ${raw}`;
|
|
3309
|
+
}
|
|
3310
|
+
/** Resolves a display name for a row's author (human or agent). */
|
|
3311
|
+
static speakerLabelForRow(row, labelsById) {
|
|
3312
|
+
const role = ConversationEngine.mapDetailRoleToChatRole(row.Role);
|
|
3313
|
+
if (role === 'assistant') {
|
|
3314
|
+
const custom = row.AgentID ? labelsById.Get(row.AgentID) : undefined;
|
|
3315
|
+
return custom || row.Agent?.trim() || null;
|
|
3316
|
+
}
|
|
3317
|
+
if (role === 'user') {
|
|
3318
|
+
const custom = row.UserID ? labelsById.Get(row.UserID) : undefined;
|
|
3319
|
+
return custom || row.User?.trim() || null;
|
|
3320
|
+
}
|
|
3321
|
+
return null;
|
|
3322
|
+
}
|
|
2533
3323
|
/**
|
|
2534
3324
|
* Maps `ConversationDetail.Role` values to ChatMessage roles. Mirrors the mapping the
|
|
2535
3325
|
* server resolver has always used for history assembly ('AI'/'Agent' → assistant,
|
|
@@ -2659,9 +3449,13 @@ export class ConversationEngine extends BaseEngine {
|
|
|
2659
3449
|
this._conversations$.next([]);
|
|
2660
3450
|
this._projects$.next([]);
|
|
2661
3451
|
this._detailCache.clear();
|
|
3452
|
+
this._sharedByByConversationId.clear();
|
|
3453
|
+
this._explicitSharedConversationIds.clear();
|
|
2662
3454
|
this._lastEnvironmentId = null;
|
|
3455
|
+
this._lastConversationsUserId = null;
|
|
2663
3456
|
this._lastProjectsEnvironmentId = null;
|
|
2664
3457
|
this._lastProjectsUserId = null;
|
|
3458
|
+
this._lastViewer = null;
|
|
2665
3459
|
}
|
|
2666
3460
|
// ========================================================================
|
|
2667
3461
|
// CONVERSATION DETAIL CRUD
|
|
@@ -2946,6 +3740,7 @@ export class ConversationEngine extends BaseEngine {
|
|
|
2946
3740
|
if (existing) {
|
|
2947
3741
|
this.mergeDataOntoRecord(existing, data);
|
|
2948
3742
|
this._conversations$.next([...this._conversations$.value]);
|
|
3743
|
+
this.reconcileFolderSharedConversations();
|
|
2949
3744
|
}
|
|
2950
3745
|
else if (event.baseEntity) {
|
|
2951
3746
|
// A conversation created OUTSIDE this engine (local save event) that we don't
|
|
@@ -2954,18 +3749,26 @@ export class ConversationEngine extends BaseEngine {
|
|
|
2954
3749
|
// app-scoped rows live in their owning surface (see CreateConversation), and
|
|
2955
3750
|
// archived rows don't belong in the active list.
|
|
2956
3751
|
const scope = data['ApplicationScope'];
|
|
3752
|
+
const anchorType = data['AnchorType'];
|
|
3753
|
+
const linkedEntityId = data['LinkedEntityID'];
|
|
2957
3754
|
const environmentId = data['EnvironmentID'];
|
|
2958
3755
|
const isArchived = data['IsArchived'] === true;
|
|
2959
3756
|
const inLoadedEnvironment = !this._lastEnvironmentId ||
|
|
2960
3757
|
(environmentId != null && UUIDsEqual(environmentId, this._lastEnvironmentId));
|
|
2961
|
-
if (scope !== 'Application' &&
|
|
3758
|
+
if (scope !== 'Application' &&
|
|
3759
|
+
anchorType == null &&
|
|
3760
|
+
linkedEntityId == null &&
|
|
3761
|
+
!isArchived &&
|
|
3762
|
+
inLoadedEnvironment) {
|
|
2962
3763
|
this._conversations$.next([event.baseEntity, ...this._conversations$.value]);
|
|
3764
|
+
this.reconcileFolderSharedConversations();
|
|
2963
3765
|
}
|
|
2964
3766
|
}
|
|
2965
3767
|
}
|
|
2966
3768
|
else if (action === 'delete') {
|
|
2967
3769
|
const existing = this.GetConversation(id);
|
|
2968
3770
|
if (existing) {
|
|
3771
|
+
this._sharedByByConversationId.delete(NormalizeUUID(id));
|
|
2969
3772
|
this.removeFromList(id);
|
|
2970
3773
|
this.removeDetailCache(id);
|
|
2971
3774
|
}
|
|
@@ -3030,6 +3833,7 @@ export class ConversationEngine extends BaseEngine {
|
|
|
3030
3833
|
if (action === 'delete') {
|
|
3031
3834
|
if (existingIdx >= 0) {
|
|
3032
3835
|
this._projects$.next(current.filter(p => !UUIDsEqual(p.ID, id)));
|
|
3836
|
+
this.reconcileFolderSharedConversations();
|
|
3033
3837
|
}
|
|
3034
3838
|
return true;
|
|
3035
3839
|
}
|
|
@@ -3072,9 +3876,11 @@ export class ConversationEngine extends BaseEngine {
|
|
|
3072
3876
|
// folder in the environment — widening on absent input is the failure mode worth
|
|
3073
3877
|
// avoiding, and it is the same rule the read path applies.
|
|
3074
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));
|
|
3075
3881
|
const isVisibleToViewer = ownerUserId == null || ownerUserId === ''
|
|
3076
3882
|
? true
|
|
3077
|
-
: !!
|
|
3883
|
+
: (!!viewerId && UUIDsEqual(ownerUserId, viewerId)) || hasProjectGrant;
|
|
3078
3884
|
const belongsInList = !isArchived && inLoadedEnvironment && isVisibleToViewer;
|
|
3079
3885
|
if (existingIdx >= 0) {
|
|
3080
3886
|
if (!belongsInList) {
|
|
@@ -3084,13 +3890,74 @@ export class ConversationEngine extends BaseEngine {
|
|
|
3084
3890
|
this.mergeDataOntoRecord(current[existingIdx], data);
|
|
3085
3891
|
this._projects$.next([...current]);
|
|
3086
3892
|
}
|
|
3893
|
+
this.reconcileFolderSharedConversations();
|
|
3087
3894
|
}
|
|
3088
3895
|
else if (event.baseEntity && belongsInList) {
|
|
3089
3896
|
// New folder from a local event — append the entity object
|
|
3090
3897
|
this._projects$.next([...current, event.baseEntity]);
|
|
3898
|
+
this.reconcileFolderSharedConversations();
|
|
3091
3899
|
}
|
|
3092
3900
|
return true;
|
|
3093
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
|
+
}
|
|
3094
3961
|
/**
|
|
3095
3962
|
* Handles save/delete events on AI Agent Run entities from local or remote code.
|
|
3096
3963
|
* Updates the AgentRunsByDetailId map so timers and status reflect reality.
|