@open-mercato/search 0.10.1-develop.7601.1.e057b693a8 → 0.10.1-develop.7614.1.75d5ac1a6a
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/modules/search/ai-tools.js +48 -3
- package/dist/modules/search/ai-tools.js.map +2 -2
- package/dist/modules/search/frontend/components/sections/VectorSearchSection.js +37 -4
- package/dist/modules/search/frontend/components/sections/VectorSearchSection.js.map +2 -2
- package/dist/modules/search/i18n/de.json +2 -0
- package/dist/modules/search/i18n/en.json +2 -0
- package/dist/modules/search/i18n/es.json +2 -0
- package/dist/modules/search/i18n/ko.json +2 -0
- package/dist/modules/search/i18n/pl.json +2 -0
- package/package.json +4 -4
- package/src/modules/search/__tests__/ai-tools.aggregate.test.ts +94 -4
- package/src/modules/search/__tests__/ai-tools.get.test.ts +101 -4
- package/src/modules/search/__tests__/ai-tools.query.test.ts +122 -0
- package/src/modules/search/ai-tools.ts +72 -3
- package/src/modules/search/frontend/components/sections/VectorSearchSection.tsx +43 -6
- package/src/modules/search/frontend/components/sections/__tests__/VectorSearchSection.test.tsx +123 -1
- package/src/modules/search/i18n/de.json +2 -0
- package/src/modules/search/i18n/en.json +2 -0
- package/src/modules/search/i18n/es.json +2 -0
- package/src/modules/search/i18n/ko.json +2 -0
- package/src/modules/search/i18n/pl.json +2 -0
|
@@ -14,7 +14,13 @@ const PERSON_CONFIG = {
|
|
|
14
14
|
|
|
15
15
|
function makeCtx(
|
|
16
16
|
record: Record<string, unknown> | undefined,
|
|
17
|
-
overrides: {
|
|
17
|
+
overrides: {
|
|
18
|
+
userFeatures?: string[]
|
|
19
|
+
isSuperAdmin?: boolean
|
|
20
|
+
userId?: string | null
|
|
21
|
+
organizationId?: string | null
|
|
22
|
+
orgScope?: { em: unknown; rbacService: unknown }
|
|
23
|
+
} = {},
|
|
18
24
|
) {
|
|
19
25
|
const items = record ? [record] : []
|
|
20
26
|
const mockQuery = jest.fn().mockResolvedValue({ items, total: items.length })
|
|
@@ -25,17 +31,52 @@ function makeCtx(
|
|
|
25
31
|
}
|
|
26
32
|
const ctx = {
|
|
27
33
|
tenantId: 'tenant-1',
|
|
28
|
-
organizationId: 'org-1',
|
|
29
|
-
userId:
|
|
34
|
+
organizationId: overrides.organizationId !== undefined ? overrides.organizationId : 'org-1',
|
|
35
|
+
userId: overrides.userId !== undefined ? overrides.userId : 'user-1',
|
|
30
36
|
userFeatures: overrides.userFeatures ?? ['customers.people.view'],
|
|
31
37
|
isSuperAdmin: overrides.isSuperAdmin ?? false,
|
|
32
38
|
container: {
|
|
33
|
-
resolve: (name: string) =>
|
|
39
|
+
resolve: (name: string) => {
|
|
40
|
+
if (name === 'searchIndexer') return searchIndexer
|
|
41
|
+
if (name === 'em') {
|
|
42
|
+
if (overrides.orgScope) return overrides.orgScope.em
|
|
43
|
+
throw new Error('em not mocked')
|
|
44
|
+
}
|
|
45
|
+
if (name === 'rbacService') {
|
|
46
|
+
if (overrides.orgScope) return overrides.orgScope.rbacService
|
|
47
|
+
throw new Error('rbacService not mocked')
|
|
48
|
+
}
|
|
49
|
+
return { query: mockQuery }
|
|
50
|
+
},
|
|
34
51
|
},
|
|
35
52
|
}
|
|
36
53
|
return { ctx, mockQuery }
|
|
37
54
|
}
|
|
38
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Builds a real `em`/`rbacService` pair so `resolveActorOrganizationScope`
|
|
58
|
+
* (issue #7808) runs the full `resolveOrganizationScopeForRequest` resolution
|
|
59
|
+
* instead of its no-DI fallback — needed to assert the organization
|
|
60
|
+
* allowlist is actually enforced (not just the caller's single current org).
|
|
61
|
+
*/
|
|
62
|
+
function makeOrgScopeResolver(options: { aclOrganizations: string[] | null; isSuperAdmin?: boolean; knownOrgIds?: string[] }) {
|
|
63
|
+
const em = {
|
|
64
|
+
find: jest.fn(async (_entity: unknown, filter: { id?: { $in: string[] } }) => {
|
|
65
|
+
const ids = filter?.id?.$in ?? []
|
|
66
|
+
const known = new Set(options.knownOrgIds ?? ['org-1', 'org-2', 'org-3'])
|
|
67
|
+
return ids.filter((id) => known.has(id)).map((id) => ({ id, descendantIds: [] }))
|
|
68
|
+
}),
|
|
69
|
+
}
|
|
70
|
+
const rbacService = {
|
|
71
|
+
loadAcl: jest.fn(async () => ({
|
|
72
|
+
isSuperAdmin: options.isSuperAdmin ?? false,
|
|
73
|
+
features: [],
|
|
74
|
+
organizations: options.aclOrganizations,
|
|
75
|
+
})),
|
|
76
|
+
}
|
|
77
|
+
return { em, rbacService }
|
|
78
|
+
}
|
|
79
|
+
|
|
39
80
|
describe('search_get tool', () => {
|
|
40
81
|
it('denies callers holding only search.view without the per-entity view feature', async () => {
|
|
41
82
|
const { ctx, mockQuery } = makeCtx(
|
|
@@ -116,4 +157,60 @@ describe('search_get tool', () => {
|
|
|
116
157
|
getTool.handler({ entityType: 'customers:customer_person_profile', recordId: 'rec-1' }, noTenantCtx),
|
|
117
158
|
).rejects.toThrow('Tenant context is required')
|
|
118
159
|
})
|
|
160
|
+
|
|
161
|
+
describe('org-allowlist enforcement (issue #7808)', () => {
|
|
162
|
+
it('scopes a restricted user with no current org to their organization allowlist', async () => {
|
|
163
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: ['org-2', 'org-3'] })
|
|
164
|
+
const { ctx, mockQuery } = makeCtx(
|
|
165
|
+
{ id: 'rec-1', first_name: 'Jane' },
|
|
166
|
+
{ organizationId: null, orgScope },
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
const result = await getTool.handler(
|
|
170
|
+
{ entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
|
|
171
|
+
ctx,
|
|
172
|
+
) as { found: boolean }
|
|
173
|
+
|
|
174
|
+
expect(result.found).toBe(true)
|
|
175
|
+
expect(mockQuery).toHaveBeenCalledWith(
|
|
176
|
+
'customers:customer_person_profile',
|
|
177
|
+
expect.objectContaining({ organizationIds: ['org-2', 'org-3'] }),
|
|
178
|
+
)
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
it('denies a restricted user whose allowlist is explicitly empty, without querying', async () => {
|
|
182
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: [] })
|
|
183
|
+
const { ctx, mockQuery } = makeCtx(
|
|
184
|
+
{ id: 'rec-1', first_name: 'Jane' },
|
|
185
|
+
{ organizationId: null, orgScope },
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
const result = await getTool.handler(
|
|
189
|
+
{ entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
|
|
190
|
+
ctx,
|
|
191
|
+
) as { found: boolean; error?: string }
|
|
192
|
+
|
|
193
|
+
expect(result.found).toBe(false)
|
|
194
|
+
expect(mockQuery).not.toHaveBeenCalled()
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
it('leaves a superadmin unfiltered regardless of the ACL allowlist', async () => {
|
|
198
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: [], isSuperAdmin: true })
|
|
199
|
+
const { ctx, mockQuery } = makeCtx(
|
|
200
|
+
{ id: 'rec-1', first_name: 'Jane' },
|
|
201
|
+
{ organizationId: null, isSuperAdmin: true, userFeatures: [], orgScope },
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
const result = await getTool.handler(
|
|
205
|
+
{ entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
|
|
206
|
+
ctx,
|
|
207
|
+
) as { found: boolean }
|
|
208
|
+
|
|
209
|
+
expect(result.found).toBe(true)
|
|
210
|
+
expect(mockQuery).toHaveBeenCalledWith(
|
|
211
|
+
'customers:customer_person_profile',
|
|
212
|
+
expect.objectContaining({ organizationIds: undefined }),
|
|
213
|
+
)
|
|
214
|
+
})
|
|
215
|
+
})
|
|
119
216
|
})
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression coverage for `search_query` (issue #7808): the AI search tool
|
|
3
|
+
* must enforce the caller's allowed-organization allowlist, not just their
|
|
4
|
+
* current `organizationId`, mirroring the HTTP search route.
|
|
5
|
+
*/
|
|
6
|
+
import { aiTools } from '../ai-tools'
|
|
7
|
+
|
|
8
|
+
const queryTool = aiTools.find((t) => t.name === 'search_query')
|
|
9
|
+
if (!queryTool) throw new Error('search_query tool not found in aiTools — was it renamed?')
|
|
10
|
+
|
|
11
|
+
function makeOrgScopeResolver(options: { aclOrganizations: string[] | null; isSuperAdmin?: boolean; knownOrgIds?: string[] }) {
|
|
12
|
+
const em = {
|
|
13
|
+
find: jest.fn(async (_entity: unknown, filter: { id?: { $in: string[] } }) => {
|
|
14
|
+
const ids = filter?.id?.$in ?? []
|
|
15
|
+
const known = new Set(options.knownOrgIds ?? ['org-1', 'org-2', 'org-3'])
|
|
16
|
+
return ids.filter((id) => known.has(id)).map((id) => ({ id, descendantIds: [] }))
|
|
17
|
+
}),
|
|
18
|
+
}
|
|
19
|
+
const rbacService = {
|
|
20
|
+
loadAcl: jest.fn(async () => ({
|
|
21
|
+
isSuperAdmin: options.isSuperAdmin ?? false,
|
|
22
|
+
features: [],
|
|
23
|
+
organizations: options.aclOrganizations,
|
|
24
|
+
})),
|
|
25
|
+
}
|
|
26
|
+
return { em, rbacService }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function makeCtx(overrides: {
|
|
30
|
+
userFeatures?: string[]
|
|
31
|
+
isSuperAdmin?: boolean
|
|
32
|
+
userId?: string | null
|
|
33
|
+
organizationId?: string | null
|
|
34
|
+
orgScope?: { em: unknown; rbacService: unknown }
|
|
35
|
+
} = {}) {
|
|
36
|
+
const mockSearch = jest.fn().mockResolvedValue([
|
|
37
|
+
{ entityId: 'catalog:product', recordId: 'c1', score: 0.8, source: 'fulltext', presenter: { title: 'Widget' } },
|
|
38
|
+
])
|
|
39
|
+
const searchIndexer = {
|
|
40
|
+
getEntityConfig: (entityId: string) =>
|
|
41
|
+
entityId === 'catalog:product' ? { aclFeatures: ['catalog.products.view'], enabled: true } : undefined,
|
|
42
|
+
getAllEntityConfigs: () => [{ entityId: 'catalog:product', aclFeatures: ['catalog.products.view'], enabled: true }],
|
|
43
|
+
}
|
|
44
|
+
const ctx = {
|
|
45
|
+
tenantId: 'tenant-1',
|
|
46
|
+
organizationId: overrides.organizationId !== undefined ? overrides.organizationId : 'org-1',
|
|
47
|
+
userId: overrides.userId !== undefined ? overrides.userId : 'user-1',
|
|
48
|
+
userFeatures: overrides.userFeatures ?? ['search.global', 'catalog.products.view'],
|
|
49
|
+
isSuperAdmin: overrides.isSuperAdmin ?? false,
|
|
50
|
+
container: {
|
|
51
|
+
resolve: (name: string) => {
|
|
52
|
+
if (name === 'searchIndexer') return searchIndexer
|
|
53
|
+
if (name === 'searchService') return { search: mockSearch }
|
|
54
|
+
if (name === 'em') {
|
|
55
|
+
if (overrides.orgScope) return overrides.orgScope.em
|
|
56
|
+
throw new Error('em not mocked')
|
|
57
|
+
}
|
|
58
|
+
if (name === 'rbacService') {
|
|
59
|
+
if (overrides.orgScope) return overrides.orgScope.rbacService
|
|
60
|
+
throw new Error('rbacService not mocked')
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`unexpected resolve ${name}`)
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
return { ctx, mockSearch }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
describe('search_query tool', () => {
|
|
70
|
+
it('throws when tenantId is missing', async () => {
|
|
71
|
+
const { ctx } = makeCtx()
|
|
72
|
+
const noTenantCtx = { ...ctx, tenantId: null }
|
|
73
|
+
|
|
74
|
+
await expect(queryTool.handler({ query: 'widget' }, noTenantCtx)).rejects.toThrow(/Tenant context/)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('returns results for an unrestricted (no-allowlist) caller', async () => {
|
|
78
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: null })
|
|
79
|
+
const { ctx, mockSearch } = makeCtx({ orgScope })
|
|
80
|
+
|
|
81
|
+
const result = await queryTool.handler({ query: 'widget' }, ctx) as { totalResults: number }
|
|
82
|
+
|
|
83
|
+
expect(result.totalResults).toBe(1)
|
|
84
|
+
expect(mockSearch).toHaveBeenCalledWith('widget', expect.objectContaining({ organizationIds: ['org-1'] }))
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
describe('org-allowlist enforcement (issue #7808)', () => {
|
|
88
|
+
it('scopes a restricted user with no current org to their organization allowlist', async () => {
|
|
89
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: ['org-2', 'org-3'] })
|
|
90
|
+
const { ctx, mockSearch } = makeCtx({ organizationId: null, orgScope })
|
|
91
|
+
|
|
92
|
+
const result = await queryTool.handler({ query: 'widget' }, ctx) as { totalResults: number }
|
|
93
|
+
|
|
94
|
+
expect(result.totalResults).toBe(1)
|
|
95
|
+
expect(mockSearch).toHaveBeenCalledWith(
|
|
96
|
+
'widget',
|
|
97
|
+
expect.objectContaining({ organizationIds: ['org-2', 'org-3'] }),
|
|
98
|
+
)
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it('denies a restricted user whose allowlist is explicitly empty, without calling search', async () => {
|
|
102
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: [] })
|
|
103
|
+
const { ctx, mockSearch } = makeCtx({ organizationId: null, orgScope })
|
|
104
|
+
|
|
105
|
+
const result = await queryTool.handler({ query: 'widget' }, ctx) as { totalResults: number; results: unknown[] }
|
|
106
|
+
|
|
107
|
+
expect(mockSearch).not.toHaveBeenCalled()
|
|
108
|
+
expect(result.totalResults).toBe(0)
|
|
109
|
+
expect(result.results).toEqual([])
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it('leaves a superadmin unfiltered regardless of the ACL allowlist', async () => {
|
|
113
|
+
const orgScope = makeOrgScopeResolver({ aclOrganizations: [], isSuperAdmin: true })
|
|
114
|
+
const { ctx, mockSearch } = makeCtx({ organizationId: null, isSuperAdmin: true, userFeatures: [], orgScope })
|
|
115
|
+
|
|
116
|
+
const result = await queryTool.handler({ query: 'widget' }, ctx) as { totalResults: number }
|
|
117
|
+
|
|
118
|
+
expect(result.totalResults).toBe(1)
|
|
119
|
+
expect(mockSearch).toHaveBeenCalledWith('widget', expect.objectContaining({ organizationIds: undefined }))
|
|
120
|
+
})
|
|
121
|
+
})
|
|
122
|
+
})
|
|
@@ -10,6 +10,10 @@ import {
|
|
|
10
10
|
resolveReadableEntityTypes,
|
|
11
11
|
type SearchEntityConfigLookup,
|
|
12
12
|
} from './lib/entity-access'
|
|
13
|
+
import { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
|
|
14
|
+
import { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'
|
|
15
|
+
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
16
|
+
import type { AwilixContainer } from 'awilix'
|
|
13
17
|
|
|
14
18
|
/**
|
|
15
19
|
* AI Tools definitions for the Search module.
|
|
@@ -112,6 +116,43 @@ function authorizeEntityAccess(entityType: string, ctx: ToolContext): SearchEnti
|
|
|
112
116
|
return config
|
|
113
117
|
}
|
|
114
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Resolve the actor's allowed-organization scope the same way the HTTP search
|
|
121
|
+
* route does, so AI search tools can never return results outside a
|
|
122
|
+
* restricted user's organization allowlist — even when their current
|
|
123
|
+
* organization is null. Mirrors packages/search/.../api/search/route.ts.
|
|
124
|
+
*
|
|
125
|
+
* `organizationId` is the re-validated selection (`scope.selectedId`), not the
|
|
126
|
+
* raw `ctx.organizationId` — `SearchOptions.organizationId` takes precedence
|
|
127
|
+
* over `organizationIds` in `normalizeOrganizationFilter`, so passing the
|
|
128
|
+
* unvalidated context value through would let a stale/out-of-allowlist
|
|
129
|
+
* selection bypass the allowlist below.
|
|
130
|
+
*/
|
|
131
|
+
async function resolveActorOrganizationScope(ctx: ToolContext): Promise<{
|
|
132
|
+
organizationId: string | undefined
|
|
133
|
+
organizationIds: string[] | undefined
|
|
134
|
+
denyAll: boolean
|
|
135
|
+
}> {
|
|
136
|
+
if (!ctx.userId) return { organizationId: undefined, organizationIds: undefined, denyAll: true }
|
|
137
|
+
const auth: AuthContext = {
|
|
138
|
+
sub: ctx.userId,
|
|
139
|
+
tenantId: ctx.tenantId,
|
|
140
|
+
orgId: ctx.organizationId,
|
|
141
|
+
isSuperAdmin: ctx.isSuperAdmin,
|
|
142
|
+
}
|
|
143
|
+
const scope = await resolveOrganizationScopeForRequest({
|
|
144
|
+
container: ctx.container as unknown as AwilixContainer,
|
|
145
|
+
auth,
|
|
146
|
+
selectedId: ctx.organizationId,
|
|
147
|
+
})
|
|
148
|
+
const scopeFilter = resolveOrganizationScopeFilter(scope, auth)
|
|
149
|
+
const denyAll = Array.isArray(scope.filterIds) && scope.filterIds.length === 0
|
|
150
|
+
const organizationId = typeof scope.selectedId === 'string' && scope.selectedId.trim().length > 0
|
|
151
|
+
? scope.selectedId.trim()
|
|
152
|
+
: undefined
|
|
153
|
+
return { organizationId, organizationIds: scopeFilter.organizationIds, denyAll }
|
|
154
|
+
}
|
|
155
|
+
|
|
115
156
|
/**
|
|
116
157
|
* Strip fields that the entity's field policy marks as sensitive
|
|
117
158
|
* (`hashOnly` exact-match PII or fully `excluded`) from a query-engine record.
|
|
@@ -202,9 +243,15 @@ Searches customers, products, orders, deals, and more in one call.`,
|
|
|
202
243
|
return { query: input.query, totalResults: 0, results: [] }
|
|
203
244
|
}
|
|
204
245
|
|
|
246
|
+
const orgScope = await resolveActorOrganizationScope(ctx)
|
|
247
|
+
if (orgScope.denyAll) {
|
|
248
|
+
return { query: input.query, totalResults: 0, results: [] }
|
|
249
|
+
}
|
|
250
|
+
|
|
205
251
|
const rawResults = await searchService.search(input.query, {
|
|
206
252
|
tenantId: ctx.tenantId,
|
|
207
|
-
organizationId:
|
|
253
|
+
organizationId: orgScope.organizationId,
|
|
254
|
+
organizationIds: orgScope.organizationIds,
|
|
208
255
|
entityTypes: readableEntityTypes,
|
|
209
256
|
strategies: input.strategies as SearchStrategyId[],
|
|
210
257
|
limit: input.limit,
|
|
@@ -287,13 +334,24 @@ const searchGetTool: AiToolDefinition = {
|
|
|
287
334
|
|
|
288
335
|
const entityConfig = authorizeEntityAccess(input.entityType, ctx)
|
|
289
336
|
|
|
337
|
+
const orgScope = await resolveActorOrganizationScope(ctx)
|
|
338
|
+
if (orgScope.denyAll) {
|
|
339
|
+
return {
|
|
340
|
+
found: false,
|
|
341
|
+
entityType: input.entityType,
|
|
342
|
+
recordId: input.recordId,
|
|
343
|
+
error: 'Record not found',
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
290
347
|
const queryEngine = ctx.container.resolve<{
|
|
291
348
|
query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>
|
|
292
349
|
}>('queryEngine')
|
|
293
350
|
|
|
294
351
|
const result = await queryEngine.query(input.entityType, {
|
|
295
352
|
tenantId: ctx.tenantId,
|
|
296
|
-
organizationId:
|
|
353
|
+
organizationId: orgScope.organizationId,
|
|
354
|
+
organizationIds: orgScope.organizationIds,
|
|
297
355
|
filters: { id: input.recordId },
|
|
298
356
|
includeCustomFields: true,
|
|
299
357
|
page: { page: 1, pageSize: 1 },
|
|
@@ -457,6 +515,16 @@ const searchAggregateTool: AiToolDefinition = {
|
|
|
457
515
|
)
|
|
458
516
|
}
|
|
459
517
|
|
|
518
|
+
const orgScope = await resolveActorOrganizationScope(ctx)
|
|
519
|
+
if (orgScope.denyAll) {
|
|
520
|
+
return {
|
|
521
|
+
entityType: input.entityType,
|
|
522
|
+
groupBy: input.groupBy,
|
|
523
|
+
total: 0,
|
|
524
|
+
buckets: [],
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
460
528
|
const queryEngine = ctx.container.resolve<{
|
|
461
529
|
query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>
|
|
462
530
|
}>('queryEngine')
|
|
@@ -465,7 +533,8 @@ const searchAggregateTool: AiToolDefinition = {
|
|
|
465
533
|
// Note: For large datasets, this should use database GROUP BY
|
|
466
534
|
const result = await queryEngine.query(input.entityType, {
|
|
467
535
|
tenantId: ctx.tenantId,
|
|
468
|
-
organizationId:
|
|
536
|
+
organizationId: orgScope.organizationId,
|
|
537
|
+
organizationIds: orgScope.organizationIds,
|
|
469
538
|
page: { page: 1, pageSize: 100 },
|
|
470
539
|
})
|
|
471
540
|
|
|
@@ -182,6 +182,11 @@ export type VectorSearchSectionProps = {
|
|
|
182
182
|
onRefreshEmbeddings: () => Promise<void>
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
function flashRequestError(err: unknown, fallbackMessage: string) {
|
|
186
|
+
const message = err instanceof Error && err.message.trim() ? err.message : fallbackMessage
|
|
187
|
+
flash(message, 'error')
|
|
188
|
+
}
|
|
189
|
+
|
|
185
190
|
export function VectorSearchSection({
|
|
186
191
|
embeddingSettings,
|
|
187
192
|
embeddingLoading,
|
|
@@ -200,6 +205,7 @@ export function VectorSearchSection({
|
|
|
200
205
|
const [selectedModel, setSelectedModel] = React.useState<string | null>(null)
|
|
201
206
|
const [customModelName, setCustomModelName] = React.useState<string>('')
|
|
202
207
|
const [customDimension, setCustomDimension] = React.useState<number>(768)
|
|
208
|
+
const [ollamaBaseUrlDraft, setOllamaBaseUrlDraft] = React.useState<string | null>(null)
|
|
203
209
|
|
|
204
210
|
const [pendingEmbeddingConfig, setPendingEmbeddingConfig] = React.useState<EmbeddingProviderConfig | null>(null)
|
|
205
211
|
const [showEmbeddingConfirmDialog, setShowEmbeddingConfirmDialog] = React.useState(false)
|
|
@@ -282,7 +288,8 @@ export function VectorSearchSection({
|
|
|
282
288
|
autoIndexingPreviousRef.current = body.settings.autoIndexingEnabled
|
|
283
289
|
}
|
|
284
290
|
flash(t('search.settings.messages.saved', 'Settings saved'), 'success')
|
|
285
|
-
} catch {
|
|
291
|
+
} catch (err) {
|
|
292
|
+
flashRequestError(err, t('search.settings.errors.saveFailed', 'Failed to save settings'))
|
|
286
293
|
if (embeddingSettings) {
|
|
287
294
|
onEmbeddingSettingsUpdate({ ...embeddingSettings, autoIndexingEnabled: autoIndexingPreviousRef.current })
|
|
288
295
|
}
|
|
@@ -297,6 +304,7 @@ export function VectorSearchSection({
|
|
|
297
304
|
setSelectedModel(null)
|
|
298
305
|
setCustomModelName('')
|
|
299
306
|
setCustomDimension(768)
|
|
307
|
+
setOllamaBaseUrlDraft(null)
|
|
300
308
|
}
|
|
301
309
|
|
|
302
310
|
const handleModelChange = (modelId: string) => {
|
|
@@ -334,6 +342,10 @@ export function VectorSearchSection({
|
|
|
334
342
|
dimension,
|
|
335
343
|
updatedAt: new Date().toISOString(),
|
|
336
344
|
}
|
|
345
|
+
const ollamaBaseUrl = (ollamaBaseUrlDraft ?? savedOllamaBaseUrl).trim()
|
|
346
|
+
if (newProviderId === 'ollama' && ollamaBaseUrl) {
|
|
347
|
+
newConfig.baseUrl = ollamaBaseUrl
|
|
348
|
+
}
|
|
337
349
|
|
|
338
350
|
if (embeddingSettings?.indexedDimension || embeddingSettings?.embeddingConfig) {
|
|
339
351
|
setPendingEmbeddingConfig(newConfig)
|
|
@@ -348,6 +360,7 @@ export function VectorSearchSection({
|
|
|
348
360
|
setSelectedModel(null)
|
|
349
361
|
setCustomModelName('')
|
|
350
362
|
setCustomDimension(768)
|
|
363
|
+
setOllamaBaseUrlDraft(null)
|
|
351
364
|
}
|
|
352
365
|
|
|
353
366
|
const applyEmbeddingConfig = async (config: EmbeddingProviderConfig) => {
|
|
@@ -367,10 +380,11 @@ export function VectorSearchSection({
|
|
|
367
380
|
)
|
|
368
381
|
setSelectedProvider(null)
|
|
369
382
|
setSelectedModel(null)
|
|
383
|
+
setOllamaBaseUrlDraft(null)
|
|
370
384
|
flash(t('search.settings.messages.providerSaved', 'Embedding provider saved'), 'success')
|
|
371
385
|
await onRefreshEmbeddings()
|
|
372
|
-
} catch {
|
|
373
|
-
|
|
386
|
+
} catch (err) {
|
|
387
|
+
flashRequestError(err, t('search.settings.errors.saveFailed', 'Failed to save settings'))
|
|
374
388
|
} finally {
|
|
375
389
|
setEmbeddingSaving(false)
|
|
376
390
|
}
|
|
@@ -407,8 +421,8 @@ export function VectorSearchSection({
|
|
|
407
421
|
)
|
|
408
422
|
flash(t('search.settings.messages.reindexStarted', 'Reindex started'), 'success')
|
|
409
423
|
await fetchActivityLogs()
|
|
410
|
-
} catch {
|
|
411
|
-
|
|
424
|
+
} catch (err) {
|
|
425
|
+
flashRequestError(err, t('search.settings.errors.reindexFailed', 'Reindex failed'))
|
|
412
426
|
} finally {
|
|
413
427
|
setVectorReindexing(false)
|
|
414
428
|
}
|
|
@@ -423,6 +437,7 @@ export function VectorSearchSection({
|
|
|
423
437
|
const savedProviderInfo = EMBEDDING_PROVIDERS[savedProvider]
|
|
424
438
|
const savedModel = embeddingSettings?.embeddingConfig?.model ?? savedProviderInfo.defaultModel
|
|
425
439
|
const savedDimension = embeddingSettings?.embeddingConfig?.dimension ?? savedProviderInfo.models[0]?.dimension ?? 768
|
|
440
|
+
const savedOllamaBaseUrl = savedProvider === 'ollama' ? embeddingSettings?.embeddingConfig?.baseUrl ?? '' : ''
|
|
426
441
|
|
|
427
442
|
const savedModelIsPredefined = savedProviderInfo.models.some((m) => m.id === savedModel)
|
|
428
443
|
const savedCustomModel = !savedModelIsPredefined && savedModel ? { id: savedModel, name: savedModel, dimension: savedDimension } : null
|
|
@@ -444,7 +459,8 @@ export function VectorSearchSection({
|
|
|
444
459
|
const hasUnsavedEmbeddingChanges = (selectedProvider !== null && selectedProvider !== savedProvider) ||
|
|
445
460
|
(selectedModel !== null && selectedModel !== savedModel) ||
|
|
446
461
|
(selectedProvider !== null && selectedModel === null && displayProviderInfo.defaultModel !== savedModel) ||
|
|
447
|
-
(isCustomModel && (customModelName.trim() !== '' || customDimension !== 768))
|
|
462
|
+
(isCustomModel && (customModelName.trim() !== '' || customDimension !== 768)) ||
|
|
463
|
+
(displayProvider === 'ollama' && ollamaBaseUrlDraft !== null && ollamaBaseUrlDraft.trim() !== savedOllamaBaseUrl)
|
|
448
464
|
|
|
449
465
|
const isEmbeddingConfigured = embeddingSettings?.configuredProviders?.includes(savedProvider)
|
|
450
466
|
const providerOptions: EmbeddingProviderId[] = ['openai', 'google', 'mistral', 'cohere', 'bedrock', 'ollama']
|
|
@@ -687,6 +703,27 @@ export function VectorSearchSection({
|
|
|
687
703
|
</Select>
|
|
688
704
|
</div>
|
|
689
705
|
|
|
706
|
+
{providerId === 'ollama' && (
|
|
707
|
+
<div className="space-y-1">
|
|
708
|
+
<Label htmlFor="ollama-base-url" className="text-xs font-medium">
|
|
709
|
+
{t('search.settings.ollama.baseUrl.label', 'Base URL')}
|
|
710
|
+
</Label>
|
|
711
|
+
<Input
|
|
712
|
+
id="ollama-base-url"
|
|
713
|
+
type="url"
|
|
714
|
+
size="sm"
|
|
715
|
+
value={ollamaBaseUrlDraft ?? savedOllamaBaseUrl}
|
|
716
|
+
onChange={(e) => setOllamaBaseUrlDraft(e.target.value)}
|
|
717
|
+
placeholder="http://localhost:11434"
|
|
718
|
+
aria-describedby="ollama-base-url-hint"
|
|
719
|
+
disabled={embeddingLoading || embeddingSaving}
|
|
720
|
+
/>
|
|
721
|
+
<p id="ollama-base-url-hint" className="text-xs text-muted-foreground">
|
|
722
|
+
{t('search.settings.ollama.baseUrl.hint', 'Leave empty to use the OLLAMA_BASE_URL environment variable.')}
|
|
723
|
+
</p>
|
|
724
|
+
</div>
|
|
725
|
+
)}
|
|
726
|
+
|
|
690
727
|
{isCustomModel && (
|
|
691
728
|
<div className="space-y-2 rounded border border-input bg-muted/30 p-2">
|
|
692
729
|
<div className="space-y-1">
|
package/src/modules/search/frontend/components/sections/__tests__/VectorSearchSection.test.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** @jest-environment jsdom */
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
-
import { fireEvent, render, screen } from '@testing-library/react'
|
|
4
|
+
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
5
5
|
import { I18nProvider } from '@open-mercato/shared/lib/i18n/context'
|
|
6
6
|
import {
|
|
7
7
|
VectorSearchSection,
|
|
@@ -12,6 +12,18 @@ jest.mock('@open-mercato/ui/backend/injection/useAppEvent', () => ({
|
|
|
12
12
|
useAppEvent: jest.fn(),
|
|
13
13
|
}))
|
|
14
14
|
|
|
15
|
+
const readApiResultOrThrowMock = jest.fn()
|
|
16
|
+
|
|
17
|
+
jest.mock('@open-mercato/ui/backend/utils/apiCall', () => ({
|
|
18
|
+
readApiResultOrThrow: (...args: unknown[]) => readApiResultOrThrowMock(...args),
|
|
19
|
+
}))
|
|
20
|
+
|
|
21
|
+
const flashMock = jest.fn()
|
|
22
|
+
|
|
23
|
+
jest.mock('@open-mercato/ui/backend/FlashMessages', () => ({
|
|
24
|
+
flash: (...args: unknown[]) => flashMock(...args),
|
|
25
|
+
}))
|
|
26
|
+
|
|
15
27
|
const embeddingSettings: NonNullable<VectorSearchSectionProps['embeddingSettings']> = {
|
|
16
28
|
openaiConfigured: true,
|
|
17
29
|
autoIndexingEnabled: true,
|
|
@@ -115,6 +127,116 @@ describe('VectorSearchSection provider controls', () => {
|
|
|
115
127
|
})
|
|
116
128
|
})
|
|
117
129
|
|
|
130
|
+
describe('VectorSearchSection Ollama base URL', () => {
|
|
131
|
+
beforeEach(() => {
|
|
132
|
+
readApiResultOrThrowMock.mockReset()
|
|
133
|
+
readApiResultOrThrowMock.mockResolvedValue(null)
|
|
134
|
+
flashMock.mockReset()
|
|
135
|
+
Object.defineProperty(globalThis, 'fetch', {
|
|
136
|
+
configurable: true,
|
|
137
|
+
value: jest.fn(() => new Promise(() => undefined)),
|
|
138
|
+
})
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
const savedEmbeddingConfigs = () =>
|
|
142
|
+
readApiResultOrThrowMock.mock.calls
|
|
143
|
+
.map(([, init]) => JSON.parse(String((init as RequestInit).body)) as { embeddingConfig?: Record<string, unknown> })
|
|
144
|
+
.map((body) => body.embeddingConfig)
|
|
145
|
+
.filter(Boolean)
|
|
146
|
+
|
|
147
|
+
it('shows a base URL field only for the Ollama provider', () => {
|
|
148
|
+
renderSection()
|
|
149
|
+
|
|
150
|
+
expect(screen.queryByLabelText('Base URL')).toBeNull()
|
|
151
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
152
|
+
|
|
153
|
+
const input = screen.getByLabelText('Base URL')
|
|
154
|
+
expect(input).toHaveProperty('value', '')
|
|
155
|
+
expect(screen.getByText('Leave empty to use the OLLAMA_BASE_URL environment variable.')).toBeTruthy()
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it('sends the typed base URL with the Ollama embedding config', async () => {
|
|
159
|
+
renderSection({ ...embeddingSettings, embeddingConfig: null })
|
|
160
|
+
|
|
161
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
162
|
+
fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: ' http://ollama.internal:11434 ' } })
|
|
163
|
+
fireEvent.click(screen.getByRole('button', { name: 'Apply' }))
|
|
164
|
+
|
|
165
|
+
await waitFor(() => expect(savedEmbeddingConfigs()).toHaveLength(1))
|
|
166
|
+
expect(savedEmbeddingConfigs()[0]).toMatchObject({
|
|
167
|
+
providerId: 'ollama',
|
|
168
|
+
model: 'nomic-embed-text',
|
|
169
|
+
baseUrl: 'http://ollama.internal:11434',
|
|
170
|
+
})
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
it('pre-fills a saved base URL and keeps it when another setting is applied', async () => {
|
|
174
|
+
renderSection({
|
|
175
|
+
...embeddingSettings,
|
|
176
|
+
embeddingConfig: {
|
|
177
|
+
providerId: 'ollama',
|
|
178
|
+
model: 'nomic-embed-text',
|
|
179
|
+
dimension: 768,
|
|
180
|
+
baseUrl: 'http://ollama.internal:11434',
|
|
181
|
+
updatedAt: '2026-07-26T12:00:00.000Z',
|
|
182
|
+
},
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
186
|
+
expect(screen.getByLabelText('Base URL')).toHaveProperty('value', 'http://ollama.internal:11434')
|
|
187
|
+
fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: 'http://ollama-2.internal:11434' } })
|
|
188
|
+
fireEvent.click(screen.getByRole('button', { name: 'Apply' }))
|
|
189
|
+
fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
|
|
190
|
+
|
|
191
|
+
await waitFor(() => expect(savedEmbeddingConfigs()).toHaveLength(1))
|
|
192
|
+
expect(savedEmbeddingConfigs()[0]).toMatchObject({ providerId: 'ollama', baseUrl: 'http://ollama-2.internal:11434' })
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
it('omits the base URL when the field is cleared', async () => {
|
|
196
|
+
renderSection({
|
|
197
|
+
...embeddingSettings,
|
|
198
|
+
embeddingConfig: {
|
|
199
|
+
providerId: 'ollama',
|
|
200
|
+
model: 'nomic-embed-text',
|
|
201
|
+
dimension: 768,
|
|
202
|
+
baseUrl: 'http://ollama.internal:11434',
|
|
203
|
+
updatedAt: '2026-07-26T12:00:00.000Z',
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
208
|
+
fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: '' } })
|
|
209
|
+
fireEvent.click(screen.getByRole('button', { name: 'Apply' }))
|
|
210
|
+
fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
|
|
211
|
+
|
|
212
|
+
await waitFor(() => expect(savedEmbeddingConfigs()).toHaveLength(1))
|
|
213
|
+
expect(savedEmbeddingConfigs()[0]).not.toHaveProperty('baseUrl')
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
it('shows the server message when the base URL is rejected', async () => {
|
|
217
|
+
readApiResultOrThrowMock.mockRejectedValue(new Error('Ollama base URL is not allowed.'))
|
|
218
|
+
renderSection({ ...embeddingSettings, embeddingConfig: null })
|
|
219
|
+
|
|
220
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
221
|
+
fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: 'http://10.0.0.5:11434' } })
|
|
222
|
+
fireEvent.click(screen.getByRole('button', { name: 'Apply' }))
|
|
223
|
+
|
|
224
|
+
await waitFor(() => expect(flashMock).toHaveBeenCalledWith('Ollama base URL is not allowed.', 'error'))
|
|
225
|
+
expect(flashMock).not.toHaveBeenCalledWith('Embedding provider saved', 'success')
|
|
226
|
+
expect(screen.getByLabelText('Base URL')).toHaveProperty('value', 'http://10.0.0.5:11434')
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it('falls back to a generic message when the rejection carries none', async () => {
|
|
230
|
+
readApiResultOrThrowMock.mockRejectedValue(new Error(''))
|
|
231
|
+
renderSection({ ...embeddingSettings, embeddingConfig: null })
|
|
232
|
+
|
|
233
|
+
fireEvent.click(screen.getByRole('button', { name: /Ollama \(Local\)/ }))
|
|
234
|
+
fireEvent.click(screen.getByRole('button', { name: 'Apply' }))
|
|
235
|
+
|
|
236
|
+
await waitFor(() => expect(flashMock).toHaveBeenCalledWith('Failed to save settings', 'error'))
|
|
237
|
+
})
|
|
238
|
+
})
|
|
239
|
+
|
|
118
240
|
describe('VectorSearchSection store availability', () => {
|
|
119
241
|
beforeEach(() => {
|
|
120
242
|
Object.defineProperty(globalThis, 'fetch', {
|
|
@@ -171,6 +171,8 @@
|
|
|
171
171
|
"search.settings.model.label": "Modell",
|
|
172
172
|
"search.settings.model.namePlaceholder": "Modellname",
|
|
173
173
|
"search.settings.noIndexMessage": "Es wurde noch kein Suchindex erstellt.",
|
|
174
|
+
"search.settings.ollama.baseUrl.hint": "Leer lassen, um die Umgebungsvariable OLLAMA_BASE_URL zu verwenden.",
|
|
175
|
+
"search.settings.ollama.baseUrl.label": "Basis-URL",
|
|
174
176
|
"search.settings.pageDescription": "Suchstrategien konfigurieren, Indizes verwalten und Aktivität überwachen.",
|
|
175
177
|
"search.settings.pageTitle": "Sucheinstellungen",
|
|
176
178
|
"search.settings.processingLabel": "Wird verarbeitet…",
|
|
@@ -171,6 +171,8 @@
|
|
|
171
171
|
"search.settings.model.label": "Model",
|
|
172
172
|
"search.settings.model.namePlaceholder": "Model name",
|
|
173
173
|
"search.settings.noIndexMessage": "No search index has been created yet.",
|
|
174
|
+
"search.settings.ollama.baseUrl.hint": "Leave empty to use the OLLAMA_BASE_URL environment variable.",
|
|
175
|
+
"search.settings.ollama.baseUrl.label": "Base URL",
|
|
174
176
|
"search.settings.pageDescription": "Configure search strategies, manage indexes, and monitor activity.",
|
|
175
177
|
"search.settings.pageTitle": "Search Settings",
|
|
176
178
|
"search.settings.processingLabel": "Processing…",
|
|
@@ -171,6 +171,8 @@
|
|
|
171
171
|
"search.settings.model.label": "Modelo",
|
|
172
172
|
"search.settings.model.namePlaceholder": "Nombre del modelo",
|
|
173
173
|
"search.settings.noIndexMessage": "Aún no se ha creado ningún índice de búsqueda.",
|
|
174
|
+
"search.settings.ollama.baseUrl.hint": "Déjalo vacío para usar la variable de entorno OLLAMA_BASE_URL.",
|
|
175
|
+
"search.settings.ollama.baseUrl.label": "URL base",
|
|
174
176
|
"search.settings.pageDescription": "Configure estrategias de búsqueda, administre índices y supervise la actividad.",
|
|
175
177
|
"search.settings.pageTitle": "Configuración de búsqueda",
|
|
176
178
|
"search.settings.processingLabel": "Procesando…",
|