diff --git a/apps/sim/lib/internal/organization-search/catalog.test.ts b/apps/sim/lib/internal/organization-search/catalog.test.ts index a4c16a5f464..fbd5674235d 100644 --- a/apps/sim/lib/internal/organization-search/catalog.test.ts +++ b/apps/sim/lib/internal/organization-search/catalog.test.ts @@ -1,31 +1,46 @@ /** - * Every organization tool reaches every surface: the MCP server registers the catalog by looping - * it, and an entry added without its execution, block tool, block operation or Assistant tool - * fails here rather than in a run. + * Every organization tool reaches the surfaces its catalog entry does not build by itself: a + * workflow run can call it, because each operation it performs admits the executor delegation, + * and the Assistant has it, under its contract's name. */ -import { describe, expect, it, vi } from 'vitest' - -vi.unmock('@/tools/registry') - +import { toArray, toRecord } from '@sim/utils/object' +import { describe, expect, it } from 'vitest' import { assistantToolContracts } from '@/lib/api/contracts/mothership-assistant-tools' +import type { ApplicationOperation } from '@/lib/core/application' import { - ORGANIZATION_TOOL_CATALOG, ORGANIZATION_TOOL_NAMES, - type OrganizationToolEntry, - organizationSearchToolId, + type OrganizationToolName, } from '@/lib/internal/organization-search/catalog' import { ORGANIZATION_TOOLS } from '@/lib/knowledge/application/organization-tool-registry' import { getRegisteredServerToolNames } from '@/lib/mothership/tools/server/router' -import { OrganizationBlock } from '@/blocks/blocks/organization' -import { tools } from '@/tools/registry' + +/** The Assistant's names that differ from the Search MCP's. */ +const ASSISTANT_NAMES: Partial> = { + search: 'search_workspace', +} + +/** Inputs that steer a tool to each operation it can perform. */ +const INPUTS: Partial> = { + search_people: [{}, { personId: 'person-1' }], +} + +/** The delegated services an operation admits from an organization caller. */ +function organizationDelegatedServices(operation: ApplicationOperation): string[] { + const organizational = + 'organizationOperation' in operation ? operation.organizationOperation : operation + return toArray(toRecord(organizational).delegatedServices) +} describe('organization tool catalog', () => { - it.each(ORGANIZATION_TOOL_NAMES)('offers %s on every surface', (name) => { - const entry: OrganizationToolEntry = ORGANIZATION_TOOL_CATALOG[name] - const assistantName = entry.assistantName ?? name - expect(Object.keys(ORGANIZATION_TOOLS)).toContain(name) - expect(tools[organizationSearchToolId(name)]?.id).toBe(organizationSearchToolId(name)) - expect(OrganizationBlock.tools.access).toContain(organizationSearchToolId(name)) + it.each(ORGANIZATION_TOOL_NAMES)('lets a workflow run call %s', (name) => { + for (const input of INPUTS[name] ?? [{}]) { + const { operation } = ORGANIZATION_TOOLS[name].prepare(input) + expect(organizationDelegatedServices(operation)).toContain('executor') + } + }) + + it.each(ORGANIZATION_TOOL_NAMES)('gives the Assistant %s', (name) => { + const assistantName = ASSISTANT_NAMES[name] ?? name expect(assistantToolContracts.map((contract) => contract.id)).toContain(assistantName) expect(getRegisteredServerToolNames()).toContain(assistantName) }) diff --git a/apps/sim/lib/internal/organization-search/catalog.ts b/apps/sim/lib/internal/organization-search/catalog.ts index 905a6fb9ccf..08cf6186462 100644 --- a/apps/sim/lib/internal/organization-search/catalog.ts +++ b/apps/sim/lib/internal/organization-search/catalog.ts @@ -53,14 +53,8 @@ export const ORGANIZATION_TOOL_NAMES = [ export type OrganizationToolName = (typeof ORGANIZATION_TOOL_NAMES)[number] export interface OrganizationToolEntry { - /** The Search MCP tool name, and the block operation that runs it. */ - name: OrganizationToolName - /** The MCP tool's title. */ - title: string - /** The block operation's label. */ + /** The block operation's label; the MCP tool's title is the same words in sentence case. */ label: string - /** The organization Assistant's name for it, whose contract describes it there; the MCP name when the same. */ - assistantName?: string /** The input every surface parses: the Search MCP schema, which reads a date without an offset as UTC. */ inputSchema: z.ZodType /** The arguments a workflow run's secret could fill, projected out of what the tool returns. */ @@ -88,10 +82,7 @@ function nameOn(surface: DescriptionSurface, name: OrganizationToolName): string /** Each organization tool, by name; `ORGANIZATION_TOOL_NAMES` orders them. */ export const ORGANIZATION_TOOL_CATALOG = { search: { - name: 'search', - title: 'Search', label: 'Search', - assistantName: 'search_workspace', inputSchema: liveSearchMcpSchema, modelInputPaths: ['query', 'source', 'involving', 'nativeQueries', 'documentIds'], description: ({ surface, offers }): string => { @@ -103,8 +94,6 @@ export const ORGANIZATION_TOOL_CATALOG = { }, }, read_document: { - name: 'read_document', - title: 'Read document', label: 'Read Document', inputSchema: readLiveDocumentMcpSchema, modelInputPaths: ['documentId', 'documentIds'], @@ -112,8 +101,6 @@ export const ORGANIZATION_TOOL_CATALOG = { `Read live documents using the exact document IDs returned by ${nameOn(surface, 'search')}: documentId for one, or documentIds to read several in one call rather than one call each. ${surface === 'mcp' ? 'A link the user shares' : 'A link'} to a Google Drive, Gmail, Calendar, Slack, Jira, Confluence, GitHub, GitLab, Linear, Notion or Fireflies item reads the same way, without searching for it first. Access and the admin’s source settings are checked again on every read. When a document’s hasMore is true, pass its next.startChunkIndex and next.startOffset with the returned documentId to continue. Cite citationUrl when available.${surface === 'workflow' ? RUN_LOGS : ''}`, }, search_people: { - name: 'search_people', - title: 'Search people', label: 'Search People', inputSchema: searchPeopleInputSchema, modelInputPaths: [ @@ -131,8 +118,6 @@ export const ORGANIZATION_TOOL_CATALOG = { `Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use ${nameOn(surface, 'search')} for customers, vendors, and other outside contacts.${offers('search_experts') ? ` Who knows a topic: ${nameOn(surface, 'search_experts')}.` : ''}${surface === 'workflow' ? RUN_LOGS : ''}`, }, list_my_chat_history: { - name: 'list_my_chat_history', - title: 'List my chat history', label: 'List My Chat History', inputSchema: listMyChatHistoryMcpSchema, modelInputPaths: [], @@ -143,8 +128,6 @@ export const ORGANIZATION_TOOL_CATALOG = { : `List the questions the person running the workflow asked Sim between startDate (inclusive, 7 days before endDate by default) and endDate (exclusive, now by default; at most 92 days apart), newest first unless sortBy is oldest: the Assistant, agent chats, the Slack app and Search MCP chat. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only their own conversations that still exist are listed. The first page carries total, the number of questions in the window; follow nextCursor for the next page.${RUN_LOGS}`, }, search_experts: { - name: 'search_experts', - title: 'Search experts', label: 'Search Experts', inputSchema: searchExpertsMcpSchema, modelInputPaths: ['query', 'source', 'startDate', 'endDate', 'department', 'location'], @@ -155,8 +138,6 @@ export const ORGANIZATION_TOOL_CATALOG = { : `${SEARCH_EXPERTS_DESCRIPTION.replace('items you can read', 'items the person running the workflow can read').replace('your own access', 'their own access')}${RUN_LOGS}`, }, list_my_activity: { - name: 'list_my_activity', - title: 'List my activity', label: 'List My Activity', inputSchema: listMyActivityMcpSchema, modelInputPaths: [], @@ -169,7 +150,7 @@ export const ORGANIZATION_TOOL_CATALOG = { return `List what ${who} did across ${their} connected sources in a date window, always newest first, each at its activity time: Slack messages and Gmail mail ${they} sent (replied when the message answers another), Google Calendar meetings ${they} organized or accepted (attended), Jira issues ${they} created or that were assigned to ${surface === 'mcp' ? 'you' : 'them'}, Confluence pages ${they} created or edited and comments ${they} wrote, GitHub issues and pull requests ${they} opened (created) and commits ${they} authored (committed), Linear issues ${they} created, Google Drive files ${they} created or edited, and the GitHub issues and pull requests and Linear issues ${they} are involved in or assigned (involved, at their last update, which may be someone else’s). Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for ${nameOn(surface, 'read_document')} and, when available, a citationUrl to cite. While nextCursor is present, call again with it and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where ${they} connect that account. unsupported names connected sources this listing does not cover; search those for the same dates with the filters each supports. For a colleague’s activity, use ${nameOn(surface, 'search')} with involving.${surface === 'workflow' ? RUN_LOGS : ''}` }, }, -} as const satisfies { [Name in OrganizationToolName]: OrganizationToolEntry & { name: Name } } +} as const satisfies Record /** The block's operations, one per tool. */ export const ORGANIZATION_SEARCH_OPERATIONS = ORGANIZATION_TOOL_NAMES.map((name) => ({ @@ -180,6 +161,12 @@ export const ORGANIZATION_SEARCH_OPERATIONS = ORGANIZATION_TOOL_NAMES.map((name) /** The internal tool that runs an operation. */ export type OrganizationSearchToolId = `organization_${OrganizationToolName}` +/** The MCP tool's title: its block label in sentence case, such as `Read document`. */ +export function organizationToolTitle(name: OrganizationToolName): string { + const { label } = ORGANIZATION_TOOL_CATALOG[name] + return label.charAt(0) + label.slice(1).toLowerCase() +} + /** The tool an operation runs. */ export function organizationSearchToolId( operation: OrganizationToolName diff --git a/apps/sim/lib/internal/organization-search/execute-tool.ts b/apps/sim/lib/internal/organization-search/execute-tool.ts index 3b20d8686c0..39e7e78e0a3 100644 --- a/apps/sim/lib/internal/organization-search/execute-tool.ts +++ b/apps/sim/lib/internal/organization-search/execute-tool.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { isPlainRecord } from '@sim/utils/object' import { orchestrationFailureResponse } from '@/lib/api/server/orchestration-response' +import { serializeZodIssues } from '@/lib/api/server/validation' import { RESOLVED_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata' import { ORGANIZATION_TOOL_CATALOG, @@ -13,7 +14,6 @@ import { internalToolIdentityFaultMessage, internalToolIdentityFaultStatus, } from '@/lib/internal/tool-operations/identity-faults' -import { parseInternalOperationInput } from '@/lib/internal/tool-operations/parse-contract-input' import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types' import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' import { KNOWLEDGE_DELEGATION_AUDIENCE } from '@/lib/knowledge/application/authorization' @@ -61,19 +61,22 @@ export const executeOrganizationSearchTool: InternalToolOperationHandler = async await requireOrganizationSearchAvailable(principal.organizationId) const raw = isPlainRecord(request.input) ? request.input : {} const { [RESOLVED_SECRET_PROVENANCE_FIELD]: _provenance, ...fields } = raw - const { inputSchema, modelInputPaths } = ORGANIZATION_TOOL_CATALOG[name] - const parsed = parseInternalOperationInput({ body: inputSchema }, fields) - if (!parsed.success) return parsed.response - const input: unknown = parsed.data.body + const call = ORGANIZATION_TOOLS[name].prepare(fields) + if (call.error) + return Response.json( + { error: 'Validation error', details: serializeZodIssues(call.error) }, + { status: 400 } + ) + const { input } = call // Every argument a run's secret could fill is projected out of what the tool returns. const modelInput = isPlainRecord(input) - ? modelInputPaths.map((path) => input[path]).filter(Boolean) + ? ORGANIZATION_TOOL_CATALOG[name].modelInputPaths.map((path) => input[path]).filter(Boolean) : [] return await respondWithResultProvenance( { principal, operation: request }, modelInput.length ? modelInput : undefined, (registry) => - ORGANIZATION_TOOLS[name].execute(input, { + call.run({ principal, organizationId: principal.organizationId, registry, diff --git a/apps/sim/lib/knowledge/application/organization-tool-registry.ts b/apps/sim/lib/knowledge/application/organization-tool-registry.ts index a47bbbe0b09..a6b22e8b032 100644 --- a/apps/sim/lib/knowledge/application/organization-tool-registry.ts +++ b/apps/sim/lib/knowledge/application/organization-tool-registry.ts @@ -44,30 +44,51 @@ interface OrganizationToolRun { execute: (input: z.output, context: OrganizationToolContext) => Promise } -/** A tool's run, taking any input: it parses with the catalog schema before it runs. */ +/** + * One call of a tool, its input parsed once with the catalog schema: the operation and cost it + * counts as, and its run. Input that does not parse carries its error, counts as the tool's + * default operation once, and fails when run. + */ +interface PreparedOrganizationToolCall { + /** The parsed input, or the raw input when it did not parse. */ + input: unknown + error?: z.ZodError + operation: ApplicationOperation + /** The operations the call counts as, or undefined for one. */ + cost?: number + run: (context: OrganizationToolContext) => Promise +} + +/** A tool's execution: it prepares each call from any input. */ export interface OrganizationToolExecution { - operation: (input: unknown) => ApplicationOperation - /** The operations a call counts as, or undefined for one. */ - cost: (input: unknown) => number | undefined - execute: (input: unknown, context: OrganizationToolContext) => Promise + prepare: (input: unknown) => PreparedOrganizationToolCall } -/** A tool's run over its catalog input schema, which parses every call before it runs. */ +/** A tool's execution over its catalog input schema. */ function bind( schema: Schema, run: OrganizationToolRun ): OrganizationToolExecution { - const parsed = (input: unknown) => schema.safeParse(input) return { - operation: (input) => { - const result = run.operationFor && parsed(input) - return result?.success && run.operationFor ? run.operationFor(result.data) : run.operation - }, - cost: (input) => { - const result = run.cost && parsed(input) - return result?.success && run.cost ? run.cost(result.data) : undefined + prepare: (raw) => { + const parsed = schema.safeParse(raw) + if (!parsed.success) + return { + input: raw, + error: parsed.error, + operation: run.operation, + run: async () => { + throw parsed.error + }, + } + const input = parsed.data + return { + input, + operation: run.operationFor ? run.operationFor(input) : run.operation, + cost: run.cost?.(input), + run: (context) => run.execute(input, context), + } }, - execute: (input, context) => run.execute(schema.parse(input), context), } } diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index ade792537b4..36637916413 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -7,6 +7,7 @@ import type { NextRequest } from 'next/server' import { chatSearchMcpSchema } from '@/lib/api/contracts/knowledge/mcp' import type { V2ApiKeyAuthContext } from '@/lib/api/server/routes/v2-api-key-auth' import { v2RateLimits } from '@/lib/api/server/routes/v2-json-route' +import type { ApplicationOperation } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' import { afterResponse } from '@/lib/core/utils/after-response' import { @@ -14,6 +15,7 @@ import { ORGANIZATION_TOOL_NAMES, type OrganizationToolEntry, type OrganizationToolName, + organizationToolTitle, } from '@/lib/internal/organization-search/catalog' import { organizationSearchChatOperation } from '@/lib/knowledge/application/chat-operations' import { ORGANIZATION_TOOLS } from '@/lib/knowledge/application/organization-tool-registry' @@ -22,16 +24,59 @@ import { recordOrganizationSearchMcpActivity, type SearchMcpActivityInput, } from '@/lib/knowledge/mcp/activity' -import { - KNOWLEDGE_MCP_READ_ONLY, - type KnowledgeMcpToolRunner, - projectResult, -} from '@/lib/knowledge/mcp/tool-runner' import { toolError } from '@/lib/mcp/tool-result' +import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' const logger = createLogger('KnowledgeMcp') +const MAX_RESULT_BYTES = 1024 * 1024 +/** The annotations of every read-only Search MCP tool. */ +const KNOWLEDGE_MCP_READ_ONLY = { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, +} as const + +/** + * Runs one Search MCP tool call: rate limit, cancellation, error projection and activity. + */ +type KnowledgeMcpToolRunner = ( + toolName: SearchMcpActivityInput['toolName'], + operation: ApplicationOperation, + toolSignal: AbortSignal, + run: ( + registry: ResolvedSecretTraceRegistry, + signal: AbortSignal, + /** + * Admits further operations for a call whose size is known only once it runs, before it does + * that work. Resolves to the rate-limit message when the budget cannot cover them. + */ + charge: (cost: number) => Promise + ) => Promise, + /** Operations the call performs for the rate limit, such as each document a batched read reads. */ + cost?: number +) => Promise + +/** A tool result projected for its resolved secrets and bounded in size. */ +function projectResult(value: unknown, registry: ResolvedSecretTraceRegistry): CallToolResult { + if (!registry.isComplete()) { + return toolError( + 'Document secret provenance is unavailable. The content cannot be returned safely.' + ) + } + const projected = projectResolvedSecretModelContent(value, registry, MAX_RESULT_BYTES) + if (!projected.safe) { + return toolError('This result cannot be safely returned. Try a smaller result page.') + } + const text = JSON.stringify(projected.value) + if (Buffer.byteLength(text) > MAX_RESULT_BYTES) { + return toolError('Result is too large. Request fewer results or a smaller page.') + } + return { content: [{ type: 'text', text }] } +} + /** Characters of text a tool result hands the client. */ function resultCharacters(result: CallToolResult): number { return result.content.reduce( @@ -135,24 +180,25 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe const registerOrganizationTool = (name: OrganizationToolName) => { if (!offers(name)) return - const { title, inputSchema, description } = ORGANIZATION_TOOL_CATALOG[name] + const { inputSchema, description } = ORGANIZATION_TOOL_CATALOG[name] const tool = ORGANIZATION_TOOLS[name] server.registerTool( name, { - title, + title: organizationToolTitle(name), description: description({ surface: 'mcp', offers }), inputSchema, annotations: KNOWLEDGE_MCP_READ_ONLY, }, - async (input: unknown, extra: { signal: AbortSignal }) => - execute( + async (input: unknown, extra: { signal: AbortSignal }) => { + const call = tool.prepare(input) + return execute( name, - tool.operation(input), + call.operation, extra.signal, async (registry, signal, charge) => projectResult( - await tool.execute(input, { + await call.run({ principal, organizationId, registry, @@ -167,8 +213,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe }), registry ), - tool.cost(input) + call.cost ) + } ) } diff --git a/apps/sim/lib/knowledge/mcp/tool-runner.ts b/apps/sim/lib/knowledge/mcp/tool-runner.ts deleted file mode 100644 index 646fef44bd0..00000000000 --- a/apps/sim/lib/knowledge/mcp/tool-runner.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js' -import type { ApplicationOperation } from '@/lib/core/application' -import type { SearchMcpActivityInput } from '@/lib/knowledge/mcp/activity' -import { toolError } from '@/lib/mcp/tool-result' -import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' -import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' - -const MAX_RESULT_BYTES = 1024 * 1024 -/** The annotations of every read-only Search MCP tool. */ -export const KNOWLEDGE_MCP_READ_ONLY = { - readOnlyHint: true, - destructiveHint: false, - idempotentHint: true, - openWorldHint: false, -} as const - -/** - * Runs one Search MCP tool call: rate limit, cancellation, error projection and activity. Handed - * to every tool registration so each backend's tools share it. - */ -export type KnowledgeMcpToolRunner = ( - toolName: SearchMcpActivityInput['toolName'], - operation: ApplicationOperation, - toolSignal: AbortSignal, - run: ( - registry: ResolvedSecretTraceRegistry, - signal: AbortSignal, - /** - * Admits further operations for a call whose size is known only once it runs, before it does - * that work. Resolves to the rate-limit message when the budget cannot cover them. - */ - charge: (cost: number) => Promise - ) => Promise, - /** Operations the call performs for the rate limit, such as each document a batched read reads. */ - cost?: number -) => Promise - -/** A tool result projected for its resolved secrets and bounded in size. */ -export function projectResult( - value: unknown, - registry: ResolvedSecretTraceRegistry -): CallToolResult { - if (!registry.isComplete()) { - return toolError( - 'Document secret provenance is unavailable. The content cannot be returned safely.' - ) - } - const projected = projectResolvedSecretModelContent(value, registry, MAX_RESULT_BYTES) - if (!projected.safe) { - return toolError('This result cannot be safely returned. Try a smaller result page.') - } - const text = JSON.stringify(projected.value) - if (Buffer.byteLength(text) > MAX_RESULT_BYTES) { - return toolError('Result is too large. Request fewer results or a smaller page.') - } - return { content: [{ type: 'text', text }] } -} diff --git a/apps/sim/lib/people/slack-identities.integration.ts b/apps/sim/lib/people/slack-identities.integration.ts index c11aaec8695..18c80a59a7a 100644 --- a/apps/sim/lib/people/slack-identities.integration.ts +++ b/apps/sim/lib/people/slack-identities.integration.ts @@ -12,6 +12,7 @@ import { slackSearchInstallation, user, } from '@sim/db/schema' +import { createDeferred } from '@sim/testing/helpers/deferred' import { generateId } from '@sim/utils/id' import { and, eq, gte, inArray } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, expect, it, vi } from 'vitest' @@ -353,6 +354,38 @@ it('refreshes the never-visited and longest-overdue organizations first', async } }) +it('skips an organization another sweep is leasing instead of waiting for it', async () => { + const busy = generateId() + await insertBotOrganization(busy) + await db.insert(peopleSlackSync).values({ organizationId: busy, nextRefreshAt: new Date(-1000) }) + const holding = createDeferred() + const release = createDeferred() + const holder = db.transaction(async (tx) => { + await tx + .select() + .from(peopleSlackSync) + .where(eq(peopleSlackSync.organizationId, busy)) + .for('update') + holding.resolve() + await release.promise + }) + await holding.promise + try { + listMembers.mockResolvedValue(page([])) + const started = Date.now() + await sweepNow() + const [state] = await db + .select({ refreshedAt: peopleSlackSync.refreshedAt }) + .from(peopleSlackSync) + .where(eq(peopleSlackSync.organizationId, organizationId)) + expect(state.refreshedAt?.getTime()).toBeGreaterThanOrEqual(started) + } finally { + release.resolve() + await holder + await db.delete(organization).where(eq(organization.id, busy)) + } +}, 15_000) + it('clears the list once the Slack Search bot is disabled', async () => { await db .update(slackSearchInstallation) diff --git a/apps/sim/lib/people/slack-identities.ts b/apps/sim/lib/people/slack-identities.ts index 163e6009a4d..1233cf53987 100644 --- a/apps/sim/lib/people/slack-identities.ts +++ b/apps/sim/lib/people/slack-identities.ts @@ -47,33 +47,39 @@ function botless(organizationId: SQL) { } /** - * Leases the next due organization: one with an enabled Slack Search bot, or one whose last bot - * was disabled or removed, so its identities go. The never-visited come first, then the longest - * overdue. The lease is fenced by its token, so a sweep that outlives it cannot overwrite the - * next one's work. + * Gives every organization with an enabled Slack Search bot and no refresh state one, due at the + * epoch, so it leases ahead of every organization already visited. + */ +async function enrollNewOrganizations(): Promise { + await db.execute(sql` + INSERT INTO ${refresh} (organization_id, next_refresh_at) + SELECT DISTINCT i.organization_id, to_timestamp(0) FROM ${installation} i + WHERE i.enabled + ON CONFLICT (organization_id) DO NOTHING + `) +} + +/** + * Leases the next due organization, the longest overdue first: one whose refresh is due, or one + * whose last bot was disabled or removed, so its identities go. A row another sweep is leasing at + * this moment is skipped, not waited on, so concurrent sweeps take different organizations. The + * lease is fenced by its token, so a sweep that outlives it cannot overwrite the next one's work. */ async function leaseNext(): Promise { const leaseToken = generateId() const [lease] = await db.execute(sql` - WITH candidates AS ( - SELECT i.organization_id, r.next_refresh_at FROM ${installation} i - LEFT JOIN ${refresh} r ON r.organization_id = i.organization_id - WHERE i.enabled AND (r.organization_id IS NULL OR r.next_refresh_at <= now()) - UNION - SELECT r.organization_id, r.next_refresh_at FROM ${refresh} r + WITH due AS ( + SELECT r.organization_id FROM ${refresh} r WHERE r.next_refresh_at <= now() OR (r.lease_token IS NULL AND ${botless(sql`r.organization_id`)}) - ), - due AS ( - SELECT organization_id FROM candidates GROUP BY organization_id - ORDER BY min(next_refresh_at) NULLS FIRST, organization_id LIMIT 1 + ORDER BY r.next_refresh_at, r.organization_id + LIMIT 1 + FOR UPDATE SKIP LOCKED ) - INSERT INTO ${refresh} (organization_id, next_refresh_at, lease_token) - SELECT organization_id, now() + make_interval(secs => ${LEASE_MS / 1000}), ${leaseToken} FROM due - ON CONFLICT (organization_id) DO UPDATE - SET next_refresh_at = excluded.next_refresh_at, lease_token = excluded.lease_token - WHERE ${refresh.nextRefreshAt} <= now() - OR (${refresh.leaseToken} IS NULL AND ${botless(sql`${refresh.organizationId}`)}) - RETURNING organization_id AS "organizationId", lease_token AS "leaseToken" + UPDATE ${refresh} SET + next_refresh_at = now() + make_interval(secs => ${LEASE_MS / 1000}), + lease_token = ${leaseToken} + FROM due WHERE ${refresh.organizationId} = due.organization_id + RETURNING ${refresh.organizationId} AS "organizationId", ${refresh.leaseToken} AS "leaseToken" `) return lease } @@ -246,6 +252,7 @@ const LEASES_PER_SWEEP = 20 export async function refreshDueSlackIdentities() { let refreshed = 0 let slots = REFRESHES_PER_SWEEP + await enrollNewOrganizations() for (let leases = 0; slots > 0 && leases < LEASES_PER_SWEEP; leases++) { const lease = await leaseNext() if (!lease) break diff --git a/apps/sim/lib/workflows/executor/resume-steering.integration.ts b/apps/sim/lib/workflows/executor/resume-steering.integration.ts new file mode 100644 index 00000000000..0fc40ef2aef --- /dev/null +++ b/apps/sim/lib/workflows/executor/resume-steering.integration.ts @@ -0,0 +1,286 @@ +/** + * Resume steering end to end, against real PostgreSQL and the real executor: a deployed run that + * pauses for approval, is resumed by someone, and then reaches an Organization Search block, which + * acts as the person who started the run. A run another member resumed must refuse there, and keep + * refusing after a later timer resume, which records no resumer of its own. + */ +import { db } from '@sim/db' +import { + member, + organization, + pausedExecutions, + permissions, + resumeQueue, + user, + workflow, + workflowDeploymentVersion, + workflowExecutionLogs, + workflowExecutionSnapshots, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createBlock } from '@sim/testing/factories/block.factory' +import { + createPersonalApiKeyPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' +import { featureFlagsMock } from '@sim/testing/mocks/feature-flags.mock' +import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock' +import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' +import { executeWorkflowOperation } from '@/lib/workflows/application/execute-workflow' +import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' +import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' +import { loadWorkflowDeploymentSnapshot } from '@/lib/workflows/persistence/utils' + +vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) +vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) +vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock) + +const organizationId = generateId() +const starterId = generateId() +const colleagueId = generateId() +const workspaceId = generateId() +const REFUSAL = 'this run was resumed by someone else' + +const approval = (id: string) => + createBlock({ + id, + type: 'human_in_the_loop', + name: 'Approval', + position: { x: 300, y: 0 }, + subBlocks: { + inputFormat: { + id: 'inputFormat', + type: 'input-format', + value: [{ id: 'approved', name: 'approved', type: 'boolean', required: true }], + }, + }, + }) + +const chatHistory = (id: string) => + createBlock({ + id, + type: 'organization', + name: 'History', + position: { x: 900, y: 0 }, + subBlocks: { + operation: { id: 'operation', type: 'dropdown', value: 'list_my_chat_history' }, + }, + }) + +/** Deploys a chain of blocks, each running after the one before. */ +async function deployChain(blocks: ReturnType[]): Promise { + const workflowId = generateId() + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId: starterId, + workspaceId, + name: `Resume steering ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const saved = await saveWorkflowToNormalizedTables(workflowId, { + blocks: Object.fromEntries(blocks.map((block) => [block.id, block])), + edges: blocks.slice(1).map((block, index) => ({ + id: generateId(), + source: blocks[index].id, + target: block.id, + })), + loops: {}, + parallels: {}, + }) + if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`) + const deployed = await loadWorkflowDeploymentSnapshot(workflowId) + if (!deployed) throw new Error('The seeded draft has no deployment snapshot') + await db + .insert(workflowDeploymentVersion) + .values({ id: generateId(), workflowId, version: 1, state: deployed, isActive: true }) + await db + .update(workflow) + .set({ isDeployed: true, deployedAt: now }) + .where(eq(workflow.id, workflowId)) + return workflowId +} + +/** Starts the deployed workflow as its starter and waits for its pause to be published. */ +async function pausedRun(workflowId: string) { + const result = await executeWorkflowOperation.execute({ + principal: createSessionPrincipal({ userId: starterId, sessionId: generateId() }), + input: { + workflowId, + requestId: generateId(), + input: {}, + mode: 'sync', + requestHeaders: new Headers(), + }, + }) + if (!result.ok || !('status' in result) || result.status !== 'paused') + throw new Error('Expected the run to pause') + return pausedPoint(result.executionId) +} + +async function pausedPoint(executionId: string, kind?: 'time') { + return vi.waitFor( + async () => { + const [row] = await db + .select() + .from(pausedExecutions) + .where(eq(pausedExecutions.executionId, executionId)) + const point = Object.values( + (row?.pausePoints ?? {}) as Record> + ).find( + (candidate) => + candidate.resumeStatus === 'paused' && (!kind || candidate.pauseKind === kind) + ) + if (!row || !point) throw new Error('Pause not yet published') + return { row, executionId, contextId: String(point.contextId) } + }, + { timeout: 20_000, interval: 250 } + ) +} + +/** Approves the run as `userId`, through the same resume use case the API serves. */ +function approveAs(userId: string, workflowId: string, runId: string, contextId: string) { + return resumeWorkflowRun.execute({ + principal: createPersonalApiKeyPrincipal({ userId, keyId: generateId() }), + input: { workflowId, runId, contextId, resumeInput: { approved: true }, surface: 'v2' }, + }) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [starterId, colleagueId].map((id) => ({ + id, + name: 'Resume steering fixture', + email: `${id}@resume-steering.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db + .insert(organization) + .values({ id: organizationId, slug: organizationId, name: 'Resume steering', createdAt: now }) + await db.insert(member).values( + [starterId, colleagueId].map((userId) => ({ + id: generateId(), + organizationId, + userId, + role: 'member', + })) + ) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Resume steering fixture', + ownerId: starterId, + billedAccountUserId: starterId, + organizationId, + }) + await db.insert(permissions).values( + [starterId, colleagueId].map((userId) => ({ + id: generateId(), + userId, + entityType: 'workspace' as const, + entityId: workspaceId, + permissionType: 'admin' as const, + })) + ) +}) + +afterAll(async () => { + const workflows = await db + .select({ id: workflow.id }) + .from(workflow) + .where(eq(workflow.workspaceId, workspaceId)) + const ids = workflows.map(({ id }) => id) + if (ids.length) { + const paused = await db + .select({ executionId: pausedExecutions.executionId }) + .from(pausedExecutions) + .where(inArray(pausedExecutions.workflowId, ids)) + for (const { executionId } of paused) + await db.delete(resumeQueue).where(eq(resumeQueue.parentExecutionId, executionId)) + await db.delete(pausedExecutions).where(inArray(pausedExecutions.workflowId, ids)) + await db.delete(workflowExecutionLogs).where(inArray(workflowExecutionLogs.workflowId, ids)) + await db + .delete(workflowExecutionSnapshots) + .where(inArray(workflowExecutionSnapshots.workflowId, ids)) + } + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, [starterId, colleagueId])) + await db.$client.end() +}) + +it('lets the organization block act as the starter when the starter resumes the run', async () => { + const workflowId = await deployChain([ + createBlock({ id: generateId(), type: 'start_trigger', name: 'Start' }), + approval(generateId()), + chatHistory(generateId()), + ]) + const { executionId, contextId } = await pausedRun(workflowId) + const resumed = await approveAs(starterId, workflowId, executionId, contextId) + expect(resumed).toMatchObject({ kind: 'sync', success: true }) +}) + +it('refuses the organization block in a run another member resumed', async () => { + const workflowId = await deployChain([ + createBlock({ id: generateId(), type: 'start_trigger', name: 'Start' }), + approval(generateId()), + chatHistory(generateId()), + ]) + const { executionId, contextId } = await pausedRun(workflowId) + const resumed = await approveAs(colleagueId, workflowId, executionId, contextId) + expect(resumed).toMatchObject({ kind: 'sync', success: false }) + expect(JSON.stringify(resumed)).toContain(REFUSAL) +}) + +it('keeps refusing after a later timer resume, which records no resumer of its own', async () => { + const workflowId = await deployChain([ + createBlock({ id: generateId(), type: 'start_trigger', name: 'Start' }), + approval(generateId()), + createBlock({ + id: generateId(), + type: 'wait', + name: 'Wait', + position: { x: 600, y: 0 }, + subBlocks: { + async: { id: 'async', type: 'switch', value: true }, + timeValue: { id: 'timeValue', type: 'short-input', value: '1' }, + timeUnitLong: { id: 'timeUnitLong', type: 'dropdown', value: 'minutes' }, + }, + }), + chatHistory(generateId()), + ]) + const { executionId, contextId } = await pausedRun(workflowId) + const approved = await approveAs(colleagueId, workflowId, executionId, contextId) + expect(approved).toMatchObject({ kind: 'sync', success: true, status: 'paused' }) + + // The timer fires as the resume poller fires it: no caller, so no resumer recorded. + const timer = await pausedPoint(executionId, 'time') + const started = await PauseResumeManager.enqueueOrStartResume({ + executionId, + workflowId, + contextId: timer.contextId, + resumeInput: {}, + userId: starterId, + allowedPauseKinds: ['time'], + }) + if (started.status !== 'starting') throw new Error('Expected the timer resume to start') + const result = await PauseResumeManager.startResumeExecution({ + resumeEntryId: started.resumeEntryId, + resumeExecutionId: started.resumeExecutionId, + pausedExecution: started.pausedExecution, + contextId: started.contextId, + resumeInput: started.resumeInput, + userId: started.userId, + }).catch((error: { executionResult?: unknown }) => error.executionResult ?? error) + expect(JSON.stringify(result)).toContain(REFUSAL) +}) diff --git a/apps/sim/tools/organization/index.ts b/apps/sim/tools/organization/index.ts index bcc78cecd8e..c077d003eec 100644 --- a/apps/sim/tools/organization/index.ts +++ b/apps/sim/tools/organization/index.ts @@ -1,5 +1,6 @@ import { z } from 'zod' import { + ORGANIZATION_SEARCH_OPERATIONS, ORGANIZATION_TOOL_CATALOG, ORGANIZATION_TOOL_NAMES, type OrganizationToolEntry, @@ -161,7 +162,11 @@ function organizationBlockTool( return { id: organizationSearchToolId(name), name: `Organization ${tool.label}`, - description: tool.description({ surface: 'workflow', offers: () => true }), + // A block run offers every operation the block lists; each one's own gates refuse at run time. + description: tool.description({ + surface: 'workflow', + offers: (other) => ORGANIZATION_SEARCH_OPERATIONS.some(({ id }) => id === other), + }), version: '1.0.0', effect: 'read', params,