diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 9c2bdb437c9..c9c89e11a45 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -241,7 +241,12 @@ search that returns no email or phone, and an email verifier. item by item where an array declares `items` (undeclared fields are dropped), and whole anywhere else, so return an undeclared shape (a `json` row) complete, with placeholders for what the request cannot know. Never guess at what the provider or stored state would add (a collision suffix on a - file name, an id). + file name, an id, a key resolved to an id, a default the provider picks): an id it would assign is + `dryRunId(kind, n)` from `@/tools/dry-run` (`dry_run_record_1`), and anything else is left out so + the sample stands. When the request builder normalises a param (parses a JSON string, builds rows + from objects), move that into a named helper the `body`/`operation.input` and the hook both call + (`appendSheetRows`, `parseHubSpotProperties`); never re-derive the request in the hook. Echoing a + secret is safe only because params arrive masked: never read credentials from anywhere else. ## Critical Rules for Parameters diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index 4f4d178f178..0d6b2098728 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -88,6 +88,9 @@ For **every** tool file, check: `request` is not `null`, and every read runs for real; a write absent from `stubbed` counts only if its block ran (not on an untaken branch or `--mock`ed) (rules: `add-tools` → Declaring the effect) +- [ ] A write's `dryRunOutput`, where it declares one, echoes only what its request determines, + provider-assigned ids as `dryRunId(kind, n)`, and shares any param normalisation with the + request builder through a named helper (rules: `add-tools` → Declaring the effect) ### Params - [ ] All required API params are marked `required: true` diff --git a/apps/sim/lib/api/contracts/workflow-tests.ts b/apps/sim/lib/api/contracts/workflow-tests.ts index 8863ff6823b..45bed8b4ba5 100644 --- a/apps/sim/lib/api/contracts/workflow-tests.ts +++ b/apps/sim/lib/api/contracts/workflow-tests.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { workspaceIdSchema } from '@/lib/api/contracts/primitives' import { type ContractJsonResponse, defineRouteContract } from '@/lib/api/contracts/types' -import { testCaseStatusSchema, testReportSchema } from '@/lib/workflow-tests/protocol' +import { storedTestReportSchema, testCaseStatusSchema } from '@/lib/workflow-tests/protocol' const versionSchema = z.enum(['draft', 'deployed']) const testNameSchema = z @@ -42,7 +42,7 @@ const runSummarySchema = z.object({ /** One run with its report, and each case's status while it goes. */ const runDetailSchema = runSummarySchema.extend({ - report: testReportSchema.nullable(), + report: storedTestReportSchema.nullable(), /** Each case's status by `describe > it` path while the run goes; null before any. */ progress: z.record(z.string(), testCaseStatusSchema).nullable(), }) diff --git a/apps/sim/lib/internal/microsoft-teams/message-rewrite.ts b/apps/sim/lib/internal/microsoft-teams/message-rewrite.ts new file mode 100644 index 00000000000..eeec7fff8d0 --- /dev/null +++ b/apps/sim/lib/internal/microsoft-teams/message-rewrite.ts @@ -0,0 +1,25 @@ +/** Each `` mention in `content` with a non-blank name, which a send tries to resolve to a member. */ +export function parseMentionNames( + content: string +): Array<{ name: string; tag: string; id: number }> { + const parsed: Array<{ name: string; tag: string; id: number }> = [] + const pattern = /([^<]+)<\/at>/gi + let match: RegExpExecArray | null + while ((match = pattern.exec(content)) !== null) { + const name = match[1].trim() + if (name) parsed.push({ name, tag: match[0], id: parsed.length }) + } + return parsed +} + +/** + * Whether sending `content` may rewrite it rather than post it as given: files attach, or a + * mention resolves into Graph's mention markup when its name matches a member, which the request + * alone cannot tell. Dependency-free, so a tool's dry-run placeholder can ask too. + */ +export function rewritesTeamsMessage( + content: string, + files: readonly unknown[] | null | undefined +): boolean { + return Boolean(files?.length) || parseMentionNames(content).length > 0 +} diff --git a/apps/sim/lib/internal/microsoft-teams/operations.ts b/apps/sim/lib/internal/microsoft-teams/operations.ts index a64b540543a..aa3545d28c2 100644 --- a/apps/sim/lib/internal/microsoft-teams/operations.ts +++ b/apps/sim/lib/internal/microsoft-teams/operations.ts @@ -8,6 +8,10 @@ import { type MicrosoftTeamsGraphObject, } from '@/lib/internal/microsoft-teams/client' import { MicrosoftTeamsOperationError } from '@/lib/internal/microsoft-teams/errors' +import { + parseMentionNames, + rewritesTeamsMessage, +} from '@/lib/internal/microsoft-teams/message-rewrite' import type { MicrosoftTeamsWriteChannelInput, MicrosoftTeamsWriteChatInput, @@ -25,7 +29,6 @@ import type { UserFile } from '@/executor/types' const MAX_GRAPH_RESPONSE_BYTES = 2 * 1024 * 1024 const MAX_TEAMS_FILE_SIZE = 4 * 1024 * 1024 -const MENTION_PATTERN = /[^<]+<\/at>/i const logger = createLogger('MicrosoftTeamsOperations') @@ -198,17 +201,6 @@ async function uploadFilesForMessage( return { attachments, files } } -function parseMentionNames(content: string): Array<{ name: string; tag: string; id: number }> { - const parsed: Array<{ name: string; tag: string; id: number }> = [] - const pattern = /([^<]+)<\/at>/gi - let match: RegExpExecArray | null - while ((match = pattern.exec(content)) !== null) { - const name = match[1].trim() - if (name) parsed.push({ name, tag: match[0], id: parsed.length }) - } - return parsed -} - async function resolveMentions( content: string, membersPath: string, @@ -286,7 +278,7 @@ async function sendMessage(args: { plainMetadata: (data: MicrosoftTeamsGraphObject) => Record enhancedMetadata: (data: MicrosoftTeamsGraphObject) => Record }) { - const enhanced = Boolean(args.files?.length || MENTION_PATTERN.test(args.content)) + const enhanced = rewritesTeamsMessage(args.content, args.files) const requestedContentType: 'text' | 'html' = args.contentType === 'html' ? 'html' : 'text' const client = new MicrosoftTeamsClient(args.accessToken) if (!enhanced) { diff --git a/apps/sim/lib/mothership/tools/server/tests.ts b/apps/sim/lib/mothership/tools/server/tests.ts index 5c7c0007b5c..79e3f4aadbe 100644 --- a/apps/sim/lib/mothership/tools/server/tests.ts +++ b/apps/sim/lib/mothership/tools/server/tests.ts @@ -18,7 +18,7 @@ import { readWorkflowTestRuns, updateWorkflowTest, } from '@/lib/workflow-tests/application/tests' -import type { TestReport } from '@/lib/workflow-tests/protocol' +import type { StoredTestReport } from '@/lib/workflow-tests/protocol' const RUN_POLL_MS = 2_000 @@ -31,7 +31,7 @@ function workspaceFor(input: { workspaceId?: string }, context?: ServerToolConte } /** Each failing case once: where it failed and why, in vitest's own words or the judge's. */ -function failures(report: TestReport | null) { +function failures(report: StoredTestReport | null) { if (!report) return [] return report.tests .filter((test) => test.status === 'fail') @@ -46,6 +46,29 @@ function failures(report: TestReport | null) { }) } +/** + * Each write a run stubbed because no mock answered it, once, as `block → tool` (a block answered + * whole by its name alone): a test that passes may still lean on a placeholder. The list is partial + * when `omittedCalls` (stubbed calls a run's full list left out) or `omittedRuns` (runs past the + * per-file cap, whose writes went unrecorded) is nonzero, and unknown (null) for a run with no + * report, such as one that errored before the sandbox returned. + */ +function unmockedWrites(report: StoredTestReport | null) { + if (!report) return null + const executions = Object.values(report.sideEffects?.executions ?? {}) + const sites = executions.flatMap((execution) => + execution.stubbed.map(({ block, blockId, tool }) => { + const site = block ?? blockId ?? 'unnamed block' + return tool ? `${site} → ${tool}` : site + }) + ) + return { + sites: [...new Set(sites)], + omittedCalls: executions.reduce((total, execution) => total + execution.omitted.stubbed, 0), + omittedRuns: report.sideEffects?.omittedExecutions ?? 0, + } +} + const TEST_READ_ACTIONS = new Set(['list', 'get']) export const testsServerTool: BaseServerTool = { @@ -123,6 +146,7 @@ export const testsServerTool: BaseServerTool = { failed: detail.latestRun.failed, error: detail.latestRun.error, failures: failures(detail.latestRun.report), + unmockedWrites: unmockedWrites(detail.latestRun.report), } : null, } @@ -161,6 +185,7 @@ export const testsServerTool: BaseServerTool = { skipped: run.skipped, ...(run.error ? { error: run.error } : {}), failures: failures(run.report), + unmockedWrites: unmockedWrites(run.report), })), } } diff --git a/apps/sim/lib/workflow-tests/application/tests.ts b/apps/sim/lib/workflow-tests/application/tests.ts index f792c1a95f2..081029e1985 100644 --- a/apps/sim/lib/workflow-tests/application/tests.ts +++ b/apps/sim/lib/workflow-tests/application/tests.ts @@ -8,7 +8,7 @@ import { workflowTestOperations } from '@/lib/workflow-tests/application/operati import { starterTestSource, testSourceHash } from '@/lib/workflow-tests/definition' import { requireWorkflowTestsEnabled } from '@/lib/workflow-tests/feature-flag' import { assertTestName, testFilePath } from '@/lib/workflow-tests/paths' -import type { TestCaseStatus, TestReport } from '@/lib/workflow-tests/protocol' +import type { StoredTestReport, TestCaseStatus } from '@/lib/workflow-tests/protocol' import { type DeploymentFacts, getLatestWorkflowTestRun, @@ -237,7 +237,7 @@ export const getWorkflowTestDetail = defineAuthorizedWorkspaceUseCase({ function presentRunDetail(row: WorkflowTestRunRow, testSourceHash: string, facts: DeploymentFacts) { return { ...presentRun(row, testSourceHash, facts), - report: row.report as TestReport | null, + report: row.report as StoredTestReport | null, progress: row.progress as Record | null, } } @@ -390,7 +390,7 @@ export const readWorkflowTestRuns = defineAuthorizedWorkspaceUseCase({ runs: rows.map((row) => ({ ...presentRun(row, row.testSourceHash, facts), name: row.testName, - report: row.report as TestReport | null, + report: row.report as StoredTestReport | null, })), } }, diff --git a/apps/sim/lib/workflow-tests/protocol.ts b/apps/sim/lib/workflow-tests/protocol.ts index b5618e2e870..de0ead44b86 100644 --- a/apps/sim/lib/workflow-tests/protocol.ts +++ b/apps/sim/lib/workflow-tests/protocol.ts @@ -127,7 +127,48 @@ export const testReportSchema = z.object({ }) ), }) -export type TestReport = z.infer + +/** What one workflow run of a test did with the writes it reached, without their payloads. */ +const testRunSideEffectsSchema = z.object({ + /** Writes no mock answered, stubbed with a placeholder; `tool` is null for a block answered whole. */ + stubbed: z.array( + z.object({ + workflowId: z.string(), + blockId: z.string().nullable(), + block: z.string().nullable(), + tool: z.string().nullable(), + /** Calls folded into this entry. */ + count: z.number().int().positive(), + }) + ), + /** Code that ran for real, whose network calls are not stubbed. */ + unchecked: z.array( + z.object({ + block: z.string().nullable(), + reason: z.string(), + count: z.number().int().positive(), + }) + ), + /** Calls each list left out once it was full. */ + omitted: z.object({ stubbed: z.number().int(), unchecked: z.number().int() }), +}) +export type TestRunSideEffects = z.infer + +/** + * A test file's report as the host stores it: the sandbox's {@link testReportSchema} report, and + * the side effects of each run that reached any, which the host records from the runs themselves, + * never from the sandbox. + */ +export const storedTestReportSchema = testReportSchema.extend({ + sideEffects: z + .object({ + /** By execution id; at most a fixed number of runs, the rest counted in `omittedExecutions`. */ + executions: z.record(z.string(), testRunSideEffectsSchema), + omittedExecutions: z.number().int(), + }) + .optional(), +}) +export type StoredTestReport = z.infer export const testCollectionSchema = z.object({ topLevel: z.array(z.object({ kind: z.enum(['suite', 'test']), name: z.string() })), diff --git a/apps/sim/lib/workflow-tests/repository.ts b/apps/sim/lib/workflow-tests/repository.ts index 52a62f0a276..8a709c8b9ac 100644 --- a/apps/sim/lib/workflow-tests/repository.ts +++ b/apps/sim/lib/workflow-tests/repository.ts @@ -9,7 +9,11 @@ import { } from '@sim/db/schema' import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm' import type { DbOrTx, DbTransaction } from '@/lib/db/types' -import type { TestCaseStatus, TestCollection, TestReport } from '@/lib/workflow-tests/protocol' +import type { + StoredTestReport, + TestCaseStatus, + TestCollection, +} from '@/lib/workflow-tests/protocol' import type { WorkflowTestVersion } from '@/lib/workflows/application/run-workflow-for-test' export type WorkflowTestRow = typeof workflowTest.$inferSelect @@ -282,7 +286,7 @@ export async function readDeploymentFacts( export async function completeWorkflowTestRun( runId: string, - report: TestReport, + report: StoredTestReport, sourceHash: string, ranAgainst: RanAgainstEntry[] ): Promise { diff --git a/apps/sim/lib/workflow-tests/run-test-file.ts b/apps/sim/lib/workflow-tests/run-test-file.ts index 49d91d389be..365330bc4c6 100644 --- a/apps/sim/lib/workflow-tests/run-test-file.ts +++ b/apps/sim/lib/workflow-tests/run-test-file.ts @@ -2,8 +2,8 @@ import type { Principal } from '@sim/auth/principal' import { generateShortId } from '@sim/utils/id' import { runSandboxTask } from '@/lib/execution/sandbox/run-task' import { + type StoredTestReport, type TestCaseStatus, - type TestReport, testReportSchema, } from '@/lib/workflow-tests/protocol' import type { EnteredWorkflow } from '@/lib/workflow-tests/repository' @@ -29,11 +29,14 @@ export interface RunWorkflowTestFileInput { /** * Runs one test file in the sandbox. Each `runWorkflow()` it makes becomes a real workflow - * run whose mocked blocks are answered by the file's own mocks. + * run whose mocked blocks are answered by the file's own mocks. The report adds what those runs + * did with the writes no mock answered, as the host saw it: only runs that finished before the + * sandbox returned, since a run the file left unawaited is cancelled when its session closes and + * reports nothing. */ export async function runWorkflowTestFile( input: RunWorkflowTestFileInput -): Promise<{ report: TestReport; entered: EnteredWorkflow[] }> { +): Promise<{ report: StoredTestReport; entered: EnteredWorkflow[] }> { const requestId = generateShortId(12) const session = new WorkflowTestSession({ workspaceId: input.workspaceId, @@ -49,8 +52,9 @@ export async function runWorkflowTestFile( { workspaceId: input.workspaceId, code: input.source, codeFilename: input.filePath }, { requestId, ownerKey: `workspace:${input.workspaceId}`, signal: input.signal } ) + const report = testReportSchema.parse(JSON.parse(Buffer.from(bytes).toString('utf-8'))) return { - report: testReportSchema.parse(JSON.parse(Buffer.from(bytes).toString('utf-8'))), + report: { ...report, sideEffects: session.sideEffects() }, entered: session.enteredWorkflows(), } } finally { diff --git a/apps/sim/lib/workflow-tests/session.ts b/apps/sim/lib/workflow-tests/session.ts index f925a4189d5..47ac25af5b1 100644 --- a/apps/sim/lib/workflow-tests/session.ts +++ b/apps/sim/lib/workflow-tests/session.ts @@ -14,14 +14,24 @@ import { type MockMatcher, type ParkedMockCall, } from '@/lib/workflow-tests/mock-channel' -import type { TestCaseStatus, TestEvent, TestTarget } from '@/lib/workflow-tests/protocol' +import type { + StoredTestReport, + TestCaseStatus, + TestEvent, + TestRunSideEffects, + TestTarget, +} from '@/lib/workflow-tests/protocol' import { type EnteredWorkflow, readDraftTimestamps } from '@/lib/workflow-tests/repository' import { runWorkflowForTest, type WorkflowTestRunResult, type WorkflowTestVersion, } from '@/lib/workflows/application/run-workflow-for-test' -import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run' +import { + type SideEffectsSummary, + sampleBlockOutput, + sampleToolOutput, +} from '@/lib/workflows/dry-run' import { loadDeployedWorkflowState, loadWorkflowFromNormalizedTables, @@ -39,6 +49,50 @@ import { hasToolId } from '@/tools/tool-ids' /** How long one `testNext` broker call waits before answering `waiting`, well under the broker timeout. */ const EVENT_WAIT_MS = 25_000 +/** Runs whose side effects a test file's report keeps; it counts the rest. */ +const MAX_RUNS_WITH_SIDE_EFFECTS = 50 + +/** Distinct entries a run keeps per list, so a report row stays small; it counts the rest. */ +const MAX_SITES_PER_RUN = 20 + +/** + * `entries` with each repeat folded into one entry and counted, at most + * {@link MAX_SITES_PER_RUN} of them; `omitted` counts the calls of the distinct ones left out. + */ +function tally(entries: readonly T[]) { + const kept = new Map() + let omitted = 0 + for (const entry of entries) { + const key = JSON.stringify(entry) + const seen = kept.get(key) + if (seen) seen.count++ + else if (kept.size < MAX_SITES_PER_RUN) kept.set(key, { ...entry, count: 1 }) + else omitted++ + } + return { kept: [...kept.values()], omitted } +} + +/** A run's side effects as a report keeps them: who did what and how often, never a payload. */ +function compactSideEffects(summary: SideEffectsSummary): TestRunSideEffects { + const stubbed = tally( + summary.stubbed.map(({ workflowId, blockId, block, tool }) => ({ + workflowId, + blockId, + block, + tool, + })) + ) + const unchecked = tally(summary.unchecked.map(({ block, reason }) => ({ block, reason }))) + return { + stubbed: stubbed.kept, + unchecked: unchecked.kept, + omitted: { + stubbed: summary.omitted.stubbed + stubbed.omitted, + unchecked: summary.omitted.unchecked + unchecked.omitted, + }, + } +} + export interface WorkflowTestSessionConfig { workspaceId: string principal: Principal @@ -515,6 +569,9 @@ export class WorkflowTestSession { private closed = false /** Stops `toMatchRubric` model calls still in flight when the sandbox run ends. */ private readonly judgeAbort = new AbortController() + /** Each finished run's side effects by execution id, for runs that reached any write or code. */ + private readonly runSideEffects = new Map() + private omittedRunSideEffects = 0 constructor(readonly config: WorkflowTestSessionConfig) {} @@ -545,6 +602,7 @@ export class WorkflowTestSession { triggerBlockId, testHooks: channel.hooks, abortSignal: abort.signal, + onSideEffects: (executionId, summary) => this.recordSideEffects(executionId, summary), }) const run = new TestWorkflowRun(channel, execution, abort, matcher) this.runs.set(run.id, run) @@ -600,6 +658,27 @@ export class WorkflowTestSession { return [...this.enteredVersions.values()] } + private recordSideEffects(executionId: string, summary: SideEffectsSummary): void { + const { stubbed, unchecked, omitted } = summary + if (stubbed.length + unchecked.length + omitted.stubbed + omitted.unchecked === 0) return + if (this.runSideEffects.size >= MAX_RUNS_WITH_SIDE_EFFECTS) { + this.omittedRunSideEffects++ + return + } + this.runSideEffects.set(executionId, compactSideEffects(summary)) + } + + /** + * What this file's runs finished so far did with the writes they reached, recorded here from + * the runs themselves: the sandbox's own report is untrusted. A run still going is absent. + */ + sideEffects(): NonNullable { + return { + executions: Object.fromEntries(this.runSideEffects), + omittedExecutions: this.omittedRunSideEffects, + } + } + close(): void { this.closed = true this.judgeAbort.abort(new Error('The test run ended')) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 4c020bcc989..193a27ac67d 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -1256,16 +1256,14 @@ describe('a dry run', () => { expect(await tableRows(tableId)).toEqual([]) }) - it('stubs a workflow test’s unmocked writes', async () => { + it('stubs a workflow test’s unmocked writes and records them on the host, payloads dropped', async () => { const tableId = await createTable() const name = `Dry test ${generateId()}` - await saveWorkflow( - graph( - [block('start', 'start_trigger'), upsertLead('save', tableId, 'a@b.co')], - [['start', 'save']] - ).state, - name + const fixture = graph( + [block('start', 'start_trigger'), upsertLead('save', tableId, 'a@b.co')], + [['start', 'save']] ) + const workflowId = await saveWorkflow(fixture.state, name) const session = new WorkflowTestSession({ workspaceId, principal, @@ -1277,8 +1275,26 @@ describe('a dry run', () => { let event = await session.start({ workflow: name, trigger: null, input: {}, targets: [] }) while (event.kind === 'waiting') event = await session.next(event.runId) - expect(event).toMatchObject({ kind: 'done' }) + if (event.kind !== 'done') throw new Error(`The run ended with ${event.kind}`) expect(await tableRows(tableId)).toEqual([]) + expect(session.sideEffects()).toEqual({ + executions: { + [event.executionId]: { + stubbed: [ + { + workflowId, + blockId: fixture.idOf('save'), + block: 'save', + tool: 'table_upsert_row', + count: 1, + }, + ], + unchecked: [], + omitted: { stubbed: 0, unchecked: 0 }, + }, + }, + omittedExecutions: 0, + }) }) it('is forwarded by the v2 execute route, a block entry’s included', async () => { diff --git a/apps/sim/lib/workflows/application/run-workflow-for-test.ts b/apps/sim/lib/workflows/application/run-workflow-for-test.ts index 16d26b389ab..c1eec4f1cf3 100644 --- a/apps/sim/lib/workflows/application/run-workflow-for-test.ts +++ b/apps/sim/lib/workflows/application/run-workflow-for-test.ts @@ -3,6 +3,8 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal, } from '@sim/auth/principal' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { getActivelyBannedUserIds } from '@/lib/auth/ban' import { @@ -16,13 +18,15 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { generateRequestId } from '@/lib/core/utils/request' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { resolveTriggerExecution } from '@/lib/workflows/application/run-workflow-from-copilot' -import { WriteStubPolicy } from '@/lib/workflows/dry-run' +import { type SideEffectsSummary, WriteStubPolicy } from '@/lib/workflows/dry-run' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import type { ExecutionTestHooks } from '@/executor/execution/types' import type { ExecutionResult } from '@/executor/types' import { attachAttemptedExecutionId } from '@/executor/utils/errors' import { TEST_TRIGGER } from '@/stores/logs/filters/types' +const logger = createLogger('RunWorkflowForTest') + export type WorkflowTestVersion = 'draft' | 'deployed' export interface WorkflowTestRunResult { @@ -41,6 +45,8 @@ export interface RunWorkflowForTestInput { triggerBlockId?: string testHooks: ExecutionTestHooks abortSignal: AbortSignal + /** What the run did with the writes it reached, once it ends, failed runs included. */ + onSideEffects: (executionId: string, sideEffects: SideEffectsSummary) => void } /** @@ -119,6 +125,7 @@ export async function runWorkflowForTest( ) } } + const sideEffects = new WriteStubPolicy({ workflowId: context.workflowId }) try { const result = await executeWorkflow( { @@ -140,7 +147,7 @@ export async function runWorkflowForTest( abortSignal: input.abortSignal, billingAttribution, testHooks: input.testHooks, - sideEffects: new WriteStubPolicy({ workflowId: context.workflowId }), + sideEffects, }, executionId ) @@ -150,6 +157,14 @@ export async function runWorkflowForTest( throw error } finally { await releaseExecutionSlot(executionId) + try { + input.onSideEffects(executionId, sideEffects.summary()) + } catch (error) { + logger.warn('Recording a test run’s side effects failed', { + executionId, + error: getErrorMessage(error), + }) + } } } diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts index ec9b6f23789..08ffe265c38 100644 --- a/apps/sim/lib/workflows/dry-run/samples.ts +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -14,9 +14,8 @@ export function sampleBlockOutput(block: { }): Record { const subBlocks: Record = {} for (const [key, value] of Object.entries(block.params)) subBlocks[key] = { value } - const sample = generateMockPayloadFromOutputsDefinition( - getEffectiveBlockOutputs(block.type, subBlocks) - ) + const outputs = getEffectiveBlockOutputs(block.type, subBlocks) + const sample = withEmptyFileLists(outputs, generateMockPayloadFromOutputsDefinition(outputs)) return Object.fromEntries( Object.entries(sample).filter(([field]) => !isRunControlledOutputField(field)) ) @@ -31,6 +30,30 @@ function declaredFields(output: unknown): Record | null { : null } +/** + * `value` with each `file[]` its declared `output` holds empty, through declared fields and array + * items: a placeholder stores no file to reference. + */ +function emptyFileLists(output: unknown, value: unknown): unknown { + if (isPlainRecord(output) && output.type === 'file[]') return [] + const fields = declaredFields(output) + if (fields) return isPlainRecord(value) ? withEmptyFileLists(fields, value) : value + if (isPlainRecord(output) && output.type === 'array' && Array.isArray(value)) { + return value.map((item) => emptyFileLists(output.items, item)) + } + return value +} + +/** {@link emptyFileLists} over each field of a sample of `fields`. */ +function withEmptyFileLists( + fields: Record, + sample: Record +): Record { + return Object.fromEntries( + Object.entries(sample).map(([field, value]) => [field, emptyFileLists(fields[field], value)]) + ) +} + /** * `echoed` laid over `sample` by the declared `output`: field by field where it declares fields, * item by item where it declares an array's `items`, and anywhere else `echoed` replaces the sample @@ -77,6 +100,6 @@ export function sampleToolOutput( ): Record { const outputs = getToolOutputsMetadata(toolId) if (!outputs) return {} - const sample = generateMockPayloadFromOutputsDefinition(outputs) + const sample = withEmptyFileLists(outputs, generateMockPayloadFromOutputsDefinition(outputs)) return echoed ? overlayFields(outputs, sample, echoed) : sample } diff --git a/apps/sim/tools/airtable/create_records.ts b/apps/sim/tools/airtable/create_records.ts index ff73f1082d6..298c48d3566 100644 --- a/apps/sim/tools/airtable/create_records.ts +++ b/apps/sim/tools/airtable/create_records.ts @@ -1,4 +1,5 @@ import type { AirtableCreateParams, AirtableCreateResponse } from '@/tools/airtable/types' +import { placeholderRecords } from '@/tools/airtable/utils' import type { ToolConfig } from '@/tools/types' export const airtableCreateRecordsTool: ToolConfig = { @@ -61,6 +62,12 @@ export const airtableCreateRecordsTool: ToolConfig ({ + records: placeholderRecords(params.records), + metadata: { recordCount: params.records.length }, + }), + transformResponse: async (response) => { const data = await response.json() return { diff --git a/apps/sim/tools/airtable/update_multiple_records.ts b/apps/sim/tools/airtable/update_multiple_records.ts index d4517c1d491..ce1fc2dcb23 100644 --- a/apps/sim/tools/airtable/update_multiple_records.ts +++ b/apps/sim/tools/airtable/update_multiple_records.ts @@ -2,6 +2,7 @@ import type { AirtableUpdateMultipleParams, AirtableUpdateMultipleResponse, } from '@/tools/airtable/types' +import { placeholderRecords } from '@/tools/airtable/utils' import type { ToolConfig } from '@/tools/types' export const airtableUpdateMultipleRecordsTool: ToolConfig< @@ -66,6 +67,15 @@ export const airtableUpdateMultipleRecordsTool: ToolConfig< }), }, + /** A dry run's placeholder holds the records the call updates, with the fields it writes. */ + dryRunOutput: (params) => ({ + records: placeholderRecords(params.records), + metadata: { + recordCount: params.records.length, + updatedRecordIds: params.records.map((record) => record.id), + }, + }), + transformResponse: async (response) => { const data = await response.json() const records = data.records ?? [] diff --git a/apps/sim/tools/airtable/update_record.ts b/apps/sim/tools/airtable/update_record.ts index 32d69b2a60b..fc7b9c3fe30 100644 --- a/apps/sim/tools/airtable/update_record.ts +++ b/apps/sim/tools/airtable/update_record.ts @@ -66,6 +66,12 @@ export const airtableUpdateRecordTool: ToolConfig ({ + record: { id: params.recordId.trim(), fields: params.fields }, + metadata: { recordCount: 1 }, + }), + transformResponse: async (response) => { const data = await response.json() return { diff --git a/apps/sim/tools/airtable/upsert_records.ts b/apps/sim/tools/airtable/upsert_records.ts index 061c92b0179..a2c52d271ee 100644 --- a/apps/sim/tools/airtable/upsert_records.ts +++ b/apps/sim/tools/airtable/upsert_records.ts @@ -1,4 +1,5 @@ import type { AirtableUpsertParams, AirtableUpsertResponse } from '@/tools/airtable/types' +import { placeholderRecords } from '@/tools/airtable/utils' import type { ToolConfig } from '@/tools/types' export const airtableUpsertRecordsTool: ToolConfig = { @@ -89,6 +90,15 @@ export const airtableUpsertRecordsTool: ToolConfig ({ + records: placeholderRecords(params.records), + metadata: { recordCount: params.records.length }, + }), + transformResponse: async (response) => { const data = await response.json() const records = data.records ?? [] diff --git a/apps/sim/tools/airtable/utils.ts b/apps/sim/tools/airtable/utils.ts new file mode 100644 index 00000000000..38265658d10 --- /dev/null +++ b/apps/sim/tools/airtable/utils.ts @@ -0,0 +1,15 @@ +import { dryRunId } from '@/tools/dry-run' + +/** + * A dry run's placeholder for the records a write returns: each with the fields the call writes + * (before Airtable's typecast, and without the fields it already held) and the id the call names, + * or a placeholder id for a record Airtable picks. + */ +export function placeholderRecords( + records: ReadonlyArray<{ id?: string; fields: Record }> +) { + return records.map((record, index) => ({ + id: record.id ?? dryRunId('record', index + 1), + fields: record.fields, + })) +} diff --git a/apps/sim/tools/asana/create_task.ts b/apps/sim/tools/asana/create_task.ts index a49c92bb24c..fe2550ac5d6 100644 --- a/apps/sim/tools/asana/create_task.ts +++ b/apps/sim/tools/asana/create_task.ts @@ -1,4 +1,5 @@ import type { AsanaCreateTaskParams, AsanaCreateTaskResponse } from '@/tools/asana/types' +import { dryRunId } from '@/tools/dry-run' import type { InternalToolConfig } from '@/tools/types' export const asanaCreateTaskTool: InternalToolConfig< @@ -66,6 +67,13 @@ export const asanaCreateTaskTool: InternalToolConfig< }), }, + /** A dry run's placeholder holds the name and notes the call sets; its gid is a placeholder. */ + dryRunOutput: (params) => ({ + gid: dryRunId('task'), + name: params.name, + ...(params.notes ? { notes: params.notes } : {}), + }), + transformResponse: async (response: Response) => { const responseText = await response.text() diff --git a/apps/sim/tools/clickup/create_task.ts b/apps/sim/tools/clickup/create_task.ts index ad4620a6bc7..a57380e7fe9 100644 --- a/apps/sim/tools/clickup/create_task.ts +++ b/apps/sim/tools/clickup/create_task.ts @@ -6,6 +6,7 @@ import { mapClickUpTask, } from '@/tools/clickup/shared' import type { ClickUpCreateTaskParams, ClickUpTaskResponse } from '@/tools/clickup/types' +import { dryRunId } from '@/tools/dry-run' import type { ToolConfig } from '@/tools/types' export const clickupCreateTaskTool: ToolConfig = { @@ -165,6 +166,20 @@ export const clickupCreateTaskTool: ToolConfig ({ + task: { + id: dryRunId('task'), + name: params.name, + ...(params.description && !params.markdownContent ? { description: params.description } : {}), + ...(params.parent ? { parent: params.parent } : {}), + }, + }), + transformResponse: async (response) => { const data = await response.json().catch(() => null) diff --git a/apps/sim/tools/confluence/create_page.ts b/apps/sim/tools/confluence/create_page.ts index a67b4cc95c0..2db9daf4426 100644 --- a/apps/sim/tools/confluence/create_page.ts +++ b/apps/sim/tools/confluence/create_page.ts @@ -1,4 +1,5 @@ import { CONTENT_BODY_OUTPUT_PROPERTIES, VERSION_OUTPUT_PROPERTIES } from '@/tools/confluence/types' +import { dryRunId } from '@/tools/dry-run' import type { InternalToolConfig } from '@/tools/types' export interface ConfluenceCreatePageParams { @@ -101,6 +102,22 @@ export const confluenceCreatePageTool: InternalToolConfig< }, }, + /** + * A dry run's placeholder holds the title of the current page the call creates, the space it + * names by id (a space key is resolved live) and the parent it names (without one, Confluence + * picks the space's homepage); its id is a placeholder. + */ + dryRunOutput: (params) => { + const spaceId = params.spaceId.trim() + return { + pageId: dryRunId('page'), + title: params.title, + status: 'current', + ...(/^\d+$/.test(spaceId) ? { spaceId } : {}), + ...(params.parentId ? { parentId: params.parentId } : {}), + } + }, + transformResponse: async (response: Response) => { const data = await response.json() return { diff --git a/apps/sim/tools/discord/send_message.ts b/apps/sim/tools/discord/send_message.ts index 4c1103d7a9d..d5fc0999ac7 100644 --- a/apps/sim/tools/discord/send_message.ts +++ b/apps/sim/tools/discord/send_message.ts @@ -1,7 +1,16 @@ import type { DiscordSendMessageParams, DiscordSendMessageResponse } from '@/tools/discord/types' +import { dryRunId } from '@/tools/dry-run' import { DISCORD_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' import type { InternalToolConfig } from '@/tools/types' +/** The text a message sends: a default when it has neither text nor files. */ +function sentContent(params: DiscordSendMessageParams): string | undefined { + return ( + params.content || + (Array.isArray(params.files) && params.files.length > 0 ? undefined : 'Message sent from Sim') + ) +} + export const discordSendMessageTool: InternalToolConfig< DiscordSendMessageParams, DiscordSendMessageResponse @@ -51,11 +60,7 @@ export const discordSendMessageTool: InternalToolConfig< return { botToken: params.botToken.trim(), channelId: params.channelId.trim(), - content: - params.content || - (Array.isArray(params.files) && params.files.length > 0 - ? undefined - : 'Message sent from Sim'), + content: sentContent(params), files: params.files || null, } }, @@ -72,6 +77,15 @@ export const discordSendMessageTool: InternalToolConfig< } }, + /** A dry run's placeholder holds the text the call sends and the channel it names. */ + dryRunOutput: (params) => { + const content = sentContent(params) ?? '' + return { + message: content, + data: { id: dryRunId('message'), content, channel_id: params.channelId.trim() }, + } + }, + outputs: { message: { type: 'string', description: 'Content of the sent message' }, files: { type: 'file[]', description: 'Files attached to the message' }, diff --git a/apps/sim/tools/dry-run.test.ts b/apps/sim/tools/dry-run.test.ts new file mode 100644 index 00000000000..5312d0c93f8 --- /dev/null +++ b/apps/sim/tools/dry-run.test.ts @@ -0,0 +1,191 @@ +/** + * @vitest-environment node + */ +import { createExecutionContext } from '@sim/testing/factories/execution.factory' +import { toRecord } from '@sim/utils/object' +import { describe, expect, it, vi } from 'vitest' +import { WriteStubPolicy } from '@/lib/workflows/dry-run' +import type { ExecutionContext } from '@/executor/types' +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' +import { confluenceCreatePageTool } from '@/tools/confluence/create_page' +import { appendV2Tool } from '@/tools/google_sheets/append' +import { hubspotUpdateContactTool } from '@/tools/hubspot/update_contact' +import { hubspotUpdateDealTool } from '@/tools/hubspot/update_deal' +import { knowledgeUpsertDocumentTool } from '@/tools/knowledge/upsert_document' +import { resendSendTool } from '@/tools/resend/send' +import { answerUnsentWrite, describeToolRequest, unsentWriteFor } from '@/tools/side-effects' +import { slackMessageTool } from '@/tools/slack/message' +import type { ExecutableToolConfig } from '@/tools/types' + +vi.unmock('@/tools/metadata-outputs') + +const TOOLS = new Map( + [ + appendV2Tool, + confluenceCreatePageTool, + hubspotUpdateContactTool, + hubspotUpdateDealTool, + knowledgeUpsertDocumentTool, + resendSendTool, + slackMessageTool, + ].map((tool) => [tool.id, tool]) +) + +const SECRET = 'live-credential-8c1f' + +/** The placeholder a dry run answers one unsent `toolId` call with, through the real seam. */ +async function placeholderFor(toolId: string, params: Record) { + const tool = TOOLS.get(toolId) + if (!tool) throw new Error(`No tool ${toolId} in this suite`) + const policy = new WriteStubPolicy({ workflowId: 'wf-1' }) + const callParams = { ...params, _context: { blockId: 'write' } } + const write = unsentWriteFor({ + toolId, + params: callParams, + executionContext: { + ...createExecutionContext({ workflowId: 'wf-1' }), + sideEffects: policy, + } as ExecutionContext, + }) + if (!write) throw new Error('The policy sent the write') + const response = await answerUnsentWrite(write, { + params: callParams, + registry: new ResolvedSecretTraceRegistry(), + describe: (masked) => describeToolRequest(tool, masked), + echo: tool.dryRunOutput, + }) + return response.output +} + +describe('a dry run’s placeholder for an unsent write', () => { + it.each([ + { + toolId: 'google_sheets_append_v2', + params: { + accessToken: SECRET, + spreadsheetId: 'sheet-1', + sheetName: 'Leads', + values: [{ name: 'Ada', note: `key ${SECRET}` }, { name: 'Bob' }], + includeValuesInResponse: true, + }, + echoed: { + updatedRows: 3, + updatedColumns: 2, + updatedCells: 6, + updatedData: { + majorDimension: 'ROWS', + values: [ + ['name', 'note'], + ['Ada', 'key [REDACTED]'], + ['Bob', ''], + ], + }, + }, + }, + { + toolId: 'hubspot_update_contact', + params: { + accessToken: SECRET, + contactId: 'ada@example.com', + idProperty: 'email', + properties: JSON.stringify({ firstname: 'Ada', zip: 94107, jobtitle: `holds ${SECRET}` }), + }, + echoed: { + contact: { + id: 'dry_run_contact_1', + properties: { firstname: 'Ada', zip: '94107', jobtitle: 'holds [REDACTED]' }, + }, + }, + }, + { + toolId: 'slack_message', + params: { + accessToken: SECRET, + destinationType: 'dm', + dmUserId: 'U123', + text: `deploy with ${SECRET}`, + threadTs: ' 1700000000.000100 ', + }, + echoed: { + message: { text: 'deploy with [REDACTED]', thread_ts: '1700000000.000100' }, + }, + }, + { + toolId: 'resend_send', + params: { + resendApiKey: SECRET, + fromAddress: 'a@b.co', + to: 'c@d.co', + subject: 'Hi', + body: `token ${SECRET}`, + }, + echoed: { to: 'c@d.co', subject: 'Hi', body: 'token [REDACTED]' }, + }, + ])( + '$toolId echoes what its request determines with its secrets masked', + async ({ toolId, params, echoed }) => { + const returned = await placeholderFor(toolId, params) + + expect(returned).toMatchObject(echoed) + expect(JSON.stringify(returned)).not.toContain(SECRET) + } + ) + + it.each([ + { + case: 'a HubSpot record named by another id property keeps a placeholder id', + toolId: 'hubspot_update_deal', + params: { accessToken: SECRET, dealId: 'deal-key', idProperty: 'deal_key', properties: {} }, + read: (returned: Record) => returned.dealId, + not: 'deal-key', + }, + { + case: 'an upsert names the document it replaces as previous, never as its own', + toolId: 'knowledge_upsert_document', + params: { knowledgeBaseId: 'kb1', name: 'Runbook', content: 'steps', documentId: 'doc-old' }, + read: (returned: Record) => toRecord(returned.data).documentId, + not: 'doc-old', + }, + { + case: 'a Slack DM reports the channel Slack opens, not the user it names', + toolId: 'slack_message', + params: { accessToken: SECRET, destinationType: 'dm', dmUserId: 'U123', text: 'hi' }, + read: (returned: Record) => returned.channel, + not: 'U123', + }, + { + case: 'Slack text that Slack returns escaped is not echoed as sent', + toolId: 'slack_message', + params: { accessToken: SECRET, channel: 'C1', text: 'Q&A ' }, + read: (returned: Record) => toRecord(returned.message).text, + not: 'Q&A ', + }, + { + case: 'a Confluence page created in a space named by key reports the id Confluence resolves', + toolId: 'confluence_create_page', + params: { + accessToken: SECRET, + domain: 'acme.atlassian.net', + spaceId: 'ENG', + title: 'Notes', + content: '

