@open-mercato/core 0.11.1-develop.8521.1.204f384ec3 → 0.11.1-develop.8527.1.47d81d2fa0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js +2 -2
  3. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js.map +2 -2
  4. package/dist/modules/entities/components/EncryptionManager.js +13 -4
  5. package/dist/modules/entities/components/EncryptionManager.js.map +2 -2
  6. package/dist/modules/messages/components/MessagesInboxPageClient.js +2 -2
  7. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  8. package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js +2 -2
  9. package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js.map +2 -2
  10. package/dist/modules/query_index/cli.js +7 -3
  11. package/dist/modules/query_index/cli.js.map +2 -2
  12. package/dist/modules/query_index/lib/batch.js +6 -1
  13. package/dist/modules/query_index/lib/batch.js.map +2 -2
  14. package/dist/modules/query_index/lib/indexer.js +14 -15
  15. package/dist/modules/query_index/lib/indexer.js.map +2 -2
  16. package/dist/modules/query_index/lib/reindexer.js +6 -3
  17. package/dist/modules/query_index/lib/reindexer.js.map +3 -3
  18. package/dist/modules/query_index/lib/search-tokens.js +10 -4
  19. package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
  20. package/dist/modules/staff/frontend/[orgSlug]/portal/support/[id]/page.js +5 -4
  21. package/dist/modules/staff/frontend/[orgSlug]/portal/support/[id]/page.js.map +2 -2
  22. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/[id]/page.js +8 -4
  23. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/[id]/page.js.map +2 -2
  24. package/dist/modules/workflows/components/run/useLiveRunUpdates.js +2 -3
  25. package/dist/modules/workflows/components/run/useLiveRunUpdates.js.map +2 -2
  26. package/package.json +7 -7
  27. package/src/modules/data_sync/backend/data-sync/runs/[id]/page.tsx +2 -2
  28. package/src/modules/entities/components/EncryptionManager.tsx +15 -5
  29. package/src/modules/messages/components/MessagesInboxPageClient.tsx +2 -2
  30. package/src/modules/messages/components/message-detail/hooks/useMessageDetails.ts +2 -2
  31. package/src/modules/query_index/cli.ts +8 -3
  32. package/src/modules/query_index/lib/batch.ts +13 -0
  33. package/src/modules/query_index/lib/indexer.ts +13 -14
  34. package/src/modules/query_index/lib/reindexer.ts +5 -2
  35. package/src/modules/query_index/lib/search-tokens.ts +22 -3
  36. package/src/modules/staff/frontend/[orgSlug]/portal/support/[id]/page.tsx +5 -4
  37. package/src/modules/warranty_claims/frontend/[orgSlug]/portal/claims/[id]/page.tsx +8 -4
  38. package/src/modules/workflows/components/run/useLiveRunUpdates.ts +2 -5
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/workflows/components/run/useLiveRunUpdates.ts"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'\n\n/** The DOM Event Bridge dispatches this after re-establishing a dropped SSE stream. */\nconst BRIDGE_RECONNECTED_EVENT = 'om:bridge:reconnected'\n\n/**\n * A busy tenant can advance dozens of instances a second, and every step\n * advance re-emits `workflows.instance.started`. Collapsing the burst into one\n * refresh is what keeps a live run list from refetching per event.\n */\nexport const LIVE_REFRESH_THROTTLE_MS = 1500\n\nexport type UseLiveRunUpdatesOptions = {\n /**\n * When set, only events carrying this instance id refresh. Omit on the run\n * list, which cares about every instance in scope.\n */\n instanceId?: string | null\n onRefresh: () => void\n /** Turn the subscription off entirely (e.g. before the instance has loaded). */\n enabled?: boolean\n throttleMs?: number\n}\n\n/**\n * Live run updates (spec \u00A78.3): \"`workflows.instance.*` lifecycle events gain\n * `clientBroadcast: true`; run views subscribe via the DOM Event Bridge.\"\n *\n * The bridge is best-effort by design \u2014 the stream can drop, and the platform\n * caps an SSE payload at 4KB and replaces anything larger with a stub. So a\n * refresh is always a REFETCH, never an attempt to patch state from the\n * payload, and the hook also refreshes on the bridge's reconnect event to\n * close whatever gap the disconnection left.\n */\nexport function useLiveRunUpdates({\n instanceId,\n onRefresh,\n enabled = true,\n throttleMs = LIVE_REFRESH_THROTTLE_MS,\n}: UseLiveRunUpdatesOptions): void {\n const onRefreshRef = React.useRef(onRefresh)\n onRefreshRef.current = onRefresh\n\n const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n const lastRunRef = React.useRef(0)\n\n const scheduleRefresh = React.useCallback(() => {\n if (timerRef.current !== null) return\n const sinceLast = Date.now() - lastRunRef.current\n const delay = Math.max(throttleMs - sinceLast, 0)\n timerRef.current = setTimeout(() => {\n timerRef.current = null\n lastRunRef.current = Date.now()\n onRefreshRef.current()\n }, delay)\n }, [throttleMs])\n\n React.useEffect(\n () => () => {\n if (timerRef.current !== null) clearTimeout(timerRef.current)\n },\n []\n )\n\n useAppEvent(\n 'workflows.instance.*',\n (event) => {\n if (!enabled) return\n if (instanceId) {\n const payloadInstanceId = event.payload?.id\n if (typeof payloadInstanceId !== 'string' || payloadInstanceId !== instanceId) return\n }\n scheduleRefresh()\n },\n [enabled, instanceId, scheduleRefresh]\n )\n\n useAppEvent(\n BRIDGE_RECONNECTED_EVENT,\n () => {\n if (!enabled) return\n scheduleRefresh()\n },\n [enabled, scheduleRefresh]\n )\n}\n"],
5
- "mappings": ";AAEA,YAAY,WAAW;AACvB,SAAS,mBAAmB;AAG5B,MAAM,2BAA2B;AAO1B,MAAM,2BAA2B;AAwBjC,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV,aAAa;AACf,GAAmC;AACjC,QAAM,eAAe,MAAM,OAAO,SAAS;AAC3C,eAAa,UAAU;AAEvB,QAAM,WAAW,MAAM,OAA6C,IAAI;AACxE,QAAM,aAAa,MAAM,OAAO,CAAC;AAEjC,QAAM,kBAAkB,MAAM,YAAY,MAAM;AAC9C,QAAI,SAAS,YAAY,KAAM;AAC/B,UAAM,YAAY,KAAK,IAAI,IAAI,WAAW;AAC1C,UAAM,QAAQ,KAAK,IAAI,aAAa,WAAW,CAAC;AAChD,aAAS,UAAU,WAAW,MAAM;AAClC,eAAS,UAAU;AACnB,iBAAW,UAAU,KAAK,IAAI;AAC9B,mBAAa,QAAQ;AAAA,IACvB,GAAG,KAAK;AAAA,EACV,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM;AAAA,IACJ,MAAM,MAAM;AACV,UAAI,SAAS,YAAY,KAAM,cAAa,SAAS,OAAO;AAAA,IAC9D;AAAA,IACA,CAAC;AAAA,EACH;AAEA;AAAA,IACE;AAAA,IACA,CAAC,UAAU;AACT,UAAI,CAAC,QAAS;AACd,UAAI,YAAY;AACd,cAAM,oBAAoB,MAAM,SAAS;AACzC,YAAI,OAAO,sBAAsB,YAAY,sBAAsB,WAAY;AAAA,MACjF;AACA,sBAAgB;AAAA,IAClB;AAAA,IACA,CAAC,SAAS,YAAY,eAAe;AAAA,EACvC;AAEA;AAAA,IACE;AAAA,IACA,MAAM;AACJ,UAAI,CAAC,QAAS;AACd,sBAAgB;AAAA,IAClB;AAAA,IACA,CAAC,SAAS,eAAe;AAAA,EAC3B;AACF;",
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { BRIDGE_RECONNECTED_EVENT_ID, useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'\n\n/**\n * A busy tenant can advance dozens of instances a second, and every step\n * advance re-emits `workflows.instance.started`. Collapsing the burst into one\n * refresh is what keeps a live run list from refetching per event.\n */\nexport const LIVE_REFRESH_THROTTLE_MS = 1500\n\nexport type UseLiveRunUpdatesOptions = {\n /**\n * When set, only events carrying this instance id refresh. Omit on the run\n * list, which cares about every instance in scope.\n */\n instanceId?: string | null\n onRefresh: () => void\n /** Turn the subscription off entirely (e.g. before the instance has loaded). */\n enabled?: boolean\n throttleMs?: number\n}\n\n/**\n * Live run updates (spec \u00A78.3): \"`workflows.instance.*` lifecycle events gain\n * `clientBroadcast: true`; run views subscribe via the DOM Event Bridge.\"\n *\n * The bridge is best-effort by design \u2014 the stream can drop, and the platform\n * caps an SSE payload at 4KB and replaces anything larger with a stub. So a\n * refresh is always a REFETCH, never an attempt to patch state from the\n * payload, and the hook also refreshes on the bridge's reconnect event to\n * close whatever gap the disconnection left.\n */\nexport function useLiveRunUpdates({\n instanceId,\n onRefresh,\n enabled = true,\n throttleMs = LIVE_REFRESH_THROTTLE_MS,\n}: UseLiveRunUpdatesOptions): void {\n const onRefreshRef = React.useRef(onRefresh)\n onRefreshRef.current = onRefresh\n\n const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n const lastRunRef = React.useRef(0)\n\n const scheduleRefresh = React.useCallback(() => {\n if (timerRef.current !== null) return\n const sinceLast = Date.now() - lastRunRef.current\n const delay = Math.max(throttleMs - sinceLast, 0)\n timerRef.current = setTimeout(() => {\n timerRef.current = null\n lastRunRef.current = Date.now()\n onRefreshRef.current()\n }, delay)\n }, [throttleMs])\n\n React.useEffect(\n () => () => {\n if (timerRef.current !== null) clearTimeout(timerRef.current)\n },\n []\n )\n\n useAppEvent(\n 'workflows.instance.*',\n (event) => {\n if (!enabled) return\n if (instanceId) {\n const payloadInstanceId = event.payload?.id\n if (typeof payloadInstanceId !== 'string' || payloadInstanceId !== instanceId) return\n }\n scheduleRefresh()\n },\n [enabled, instanceId, scheduleRefresh]\n )\n\n useAppEvent(\n BRIDGE_RECONNECTED_EVENT_ID,\n () => {\n if (!enabled) return\n scheduleRefresh()\n },\n [enabled, scheduleRefresh]\n )\n}\n"],
5
+ "mappings": ";AAEA,YAAY,WAAW;AACvB,SAAS,6BAA6B,mBAAmB;AAOlD,MAAM,2BAA2B;AAwBjC,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV,aAAa;AACf,GAAmC;AACjC,QAAM,eAAe,MAAM,OAAO,SAAS;AAC3C,eAAa,UAAU;AAEvB,QAAM,WAAW,MAAM,OAA6C,IAAI;AACxE,QAAM,aAAa,MAAM,OAAO,CAAC;AAEjC,QAAM,kBAAkB,MAAM,YAAY,MAAM;AAC9C,QAAI,SAAS,YAAY,KAAM;AAC/B,UAAM,YAAY,KAAK,IAAI,IAAI,WAAW;AAC1C,UAAM,QAAQ,KAAK,IAAI,aAAa,WAAW,CAAC;AAChD,aAAS,UAAU,WAAW,MAAM;AAClC,eAAS,UAAU;AACnB,iBAAW,UAAU,KAAK,IAAI;AAC9B,mBAAa,QAAQ;AAAA,IACvB,GAAG,KAAK;AAAA,EACV,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM;AAAA,IACJ,MAAM,MAAM;AACV,UAAI,SAAS,YAAY,KAAM,cAAa,SAAS,OAAO;AAAA,IAC9D;AAAA,IACA,CAAC;AAAA,EACH;AAEA;AAAA,IACE;AAAA,IACA,CAAC,UAAU;AACT,UAAI,CAAC,QAAS;AACd,UAAI,YAAY;AACd,cAAM,oBAAoB,MAAM,SAAS;AACzC,YAAI,OAAO,sBAAsB,YAAY,sBAAsB,WAAY;AAAA,MACjF;AACA,sBAAgB;AAAA,IAClB;AAAA,IACA,CAAC,SAAS,YAAY,eAAe;AAAA,EACvC;AAEA;AAAA,IACE;AAAA,IACA,MAAM;AACJ,UAAI,CAAC,QAAS;AACd,sBAAgB;AAAA,IAClB;AAAA,IACA,CAAC,SAAS,eAAe;AAAA,EAC3B;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.11.1-develop.8521.1.204f384ec3",
3
+ "version": "0.11.1-develop.8527.1.47d81d2fa0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -268,16 +268,16 @@
268
268
  "zod": "^4.6.6"
269
269
  },
