diff --git a/apps/sim/blocks/blocks/google_forms.test.ts b/apps/sim/blocks/blocks/google_forms.test.ts index b55c0670b23..db62f9cfbad 100644 --- a/apps/sim/blocks/blocks/google_forms.test.ts +++ b/apps/sim/blocks/blocks/google_forms.test.ts @@ -10,4 +10,25 @@ describe('GoogleFormsBlock agent tool calls', () => { const mapped = GoogleFormsBlock.tools.config?.params?.(inputs, { operation: 'get_responses' }) expect(mapped).toMatchObject({ formId: 'form-1', pageSize: 5 }) }) + + it.each([ + { operation: 'create_form', inputs: { documentTitle: 'd' }, missing: 'title' }, + { operation: 'create_watch', inputs: { formId: 'f', topicName: 't' }, missing: 'eventType' }, + { + operation: 'create_watch', + inputs: { formId: 'f', eventType: 'RESPONSES' }, + missing: 'topicName', + }, + { operation: 'delete_watch', inputs: { formId: 'f' }, missing: 'watchId' }, + { operation: 'renew_watch', inputs: { formId: 'f' }, missing: 'watchId' }, + ])( + 'leaves a $missing the model omitted on $operation for the required-param check', + ({ operation, inputs, missing }) => { + const mapped = GoogleFormsBlock.tools.config?.params?.( + { oauthCredential: 'cred-1', ...inputs }, + { operation } + ) + expect(mapped?.[missing]).toBeUndefined() + } + ) }) diff --git a/apps/sim/blocks/blocks/google_forms.ts b/apps/sim/blocks/blocks/google_forms.ts index 765a518334f..8761fed0e0f 100644 --- a/apps/sim/blocks/blocks/google_forms.ts +++ b/apps/sim/blocks/blocks/google_forms.ts @@ -355,7 +355,7 @@ Example for "Add a required multiple choice question about favorite color": case 'create_form': return { ...baseParams, - title: String(title).trim(), + title: title == null ? undefined : String(title).trim(), documentTitle: documentTitle ? String(documentTitle).trim() : undefined, unpublished: unpublished ?? false, } @@ -377,8 +377,8 @@ Example for "Add a required multiple choice question about favorite color": return { ...baseParams, formId: effectiveFormId, - eventType: String(eventType), - topicName: String(topicName).trim(), + eventType: eventType == null ? undefined : String(eventType), + topicName: topicName == null ? undefined : String(topicName).trim(), watchId: watchId ? String(watchId).trim() : undefined, } case 'delete_watch': @@ -386,7 +386,7 @@ Example for "Add a required multiple choice question about favorite color": return { ...baseParams, formId: effectiveFormId, - watchId: String(watchId).trim(), + watchId: watchId == null ? undefined : String(watchId).trim(), } default: throw new Error(`Invalid Google Forms operation: ${operation}`) diff --git a/apps/sim/blocks/blocks/hubspot.test.ts b/apps/sim/blocks/blocks/hubspot.test.ts new file mode 100644 index 00000000000..bbf335e25f2 --- /dev/null +++ b/apps/sim/blocks/blocks/hubspot.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { HubSpotBlock } from '@/blocks/blocks/hubspot' + +function mapParams(params: Record, operation: string) { + const mapper = HubSpotBlock.tools.config?.params + if (!mapper) throw new Error('HubSpot block has no params mapper') + return mapper(params, { operation }) +} + +describe('HubSpot create_list name on a tool call', () => { + const list = { oauthCredential: 'cred-1', objectTypeId: '0-1', processingType: 'MANUAL' } + + it('keeps the List Name pinned on the tool row over the model name', () => { + expect( + mapParams({ ...list, listName: 'My List', name: 'Model Name' }, 'create_list').name + ).toBe('My List') + }) + + it('uses the model name when the row leaves List Name empty', () => { + expect(mapParams({ ...list, name: 'Model Name' }, 'create_list').name).toBe('Model Name') + }) +}) diff --git a/apps/sim/blocks/blocks/hubspot.ts b/apps/sim/blocks/blocks/hubspot.ts index 6c50936b3b2..b689e2b430b 100644 --- a/apps/sim/blocks/blocks/hubspot.ts +++ b/apps/sim/blocks/blocks/hubspot.ts @@ -1726,10 +1726,6 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no cleanParams.associations = associations } - if (listName && operation === 'create_list') { - cleanParams.name = listName - } - if ( operation === 'create_association' && associationTypeId !== undefined && @@ -1768,6 +1764,11 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no } }) + // After the copy so the row's List Name beats a model `name` on a tool call. + if (listName && operation === 'create_list') { + cleanParams.name = listName + } + return cleanParams }, }, diff --git a/apps/sim/blocks/blocks/intercom.test.ts b/apps/sim/blocks/blocks/intercom.test.ts index 8e761a8c81a..077c4c2a58a 100644 --- a/apps/sim/blocks/blocks/intercom.test.ts +++ b/apps/sim/blocks/blocks/intercom.test.ts @@ -74,3 +74,35 @@ describe('Intercom role defaults', () => { expect(options()[0]?.id).toBe('lead') }) }) + +describe('Intercom tool-row fields on a tool call', () => { + it.each([ + { operation: 'update_ticket', field: 'ticket_assignee_id', param: 'assignee_id' }, + { operation: 'create_contact', field: 'contact_company_id', param: 'company_id' }, + { operation: 'close_conversation', field: 'close_body', param: 'body' }, + { operation: 'assign_conversation', field: 'assign_body', param: 'body' }, + { operation: 'create_note', field: 'note_body', param: 'body' }, + { operation: 'create_note', field: 'tag_contact_id', param: 'contactId' }, + { operation: 'attach_contact_to_company', field: 'attach_company_id', param: 'companyId' }, + { operation: 'create_tag', field: 'tag_name', param: 'name' }, + { operation: 'create_tag', field: 'tag_id_update', param: 'id' }, + { operation: 'create_event', field: 'event_user_id', param: 'user_id' }, + { operation: 'create_event', field: 'event_email', param: 'email' }, + { operation: 'create_event', field: 'event_contact_id', param: 'id' }, + { operation: 'create_event', field: 'event_metadata', param: 'metadata' }, + { operation: 'create_message', field: 'message_type_msg', param: 'message_type' }, + { operation: 'create_company', field: 'company_name', param: 'name' }, + ])( + 'keeps the pinned $field over the model $param on $operation', + ({ operation, field, param }) => { + const mapped = mapParams({ [field]: 'pinned', [param]: 'model' }, { operation }) + expect(mapped[param]).toBe('pinned') + } + ) + + it('fills a param from the model when the row leaves its field empty', () => { + expect(mapParams({ assignee_id: 'model' }, { operation: 'update_ticket' }).assignee_id).toBe( + 'model' + ) + }) +}) diff --git a/apps/sim/blocks/blocks/intercom.ts b/apps/sim/blocks/blocks/intercom.ts index d95966cc3e8..7f92408daac 100644 --- a/apps/sim/blocks/blocks/intercom.ts +++ b/apps/sim/blocks/blocks/intercom.ts @@ -173,8 +173,9 @@ const mapIntercomParams: IntercomParamsMapper = (params, context) => { if (event_created_at) cleanParams.created_at = Number(event_created_at) } + // A block field mapped above (pinned on a tool row) beats the model's arg under the tool's name. Object.entries(rest).forEach(([key, value]) => { - if (value !== undefined && value !== null && value !== '') { + if (hasInput(value) && cleanParams[key] === undefined) { cleanParams[key] = value } }) diff --git a/apps/sim/blocks/blocks/kalshi.test.ts b/apps/sim/blocks/blocks/kalshi.test.ts index cdda31845f1..0ba5bb8ef46 100644 --- a/apps/sim/blocks/blocks/kalshi.test.ts +++ b/apps/sim/blocks/blocks/kalshi.test.ts @@ -14,4 +14,51 @@ describe('KalshiBlock', () => { expect({ ...args, ...buildParams(args, { operation: 'cancel_order' }) }.orderId).toBe('ord-1') }) + + it.each([ + { operation: 'cancel_order', stale: { orderId: 'O-STALE' }, field: { orderIdParam: 'O-NEW' } }, + { operation: 'get_order', stale: { orderId: 'O-STALE' }, field: { orderIdParam: 'O-NEW' } }, + { + operation: 'amend_order', + stale: { clientOrderId: 'C-STALE' }, + field: { clientOrderIdAmend: 'C-NEW' }, + }, + { operation: 'get_orders', stale: { status: 'open' }, field: { orderStatus: 'resting' } }, + ])( + 'sends the $operation field over a stale canvas value under the tool param name', + ({ operation, stale, field }) => { + const canvas: Record = { + operation, + keyId: 'key', + privateKey: 'pem', + ...stale, + ...field, + } + const sent: Record = { ...canvas, ...buildParams(canvas) } + expect(sent[Object.keys(stale)[0]]).toBe(Object.values(field)[0]) + } + ) + + it('drops a stale canvas order ID when the operation field is empty', () => { + const canvas = { operation: 'get_order', orderId: 'O-STALE', orderIdParam: '' } + expect({ ...canvas, ...buildParams(canvas) }.orderId).toBeUndefined() + }) + + it.each([ + { operation: 'cancel_order', param: 'orderId', field: 'orderIdParam' }, + { operation: 'get_orders', param: 'status', field: 'orderStatus' }, + { operation: 'create_order', param: 'type', field: 'orderType' }, + { operation: 'create_order', param: 'ticker', field: 'tickerOrder' }, + ])( + 'keeps the row-pinned $field over the model $param on a $operation tool call', + ({ operation, param, field }) => { + const args = { [field]: 'pinned', [param]: 'model' } + expect({ ...args, ...buildParams(args, { operation }) }[param]).toBe('pinned') + } + ) + + it('keeps the model order ID on a tool call when the row leaves the field empty', () => { + const args = { orderId: 'model' } + expect({ ...args, ...buildParams(args, { operation: 'cancel_order' }) }.orderId).toBe('model') + }) }) diff --git a/apps/sim/blocks/blocks/kalshi.ts b/apps/sim/blocks/blocks/kalshi.ts index f11ef0a82cb..500fc67e0da 100644 --- a/apps/sim/blocks/blocks/kalshi.ts +++ b/apps/sim/blocks/blocks/kalshi.ts @@ -1,7 +1,12 @@ import { KalshiIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, mapperOperation, withSavedCredential } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /* * Mutually exclusive alternates, not canonical pairs — an order carries either @@ -712,69 +717,72 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations, ...rest } = params const cleanParams: Record = {} + Object.entries(rest).forEach(([key, value]) => { + if (value !== undefined && value !== null && value !== '') { + cleanParams[key] = value + } + }) + + /** + * The operation's own field wins over a value under the tool's param name: on the canvas + * that value is stale from another operation, and on a tool call the row's field is pinned. + * The model's value fills the param only on a tool call with the field empty. + */ + const mapField = (key: string, field: unknown) => { + cleanParams[key] = field || toolCallArg(context, cleanParams[key]) + } - if (operation === 'get_orders' && orderStatus) { - cleanParams.status = orderStatus + if (operation === 'get_orders') { + mapField('status', orderStatus) } if ( - (operation === 'get_orders' || - operation === 'get_positions' || - operation === 'get_settlements') && - tickerFilter + operation === 'get_orders' || + operation === 'get_positions' || + operation === 'get_settlements' ) { - cleanParams.ticker = tickerFilter + mapField('ticker', tickerFilter) } - if (operation === 'get_fills' && tickerFills) { - cleanParams.ticker = tickerFills + if (operation === 'get_fills') { + mapField('ticker', tickerFills) } if (operation === 'get_candlesticks') { - if (seriesTickerCandlesticks) cleanParams.seriesTicker = seriesTickerCandlesticks - if (tickerCandlesticks) cleanParams.ticker = tickerCandlesticks + mapField('seriesTicker', seriesTickerCandlesticks) + mapField('ticker', tickerCandlesticks) } - // Map series ticker for get_event_candlesticks (event ticker flows through eventTicker) - if (operation === 'get_event_candlesticks' && seriesTickerCandlesticks) { - cleanParams.seriesTicker = seriesTickerCandlesticks + // Event candlesticks take the event ticker through eventTicker + if (operation === 'get_event_candlesticks') { + mapField('seriesTicker', seriesTickerCandlesticks) } - if (operation === 'get_series_by_ticker' && seriesTickerGet) { - cleanParams.seriesTicker = seriesTickerGet + if (operation === 'get_series_by_ticker') { + mapField('seriesTicker', seriesTickerGet) } if ( - (operation === 'get_order' || - operation === 'cancel_order' || - operation === 'amend_order') && - orderIdParam + operation === 'get_order' || + operation === 'cancel_order' || + operation === 'amend_order' ) { - cleanParams.orderId = orderIdParam + mapField('orderId', orderIdParam) } - if ((operation === 'create_order' || operation === 'amend_order') && tickerOrder) { - cleanParams.ticker = tickerOrder + if (operation === 'create_order' || operation === 'amend_order') { + mapField('ticker', tickerOrder) } - if (operation === 'create_order' && orderType) { - cleanParams.type = orderType + if (operation === 'create_order') { + mapField('type', orderType) } - if (operation === 'amend_order' && countAmend) { - cleanParams.count = countAmend + if (operation === 'amend_order') { + mapField('count', countAmend) + mapField('clientOrderId', clientOrderIdAmend) } - if (operation === 'amend_order' && clientOrderIdAmend) { - cleanParams.clientOrderId = clientOrderIdAmend - } - - Object.entries(rest).forEach(([key, value]) => { - if (value !== undefined && value !== null && value !== '') { - cleanParams[key] = value - } - }) - return cleanParams }, }, diff --git a/apps/sim/blocks/blocks/resend.ts b/apps/sim/blocks/blocks/resend.ts index 0992a38b2f0..2d27059693a 100644 --- a/apps/sim/blocks/blocks/resend.ts +++ b/apps/sim/blocks/blocks/resend.ts @@ -455,11 +455,16 @@ Return ONLY the email body - no explanations, no extra text.`, if (operation === 'send_email') return 'resend_send' return `resend_${operation}` }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params rest.unsubscribed = toBooleanFromInput(rest.unsubscribed) + // The tool prefers a segment, so a model's segmentId would retarget a row's pinned audience. + if (context?.pinnedParams?.has('audienceId') && !context.pinnedParams.has('segmentId')) { + rest.segmentId = undefined + } + if (typeof rest.limit === 'string') { const limit = rest.limit.trim() rest.limit = limit ? Number(limit) : undefined diff --git a/apps/sim/blocks/blocks/rippling.test.ts b/apps/sim/blocks/blocks/rippling.test.ts index 1a002ebb9e6..819bd288c34 100644 --- a/apps/sim/blocks/blocks/rippling.test.ts +++ b/apps/sim/blocks/blocks/rippling.test.ts @@ -88,4 +88,80 @@ describe('RipplingBlock canvas', () => { }) expect(mapped.orderBy).toBe('name desc') }) + + it.each([ + { operation: 'bulk_delete_custom_object_records', flag: 'allOrNothing' }, + { operation: 'create_custom_object_field', flag: 'isUnique' }, + { operation: 'update_custom_object_field', flag: 'enableHistory' }, + { operation: 'trigger_report_run', flag: 'includeObjectIds' }, + { operation: 'trigger_report_run', flag: 'includeTotalRows' }, + ])('sends a $flag left on No as a boolean false on $operation', ({ operation, flag }) => { + expect(canvasRun({ operation, apiKey: 'key', [flag]: 'false' })[flag]).toBe(false) + }) + + it.each([ + { operation: 'create_custom_app', key: 'apiName', field: 'apiName', value: 'my_app' }, + { operation: 'update_custom_app', key: 'apiName', field: 'apiName', value: 'my_app' }, + { + operation: 'create_custom_object_field', + key: 'dataType', + field: 'dataType', + value: '{"type":"TEXT"}', + }, + ])( + 'ignores a custom setting $key left from a setting operation on $operation', + ({ operation, key, field, value }) => { + const mapped = canvasRun({ + operation, + apiKey: 'key', + [field]: value, + settingApiName: 'stale_setting', + settingDataType: 'STRING', + }) + expect(mapped[key]).toEqual(key === 'dataType' ? { type: 'TEXT' } : value) + } + ) + + it('sends the setting API name and data type on a custom setting write', () => { + const mapped = canvasRun({ + operation: 'update_custom_setting', + apiKey: 'key', + id: 'setting-1', + settingApiName: 'region', + settingDataType: 'STRING', + }) + expect(mapped).toMatchObject({ apiName: 'region', dataType: 'STRING' }) + }) +}) + +describe('RipplingBlock custom object field flags', () => { + const flags = ['isUnique', 'enableHistory'] as const + + it.each(flags)('offers No change for %s everywhere except a known create', (id) => { + const subBlock = RipplingBlock.subBlocks.find((candidate) => candidate.id === id) + const options = subBlock?.options + if (typeof options !== 'function') throw new Error(`${id} options are static`) + expect(options({ values: {} })[0]?.id).toBe('') + expect(options({ values: { operation: 'update_custom_object_field' } })[0]?.id).toBe('') + expect(options({ values: { operation: 'create_custom_object_field' } })[0]?.id).toBe('false') + expect(subBlock?.value?.({ operation: 'create_custom_object_field' })).toBe('false') + expect(subBlock?.value?.({ operation: 'update_custom_object_field' })).toBe('') + expect(subBlock?.value?.({})).toBeUndefined() + expect(subBlock?.dependsOn).toEqual(expect.arrayContaining(['operation'])) + }) + + it.each(flags)('sends no %s when an update leaves it on No change', (id) => { + const mapped = canvasRun({ operation: 'update_custom_object_field', apiKey: 'key', [id]: '' }) + expect(mapped).toHaveProperty(id, undefined) + }) + + it.each(['true', 'false'])('keeps sending a saved %s as a boolean on an update', (saved) => { + const mapped = canvasRun({ + operation: 'update_custom_object_field', + apiKey: 'key', + isUnique: saved, + enableHistory: saved, + }) + expect(mapped).toMatchObject({ isUnique: saved === 'true', enableHistory: saved === 'true' }) + }) }) diff --git a/apps/sim/blocks/blocks/rippling.ts b/apps/sim/blocks/blocks/rippling.ts index 723b4fb4530..9fa3487ceb2 100644 --- a/apps/sim/blocks/blocks/rippling.ts +++ b/apps/sim/blocks/blocks/rippling.ts @@ -1,5 +1,5 @@ import { RipplingIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { isToolCall, @@ -202,6 +202,33 @@ const CUSTOM_OBJECT_FIELD_WRITE_OPS = [ 'update_custom_object_field', ] as const +/** + * A Yes/No custom object field setting. Create defaults to No; every other context (an update, an + * agent tool row with no operation) leads with "No change" so an update does not resend it. + */ +const customObjectFieldFlag = ( + id: 'isUnique' | 'enableHistory', + title: string +): SubBlockConfig => ({ + id, + title, + type: 'dropdown', + options: ({ values } = { values: {} }) => [ + ...(values?.operation === 'create_custom_object_field' ? [] : [{ label: 'No change', id: '' }]), + { label: 'No', id: 'false' }, + { label: 'Yes', id: 'true' }, + ], + value: (p) => + p?.operation === 'create_custom_object_field' + ? 'false' + : p?.operation === 'update_custom_object_field' + ? '' + : undefined, + dependsOn: ['operation'], + mode: 'advanced', + condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, +}) + /** Operations for custom setting fields */ const CUSTOM_SETTING_WRITE_OPS = ['create_custom_setting', 'update_custom_setting'] as const @@ -800,28 +827,8 @@ Return ONLY the JSON - no explanations, no extra text.`, mode: 'advanced', condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, }, - { - id: 'isUnique', - title: 'Unique', - type: 'dropdown', - options: [ - { label: 'No', id: 'false' }, - { label: 'Yes', id: 'true' }, - ], - mode: 'advanced', - condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, - }, - { - id: 'enableHistory', - title: 'Enable History', - type: 'dropdown', - options: [ - { label: 'No', id: 'false' }, - { label: 'Yes', id: 'true' }, - ], - mode: 'advanced', - condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, - }, + customObjectFieldFlag('isUnique', 'Unique'), + customObjectFieldFlag('enableHistory', 'Enable History'), { id: 'rqlDefinition', title: 'RQL Definition', @@ -1255,6 +1262,16 @@ Return ONLY the sort expression - no explanations, no extra text.`, const setFlag = (key: string, value: unknown) => { if (parseOptionalBooleanInput(value) === true) mapped[key] = true } + /** + * A Yes/No field whose id is the tool's own param: a `'false'` left unmapped would reach the + * tool as text, so both answers are sent as booleans and "No change" (`''`) sends nothing. + */ + const setBoolean = (key: string, value: unknown) => { + const flag = parseOptionalBooleanInput(value) + if (flag !== undefined) mapped[key] = flag + else if (value === '') mapped[key] = undefined + } + const isSettingWrite = (CUSTOM_SETTING_WRITE_OPS as readonly string[]).includes(op) if (params.id != null && params.id !== '') mapped.id = params.id if (params.customObjectId != null && params.customObjectId !== '') @@ -1308,8 +1325,8 @@ Return ONLY the sort expression - no explanations, no extra text.`, } } setFlag('required', params.fieldRequired) - setFlag('isUnique', params.isUnique) - setFlag('enableHistory', params.enableHistory) + setBoolean('isUnique', params.isUnique) + setBoolean('enableHistory', params.enableHistory) if (params.rqlDefinition != null && params.rqlDefinition !== '') { try { mapped.rqlDefinition = @@ -1365,9 +1382,9 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.displayName != null && params.displayName !== '') mapped.displayName = params.displayName - if (params.settingApiName != null && params.settingApiName !== '') + if (isSettingWrite && params.settingApiName != null && params.settingApiName !== '') mapped.apiName = params.settingApiName - if (params.settingDataType != null && params.settingDataType !== '') + if (isSettingWrite && params.settingDataType != null && params.settingDataType !== '') mapped.dataType = params.settingDataType if (params.secretValue != null && params.secretValue !== '') mapped.secretValue = params.secretValue @@ -1378,8 +1395,8 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.settingBooleanValue != null && params.settingBooleanValue !== '') mapped.booleanValue = params.settingBooleanValue === 'true' - setFlag('includeObjectIds', params.includeObjectIds) - setFlag('includeTotalRows', params.includeTotalRows) + setBoolean('includeObjectIds', params.includeObjectIds) + setBoolean('includeTotalRows', params.includeTotalRows) if (params.formatDateFields != null && params.formatDateFields !== '') { try { mapped.formatDateFields = @@ -1403,7 +1420,7 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.outputType != null && params.outputType !== '') mapped.outputType = params.outputType - setFlag('allOrNothing', params.allOrNothing) + setBoolean('allOrNothing', params.allOrNothing) for (const [key, ops] of QUERY_PARAM_OPS) { const value = params[key] diff --git a/apps/sim/blocks/types.ts b/apps/sim/blocks/types.ts index 2d05ca153fe..4968dd54b15 100644 --- a/apps/sim/blocks/types.ts +++ b/apps/sim/blocks/types.ts @@ -615,6 +615,12 @@ export type CanvasSentence = readonly CanvasSentenceClause[] export interface BlockToolParamsContext { /** Operation selected by the configuring surface. */ operation?: string + /** + * Ids of the values the tool row itself stores non-empty (as stored, before canonical + * resolution). A model argument never overrides one of these, so a mapper can tell a pinned + * value from one the model chose when two params name the same thing. + */ + pinnedParams?: ReadonlySet } export interface BlockConfig { diff --git a/apps/sim/executor/handlers/human-in-the-loop/handler.ts b/apps/sim/executor/handlers/human-in-the-loop/handler.ts index 1585d798a36..c20676f8e8c 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/handler.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/handler.ts @@ -440,6 +440,7 @@ export class HumanInTheLoopBlockHandler implements BlockHandler { toolIndex, toolConfig.type ), + storedParams: visibleParams, }) if (!paramsTransform) return visibleParams diff --git a/apps/sim/lib/workflows/tool-input/hidden-params.ts b/apps/sim/lib/workflows/tool-input/hidden-params.ts index 19240580049..5315a260106 100644 --- a/apps/sim/lib/workflows/tool-input/hidden-params.ts +++ b/apps/sim/lib/workflows/tool-input/hidden-params.ts @@ -65,8 +65,10 @@ function decodeScalar(value: unknown): unknown { /** * True only when the clause is decidably false. A clause on a field with no decidable value is - * treated as satisfiable, and a stored string is also tried in its typed reading, so every doubt - * resolves toward keeping the value. + * treated as satisfiable, and the stored value is also tried in the clause's own type, so every + * doubt resolves toward keeping the value. A clause whose options are all strings compares the + * stored value as text: a typed reading of `'true'` would always satisfy a `not` clause on the + * string option `'true'`, leaving it undecidable. */ function isClauseFalse( clause: SubBlockCondition, @@ -77,8 +79,12 @@ function isClauseFalse( if (!isDecidableField(field)) return false const single: SubBlockCondition = { field, value: clause.value, not: clause.not } if (evaluateSubBlockCondition(single, values)) return false - const decoded = decodeScalar(values[field]) - return decoded === values[field] || !evaluateSubBlockCondition(single, { [field]: decoded }) + const stored = values[field] + const options = Array.isArray(clause.value) ? clause.value : [clause.value] + const alternate = options.every((option) => typeof option === 'string') + ? String(stored) + : decodeScalar(stored) + return alternate === stored || !evaluateSubBlockCondition(single, { [field]: alternate }) } /** diff --git a/apps/sim/providers/utils.test.ts b/apps/sim/providers/utils.test.ts index 40581d0c0cf..fc00bfb146e 100644 --- a/apps/sim/providers/utils.test.ts +++ b/apps/sim/providers/utils.test.ts @@ -19,7 +19,9 @@ import { GreenhouseV2Block } from '@/blocks/blocks/greenhouse' import { IntuneBlock } from '@/blocks/blocks/intune' import { MicrosoftExcelV2Block } from '@/blocks/blocks/microsoft_excel' import { RampBlock } from '@/blocks/blocks/ramp' +import { ResendV2Block } from '@/blocks/blocks/resend' import { RevenueCatBlock } from '@/blocks/blocks/revenuecat' +import { SharepointV2Block } from '@/blocks/blocks/sharepoint' import { TrelloBlock } from '@/blocks/blocks/trello' import { VideoGeneratorV3Block } from '@/blocks/blocks/video_generator' import * as blockRegistry from '@/blocks/registry' @@ -91,7 +93,10 @@ import { sortRangeTool } from '@/tools/microsoft_excel/sort_range' import { getSubBlocksForToolInput } from '@/tools/params' import { rampListReimbursementsTool } from '@/tools/ramp/list-reimbursements' import { rampListTransactionsTool } from '@/tools/ramp/list-transactions' +import { resendCreateBroadcastTool } from '@/tools/resend/create_broadcast' +import type { CreateBroadcastParams } from '@/tools/resend/types' import { revenuecatGetCustomerTool } from '@/tools/revenuecat/get_customer' +import { getListTool as sharepointGetListTool } from '@/tools/sharepoint/get_list' import { trelloListListsTool } from '@/tools/trello/list_lists' import { trelloUpdateListTool } from '@/tools/trello/update_list' import { falaiVideoTool } from '@/tools/video/falai' @@ -804,6 +809,37 @@ describe('tool-row values hidden by the selected operation', () => { expect(toolParams.boardId).toBe(Object.values(stored)[0]) }) + it.each([ + { includeColumns: 'true', kept: false }, + { includeColumns: 'false', kept: true }, + ])( + 'applies the SharePoint item filters left on a Get List row only when Include Columns is $includeColumns', + async ({ includeColumns, kept }) => { + const stored = { + siteId: 'site-1', + listId: 'list-1', + includeColumns, + filter: "fields/Status eq 'Active'", + top: '10', + selectFields: 'Title', + } + const providerTool = await transformBlockTool( + { type: 'sharepoint_v2', operation: 'sharepoint_get_list', params: stored }, + { + selectedOperation: 'sharepoint_get_list', + getAllBlocks: () => [SharepointV2Block], + getTool: () => sharepointGetListTool, + } + ) + if (!providerTool) throw new Error('SharePoint agent tool was not created') + const { toolParams } = prepareToolExecution(providerTool, {}, {}, undefined) + expect(toolParams.includeColumns).toBe(includeColumns === 'true') + expect(toolParams.filter).toBe(kept ? stored.filter : undefined) + expect(toolParams.top).toBe(kept ? 10 : undefined) + expect(toolParams.selectFields).toBe(kept ? stored.selectFields : undefined) + } + ) + it('keeps a stored tool param no sub-block writes', async () => { const providerTool = await transformBlockTool( { type: 'trello', operation: 'trello_update_list', params: { listId: 'l', idBoard: 'b' } }, @@ -845,6 +881,49 @@ describe('tool-row values hidden by the selected operation', () => { }) }) +describe('Resend broadcast recipient on a tool row', () => { + const sender = { broadcastFrom: 'team@example.com', broadcastSubject: 'News' } + + it.each([ + { + name: 'a pinned audience over the model segment', + stored: { audienceId: 'aud_row' }, + args: { segmentId: 'seg_model' }, + recipient: { audience_id: 'aud_row' }, + }, + { + name: 'a pinned segment over the model audience', + stored: { segmentId: 'seg_row' }, + args: { audienceId: 'aud_model' }, + recipient: { segment_id: 'seg_row' }, + }, + { + name: 'the model segment when the row pins no recipient', + stored: {}, + args: { segmentId: 'seg_model' }, + recipient: { segment_id: 'seg_model' }, + }, + ])('sends to $name', async ({ stored, args, recipient }) => { + const providerTool = await transformBlockTool( + { + type: 'resend_v2', + operation: 'create_broadcast', + params: { ...sender, credential: 'fixture-credential', ...stored }, + }, + { + selectedOperation: 'create_broadcast', + getAllBlocks: () => [ResendV2Block], + getTool: () => resendCreateBroadcastTool, + } + ) + if (!providerTool) throw new Error('Resend agent tool was not created') + const { toolParams } = prepareToolExecution(providerTool, args, {}, undefined) + const body = resendCreateBroadcastTool.request.body?.(toolParams as CreateBroadcastParams) + expect(body).toMatchObject(recipient) + expect(body).not.toHaveProperty('audience_id' in recipient ? 'segment_id' : 'audience_id') + }) +}) + describe('Excel targets through agent execution', () => { it.each(['model', 'configured'] as const)( 'clears the %s range after canonical argument mapping', diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 7ab3a6aebea..955a96b865f 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -53,7 +53,7 @@ import { registerPreparedProviderToolInputProvenance, } from '@/providers/tool-input-provenance' import type { ModelPricing, ProviderId, ProviderToolConfig } from '@/providers/types' -import { mergeToolParameters } from '@/tools/merge-params' +import { isNonEmpty, mergeToolParameters } from '@/tools/merge-params' import { buildToolParamShapes, decodeToolParams } from '@/tools/param-shape' import type { WorkflowToolExecutionContext } from '@/tools/types' @@ -559,6 +559,8 @@ export function buildBlockToolParamsTransform(config: { toolParams: Record | undefined canonicalGroups: CanonicalGroup[] scopedCanonicalModes: CanonicalModeOverrides | undefined + /** The params the tool row stores; their non-empty ids reach the mapper as `pinnedParams`. */ + storedParams?: Record }): { paramsTransform: BlockToolParamsFn | undefined jsonShapedParamKeys: string[] @@ -571,7 +573,13 @@ export function buildBlockToolParamsTransform(config: { toolParams, canonicalGroups, scopedCanonicalModes, + storedParams, } = config + const pinnedParams = new Set( + Object.entries(storedParams ?? {}) + .filter(([, value]) => isNonEmpty(value)) + .map(([paramId]) => paramId) + ) /** * The value shape of every key this tool can receive. Keyed by the sub-block that @@ -620,7 +628,7 @@ export function buildBlockToolParamsTransform(config: { } if (blockParamsFn) { - const transformed = blockParamsFn(result, { operation }) + const transformed = blockParamsFn(result, { operation, pinnedParams }) result = { ...result, ...transformed } } @@ -914,6 +922,7 @@ export async function transformBlockTool( toolParams: toolConfig.params, canonicalGroups, scopedCanonicalModes, + storedParams: userProvidedParams, }) const providerTool: ProviderToolConfig = { diff --git a/apps/sim/tools/attio/json-inputs.test.ts b/apps/sim/tools/attio/json-inputs.test.ts index b92cd9869c4..71b98b64bbf 100644 --- a/apps/sim/tools/attio/json-inputs.test.ts +++ b/apps/sim/tools/attio/json-inputs.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { attioCreateWebhookTool } from '@/tools/attio/create_webhook' +import { attioListRecordsTool } from '@/tools/attio/list_records' import { attioQueryListEntriesTool } from '@/tools/attio/query_list_entries' import { attioUpdateTaskTool } from '@/tools/attio/update_task' @@ -29,4 +30,23 @@ describe('Attio JSON inputs', () => { }) ).toThrow('Invalid JSON provided for subscriptions') }) + + it('sends a filter and sorts the json input already parsed', () => { + const filter = { name: { $eq: 'Acme' } } + const sorts = [{ direction: 'asc', attribute: 'name' }] + expect( + bodyOf(attioListRecordsTool, { accessToken: 't', objectType: 'companies', filter, sorts }) + ).toEqual({ filter, sorts }) + }) + + it('parses a filter and sorts sent as JSON text', () => { + expect( + bodyOf(attioListRecordsTool, { + accessToken: 't', + objectType: 'companies', + filter: '{"name":"Acme"}', + sorts: '[{"direction":"desc","attribute":"name"}]', + }) + ).toEqual({ filter: { name: 'Acme' }, sorts: [{ direction: 'desc', attribute: 'name' }] }) + }) }) diff --git a/apps/sim/tools/attio/list_records.ts b/apps/sim/tools/attio/list_records.ts index 49b917a0f18..6ed1e7429c7 100644 --- a/apps/sim/tools/attio/list_records.ts +++ b/apps/sim/tools/attio/list_records.ts @@ -66,14 +66,15 @@ export const attioListRecordsTool: ToolConfig = {} if (params.filter) { try { - body.filter = JSON.parse(params.filter) + body.filter = + typeof params.filter === 'string' ? JSON.parse(params.filter) : params.filter } catch { throw new Error('Invalid JSON provided for filter') } } if (params.sorts) { try { - body.sorts = JSON.parse(params.sorts) + body.sorts = typeof params.sorts === 'string' ? JSON.parse(params.sorts) : params.sorts } catch { throw new Error('Invalid JSON provided for sorts') } diff --git a/apps/sim/tools/attio/types.ts b/apps/sim/tools/attio/types.ts index faa1dc55c60..b8b2fb880e3 100644 --- a/apps/sim/tools/attio/types.ts +++ b/apps/sim/tools/attio/types.ts @@ -330,8 +330,10 @@ interface AttioRecord { export interface AttioListRecordsParams { accessToken: string objectType: string - filter?: string - sorts?: string + /** JSON text, or the object the block's `json` input already parsed. */ + filter?: string | Record + /** JSON text, or the array the block's `json` input already parsed. */ + sorts?: string | unknown[] limit?: number offset?: number }