Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .agents/skills/add-tools/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions .agents/skills/validate-integration/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/lib/api/contracts/workflow-tests.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(),
})
Expand Down
25 changes: 25 additions & 0 deletions apps/sim/lib/internal/microsoft-teams/message-rewrite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/** Each `<at>` 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>([^<]+)<\/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
}
18 changes: 5 additions & 13 deletions apps/sim/lib/internal/microsoft-teams/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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>[^<]+<\/at>/i

const logger = createLogger('MicrosoftTeamsOperations')

Expand Down Expand Up @@ -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>([^<]+)<\/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,
Expand Down Expand Up @@ -286,7 +278,7 @@ async function sendMessage(args: {
plainMetadata: (data: MicrosoftTeamsGraphObject) => Record<string, unknown>
enhancedMetadata: (data: MicrosoftTeamsGraphObject) => Record<string, unknown>
}) {
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) {
Expand Down
29 changes: 27 additions & 2 deletions apps/sim/lib/mothership/tools/server/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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')
Expand All @@ -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 = {
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -161,6 +185,7 @@ export const testsServerTool: BaseServerTool = {
skipped: run.skipped,
...(run.error ? { error: run.error } : {}),
failures: failures(run.report),
unmockedWrites: unmockedWrites(run.report),
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
})),
}
}
Expand Down
6 changes: 3 additions & 3 deletions apps/sim/lib/workflow-tests/application/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, TestCaseStatus> | null,
}
}
Expand Down Expand Up @@ -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,
})),
}
},
Expand Down
43 changes: 42 additions & 1 deletion apps/sim/lib/workflow-tests/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,48 @@ export const testReportSchema = z.object({
})
),
})
export type TestReport = z.infer<typeof testReportSchema>

/** 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<typeof testRunSideEffectsSchema>

/**
* 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<typeof storedTestReportSchema>

export const testCollectionSchema = z.object({
topLevel: z.array(z.object({ kind: z.enum(['suite', 'test']), name: z.string() })),
Expand Down
8 changes: 6 additions & 2 deletions apps/sim/lib/workflow-tests/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -282,7 +286,7 @@ export async function readDeploymentFacts(

export async function completeWorkflowTestRun(
runId: string,
report: TestReport,
report: StoredTestReport,
sourceHash: string,
ranAgainst: RanAgainstEntry[]
): Promise<void> {
Expand Down
12 changes: 8 additions & 4 deletions apps/sim/lib/workflow-tests/run-test-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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,
Expand All @@ -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 {
Expand Down
Loading
Loading