From 2107969b9a9104cbf1a0fb5675c80fadd6fc3144 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 09:46:57 -0800 Subject: [PATCH 1/3] fix(organization-search): hide the block where its organization lacks Search; isolate the Slack identity sweep in the People cron - getBlockVisibility disables the Organization Search block, as a kill switch does, for a personal workspace or an organization without Search, so every discovery surface (toolbar, search, mentions, tool pickers, the Assistant's workflow authoring, the catalog) stops offering a block that always fails there. Execution of placed blocks is not gated. - The People cron logs and names a failed sweep in failed, reports the other sweep's count, and fails the invocation only when the directory sweep fails. --- .../cron/people-directory-sync/route.test.ts | 49 +++++++++++++++++++ .../api/cron/people-directory-sync/route.ts | 30 +++++++++--- .../sim/lib/api/contracts/people-sync-cron.ts | 2 + .../lib/core/config/block-visibility.test.ts | 36 +++++++++++++- apps/sim/lib/core/config/block-visibility.ts | 18 +++++-- 5 files changed, 124 insertions(+), 11 deletions(-) create mode 100644 apps/sim/app/api/cron/people-directory-sync/route.test.ts diff --git a/apps/sim/app/api/cron/people-directory-sync/route.test.ts b/apps/sim/app/api/cron/people-directory-sync/route.test.ts new file mode 100644 index 00000000000..649bfe6919a --- /dev/null +++ b/apps/sim/app/api/cron/people-directory-sync/route.test.ts @@ -0,0 +1,49 @@ +import { createMockRequest } from '@sim/testing' +import { authInternalMock, authInternalMockFns } from '@sim/testing/mocks/auth-internal.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { syncDueDirectories, refreshDueSlackIdentities } = vi.hoisted(() => ({ + syncDueDirectories: vi.fn(), + refreshDueSlackIdentities: vi.fn(), +})) +vi.mock('@/lib/auth/internal', () => authInternalMock) +vi.mock('@/lib/people/sync/runner', () => ({ syncDueDirectories })) +vi.mock('@/lib/people/slack-identities', () => ({ refreshDueSlackIdentities })) + +import { GET } from '@/app/api/cron/people-directory-sync/route' + +function sweep() { + return GET( + createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/cron/people-directory-sync') + ) +} + +describe('people directory sync cron', () => { + beforeEach(() => { + authInternalMockFns.mockVerifyCronAuth.mockReturnValue(null) + syncDueDirectories.mockReset().mockResolvedValue({ attempted: 3 }) + refreshDueSlackIdentities.mockReset().mockResolvedValue({ refreshed: 2 }) + }) + + it('reports a directory sync that succeeded when only the Slack identity sweep failed', async () => { + refreshDueSlackIdentities.mockRejectedValue(new Error('connection terminated')) + const response = await sweep() + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ + attempted: 3, + slackIdentitiesRefreshed: 0, + failed: ['slackIdentities'], + }) + }) + + it('fails the invocation for a failed directory sweep, still reporting the Slack refresh', async () => { + syncDueDirectories.mockRejectedValue(new Error('connection terminated')) + const response = await sweep() + expect(response.status).toBe(500) + expect(await response.json()).toEqual({ + attempted: 0, + slackIdentitiesRefreshed: 2, + failed: ['directories'], + }) + }) +}) diff --git a/apps/sim/app/api/cron/people-directory-sync/route.ts b/apps/sim/app/api/cron/people-directory-sync/route.ts index a56a20427b3..3948f1ae0e9 100644 --- a/apps/sim/app/api/cron/people-directory-sync/route.ts +++ b/apps/sim/app/api/cron/people-directory-sync/route.ts @@ -1,3 +1,4 @@ +import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { sweepPeopleDirectoriesContract } from '@/lib/api/contracts/people-sync-cron' import { parseRequest } from '@/lib/api/server' @@ -8,6 +9,13 @@ import { syncDueDirectories } from '@/lib/people/sync/runner' export const maxDuration = 300 +const logger = createLogger('PeopleDirectorySyncCron') + +/** + * Syncs due directories and refreshes due Slack identities, each on its own: either sweep's + * failure is logged and named in `failed`, and the other's result is still reported. Only a + * directory sweep that failed fails the invocation, since a Slack refresh retries on its own. + */ export const GET = withRouteHandler(async (request: NextRequest) => { const authError = verifyCronAuth(request, 'People directory synchronization') if (authError) return authError @@ -17,10 +25,20 @@ export const GET = withRouteHandler(async (request: NextRequest) => { syncDueDirectories(), refreshDueSlackIdentities(), ]) - if (directories.status === 'rejected') throw directories.reason - if (slack.status === 'rejected') throw slack.reason - return NextResponse.json({ - ...directories.value, - slackIdentitiesRefreshed: slack.value.refreshed, - }) + if (directories.status === 'rejected') + logger.error('People directory sweep failed', { error: directories.reason }) + if (slack.status === 'rejected') + logger.error('Slack identity sweep failed', { error: slack.reason }) + const failed = [ + ...(directories.status === 'rejected' ? (['directories'] as const) : []), + ...(slack.status === 'rejected' ? (['slackIdentities'] as const) : []), + ] + return NextResponse.json( + { + attempted: directories.status === 'fulfilled' ? directories.value.attempted : 0, + slackIdentitiesRefreshed: slack.status === 'fulfilled' ? slack.value.refreshed : 0, + ...(failed.length ? { failed } : {}), + }, + { status: directories.status === 'rejected' ? 500 : 200 } + ) }) diff --git a/apps/sim/lib/api/contracts/people-sync-cron.ts b/apps/sim/lib/api/contracts/people-sync-cron.ts index f37a0a531cf..91156d9008b 100644 --- a/apps/sim/lib/api/contracts/people-sync-cron.ts +++ b/apps/sim/lib/api/contracts/people-sync-cron.ts @@ -9,6 +9,8 @@ export const sweepPeopleDirectoriesContract = defineRouteContract({ schema: z.object({ attempted: z.number().int().nonnegative(), slackIdentitiesRefreshed: z.number().int().nonnegative(), + /** The sweeps that failed; each is logged, and the other's count still reported. */ + failed: z.array(z.enum(['directories', 'slackIdentities'])).optional(), }), }, }) diff --git a/apps/sim/lib/core/config/block-visibility.test.ts b/apps/sim/lib/core/config/block-visibility.test.ts index 14fd6034182..ab093c0638c 100644 --- a/apps/sim/lib/core/config/block-visibility.test.ts +++ b/apps/sim/lib/core/config/block-visibility.test.ts @@ -1,10 +1,16 @@ import { envFlagsMockFns, resetEnvFlagsMock, resetEnvMock, setEnv, setEnvFlags } from '@sim/testing' +import { + knowledgeAvailabilityMock, + knowledgeAvailabilityMockFns, +} from '@sim/testing/mocks/knowledge-availability.mock' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' const { mockFetch, mockIsPlatformAdmin } = vi.hoisted(() => ({ mockFetch: vi.fn(), mockIsPlatformAdmin: vi.fn(), })) +/** Organizations with Search on; every other owner lacks it. */ +const searchOrganizations = new Set() beforeAll(() => { setEnv({ APPCONFIG_APPLICATION: 'sim-staging', APPCONFIG_ENVIRONMENT: 'staging' }) @@ -18,6 +24,8 @@ vi.mock('@/lib/permissions/super-user', () => ({ isPlatformAdmin: mockIsPlatformAdmin, })) +vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock) + import { getBlockVisibility } from '@/lib/core/config/block-visibility' /** Make `getBlockVisibility` resolve `doc` via the AppConfig path (also exercises parsing). */ @@ -33,6 +41,12 @@ afterAll(() => { describe('getBlockVisibility', () => { beforeEach(() => { + searchOrganizations.clear() + searchOrganizations.add('search-org') + knowledgeAvailabilityMockFns.mockIsKnowledgeMemberAccessAvailable.mockImplementation( + async ({ organizationId }) => + Boolean(organizationId && searchOrganizations.has(organizationId)) + ) setEnvFlags({ isAppConfigEnabled: false }) envFlagsMockFns.getPreviewBlocksFromEnv.mockReturnValue([]) }) @@ -40,7 +54,7 @@ describe('getBlockVisibility', () => { describe('off-AppConfig (env fallback)', () => { it('reveals and preview-tags the PREVIEW_BLOCKS types without fetching', async () => { envFlagsMockFns.getPreviewBlocksFromEnv.mockReturnValue(['gmail_v2', 'notion_v3']) - const vis = await getBlockVisibility({ userId: 'u1' }) + const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' }) expect(vis.revealed).toEqual(new Set(['gmail_v2', 'notion_v3'])) expect(vis.previewTagged).toEqual(new Set(['gmail_v2', 'notion_v3'])) expect(vis.disabled.size).toBe(0) @@ -101,7 +115,7 @@ describe('getBlockVisibility', () => { c: { enabled: false }, }) mockIsPlatformAdmin.mockResolvedValue(true) - const vis = await getBlockVisibility({ userId: 'u1' }) + const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' }) expect(mockIsPlatformAdmin).toHaveBeenCalledTimes(1) expect(vis.revealed).toEqual(new Set(['a', 'b'])) expect(vis.previewTagged).toEqual(new Set(['a', 'b'])) @@ -126,4 +140,22 @@ describe('getBlockVisibility', () => { expect(mockIsPlatformAdmin).not.toHaveBeenCalled() }) }) + + it.each([ + ['an organization without Search', { appConfig: true, orgId: 'other-org' }], + ['a workspace outside any organization', { appConfig: false, orgId: undefined }], + ])( + 'hides the Organization Search block for %s, and only it', + async (_owner, { appConfig, orgId }) => { + if (appConfig) withAppConfig({}) + const vis = await getBlockVisibility({ userId: 'u1', orgId }) + expect(vis.disabled).toEqual(new Set(['organization'])) + } + ) + + it('offers the Organization Search block where its organization has Search', async () => { + withAppConfig({}) + const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' }) + expect(vis.disabled.has('organization')).toBe(false) + }) }) diff --git a/apps/sim/lib/core/config/block-visibility.ts b/apps/sim/lib/core/config/block-visibility.ts index 066a8e44ede..591f14b8787 100644 --- a/apps/sim/lib/core/config/block-visibility.ts +++ b/apps/sim/lib/core/config/block-visibility.ts @@ -4,6 +4,7 @@ import { matchesRule, parseGateConfig } from '@/lib/core/config/appconfig-rules' import { env } from '@/lib/core/config/env' import { getPreviewBlocksFromEnv, isAppConfigEnabled } from '@/lib/core/config/env-flags' import type { DbOrTx } from '@/lib/db/types' +import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability' /** * Name of the AppConfig configuration profile holding per-block visibility rules. @@ -60,12 +61,22 @@ async function resolveAdmin(userId: string, executor?: DbOrTx): Promise return isPlatformAdmin(userId, executor) } +/** + * Blocks that work only where their organization has a feature, hidden like a kill switch + * everywhere else: the Organization Search block needs Search on in the workspace's organization, + * so a personal workspace or an organization without Search never offers a block that would fail. + */ +async function unavailableOrganizationBlocks(orgId: string | null | undefined): Promise { + if (orgId && (await isKnowledgeMemberAccessAvailable({ organizationId: orgId }))) return [] + return ['organization'] +} + /** * Evaluate the block-visibility document for a viewer. * * On hosted deployments the rules come from the AppConfig profile (cached, * ~30s TTL); off-AppConfig the `PREVIEW_BLOCKS` env allowlist is the only - * reveal path and nothing is disabled. + * reveal path. Either way, a block its organization lacks the feature for is disabled. * * Unlike feature-flags (one rule per call, admin resolved lazily per rule), * this evaluates the whole document, so platform-admin status is resolved at @@ -76,9 +87,10 @@ export async function getBlockVisibility( ctx: BlockVisibilityContext = {}, executor?: DbOrTx ): Promise { + const unavailable = await unavailableOrganizationBlocks(ctx.orgId) if (!isAppConfigEnabled) { const revealed = new Set(getPreviewBlocksFromEnv()) - return { revealed, disabled: new Set(), previewTagged: new Set(revealed) } + return { revealed, disabled: new Set(unavailable), previewTagged: new Set(revealed) } } const rules = @@ -100,7 +112,7 @@ export async function getBlockVisibility( ctx.isAdmin ?? (needsAdmin ? await resolveAdmin(ctx.userId as string, executor) : false) const revealed = new Set() - const disabled = new Set() + const disabled = new Set(unavailable) const previewTagged = new Set() for (const [type, rule] of Object.entries(rules)) { if (matchesRule(rule, ctx, isAdmin)) { From 86d5ab81aeb1367792535be37b630cd9573780aa Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 09:47:33 -0800 Subject: [PATCH 2/3] test(people): pass the route context the handler type expects --- apps/sim/app/api/cron/people-directory-sync/route.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/sim/app/api/cron/people-directory-sync/route.test.ts b/apps/sim/app/api/cron/people-directory-sync/route.test.ts index 649bfe6919a..38480a814ca 100644 --- a/apps/sim/app/api/cron/people-directory-sync/route.test.ts +++ b/apps/sim/app/api/cron/people-directory-sync/route.test.ts @@ -14,7 +14,8 @@ import { GET } from '@/app/api/cron/people-directory-sync/route' function sweep() { return GET( - createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/cron/people-directory-sync') + createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/cron/people-directory-sync'), + undefined ) } From 851d269a071bcf78df5c596f0b0748827e692184 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 10:19:49 -0800 Subject: [PATCH 3/3] fix(organization-search): hide only the Organization Search block when its Search availability cannot be read --- .../cron/people-directory-sync/route.test.ts | 2 +- .../lib/core/config/block-visibility.test.ts | 10 ++++++++++ apps/sim/lib/core/config/block-visibility.ts | 19 +++++++++++++++++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/apps/sim/app/api/cron/people-directory-sync/route.test.ts b/apps/sim/app/api/cron/people-directory-sync/route.test.ts index 38480a814ca..a5e98c7dd0d 100644 --- a/apps/sim/app/api/cron/people-directory-sync/route.test.ts +++ b/apps/sim/app/api/cron/people-directory-sync/route.test.ts @@ -1,5 +1,5 @@ -import { createMockRequest } from '@sim/testing' import { authInternalMock, authInternalMockFns } from '@sim/testing/mocks/auth-internal.mock' +import { createMockRequest } from '@sim/testing/mocks/request.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' const { syncDueDirectories, refreshDueSlackIdentities } = vi.hoisted(() => ({ diff --git a/apps/sim/lib/core/config/block-visibility.test.ts b/apps/sim/lib/core/config/block-visibility.test.ts index ab093c0638c..b51ab4019bd 100644 --- a/apps/sim/lib/core/config/block-visibility.test.ts +++ b/apps/sim/lib/core/config/block-visibility.test.ts @@ -158,4 +158,14 @@ describe('getBlockVisibility', () => { const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' }) expect(vis.disabled.has('organization')).toBe(false) }) + + it('hides only the Organization Search block when its Search availability cannot be read', async () => { + withAppConfig({ gmail_v2: { enabled: true } }) + knowledgeAvailabilityMockFns.mockIsKnowledgeMemberAccessAvailable.mockRejectedValueOnce( + new Error('billing read failed') + ) + const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' }) + expect(vis.disabled).toEqual(new Set(['organization'])) + expect(vis.revealed.has('gmail_v2')).toBe(true) + }) }) diff --git a/apps/sim/lib/core/config/block-visibility.ts b/apps/sim/lib/core/config/block-visibility.ts index 591f14b8787..e78c6e32ef4 100644 --- a/apps/sim/lib/core/config/block-visibility.ts +++ b/apps/sim/lib/core/config/block-visibility.ts @@ -1,3 +1,5 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { fetchAppConfigProfile } from '@/lib/core/config/appconfig' import type { AppConfigGateContext, AppConfigGateRule } from '@/lib/core/config/appconfig-rules' import { matchesRule, parseGateConfig } from '@/lib/core/config/appconfig-rules' @@ -13,6 +15,8 @@ import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availab */ const BLOCK_VISIBILITY_PROFILE = 'block-visibility' +const logger = createLogger('BlockVisibility') + /** * Custom (deploy-as-block) block types are org-scoped and managed by their own * enabled/disabled lifecycle — the visibility document must never gate them. @@ -67,8 +71,19 @@ async function resolveAdmin(userId: string, executor?: DbOrTx): Promise * so a personal workspace or an organization without Search never offers a block that would fail. */ async function unavailableOrganizationBlocks(orgId: string | null | undefined): Promise { - if (orgId && (await isKnowledgeMemberAccessAvailable({ organizationId: orgId }))) return [] - return ['organization'] + if (!orgId) return ['organization'] + try { + return (await isKnowledgeMemberAccessAvailable({ organizationId: orgId })) + ? [] + : ['organization'] + } catch (error) { + // An unknown answer hides only the block it is about; every other block stays offered. + logger.warn('Could not resolve Search availability for block visibility', { + organizationId: orgId, + error: getErrorMessage(error), + }) + return ['organization'] + } } /**