270
270
  "peerDependencies": {
271
- "@open-mercato/ai-assistant": "0.11.1-develop.8521.1.204f384ec3",
272
- "@open-mercato/shared": "0.11.1-develop.8521.1.204f384ec3",
273
- "@open-mercato/ui": "0.11.1-develop.8521.1.204f384ec3",
271
+ "@open-mercato/ai-assistant": "0.11.1-develop.8527.1.47d81d2fa0",
272
+ "@open-mercato/shared": "0.11.1-develop.8527.1.47d81d2fa0",
273
+ "@open-mercato/ui": "0.11.1-develop.8527.1.47d81d2fa0",
274
274
  "react": "^19.0.0",
275
275
  "react-dom": "^19.0.0"
276
276
  },
277
277
  "devDependencies": {
278
- "@open-mercato/ai-assistant": "0.11.1-develop.8521.1.204f384ec3",
279
- "@open-mercato/shared": "0.11.1-develop.8521.1.204f384ec3",
280
- "@open-mercato/ui": "0.11.1-develop.8521.1.204f384ec3",
278
+ "@open-mercato/ai-assistant": "0.11.1-develop.8527.1.47d81d2fa0",
279
+ "@open-mercato/shared": "0.11.1-develop.8527.1.47d81d2fa0",
280
+ "@open-mercato/ui": "0.11.1-develop.8527.1.47d81d2fa0",
281
281
  "@testing-library/dom": "^10.4.1",
282
282
  "@testing-library/jest-dom": "^7.0.1",
283
283
  "@testing-library/react": "^16.3.3",
@@ -16,7 +16,7 @@ import { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuarde
16
16
  import { flash } from '@open-mercato/ui/backend/FlashMessages'
17
17
  import { useT } from '@open-mercato/shared/lib/i18n/context'
18
18
  import { LoadingMessage, ErrorMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail'
19
- import { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
19
+ import { BRIDGE_RECONNECTED_EVENT_ID, useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
20
20
  import { Bookmark, Lock, Play, RotateCcw, XCircle } from 'lucide-react'
21
21
  import { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'
22
22
  import { getSyncRunStatusVariant } from '../../../../lib/syncRunStatus'
@@ -265,7 +265,7 @@ export default function SyncRunDetailPage({ params }: SyncRunDetailPageProps) {
265
265
  void loadLogs()
266
266
  }, [handleProgressEvent, loadLogs, loadRun])
267
267
 
268
- useAppEvent('om:bridge:reconnected', () => {
268
+ useAppEvent(BRIDGE_RECONNECTED_EVENT_ID, () => {
269
269
  void loadRun()
270
270
  void loadLogs()
271
271
  }, [loadLogs, loadRun])
@@ -17,6 +17,8 @@ import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@ope
17
17
  import { raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'
18
18
  import { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'
19
19
  import { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'
20
+ import { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'
21
+ import { useInFlightGuard } from '@open-mercato/ui/hooks/useInFlightGuard'
20
22
  import { useCustomFieldDefs, type CustomFieldDefDto } from '@open-mercato/ui/backend/utils/customFieldDefs'
21
23
  import { Plus, Save, Trash2 } from 'lucide-react'
22
24
  import { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'
@@ -275,16 +277,24 @@ export function EncryptionManager() {
275
277
  mutationPayload: payload,
276
278
  })
277
279
  },
278
- onSuccess: () => {
280
+ onSuccess: async () => {
279
281
  flash(t('entities.encryption.flash.saved', 'Encryption map saved'), 'success')
280
- void refetchMap()
282
+ await refetchMap()
281
283
  },
282
- onError: (err: any) => {
283
- const message = err?.message || t('entities.encryption.errors.save', 'Failed to save encryption map')
284
+ onError: (err: unknown) => {
285
+ if (surfaceRecordConflict(err, t, { onRefresh: () => { void refetchMap() } })) return
286
+ const message = err instanceof Error && err.message
287
+ ? err.message
288
+ : t('entities.encryption.errors.save', 'Failed to save encryption map')
284
289
  flash(message, 'error')
285
290
  },
286
291
  })
287
292
 
293
+ const saveGuard = useInFlightGuard()
294
+ const handleSave = () => {
295
+ void saveGuard.run(() => mutation.mutateAsync()).catch(() => undefined)
296
+ }
297
+
288
298
  const addField = () => {
289
299
  setHasUserEdited(true)
290
300
  setFields((prev) => [...prev, { id: buildRowId(), field: '', hashField: null }])
@@ -485,7 +495,7 @@ export function EncryptionManager() {
485
495
  <div className="flex justify-end">
486
496
  <Button
487
497
  type="button"
488
- onClick={() => mutation.mutate()}
498
+ onClick={handleSave}
489
499
  disabled={mutation.isPending || loadingEntities || !!entitiesError || !selectedEntityId}
490
500
  >
491
501
  <Save className="mr-2 h-4 w-4" />
@@ -14,7 +14,7 @@ import type { FilterDef, FilterValues } from '@open-mercato/ui/backend/FilterBar
14
14
  import { Button } from '@open-mercato/ui/primitives/button'
15
15
  import { apiCall } from '@open-mercato/ui/backend/utils/apiCall'
16
16
  import { flash } from '@open-mercato/ui/backend/FlashMessages'
17
- import { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
17
+ import { BRIDGE_RECONNECTED_EVENT_ID, useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
18
18
  import { useAppEventCoalesced } from '@open-mercato/ui/backend/injection/useAppEventCoalesced'
19
19
  import { Archive, ChevronDown, FilePenLine, Inbox, Layers, Send } from 'lucide-react'
20
20
  import { getMessageUiComponentRegistry } from './utils/typeUiRegistry'
@@ -95,7 +95,7 @@ export function MessagesInboxPageClient() {
95
95
  useAppEventCoalesced('messages.message.*', invalidateMessageListQueries, [invalidateMessageListQueries])
96
96
 
97
97
  // Reconnect means events were missed while offline, so it refreshes uncoalesced.
98
- useAppEvent('om:bridge:reconnected', invalidateMessageListQueries, [invalidateMessageListQueries])
98
+ useAppEvent(BRIDGE_RECONNECTED_EVENT_ID, invalidateMessageListQueries, [invalidateMessageListQueries])
99
99
 
100
100
  const [folder, setFolder] = React.useState<MessageFolder>('inbox')
101
101
  const [folderMenuOpen, setFolderMenuOpen] = React.useState(false)
@@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation'
5
5
  import { useQueryClient } from '@tanstack/react-query'
6
6
  import { useT } from '@open-mercato/shared/lib/i18n/context'
7
7
  import { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'
8
- import { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
8
+ import { BRIDGE_RECONNECTED_EVENT_ID, useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
9
9
  import { useMessageDetailsQueries } from './useMessageDetailsQueries'
10
10
  import { useMessageDetailsActions } from './useMessageDetailsActions'
11
11
  import { useMessageDetailsConversation } from './useMessageDetailsConversation'
@@ -44,7 +44,7 @@ export function useMessageDetails(id: string) {
44
44
  )
45
45
 
46
46
  useAppEvent(
47
- 'om:bridge:reconnected',
47
+ BRIDGE_RECONNECTED_EVENT_ID,
48
48
  () => {
49
49
  void queryClient.invalidateQueries({ queryKey: ['messages', 'detail', id] })
50
50
  },
@@ -23,6 +23,7 @@ import {
23
23
  type AnyRow,
24
24
  } from './lib/batch'
25
25
  import { createSearchTokenGateQueryEngine } from './lib/search-entity-policy'
26
+ import { resolveCiphertextGuard } from './lib/search-tokens'
26
27
  import { reindexEntity, isTenantlessReindexTarget, DEFAULT_REINDEX_PARTITIONS } from './lib/reindexer'
27
28
  import type { ReindexJobResult } from './lib/reindexer'
28
29
 
@@ -216,15 +217,19 @@ async function rebuildEntityIndexes(options: RebuildExecutionOptions): Promise<R
216
217
  doc: Record<string, unknown>,
217
218
  scope: { organizationId: string | null; tenantId: string | null },
218
219
  ) => {
220
+ const tenantId = scope.tenantId ?? null
221
+ if (dekKeyCache.get(tenantId) === null) dekKeyCache.delete(tenantId)
219
222
  return await decryptIndexDocForSearch(
220
223
  targetEntity,
221
224
  doc,
222
- { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },
225
+ { tenantId, organizationId: scope.organizationId ?? null },
223
226
  encryption,
224
227
  dekKeyCache,
225
228
  )
226
229
  }
227
230
 
231
+ const ciphertextGuard = () => resolveCiphertextGuard(encryption)
232
+
228
233
  const applyFilters = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {
229
234
  let chain = q
230
235
  if (!global) {
@@ -249,7 +254,7 @@ async function rebuildEntityIndexes(options: RebuildExecutionOptions): Promise<R
249
254
  .executeTakeFirst() as AnyRow | undefined
250
255
  if (!row) return { processed: 0, matched: 0 }
251
256
  const bar = createProgressBar(progressLabel ?? `Rebuilding ${entityType}`, 1)
252
- const singleResult = await upsertIndexBatch(db, entityType, [row], { orgId: orgOverride, tenantId: tenantOverride }, { encryptDoc, decryptDoc, searchTokenGateQueryEngine })
257
+ const singleResult = await upsertIndexBatch(db, entityType, [row], { orgId: orgOverride, tenantId: tenantOverride }, { encryptDoc, decryptDoc, searchTokenGateQueryEngine, ciphertextGuard })
253
258
  bar.update(singleResult.written)
254
259
  bar.complete()
255
260
  assertIndexBatchWritesLanded(entityType, singleResult)
@@ -291,7 +296,7 @@ async function rebuildEntityIndexes(options: RebuildExecutionOptions): Promise<R
291
296
  const chunkResult = await upsertIndexBatch(db, entityType, chunk as AnyRow[], {
292
297
  orgId: orgOverride,
293
298
  tenantId: tenantOverride,
294
- }, { encryptDoc, decryptDoc, searchTokenGateQueryEngine })
299
+ }, { encryptDoc, decryptDoc, searchTokenGateQueryEngine, ciphertextGuard })
295
300
  mergeUpsertIndexBatchResults(writeTotals, chunkResult)
296
301
 
297
302
  processed += chunkResult.written
@@ -105,6 +105,13 @@ export type IndexBatchOptions = {
105
105
  ) => Promise<Record<string, unknown> | null | undefined>
106
106
  /** Query engine handed to the entity's `shouldIndex` gates before its search tokens are written. */
107
107
  searchTokenGateQueryEngine?: QueryEngine
108
+ /**
109
+ * Whether the token writer must skip ciphertext-shaped fields, evaluated per row straight after
110
+ * that row's `decryptDoc`, so a Vault that recovers mid-batch cannot clear the guard for rows
111
+ * decrypted while it was down. Pass `() => resolveCiphertextGuard(encryption)` with the service
112
+ * `decryptDoc` uses. A row whose `decryptDoc` throws is always guarded.
113
+ */
114
+ ciphertextGuard?: () => boolean
108
115
  }
109
116
 
110
117
  function normalizeId(value: unknown): string {
@@ -123,6 +130,7 @@ type IndexRowPayload = {
123
130
  tenant_id: string | null
124
131
  doc: Record<string, unknown>
125
132
  tokenDoc: Record<string, unknown>
133
+ guardCiphertext?: boolean
126
134
  index_version: number
127
135
  }
128
136
 
@@ -296,6 +304,7 @@ export async function upsertIndexBatch(
296
304
  const scopeTenant = built.tenantId
297
305
  let doc = built.doc
298
306
  let tokenDoc: Record<string, unknown> = doc
307
+ let guardCiphertext: boolean | undefined
299
308
  if (typeof options.encryptDoc === 'function') {
300
309
  try {
301
310
  const encrypted = await options.encryptDoc(entityType, doc, {
@@ -336,6 +345,7 @@ export async function upsertIndexBatch(
336
345
  // Only affects the search tokens built below; the indexed document itself is
337
346
  // unharmed, so the row still counts as written.
338
347
  logger.warn('Failed to decrypt index document for search tokens', { entityType, recordId })
348
+ guardCiphertext = true
339
349
  await recordIndexerError(
340
350
  { db },
341
351
  {
@@ -350,6 +360,7 @@ export async function upsertIndexBatch(
350
360
  ).catch(() => undefined)
351
361
  }
352
362
  }
363
+ guardCiphertext ??= options.ciphertextGuard?.()
353
364
  basePayloads.push({
354
365
  entity_type: entityType,
355
366
  entity_id: recordId,
@@ -357,6 +368,7 @@ export async function upsertIndexBatch(
357
368
  tenant_id: scopeTenant ?? null,
358
369
  doc,
359
370
  tokenDoc,
371
+ ...(guardCiphertext === undefined ? {} : { guardCiphertext }),
360
372
  index_version: 1,
361
373
  })
362
374
  if (debugEnabled) {
@@ -410,6 +422,7 @@ export async function upsertIndexBatch(
410
422
  organizationId: payload.organization_id,
411
423
  tenantId: payload.tenant_id,
412
424
  doc: payload.tokenDoc,
425
+ ...(payload.guardCiphertext === undefined ? {} : { guardCiphertext: payload.guardCiphertext }),
413
426
  }))
414
427
 
415
428
  const writeSearchTokens = async (payloads = tokenPayloads): Promise<void> => {
@@ -16,7 +16,7 @@ import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'
16
16
  import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
17
17
  import { tryGetModules } from '@open-mercato/shared/lib/modules/registry'
18
18
  import { resolveSearchConfig } from '@open-mercato/shared/lib/search/config'
19
- import { replaceSearchTokensForRecord, deleteSearchTokensForRecord } from './search-tokens'
19
+ import { replaceSearchTokensForRecord, deleteSearchTokensForRecord, resolveCiphertextGuard } from './search-tokens'
20
20
  import { attachAggregateSearchField, rebuildAggregateSearchField } from './document'
21
21
  import { applyIndexDocEnrichers } from './doc-enrichers'
22
22
  import {
@@ -454,22 +454,20 @@ export async function reindexSearchTokensForRecord(
454
454
  }, { trx: args.trx })
455
455
  return
456
456
  }
457
- const tokenDoc = args.searchTokenDoc ?? (() => {
458
- const encryption = resolveTenantEncryptionService(em as any)
459
- const dekKeyCache = new Map<string | null, string | null>()
460
- return decryptIndexDocForSearch(
461
- args.entityType,
462
- args.doc,
463
- { tenantId: args.tenantId ?? null, organizationId: args.organizationId ?? null },
464
- encryption,
465
- dekKeyCache,
466
- )
467
- })()
457
+ const encryption = resolveTenantEncryptionService(em as any)
458
+ const tokenDoc = args.searchTokenDoc ?? await decryptIndexDocForSearch(
459
+ args.entityType,
460
+ args.doc,
461
+ { tenantId: args.tenantId ?? null, organizationId: args.organizationId ?? null },
462
+ encryption,
463
+ new Map<string | null, string | null>(),
464
+ )
465
+ const guardCiphertext = resolveCiphertextGuard(encryption)
468
466
  const gates = resolveSearchTokenIndexGates(args.entityType)
469
467
  if (gates.length) {
470
468
  const allowed = await passesSearchTokenIndexGates(args.entityType, gates, {
471
469
  recordId: String(args.recordId),
472
- record: await tokenDoc,
470
+ record: tokenDoc,
473
471
  tenantId: args.tenantId ?? null,
474
472
  organizationId: args.organizationId ?? null,
475
473
  queryEngine: createSearchTokenGateQueryEngine(em),
@@ -491,7 +489,7 @@ export async function reindexSearchTokensForRecord(
491
489
  // rebuild and the token writer — that also makes the aggregate's blocklist filter and
492
490
  // the per-field one provably read the same snapshot, as the batch path already does.
493
491
  const searchConfig = resolveSearchConfig()
494
- const searchDoc = rebuildAggregateSearchField(await tokenDoc, {
492
+ const searchDoc = rebuildAggregateSearchField(tokenDoc, {
495
493
  entityType: args.entityType,
496
494
  config: searchConfig,
497
495
  })
@@ -502,6 +500,7 @@ export async function reindexSearchTokensForRecord(
502
500
  tenantId: args.tenantId ?? null,
503
501
  doc: searchDoc,
504
502
  config: searchConfig,
503
+ guardCiphertext,
505
504
  }, { trx: args.trx })
506
505
  }
507
506
 
@@ -21,7 +21,7 @@ import {
21
21
  import { prepareJob, updateJobProgress, finalizeJob, type JobScope } from './jobs'
22
22
  import { purgeOrphans, retireScopedCatalogueRows } from './stale'
23
23
  import type { VectorIndexService } from '@open-mercato/search/vector'
24
- import { isSearchDebugEnabled } from './search-tokens'
24
+ import { isSearchDebugEnabled, resolveCiphertextGuard } from './search-tokens'
25
25
  import { isTenantGlobalEntityType } from './tenant-global'
26
26
  import { createLogger } from '@open-mercato/shared/lib/logger'
27
27
  import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
@@ -653,10 +653,12 @@ export async function reindexEntity(
653
653
  doc: Record<string, unknown>,
654
654
  scope: { organizationId: string | null; tenantId: string | null },
655
655
  ) => {
656
+ const tenantId = scope.tenantId ?? null
657
+ if (dekKeyCache.get(tenantId) === null) dekKeyCache.delete(tenantId)
656
658
  const result = await decryptIndexDocForSearch(
657
659
  targetEntity,
658
660
  doc,
659
- { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },
661
+ { tenantId, organizationId: scope.organizationId ?? null },
660
662
  encryption,
661
663
  dekKeyCache,
662
664
  )
@@ -671,6 +673,7 @@ export async function reindexEntity(
671
673
  encryptDoc,
672
674
  decryptDoc,
673
675
  searchTokenGateQueryEngine,
676
+ ciphertextGuard: () => resolveCiphertextGuard(encryption),
674
677
  })
675
678
  mergeUpsertIndexBatchResults(writeTotals, batchResult)
676
679
 
@@ -102,6 +102,23 @@ function shouldGuardCiphertext(): boolean {
102
102
  return resolveEncryptionMode(guardKmsService) !== 'active'
103
103
  }
104
104
 
105
+ export type CiphertextGuardSource = { isEnabled?: () => boolean } | null | undefined
106
+
107
+ /**
108
+ * The guard decision for a document decrypted by `encryption`, read AFTER that decrypt.
109
+ *
110
+ * {@link shouldGuardCiphertext} asks a KMS that never fetches a key, so its Vault circuit breaker
111
+ * never trips: it reports `active` through a real outage while the decrypt that ran just before
112
+ * got no DEK and handed back ciphertext. `encryption.isEnabled()` is the toggle ANDed with the
113
+ * health of the KMS whose `getDek` just called Vault, and it is the same signal
114
+ * `decryptIndexDocForSearch` uses to skip decryption, so the decrypt and the guard cannot disagree.
115
+ * Callers without a service keep the process-level check.
116
+ */
117
+ export function resolveCiphertextGuard(encryption: CiphertextGuardSource): boolean {
118
+ if (typeof encryption?.isEnabled !== 'function') return shouldGuardCiphertext()
119
+ return !encryption.isEnabled()
120
+ }
121
+
105
122
  /**
106
123
  * Fields whose value is an AES-GCM envelope rather than the text it is supposed to hold.
107
124
  *
@@ -516,10 +533,12 @@ export async function replaceSearchTokensForBatch(
516
533
  // here would still delete the tokens we are trying to protect. Skipping the record leaves every
517
534
  // one of its tokens, encrypted-field and plaintext-field alike, exactly as it was. The state is
518
535
  // transient by construction: `decrypt-database` followed by a reindex rebuilds all of it.
519
- const guardCiphertext = shouldGuardCiphertext()
536
+ let processGuard: boolean | undefined
537
+ const guardFor = (payload: BuildTokenOptions): boolean =>
538
+ payload.guardCiphertext ?? (processGuard ??= shouldGuardCiphertext())
520
539
  const preservedRecordIds = new Set<string>()
521
540
  const payloads = indexablePayloads.filter((payload) => {
522
- const ciphertextFields = ciphertextFieldsOf(payload.doc, guardCiphertext)
541
+ const ciphertextFields = ciphertextFieldsOf(payload.doc, guardFor(payload))
523
542
  if (!ciphertextFields.size) return true
524
543
  warnCiphertextSkipped(payload.entityType, payload.tenantId ?? null, ciphertextFields)
525
544
  preservedRecordIds.add(String(payload.recordId))
@@ -527,7 +546,7 @@ export async function replaceSearchTokensForBatch(
527
546
  })
528
547
  if (!payloads.length) return
529
548
 
530
- const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext }))
549
+ const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext: guardFor(payload) }))
531
550
  if (!rows.length) {
532
551
  const entityType = payloads[0]?.entityType
533
552
  if (!entityType) return
@@ -19,7 +19,7 @@ import { apiCall } from '@open-mercato/ui/backend/utils/apiCall'
19
19
  import { usePortalContext } from '@open-mercato/ui/portal/PortalContext'
20
20
  import { PortalCard } from '@open-mercato/ui/portal/components/PortalCard'
21
21
  import { PortalEmptyState } from '@open-mercato/ui/portal/components/PortalEmptyState'
22
- import { usePortalAppEvent } from '@open-mercato/ui/portal/hooks/usePortalAppEvent'
22
+ import { usePortalLiveRefetch } from '@open-mercato/ui/portal/hooks/usePortalLiveRefetch'
23
23
  import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
24
24
  import {
25
25
  ATTACHMENT_ACCEPT_TYPES,
@@ -147,9 +147,10 @@ export default function PortalSupportTicketDetailPage({ params }: Props) {
147
147
  void load()
148
148
  }, [load])
149
149
 
150
- usePortalAppEvent(PORTAL_SUPPORT_UPDATED_EVENT, (event) => {
151
- if (readPortalTicketIdFromEvent(event) === params.id) void load()
152
- }, [load, params.id])
150
+ usePortalLiveRefetch(PORTAL_SUPPORT_UPDATED_EVENT, () => void load(), {
151
+ filter: (event) => readPortalTicketIdFromEvent(event) === params.id,
152
+ deps: [load, params.id],
153
+ })
153
154
 
154
155
  const clearFailed = React.useCallback((fileName: string) => {
155
156
  forgetFailedUpload(params.id, fileName)
@@ -32,6 +32,7 @@ import { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimi
32
32
  import { usePortalContext } from '@open-mercato/ui/portal/PortalContext'
33
33
  import { PortalEmptyState } from '@open-mercato/ui/portal/components/PortalEmptyState'
34
34
  import { usePortalAppEvent } from '@open-mercato/ui/portal/hooks/usePortalAppEvent'
35
+ import { usePortalLiveRefetch } from '@open-mercato/ui/portal/hooks/usePortalLiveRefetch'
35
36
 
36
37
  type Props = { params: { orgSlug: string; id: string } }
37
38
 
@@ -419,10 +420,13 @@ export default function WarrantyClaimPortalDetailPage({ params }: Props) {
419
420
  if (user) void loadClaim()
420
421
  }, [loadClaim, user])
421
422
 
422
- usePortalAppEvent('warranty_claims.claim.portal_status_changed', (event) => {
423
- if (!user || event.payload.claimId !== params.id) return
424
- void loadClaim(false)
425
- })
423
+ usePortalLiveRefetch(
424
+ 'warranty_claims.claim.portal_status_changed',
425
+ () => {
426
+ if (user) void loadClaim(false)
427
+ },
428
+ { filter: (event) => event.payload.claimId === params.id },
429
+ )
426
430
 
427
431
  usePortalAppEvent('warranty_claims.claim.comment_added', (event) => {
428
432
  if (!user || event.payload.claimId !== params.id) return
@@ -1,10 +1,7 @@
1
1
  'use client'
2
2
 
3
3
  import * as React from 'react'
4
- import { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
5
-
6
- /** The DOM Event Bridge dispatches this after re-establishing a dropped SSE stream. */
7
- const BRIDGE_RECONNECTED_EVENT = 'om:bridge:reconnected'
4
+ import { BRIDGE_RECONNECTED_EVENT_ID, useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
8
5
 
9
6
  /**
10
7
  * A busy tenant can advance dozens of instances a second, and every step
@@ -79,7 +76,7 @@ export function useLiveRunUpdates({
79
76
  )
80
77
 
81
78
  useAppEvent(
82
- BRIDGE_RECONNECTED_EVENT,
79
+ BRIDGE_RECONNECTED_EVENT_ID,
83
80
  () => {
84
81
  if (!enabled) return
85
82
  scheduleRefresh()