x

', + }, + read: (returned: Record) => returned.spaceId, + not: 'ENG', + }, + ])('$case', async ({ toolId, params, read, not }) => { + const returned = await placeholderFor(toolId, params) + + expect(read(returned)).not.toBe(not) + }) + + it('samples a file list a placeholder cannot hold as empty', async () => { + const returned = await placeholderFor('slack_message', { + accessToken: SECRET, + channel: 'C1', + text: 'hi', + }) + + expect(returned.files).toEqual([]) + }) +}) diff --git a/apps/sim/tools/dry-run.ts b/apps/sim/tools/dry-run.ts new file mode 100644 index 00000000000..5dbb86c40cb --- /dev/null +++ b/apps/sim/tools/dry-run.ts @@ -0,0 +1,8 @@ +/** + * The id a dry run's placeholder carries where the provider or stored state would assign one + * (`dry_run_row_1`, `dry_run_record_2`): recognisably not real, and distinct per item the call + * writes. `n` counts from 1. + */ +export function dryRunId(kind: string, n = 1): string { + return `dry_run_${kind}_${n}` +} diff --git a/apps/sim/tools/github/create_issue.ts b/apps/sim/tools/github/create_issue.ts index b8970c1b96d..8c90eb015f7 100644 --- a/apps/sim/tools/github/create_issue.ts +++ b/apps/sim/tools/github/create_issue.ts @@ -9,6 +9,26 @@ import { import { GITHUB_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' import type { ToolConfig } from '@/tools/types' +/** A comma-separated `assignees` or `labels` param as the names the request sends. */ +function nameList(value: string | undefined): string[] { + return (value ?? '') + .split(',') + .map((name) => name.trim()) + .filter(Boolean) +} + +/** The issue fields a create request sends: its title, and the body, labels and assignees it sets. */ +function requestedIssue(params: CreateIssueParams) { + const labels = nameList(params.labels) + const assignees = nameList(params.assignees) + return { + title: params.title, + ...(params.body ? { body: params.body } : {}), + ...(labels.length > 0 ? { labels } : {}), + ...(assignees.length > 0 ? { assignees } : {}), + } +} + export const createIssueTool: ToolConfig = { id: 'github_create_issue', name: 'GitHub Create Issue', @@ -77,30 +97,18 @@ export const createIssueTool: ToolConfig = { Authorization: `Bearer ${params.apiKey}`, 'X-GitHub-Api-Version': '2022-11-28', }), - body: (params) => { - const body: any = { - title: params.title, - } - if (params.body) body.body = params.body - if (params.assignees) { - const assigneesArray = params.assignees - .split(',') - .map((a) => a.trim()) - .filter((a) => a) - if (assigneesArray.length > 0) body.assignees = assigneesArray - } - if (params.labels) { - const labelsArray = params.labels - .split(',') - .map((l) => l.trim()) - .filter((l) => l) - if (labelsArray.length > 0) body.labels = labelsArray - } - if (params.milestone) body.milestone = params.milestone - return body - }, + body: (params) => ({ + ...requestedIssue(params), + ...(params.milestone ? { milestone: params.milestone } : {}), + }), }, + /** + * A dry run's placeholder holds what the call sets on the issue it creates; its number, state, + * URL and times stay placeholders. + */ + dryRunOutput: (params) => ({ metadata: requestedIssue(params) }), + transformResponse: async (response) => { const issue = await response.json() @@ -163,6 +171,21 @@ export const createIssueV2Tool: ToolConfig = { params: createIssueTool.params, request: createIssueTool.request, + /** + * A dry run's placeholder holds what the call sets on the issue it creates, each label and + * assignee by the name it sends and the milestone by its number (null when none is set); its + * id, number, state, URL and times stay placeholders. + */ + dryRunOutput: (params) => { + const { labels, assignees, ...issue } = requestedIssue(params) + return { + ...issue, + ...(labels ? { labels: labels.map((name) => ({ name })) } : {}), + ...(assignees ? { assignees: assignees.map((login) => ({ login })) } : {}), + milestone: params.milestone ? { number: params.milestone } : null, + } + }, + transformResponse: async (response: Response) => { const issue = await response.json() return { diff --git a/apps/sim/tools/gmail/send.ts b/apps/sim/tools/gmail/send.ts index 0be8a96f789..5ac18562f88 100644 --- a/apps/sim/tools/gmail/send.ts +++ b/apps/sim/tools/gmail/send.ts @@ -1,3 +1,4 @@ +import { dryRunId } from '@/tools/dry-run' import type { GmailSendParams, GmailToolResponse } from '@/tools/gmail/types' import type { InternalToolConfig } from '@/tools/types' @@ -167,6 +168,12 @@ export const gmailSendV2Tool: InternalToolConfig { + const threadId = params.threadId?.trim() + return { id: dryRunId('message'), ...(threadId ? { threadId } : {}) } + }, + transformResponse: async (response) => { const legacy = await gmailSendTool.transformResponse!(response) if (!legacy.success) { diff --git a/apps/sim/tools/google_docs/create.ts b/apps/sim/tools/google_docs/create.ts index 76551ee0c54..95439493741 100644 --- a/apps/sim/tools/google_docs/create.ts +++ b/apps/sim/tools/google_docs/create.ts @@ -1,5 +1,6 @@ import { generateShortId } from '@sim/utils/id' import { toRecord } from '@sim/utils/object' +import { dryRunId } from '@/tools/dry-run' import type { GoogleDocsCreateResponse, GoogleDocsToolParams } from '@/tools/google_docs/types' import type { ToolConfig } from '@/tools/types' @@ -151,6 +152,19 @@ export const createTool: ToolConfig { + const documentId = dryRunId('document') + return { + metadata: { + documentId, + title: params.title, + mimeType: DOC_MIME_TYPE, + url: `https://docs.google.com/document/d/${documentId}/edit`, + }, + } + }, + transformResponse: async (response: Response) => { const data = toRecord(await response.json()) if (typeof data.id !== 'string' || !data.id) diff --git a/apps/sim/tools/google_drive/upload.ts b/apps/sim/tools/google_drive/upload.ts index 93cc2a2fdea..b061e622ff9 100644 --- a/apps/sim/tools/google_drive/upload.ts +++ b/apps/sim/tools/google_drive/upload.ts @@ -1,3 +1,4 @@ +import { dryRunId } from '@/tools/dry-run' import type { GoogleDriveToolParams, GoogleDriveUploadResponse } from '@/tools/google_drive/types' import type { InternalToolConfig } from '@/tools/types' @@ -69,6 +70,24 @@ export const uploadTool: InternalToolConfig { + const mimeType = params.mimeType || (params.file ? undefined : 'text/plain') + const folderId = (params.folderSelector || params.folderId)?.trim() + return { + file: { + id: dryRunId('file'), + name: params.fileName, + ...(mimeType ? { mimeType } : {}), + ...(folderId ? { parents: [folderId] } : {}), + }, + } + }, + transformResponse: async (response: Response) => { const data = (await response.json()) as { success?: boolean diff --git a/apps/sim/tools/google_sheets/append.ts b/apps/sim/tools/google_sheets/append.ts index 03cec57aeda..de74267f281 100644 --- a/apps/sim/tools/google_sheets/append.ts +++ b/apps/sim/tools/google_sheets/append.ts @@ -6,8 +6,10 @@ import type { } from '@/tools/google_sheets/types' import { appendResponseRenderParams, + appendSheetRows, mapValueRange, RESPONSE_RENDER_PARAMS, + sheetWritePlaceholder, UPDATED_DATA_OUTPUT, } from '@/tools/google_sheets/utils' import type { ToolConfig } from '@/tools/types' @@ -100,94 +102,15 @@ export const appendTool: ToolConfig { - let processedValues: any = params.values || [] - - // Handle case where values might be a string (potentially JSON string) - if (typeof processedValues === 'string') { - try { - // Try to parse it as JSON - processedValues = JSON.parse(processedValues) - } catch (_error) { - // If the input contains literal newlines causing JSON parse to fail, - // try a more robust approach - try { - // Replace literal newlines with escaped newlines for JSON parsing - const sanitizedInput = (processedValues as string) - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t') - - // Try to parse again with sanitized input - processedValues = JSON.parse(sanitizedInput) - } catch (_secondError) { - // If all parsing attempts fail, wrap as a single cell value - processedValues = [[processedValues]] - } - } - } - - // New logic to handle array of objects - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - // It's an array of objects - - // First, extract all unique keys from all objects to create headers - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - // Then create rows with object values in the order of headers - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - // Handle non-object items by creating an array with empty values - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - // Handle nested objects/arrays by converting to JSON string - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - // Add headers as the first row, then add data rows - processedValues = [headers, ...rows] - } - // Continue with existing logic for other array types - else if (!Array.isArray(processedValues)) { - processedValues = [[String(processedValues)]] - } else if (!processedValues.every((item: any) => Array.isArray(item))) { - // If it's an array but not all elements are arrays, wrap each element - processedValues = (processedValues as any[]).map((row: any) => - Array.isArray(row) ? row : [String(row)] - ) - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - - // Only include range if it's provided - if (params.range) { - body.range = params.range - } - - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: appendSheetRows(params.values), + ...(params.range ? { range: params.range } : {}), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, appendSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() @@ -326,70 +249,14 @@ export const appendV2Tool: ToolConfig { - let processedValues: any = params.values || [] - - if (typeof processedValues === 'string') { - try { - processedValues = JSON.parse(processedValues) - } catch (_error) { - try { - const sanitizedInput = (processedValues as string) - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t') - processedValues = JSON.parse(sanitizedInput) - } catch (_secondError) { - processedValues = [[processedValues]] - } - } - } - - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - processedValues = [headers, ...rows] - } else if (!Array.isArray(processedValues)) { - processedValues = [[String(processedValues)]] - } else if (!processedValues.every((item: any) => Array.isArray(item))) { - processedValues = (processedValues as any[]).map((row: any) => - Array.isArray(row) ? row : [String(row)] - ) - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: appendSheetRows(params.values), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, appendSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/google_sheets/update.ts b/apps/sim/tools/google_sheets/update.ts index 168bce169e3..328c0770170 100644 --- a/apps/sim/tools/google_sheets/update.ts +++ b/apps/sim/tools/google_sheets/update.ts @@ -8,7 +8,9 @@ import { appendResponseRenderParams, mapValueRange, RESPONSE_RENDER_PARAMS, + sheetWritePlaceholder, UPDATED_DATA_OUTPUT, + updateSheetRows, } from '@/tools/google_sheets/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -89,60 +91,15 @@ export const updateTool: ToolConfig { - let processedValues: any = params.values || [] - - // Minimal shape enforcement: Google requires a 2D array - if (!Array.isArray(processedValues)) { - processedValues = [[processedValues]] - } else if (!processedValues.every((item: any) => Array.isArray(item))) { - processedValues = (processedValues as any[]).map((row: any) => - Array.isArray(row) ? row : [row] - ) - } - - // Handle array of objects (existing behavior) - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - processedValues = [headers, ...rows] - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - if (params.range) { - body.range = params.range - } - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: updateSheetRows(params.values), + ...(params.range ? { range: params.range } : {}), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, updateSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() @@ -279,58 +236,14 @@ export const updateV2Tool: ToolConfig { - let processedValues: any = params.values || [] - - // Minimal shape enforcement: Google requires a 2D array - if (!Array.isArray(processedValues)) { - processedValues = [[processedValues]] - } else if (!processedValues.every((item: any) => Array.isArray(item))) { - processedValues = (processedValues as any[]).map((row: any) => - Array.isArray(row) ? row : [row] - ) - } - - // Handle array of objects - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - processedValues = [headers, ...rows] - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: updateSheetRows(params.values), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, updateSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/google_sheets/utils.ts b/apps/sim/tools/google_sheets/utils.ts index dd42dab063f..55e5c022037 100644 --- a/apps/sim/tools/google_sheets/utils.ts +++ b/apps/sim/tools/google_sheets/utils.ts @@ -107,3 +107,126 @@ export const UPDATED_DATA_OUTPUT: ToolOutputProperty = { values: { type: 'array', description: 'The cell values as a 2D array' }, }, } + +/** Whether `value` is any object (an array or class instance included) a row reads keys from. */ +function isKeyedRow(value: unknown): value is object { + return typeof value === 'object' && value !== null +} + +/** + * Objects as sheet rows: a header row of every key the entries hold, then one row per entry, a + * nested value as its JSON and a missing one empty. Any object entry (an array included) gives + * its keys; anything else is an empty row. + */ +function objectsToSheetRows(objects: unknown[]): unknown[][] { + const headers = [...new Set(objects.flatMap((row) => (isKeyedRow(row) ? Object.keys(row) : [])))] + const rows = objects.map((row) => { + if (!isKeyedRow(row)) return Array(headers.length).fill('') + return headers.map((key) => { + const value: unknown = Reflect.get(row, key) + if (value !== null && typeof value === 'object') return JSON.stringify(value) + return value === undefined ? '' : value + }) + }) + return [headers, ...rows] +} + +/** Whether `values` is a non-empty array whose first entry is an object, not a row. */ +function holdsObjects(values: unknown): values is unknown[] { + return ( + Array.isArray(values) && + values.length > 0 && + typeof values[0] === 'object' && + !Array.isArray(values[0]) + ) +} + +/** `values` as written: an array of objects as {@link objectsToSheetRows}, anything else as given. */ +export function writeSheetRows(values: unknown): unknown { + const given = values || [] + return holdsObjects(given) ? objectsToSheetRows(given) : given +} + +/** `values` parsed from a JSON string, or the string as one cell when it is not JSON. */ +function parseSheetValues(values: string): unknown { + try { + return JSON.parse(values) + } catch { + try { + return JSON.parse(values.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t')) + } catch { + return [[values]] + } + } +} + +/** + * `values` as appended: a JSON string parsed, an array of objects as {@link objectsToSheetRows}, + * a scalar as one cell, and each scalar entry of an array as a one-cell row. + */ +export function appendSheetRows(values: unknown): unknown[][] { + const given = values || [] + const parsed = typeof given === 'string' ? parseSheetValues(given) : given + if (holdsObjects(parsed)) return objectsToSheetRows(parsed) + if (!Array.isArray(parsed)) return [[String(parsed)]] + return parsed.map((row) => (Array.isArray(row) ? row : [String(row)])) +} + +interface SheetWriteCounts { + updatedRows: number + updatedColumns: number + updatedCells: number +} + +/** + * The counts a write of `values` reports, or null when the request alone cannot say: `values` + * is not a grid, or a null cell leaves the sheet's value in place. An empty row or column writes + * no cell, so it is not counted as updated. + */ +function sheetWriteCounts(values: unknown, majorDimension: string): SheetWriteCounts | null { + if (!Array.isArray(values) || !values.every(Array.isArray)) return null + const rows: unknown[][] = values + if (rows.some((row) => row.some((cell) => cell === null || cell === undefined))) return null + const lines = rows.filter((row) => row.length > 0).length + const width = rows.reduce((widest, row) => Math.max(widest, row.length), 0) + const cells = rows.reduce((total, row) => total + row.length, 0) + const byColumns = majorDimension === 'COLUMNS' + return { + updatedRows: byColumns ? width : lines, + updatedColumns: byColumns ? lines : width, + updatedCells: cells, + } +} + +/** `values` as updated: a scalar as one cell, and each scalar entry of an array as a one-cell row. */ +export function updateSheetRows(values: unknown): unknown[][] { + const given = values || [] + if (!Array.isArray(given)) return [[given]] + return given.map((row) => (Array.isArray(row) ? row : [row])) +} + +/** + * A dry run's placeholder for a values write (append, write or update) of `values` as sent: the + * counts the grid determines, the spreadsheet it names, and `updatedData` (dropped by a tool that + * does not declare it) holding the values as written, before the sheet renders them, or null when + * the call asks for none. The ranges the sheet resolves stay placeholders. + */ +export function sheetWritePlaceholder( + params: { + spreadsheetId: string + majorDimension?: string + includeValuesInResponse?: boolean + }, + values: unknown +): Record { + const majorDimension = params.majorDimension || 'ROWS' + const spreadsheetId = String(params.spreadsheetId).trim() + return { + ...sheetWriteCounts(values, majorDimension), + metadata: { + spreadsheetId, + spreadsheetUrl: `https://docs.google.com/spreadsheets/d/${spreadsheetId}`, + }, + updatedData: params.includeValuesInResponse ? { majorDimension, values } : null, + } +} diff --git a/apps/sim/tools/google_sheets/write.ts b/apps/sim/tools/google_sheets/write.ts index 82b0dcb7ea3..bf45bde9512 100644 --- a/apps/sim/tools/google_sheets/write.ts +++ b/apps/sim/tools/google_sheets/write.ts @@ -8,7 +8,9 @@ import { appendResponseRenderParams, mapValueRange, RESPONSE_RENDER_PARAMS, + sheetWritePlaceholder, UPDATED_DATA_OUTPUT, + writeSheetRows, } from '@/tools/google_sheets/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -91,61 +93,15 @@ export const writeTool: ToolConfig { - let processedValues: any = params.values || [] - - // Handle array of objects - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - // It's an array of objects - - // First, extract all unique keys from all objects to create headers - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - // Then create rows with object values in the order of headers - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - // Handle non-object items by creating an array with empty values - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - // Handle nested objects/arrays by converting to JSON string - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - // Add headers as the first row, then add data rows - processedValues = [headers, ...rows] - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - - // Only include range if it's provided - if (params.range) { - body.range = params.range - } - - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: writeSheetRows(params.values), + ...(params.range ? { range: params.range } : {}), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, writeSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() @@ -293,49 +249,14 @@ export const writeV2Tool: ToolConfig { - let processedValues: any = params.values || [] - - // Handle array of objects - if ( - Array.isArray(processedValues) && - processedValues.length > 0 && - typeof processedValues[0] === 'object' && - !Array.isArray(processedValues[0]) - ) { - const allKeys = new Set() - processedValues.forEach((obj: any) => { - if (obj && typeof obj === 'object') { - Object.keys(obj).forEach((key) => allKeys.add(key)) - } - }) - const headers = Array.from(allKeys) - - const rows = processedValues.map((obj: any) => { - if (!obj || typeof obj !== 'object') { - return Array(headers.length).fill('') - } - return headers.map((key) => { - const value = obj[key] - if (value !== null && typeof value === 'object') { - return JSON.stringify(value) - } - return value === undefined ? '' : value - }) - }) - - processedValues = [headers, ...rows] - } - - const body: Record = { - majorDimension: params.majorDimension || 'ROWS', - values: processedValues, - } - - return body - }, + body: (params) => ({ + majorDimension: params.majorDimension || 'ROWS', + values: writeSheetRows(params.values), + }), }, + dryRunOutput: (params) => sheetWritePlaceholder(params, writeSheetRows(params.values)), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/hubspot/create_company.ts b/apps/sim/tools/hubspot/create_company.ts index 754e1b335cd..7ad5bb7469b 100644 --- a/apps/sim/tools/hubspot/create_company.ts +++ b/apps/sim/tools/hubspot/create_company.ts @@ -4,6 +4,7 @@ import type { HubSpotCreateCompanyResponse, } from '@/tools/hubspot/types' import { COMPANY_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' const logger = createLogger('HubSpotCreateCompany') @@ -60,14 +61,7 @@ export const hubspotCreateCompanyTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) const body: any = { properties, @@ -91,6 +85,8 @@ export const hubspotCreateCompanyTool: ToolConfig< }, }, + dryRunOutput: (params) => placeholderCrmRecord('company', params.properties), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/hubspot/create_contact.ts b/apps/sim/tools/hubspot/create_contact.ts index 595cd5a96ab..98c8134f278 100644 --- a/apps/sim/tools/hubspot/create_contact.ts +++ b/apps/sim/tools/hubspot/create_contact.ts @@ -4,6 +4,7 @@ import type { HubSpotCreateContactResponse, } from '@/tools/hubspot/types' import { CONTACT_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' const logger = createLogger('HubSpotCreateContact') @@ -61,14 +62,7 @@ export const hubspotCreateContactTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) const body: any = { properties, @@ -92,6 +86,8 @@ export const hubspotCreateContactTool: ToolConfig< }, }, + dryRunOutput: (params) => placeholderCrmRecord('contact', params.properties), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/hubspot/create_deal.ts b/apps/sim/tools/hubspot/create_deal.ts index eabd156b1e3..7f4a2f2c8bd 100644 --- a/apps/sim/tools/hubspot/create_deal.ts +++ b/apps/sim/tools/hubspot/create_deal.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import type { HubSpotCreateDealParams, HubSpotCreateDealResponse } from '@/tools/hubspot/types' import { DEAL_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' const logger = createLogger('HubSpotCreateDeal') @@ -55,16 +56,7 @@ export const hubspotCreateDealTool: ToolConfig { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error( - 'Invalid JSON format for properties. Please provide a valid JSON object.' - ) - } - } + const properties = parseHubSpotProperties(params.properties) const body: Record = { properties } let associations = params.associations if (typeof associations === 'string') { @@ -83,6 +75,8 @@ export const hubspotCreateDealTool: ToolConfig placeholderCrmRecord('deal', params.properties), + transformResponse: async (response: Response) => { const data = await response.json() if (!response.ok) { diff --git a/apps/sim/tools/hubspot/create_ticket.ts b/apps/sim/tools/hubspot/create_ticket.ts index 49c9239cf10..2e1e5dbbc81 100644 --- a/apps/sim/tools/hubspot/create_ticket.ts +++ b/apps/sim/tools/hubspot/create_ticket.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import type { HubSpotCreateTicketParams, HubSpotCreateTicketResponse } from '@/tools/hubspot/types' import { TICKET_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' const logger = createLogger('HubSpotCreateTicket') @@ -56,14 +57,7 @@ export const hubspotCreateTicketTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) const body: Record = { properties } let associations = params.associations if (typeof associations === 'string') { @@ -82,6 +76,8 @@ export const hubspotCreateTicketTool: ToolConfig< }, }, + dryRunOutput: (params) => placeholderCrmRecord('ticket', params.properties), + transformResponse: async (response: Response) => { const data = await response.json() if (!response.ok) { diff --git a/apps/sim/tools/hubspot/update_company.ts b/apps/sim/tools/hubspot/update_company.ts index f680363b065..10f6f06bc3d 100644 --- a/apps/sim/tools/hubspot/update_company.ts +++ b/apps/sim/tools/hubspot/update_company.ts @@ -4,6 +4,7 @@ import type { HubSpotUpdateCompanyResponse, } from '@/tools/hubspot/types' import { COMPANY_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -73,14 +74,7 @@ export const hubspotUpdateCompanyTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) return { properties, @@ -88,6 +82,13 @@ export const hubspotUpdateCompanyTool: ToolConfig< }, }, + dryRunOutput: (params) => + placeholderCrmRecord( + 'company', + params.properties, + params.idProperty ? undefined : String(params.companyId).trim() + ), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/hubspot/update_contact.ts b/apps/sim/tools/hubspot/update_contact.ts index b457d6780c3..3298c5a9323 100644 --- a/apps/sim/tools/hubspot/update_contact.ts +++ b/apps/sim/tools/hubspot/update_contact.ts @@ -4,6 +4,7 @@ import type { HubSpotUpdateContactResponse, } from '@/tools/hubspot/types' import { CONTACT_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -73,14 +74,7 @@ export const hubspotUpdateContactTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) return { properties, @@ -88,6 +82,13 @@ export const hubspotUpdateContactTool: ToolConfig< }, }, + dryRunOutput: (params) => + placeholderCrmRecord( + 'contact', + params.properties, + params.idProperty ? undefined : String(params.contactId).trim() + ), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/hubspot/update_deal.ts b/apps/sim/tools/hubspot/update_deal.ts index 281a7237356..0281f21f8c4 100644 --- a/apps/sim/tools/hubspot/update_deal.ts +++ b/apps/sim/tools/hubspot/update_deal.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import type { HubSpotUpdateDealParams, HubSpotUpdateDealResponse } from '@/tools/hubspot/types' import { DEAL_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -66,20 +67,18 @@ export const hubspotUpdateDealTool: ToolConfig { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error( - 'Invalid JSON format for properties. Please provide a valid JSON object.' - ) - } - } + const properties = parseHubSpotProperties(params.properties) return { properties } }, }, + dryRunOutput: (params) => + placeholderCrmRecord( + 'deal', + params.properties, + params.idProperty ? undefined : String(params.dealId).trim() + ), + transformResponse: async (response: Response) => { const data = await response.json() if (!response.ok) { diff --git a/apps/sim/tools/hubspot/update_ticket.ts b/apps/sim/tools/hubspot/update_ticket.ts index 85bd5222ae2..261900a29d5 100644 --- a/apps/sim/tools/hubspot/update_ticket.ts +++ b/apps/sim/tools/hubspot/update_ticket.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import type { HubSpotUpdateTicketParams, HubSpotUpdateTicketResponse } from '@/tools/hubspot/types' import { TICKET_OBJECT_OUTPUT } from '@/tools/hubspot/types' +import { parseHubSpotProperties, placeholderCrmRecord } from '@/tools/hubspot/utils' import type { ToolConfig } from '@/tools/types' import { safeUrlPathSegment } from '@/tools/url-path' @@ -68,18 +69,18 @@ export const hubspotUpdateTicketTool: ToolConfig< } }, body: (params) => { - let properties = params.properties - if (typeof properties === 'string') { - try { - properties = JSON.parse(properties) - } catch { - throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') - } - } + const properties = parseHubSpotProperties(params.properties) return { properties } }, }, + dryRunOutput: (params) => + placeholderCrmRecord( + 'ticket', + params.properties, + params.idProperty ? undefined : String(params.ticketId).trim() + ), + transformResponse: async (response: Response) => { const data = await response.json() if (!response.ok) { diff --git a/apps/sim/tools/hubspot/utils.ts b/apps/sim/tools/hubspot/utils.ts new file mode 100644 index 00000000000..c768ff1bd63 --- /dev/null +++ b/apps/sim/tools/hubspot/utils.ts @@ -0,0 +1,39 @@ +import { isPlainRecord } from '@sim/utils/object' +import { dryRunId } from '@/tools/dry-run' + +/** A CRM write's `properties`, a JSON string parsed. */ +export function parseHubSpotProperties(properties: unknown): unknown { + if (typeof properties !== 'string') return properties + try { + return JSON.parse(properties) + } catch { + throw new Error('Invalid JSON format for properties. Please provide a valid JSON object.') + } +} + +/** Properties as HubSpot returns them: every scalar value a string. */ +function asReturnedProperties(properties: unknown): unknown { + if (!isPlainRecord(properties)) return properties + return Object.fromEntries( + Object.entries(properties).map(([name, value]) => [ + name, + typeof value === 'number' || typeof value === 'boolean' ? String(value) : value, + ]) + ) +} + +/** + * A dry run's placeholder for the CRM record a create or update of `kind` returns, under `kind` + * and `${kind}Id`: the properties the call writes, as the strings HubSpot returns (it returns the + * rest of the record's too), with the record id the call names, or a placeholder id for one + * HubSpot assigns or resolves from another id property. + */ +export function placeholderCrmRecord(kind: string, properties: unknown, id = dryRunId(kind)) { + return { + [kind]: { + id, + properties: asReturnedProperties(parseHubSpotProperties(properties)), + }, + [`${kind}Id`]: id, + } +} diff --git a/apps/sim/tools/jira/write.ts b/apps/sim/tools/jira/write.ts index da64cf5ad15..fc1a2ffb68e 100644 --- a/apps/sim/tools/jira/write.ts +++ b/apps/sim/tools/jira/write.ts @@ -1,3 +1,4 @@ +import { dryRunId } from '@/tools/dry-run' import type { JiraWriteParams, JiraWriteResponse } from '@/tools/jira/types' import { TIMESTAMP_OUTPUT } from '@/tools/jira/types' import { parseJiraFieldMap } from '@/tools/jira/utils' @@ -180,6 +181,9 @@ export const jiraWriteTool: InternalToolConfig ({ id: dryRunId('issue'), summary: params.summary }), + transformResponse: async (response: Response) => { const responseText = await response.text() diff --git a/apps/sim/tools/knowledge/upsert_document.ts b/apps/sim/tools/knowledge/upsert_document.ts index bdf849ea35d..bae9d5f82a7 100644 --- a/apps/sim/tools/knowledge/upsert_document.ts +++ b/apps/sim/tools/knowledge/upsert_document.ts @@ -124,6 +124,14 @@ export const knowledgeUpsertDocumentTool: InternalToolConfig< }, }, + /** + * A dry run's placeholder names the document the call writes. Its id stays a placeholder: an + * upsert always creates a new document, and an id the call names becomes `previousDocumentId`. + */ + dryRunOutput: (params) => ({ + data: { documentName: inferDocumentFileInfo(params.name.trim()).filename }, + }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data ?? result diff --git a/apps/sim/tools/linear/create_issue.ts b/apps/sim/tools/linear/create_issue.ts index ffec060b8c6..a50db2884ce 100644 --- a/apps/sim/tools/linear/create_issue.ts +++ b/apps/sim/tools/linear/create_issue.ts @@ -1,8 +1,59 @@ +import { dryRunId } from '@/tools/dry-run' import type { LinearCreateIssueParams, LinearCreateIssueResponse } from '@/tools/linear/types' import { ISSUE_EXTENDED_OUTPUT_PROPERTIES } from '@/tools/linear/types' import { linearAuthorizationHeader } from '@/tools/linear/utils' import type { ToolConfig } from '@/tools/types' +/** The `IssueCreateInput` a call sends: its title and team, and each optional field it sets. */ +function issueCreateInput(params: LinearCreateIssueParams): Record { + if (!params.title || !params.title.trim()) { + throw new Error('Title is required to create a Linear issue') + } + + const input: Record = { + teamId: params.teamId, + title: params.title, + } + + if (params.projectId != null && params.projectId !== '') { + input.projectId = params.projectId + } + if (params.description != null && params.description !== '') { + input.description = params.description + } + if (params.stateId != null && params.stateId !== '') { + input.stateId = params.stateId + } + if (params.assigneeId != null && params.assigneeId !== '') { + input.assigneeId = params.assigneeId + } + if (params.priority != null) { + input.priority = Number(params.priority) + } + if (params.estimate != null) { + input.estimate = Number(params.estimate) + } + if (Array.isArray(params.labelIds)) { + input.labelIds = params.labelIds + } + if (params.cycleId != null && params.cycleId !== '') { + input.cycleId = params.cycleId + } + if (params.parentId != null && params.parentId !== '') { + input.parentId = params.parentId + } + if (params.dueDate != null && params.dueDate !== '') { + input.dueDate = params.dueDate + } + if (Array.isArray(params.subscriberIds)) { + input.subscriberIds = params.subscriberIds + } + if (params.projectMilestoneId != null && params.projectMilestoneId !== '') { + input.projectMilestoneId = params.projectMilestoneId + } + return input +} + export const linearCreateIssueTool: ToolConfig = { id: 'linear_create_issue', @@ -116,52 +167,7 @@ export const linearCreateIssueTool: ToolConfig { - if (!params.title || !params.title.trim()) { - throw new Error('Title is required to create a Linear issue') - } - - const input: Record = { - teamId: params.teamId, - title: params.title, - } - - if (params.projectId != null && params.projectId !== '') { - input.projectId = params.projectId - } - if (params.description != null && params.description !== '') { - input.description = params.description - } - if (params.stateId != null && params.stateId !== '') { - input.stateId = params.stateId - } - if (params.assigneeId != null && params.assigneeId !== '') { - input.assigneeId = params.assigneeId - } - if (params.priority != null) { - input.priority = Number(params.priority) - } - if (params.estimate != null) { - input.estimate = Number(params.estimate) - } - if (params.labelIds != null && Array.isArray(params.labelIds)) { - input.labelIds = params.labelIds - } - if (params.cycleId != null && params.cycleId !== '') { - input.cycleId = params.cycleId - } - if (params.parentId != null && params.parentId !== '') { - input.parentId = params.parentId - } - if (params.dueDate != null && params.dueDate !== '') { - input.dueDate = params.dueDate - } - if (params.subscriberIds != null && Array.isArray(params.subscriberIds)) { - input.subscriberIds = params.subscriberIds - } - if (params.projectMilestoneId != null && params.projectMilestoneId !== '') { - input.projectMilestoneId = params.projectMilestoneId - } - + const input = issueCreateInput(params) return { query: ` mutation CreateIssue($input: IssueCreateInput!) { @@ -223,6 +229,16 @@ export const linearCreateIssueTool: ToolConfig { + const { stateId, assigneeId, labelIds, subscriberIds, ...fields } = issueCreateInput(params) + return { issue: { id: dryRunId('issue'), ...fields } } + }, + transformResponse: async (response) => { const data = await response.json() diff --git a/apps/sim/tools/microsoft_teams/dry-run.ts b/apps/sim/tools/microsoft_teams/dry-run.ts new file mode 100644 index 00000000000..61dad63b1e3 --- /dev/null +++ b/apps/sim/tools/microsoft_teams/dry-run.ts @@ -0,0 +1,17 @@ +import { rewritesTeamsMessage } from '@/lib/internal/microsoft-teams/message-rewrite' +import { dryRunId } from '@/tools/dry-run' +import type { MicrosoftTeamsToolParams } from '@/tools/microsoft_teams/types' + +/** + * A dry run's placeholder for a message a write tool sends: the content as sent, unless files or + * mentions make Teams rewrite it, and a placeholder message id. Where it was sent the tool's own + * hook adds from the ids the call names. + */ +export function placeholderTeamsMessage(params: MicrosoftTeamsToolParams) { + const content = params.content ?? '' + return { + messageId: dryRunId('message'), + updatedContent: true, + ...(rewritesTeamsMessage(content, params.files) ? {} : { content }), + } +} diff --git a/apps/sim/tools/microsoft_teams/write_channel.ts b/apps/sim/tools/microsoft_teams/write_channel.ts index bb66ee83fe2..8535eaac485 100644 --- a/apps/sim/tools/microsoft_teams/write_channel.ts +++ b/apps/sim/tools/microsoft_teams/write_channel.ts @@ -1,3 +1,4 @@ +import { placeholderTeamsMessage } from '@/tools/microsoft_teams/dry-run' import type { MicrosoftTeamsToolParams, MicrosoftTeamsWriteResponse, @@ -69,6 +70,12 @@ export const writeChannelTool: InternalToolConfig< }, }, + dryRunOutput: (params) => ({ + ...placeholderTeamsMessage(params), + teamId: params.teamId?.trim(), + channelId: params.channelId?.trim(), + }), + outputs: { success: { type: 'boolean', description: 'Teams channel message send success status' }, messageId: { type: 'string', description: 'Unique identifier for the sent message' }, diff --git a/apps/sim/tools/microsoft_teams/write_chat.ts b/apps/sim/tools/microsoft_teams/write_chat.ts index 93dd4db8644..431e5324d47 100644 --- a/apps/sim/tools/microsoft_teams/write_chat.ts +++ b/apps/sim/tools/microsoft_teams/write_chat.ts @@ -1,3 +1,4 @@ +import { placeholderTeamsMessage } from '@/tools/microsoft_teams/dry-run' import type { MicrosoftTeamsToolParams, MicrosoftTeamsWriteResponse, @@ -61,6 +62,8 @@ export const writeChatTool: InternalToolConfig< }, }, + dryRunOutput: (params) => ({ ...placeholderTeamsMessage(params), chatId: params.chatId?.trim() }), + outputs: { success: { type: 'boolean', description: 'Teams chat message send success status' }, messageId: { type: 'string', description: 'Unique identifier for the sent message' }, diff --git a/apps/sim/tools/mysql/insert.ts b/apps/sim/tools/mysql/insert.ts index 250de842f49..ae71205631f 100644 --- a/apps/sim/tools/mysql/insert.ts +++ b/apps/sim/tools/mysql/insert.ts @@ -74,6 +74,13 @@ export const insertTool: InternalToolConfig = }), }, + /** A dry run's placeholder counts the one row the call inserts; MySQL returns no rows for it. */ + dryRunOutput: () => ({ + message: 'Data inserted successfully. 1 row(s) affected.', + rows: [], + rowCount: 1, + }), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/notion/create_page.ts b/apps/sim/tools/notion/create_page.ts index f126f3df533..095ebcb8454 100644 --- a/apps/sim/tools/notion/create_page.ts +++ b/apps/sim/tools/notion/create_page.ts @@ -1,3 +1,4 @@ +import { dryRunId } from '@/tools/dry-run' import type { NotionCreatePageParams, NotionResponse } from '@/tools/notion/types' import { PAGE_OUTPUT_PROPERTIES } from '@/tools/notion/types' import { extractTitle, toNotionRichText } from '@/tools/notion/utils' @@ -98,6 +99,15 @@ export const notionCreatePageTool: ToolConfig { + const title = params.title || 'Untitled' + return { + content: `Successfully created page "${title}"`, + metadata: { title, pageId: dryRunId('page') }, + } + }, + transformResponse: async (response: Response) => { const data = await response.json() const pageTitle = extractTitle(data.properties ?? {}) || 'Untitled' @@ -161,6 +171,9 @@ export const notionCreatePageV2Tool: ToolConfig< params: notionCreatePageTool.params, request: notionCreatePageTool.request, + /** A dry run's placeholder names the page the call creates; its id is a placeholder. */ + dryRunOutput: (params) => ({ id: dryRunId('page'), title: params.title || 'Untitled' }), + transformResponse: async (response: Response) => { const data = await response.json() const pageTitle = extractTitle(data.properties ?? {}) || 'Untitled' diff --git a/apps/sim/tools/postgresql/insert.ts b/apps/sim/tools/postgresql/insert.ts index 7b4a5b35d64..1a00f13ea6c 100644 --- a/apps/sim/tools/postgresql/insert.ts +++ b/apps/sim/tools/postgresql/insert.ts @@ -74,6 +74,16 @@ export const insertTool: InternalToolConfig ({ + message: 'Data inserted successfully. 1 row(s) affected.', + rows: [params.data], + rowCount: 1, + }), + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/request-builders.test.ts b/apps/sim/tools/request-builders.test.ts new file mode 100644 index 00000000000..b79b8893b46 --- /dev/null +++ b/apps/sim/tools/request-builders.test.ts @@ -0,0 +1,159 @@ +/** + * @vitest-environment node + */ +import { toRecord } from '@sim/utils/object' +import { describe, expect, it } from 'vitest' +import { discordSendMessageTool } from '@/tools/discord/send_message' +import { appendTool, appendV2Tool } from '@/tools/google_sheets/append' +import { updateV2Tool } from '@/tools/google_sheets/update' +import { writeV2Tool } from '@/tools/google_sheets/write' +import { hubspotCreateContactTool } from '@/tools/hubspot/create_contact' +import { linearCreateIssueTool } from '@/tools/linear/create_issue' +import { describeToolRequest } from '@/tools/side-effects' +import { insertTool as supabaseInsertTool } from '@/tools/supabase/insert' +import type { ExecutableToolConfig } from '@/tools/types' + +/** What `tool` sends for `params`: an HTTP request's body, or an in-process operation's input. */ +function sent(tool: ExecutableToolConfig, params: Record): unknown { + const request = describeToolRequest(tool, params) + return tool.operation ? request : toRecord(request).body +} + +const SHEET = { accessToken: 'token', spreadsheetId: 'sheet-1', sheetName: 'Leads' } + +/** + * The request builders whose normalisation dry-run placeholders now share, held to the bodies they + * sent before that normalisation moved into shared helpers. + */ +describe('a write request built from edge-case params', () => { + it.each([ + { + case: 'append: objects and arrays mixed read keys from both', + tool: appendV2Tool, + params: { ...SHEET, values: [{ a: 1 }, ['x', 'y']] }, + body: { + majorDimension: 'ROWS', + values: [ + ['a', '0', '1'], + [1, '', ''], + ['', 'x', 'y'], + ], + }, + }, + { + case: 'append: a null first entry takes the object path', + tool: appendV2Tool, + params: { ...SHEET, values: [null, { a: 1, b: { c: 2 } }] }, + body: { + majorDimension: 'ROWS', + values: [ + ['a', 'b'], + ['', ''], + [1, '{"c":2}'], + ], + }, + }, + { + case: 'append: a JSON string is parsed', + tool: appendV2Tool, + params: { ...SHEET, values: '[["a",1]]' }, + body: { majorDimension: 'ROWS', values: [['a', 1]] }, + }, + { + case: 'append: a string that is not JSON is one cell', + tool: appendV2Tool, + params: { ...SHEET, values: 'not json' }, + body: { majorDimension: 'ROWS', values: [['not json']] }, + }, + { + case: 'append: scalars become one-cell rows as strings', + tool: appendTool, + params: { accessToken: 'token', spreadsheetId: 'sheet-1', range: 'A1', values: ['a', 2] }, + body: { majorDimension: 'ROWS', values: [['a'], ['2']], range: 'A1' }, + }, + { + case: 'write: objects and arrays mixed read keys from both', + tool: writeV2Tool, + params: { ...SHEET, values: [{ a: 1 }, ['x']] }, + body: { + majorDimension: 'ROWS', + values: [ + ['a', '0'], + [1, ''], + ['', 'x'], + ], + }, + }, + { + case: 'write: a scalar is sent as given', + tool: writeV2Tool, + params: { ...SHEET, values: 'x' }, + body: { majorDimension: 'ROWS', values: 'x' }, + }, + { + case: 'update: scalars and objects are wrapped, never turned into headers', + tool: updateV2Tool, + params: { ...SHEET, values: ['a', { b: 2 }] }, + body: { majorDimension: 'ROWS', values: [['a'], [{ b: 2 }]] }, + }, + { + case: 'HubSpot: properties given as a JSON string are parsed', + tool: hubspotCreateContactTool, + params: { accessToken: 'token', properties: '{"email":"a@b.co"}' }, + body: { properties: { email: 'a@b.co' } }, + }, + { + case: 'Supabase: one row is sent as a one-row array', + tool: supabaseInsertTool, + params: { apiKey: 'key', projectId: 'abcdefghijklmnop', table: 'leads', data: { a: 1 } }, + body: [{ a: 1 }], + }, + { + case: 'Supabase: an array of rows is sent as given', + tool: supabaseInsertTool, + params: { apiKey: 'key', projectId: 'abcdefghijklmnop', table: 'leads', data: [{ a: 1 }] }, + body: [{ a: 1 }], + }, + ])('$case', ({ tool, params, body }) => { + expect(sent(tool, params)).toEqual(body) + }) + + it('Linear sends only the optional fields that are set, numbers coerced', () => { + const body = sent(linearCreateIssueTool, { + accessToken: 'token', + teamId: 'team-1', + title: 'Fix it', + projectId: '', + priority: '2', + labelIds: ['l1'], + }) + + expect(body).toMatchObject({ + variables: { input: { teamId: 'team-1', title: 'Fix it', priority: 2, labelIds: ['l1'] } }, + }) + }) + + it('a malformed HubSpot properties string fails the request', () => { + expect(() => + sent(hubspotCreateContactTool, { accessToken: 'token', properties: '{not json' }) + ).toThrow('Invalid JSON format for properties') + }) + + it.each([ + { content: '', files: [], sent: 'Message sent from Sim' }, + { content: '', files: [{ name: 'a.txt' }], sent: undefined }, + { content: 'hi', files: [], sent: 'hi' }, + ])( + 'Discord sends $sent for content "$content" and $files.length files', + ({ content, files, sent: expected }) => { + const input = sent(discordSendMessageTool, { + botToken: 'bot', + channelId: '42', + content, + files, + }) + + expect(input).toMatchObject({ content: expected }) + } + ) +}) diff --git a/apps/sim/tools/resend/send.ts b/apps/sim/tools/resend/send.ts index 373e422bf93..5cffaa27cd0 100644 --- a/apps/sim/tools/resend/send.ts +++ b/apps/sim/tools/resend/send.ts @@ -1,3 +1,4 @@ +import { dryRunId } from '@/tools/dry-run' import type { MailSendParams, MailSendResult } from '@/tools/resend/types' import { RESEND_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' import type { InternalToolConfig } from '@/tools/types' @@ -99,6 +100,14 @@ export const resendSendTool: InternalToolConfig }), }, + /** A dry run's placeholder holds the recipient, subject and body the call sends; its id is a placeholder. */ + dryRunOutput: (params) => ({ + id: dryRunId('email'), + to: params.to, + subject: params.subject, + body: params.body, + }), + transformResponse: async (response: Response, params): Promise => { const result = await response.json() diff --git a/apps/sim/tools/sendgrid/send_mail.ts b/apps/sim/tools/sendgrid/send_mail.ts index a4575089f84..adac89aa26c 100644 --- a/apps/sim/tools/sendgrid/send_mail.ts +++ b/apps/sim/tools/sendgrid/send_mail.ts @@ -1,4 +1,5 @@ import { selectModelBoundFileInputPaths } from '@/lib/uploads/utils/model-input' +import { dryRunId } from '@/tools/dry-run' import type { SendMailParams, SendMailResult } from '@/tools/sendgrid/types' import { SENDGRID_REGIONS } from '@/tools/sendgrid/utils' import { SENDGRID_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' @@ -134,6 +135,13 @@ export const sendGridSendMailTool: InternalToolConfig ({ + messageId: dryRunId('message'), + to: params.to, + subject: params.subject || '', + }), + transformResponse: async (response): Promise => { const data = await response.json() diff --git a/apps/sim/tools/slack/message.ts b/apps/sim/tools/slack/message.ts index c044511c757..c01b09a6266 100644 --- a/apps/sim/tools/slack/message.ts +++ b/apps/sim/tools/slack/message.ts @@ -108,6 +108,24 @@ export const slackMessageTool: InternalToolConfig`, which + * Slack returns escaped or as links; the thread it replies in (which a message with files does + * not report); and how many files it attaches. The channel stays a placeholder: a DM's is the one + * Slack opens. + */ + dryRunOutput: (params) => { + const threadTs = params.threadTs?.trim() + const fileCount = params.files?.length ?? 0 + return { + message: { + ...(/[&<>]/.test(params.text) ? {} : { text: params.text }), + ...(threadTs && fileCount === 0 ? { thread_ts: threadTs } : {}), + }, + ...(fileCount > 0 ? { fileCount } : {}), + } + }, + transformResponse: async (response: Response) => { const data = await response.json() if (!data.success) { diff --git a/apps/sim/tools/supabase/insert.ts b/apps/sim/tools/supabase/insert.ts index 7ed8017b5f8..ef4a74fc75c 100644 --- a/apps/sim/tools/supabase/insert.ts +++ b/apps/sim/tools/supabase/insert.ts @@ -1,7 +1,12 @@ import { validateDatabaseIdentifier } from '@/lib/core/security/input-validation' import { SUPABASE_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' import type { SupabaseInsertParams, SupabaseInsertResponse } from '@/tools/supabase/types' -import { supabaseBaseUrl } from '@/tools/supabase/utils' +import { + supabaseBaseUrl, + supabaseWriteMessage, + supabaseWritePlaceholder, + supabaseWriteRows, +} from '@/tools/supabase/utils' import type { ToolConfig } from '@/tools/types' export const insertTool: ToolConfig = { @@ -65,15 +70,11 @@ export const insertTool: ToolConfig { - // Prepare the data - if it's an object but not an array, wrap it in an array - const dataToSend = - typeof params.data === 'object' && !Array.isArray(params.data) ? [params.data] : params.data - - return dataToSend - }, + body: (params) => supabaseWriteRows(params.data), }, + dryRunOutput: (params) => supabaseWritePlaceholder(params.data, 'inserted'), + transformResponse: async (response: Response) => { const text = await response.text() @@ -115,7 +116,7 @@ export const insertTool: ToolConfig = { @@ -76,15 +81,11 @@ export const upsertTool: ToolConfig { - // Prepare the data - if it's an object but not an array, wrap it in an array - const dataToSend = - typeof params.data === 'object' && !Array.isArray(params.data) ? [params.data] : params.data - - return dataToSend - }, + body: (params) => supabaseWriteRows(params.data), }, + dryRunOutput: (params) => supabaseWritePlaceholder(params.data, 'upserted'), + transformResponse: async (response: Response) => { const text = await response.text() @@ -126,7 +127,7 @@ export const upsertTool: ToolConfig encodeURIComponent(segment.trim())) .join('/') } + +/** The rows an insert or upsert sends: one object as a one-row array, anything else as given. */ +export function supabaseWriteRows(data: T): T | T[] { + return typeof data === 'object' && !Array.isArray(data) ? [data] : data +} + +/** The message an insert or upsert reports for the rows it wrote. */ +export function supabaseWriteMessage(verb: 'inserted' | 'upserted', count: number): string { + return `Successfully ${verb} ${count} row${count === 1 ? '' : 's'} into Supabase` +} + +/** + * A dry run's placeholder for an insert or upsert: the rows the call writes, without the columns + * the database fills in. + */ +export function supabaseWritePlaceholder(data: unknown, verb: 'inserted' | 'upserted') { + const rows = supabaseWriteRows(data) + if (!Array.isArray(rows)) return {} + return { + message: supabaseWriteMessage(verb, rows.length), + results: rows, + } +} diff --git a/apps/sim/tools/table/response.ts b/apps/sim/tools/table/response.ts index 82a046af668..d22834a2164 100644 --- a/apps/sim/tools/table/response.ts +++ b/apps/sim/tools/table/response.ts @@ -1,3 +1,5 @@ +import { dryRunId } from '@/tools/dry-run' + /** Table output schemas expose operation status to downstream workflow references. */ export function tableSuccess>( output: T @@ -15,7 +17,7 @@ const PLACEHOLDER_ROW_TIMESTAMP = '1970-01-01T00:00:00.000Z' */ export function placeholderRow(data: unknown, position: number, id?: string) { return { - id: id ?? `dry_run_row_${position + 1}`, + id: id ?? dryRunId('row', position + 1), data, position, createdAt: PLACEHOLDER_ROW_TIMESTAMP, diff --git a/apps/sim/tools/telegram/message.ts b/apps/sim/tools/telegram/message.ts index 1d2b19e7e37..f0f137a0360 100644 --- a/apps/sim/tools/telegram/message.ts +++ b/apps/sim/tools/telegram/message.ts @@ -56,6 +56,19 @@ export const telegramMessageTool: ToolConfig< }), }, + /** + * A dry run's placeholder holds the chat the call names, when it names one by numeric id. The + * text stays a placeholder: Telegram returns it with the formatting the HTML conversion adds + * stripped. + */ + dryRunOutput: (params) => { + const chatId = params.chatId.trim() + return { + message: 'Message sent successfully', + ...(/^-?\d+$/.test(chatId) ? { data: { chat: { id: Number(chatId) } } } : {}), + } + }, + transformResponse: async (response: Response) => { const data = await response.json() diff --git a/apps/sim/tools/trello/create_card.ts b/apps/sim/tools/trello/create_card.ts index 25718cdc64d..d00ecfa1c36 100644 --- a/apps/sim/tools/trello/create_card.ts +++ b/apps/sim/tools/trello/create_card.ts @@ -1,5 +1,6 @@ import { getErrorMessage } from '@sim/utils/errors' import { env } from '@/lib/core/config/env' +import { dryRunId } from '@/tools/dry-run' import { extractTrelloErrorMessage, mapTrelloCard, @@ -136,6 +137,19 @@ export const trelloCreateCardTool: ToolConfig ({ + card: { + id: dryRunId('card'), + name: params.name, + ...(params.desc ? { desc: params.desc } : {}), + idList: params.listId.trim(), + }, + }), + transformResponse: async (response) => { const data = await response.json().catch(() => null) diff --git a/apps/sim/tools/types.ts b/apps/sim/tools/types.ts index 3c1322a9399..9855cc69dd3 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -287,7 +287,9 @@ export interface ToolConfig

{ * `properties` (a field it does not declare is dropped), item by item where it declares array * `items`, and anywhere else the value replaces the sample whole, so a hook returns an undeclared * shape (a `json` row) complete, with placeholders for what the request cannot know. Whatever it - * leaves out keeps the sample. + * leaves out keeps the sample. An id the provider would assign is `dryRunId` (`@/tools/dry-run`), + * and a value the request builder normalises (parsed JSON, rows built from objects) comes from a + * named helper the builder and the hook share, never a second copy of the builder's logic. */ dryRunOutput?: (params: P) => Record diff --git a/apps/sim/tools/zendesk/create_ticket.ts b/apps/sim/tools/zendesk/create_ticket.ts index 7cca0903a56..a19b0479b72 100644 --- a/apps/sim/tools/zendesk/create_ticket.ts +++ b/apps/sim/tools/zendesk/create_ticket.ts @@ -164,6 +164,33 @@ export const zendeskCreateTicketTool: ToolConfig< }, }, + /** + * A dry run's placeholder holds the subject, first comment and the priority, status, type, + * assignee, group and requester the call sets on the ticket it creates (each id as the number + * Zendesk returns); Zendesk's defaults and the ticket's id stay placeholders. + */ + dryRunOutput: (params) => { + const ids = Object.entries({ + assignee_id: params.assigneeId, + group_id: params.groupId, + requester_id: params.requesterId, + }).flatMap(([field, id]) => { + const digits = id ? String(id).trim() : '' + return /^\d+$/.test(digits) ? [[field, Number(digits)] as const] : [] + }) + return { + ticket: { + subject: params.subject, + raw_subject: params.subject, + description: params.description, + ...(params.priority ? { priority: params.priority } : {}), + ...(params.status ? { status: params.status } : {}), + ...(params.type ? { type: params.type } : {}), + ...Object.fromEntries(ids), + }, + } + }, + transformResponse: async (response: Response) => { if (!response.ok) { const data = await response.json() diff --git a/scripts/check-explicit-any.baseline.json b/scripts/check-explicit-any.baseline.json index 70d8740321b..828d79de638 100644 --- a/scripts/check-explicit-any.baseline.json +++ b/scripts/check-explicit-any.baseline.json @@ -436,7 +436,7 @@ "apps/sim/tools/github/create_comment_reaction.ts": 1, "apps/sim/tools/github/create_file.ts": 1, "apps/sim/tools/github/create_gist.ts": 2, - "apps/sim/tools/github/create_issue.ts": 4, + "apps/sim/tools/github/create_issue.ts": 3, "apps/sim/tools/github/create_issue_reaction.ts": 1, "apps/sim/tools/github/create_milestone.ts": 1, "apps/sim/tools/github/create_pr.ts": 1, @@ -527,14 +527,11 @@ "apps/sim/tools/google_drive/get_file.ts": 1, "apps/sim/tools/google_drive/update.ts": 1, "apps/sim/tools/google_drive/utils.ts": 9, - "apps/sim/tools/google_sheets/append.ts": 14, "apps/sim/tools/google_sheets/batch_get.ts": 1, "apps/sim/tools/google_sheets/batch_update.ts": 2, "apps/sim/tools/google_sheets/create_spreadsheet.ts": 2, "apps/sim/tools/google_sheets/get_spreadsheet.ts": 1, "apps/sim/tools/google_sheets/types.ts": 6, - "apps/sim/tools/google_sheets/update.ts": 14, - "apps/sim/tools/google_sheets/write.ts": 8, "apps/sim/tools/google_slides/add_slide.ts": 1, "apps/sim/tools/google_slides/create.ts": 1, "apps/sim/tools/google_slides/duplicate_object.ts": 1, @@ -645,7 +642,6 @@ "apps/sim/tools/linear/create_customer_tier.ts": 1, "apps/sim/tools/linear/create_cycle.ts": 1, "apps/sim/tools/linear/create_favorite.ts": 1, - "apps/sim/tools/linear/create_issue.ts": 1, "apps/sim/tools/linear/create_label.ts": 1, "apps/sim/tools/linear/create_project.ts": 1, "apps/sim/tools/linear/create_project_label.ts": 1,