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
2 changes: 1 addition & 1 deletion apps/docs/content/docs/workflows/code/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ A secret is never printed. A literal value in a password field prints as `stored

### JSON fields

A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A field of a Function's `result` has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not). A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`.
A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A Function's `result`, or a field of it, has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not); a Function `result` or an API `data` whose code or response may be text is untyped unless the code says. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`.

### Input formats and tools

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ check(
const written = edit(
edit(source.files, 'skills: []', "skills: [skill('listed-only')]"),
'tools: []',
"tools: [customTool('listed-lookup')]"
"tools: [customTool('listed_lookup')]"
)
written['workflow.ts'] = written['workflow.ts'].replace(
/^import \{ /m,
Expand All @@ -313,7 +313,7 @@ check(
])
expect(manifest.skills).toContainEqual({ key: 'listed-only', id: skillId, name: 'Listed only' })
expect(manifest.customTools).toContainEqual({
key: 'listed-lookup',
key: 'listed_lookup',
id: toolId,
name: 'listed_lookup',
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ describe('source resources manifest', () => {
{ key: 'tone', id: ids.laterSkill, name: 'Tone' },
])
expect(manifest.customTools).toEqual([
{ key: 'lookup-order', id: ids.customTool, name: 'lookup_order' },
{ key: 'lookup_order', id: ids.customTool, name: 'lookup_order' },
])
})

Expand Down
29 changes: 29 additions & 0 deletions apps/sim/lib/workspaces/resource-keys.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,35 @@ describe('workspace resource keys against PostgreSQL', () => {
expect(new Set(keys)).toEqual(new Set(['invoices', 'invoices-2', 'invoices-3']))
})

it('keys a name with underscores by its own spelling, apart from the hyphenated one', async () => {
const underscored = generateId()
const hyphenated = generateId()
await insertTable(underscored, workspaceId, 'daily_totals', at(40))
await insertTable(hyphenated, workspaceId, 'daily-totals', at(41))

expect(await keyOf('table', hyphenated)).toBe('daily-totals')
expect(await keyOf('table', underscored)).toBe('daily_totals')
expect(await idOf('table', 'daily_totals')).toBe(underscored)
})

it('suffixes an underscored name whose key is taken, and leaves a persisted hyphen key alone', async () => {
const legacy = generateId()
const first = generateId()
const second = generateId()
await insertTable(legacy, workspaceId, 'weekly-totals', at(42))
expect(await keyOf('table', legacy)).toBe('weekly-totals')
await db
.update(userTableDefinitions)
.set({ name: 'weekly_totals' })
.where(eq(userTableDefinitions.id, legacy))
await insertTable(first, workspaceId, 'monthly_totals', at(43))
await insertTable(second, workspaceId, 'Monthly_Totals!', at(44))

expect(await keyOf('table', legacy)).toBe('weekly-totals')
expect(await keyOf('table', first)).toBe('monthly_totals')
expect(await keyOf('table', second)).toBe('monthly_totals-2')
})

it('keeps every kind’s key through a rename', async () => {
const ids = {
table: generateId(),
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/workspaces/resource-keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ describe('resourceKeyBase', () => {
expect(resourceKeyBase('table', 'Leads (EU)!')).toBe('leads-eu')
})

it('keeps the underscores of a name, the spelling its author types', () => {
expect(resourceKeyBase('table', 'daily_totals')).toBe('daily_totals')
expect(resourceKeyBase('table', 'Daily_Totals (v2)')).toBe('daily_totals-v2')
expect(resourceKeyBase('table', '_scratch_')).toBe('scratch')
})

it('keys a name with no slug characters by its kind', () => {
expect(resourceKeyBase('knowledge-base', '***')).toBe('knowledge-base')
expect(resourceKeyBase('credential', '')).toBe('credential')
Expand Down
28 changes: 22 additions & 6 deletions apps/sim/lib/workspaces/resource-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { compareStrings, slugify } from '@sim/utils/string'
import { compareStrings, escapeLikePattern } from '@sim/utils/string'
import type { ResourceKind } from '@sim/workflow-code'
import { and, asc, eq, inArray, isNull, like, or } from 'drizzle-orm'
import { OrchestrationError } from '@/lib/core/orchestration/types'
Expand Down Expand Up @@ -203,12 +203,24 @@ function trimKey(value: string, maxLength: number): string {
}

/**
* The key a resource is first offered: its name's slug, or the kind when the name has no slug
* characters; prefixed with the kind when the slug starts with a digit, and cut to the key
* length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`.
* A name's key characters: lowercased, with every run of other characters one hyphen and no
* leading or trailing separator. Underscores stay, so a table named `daily_totals` is keyed
* `daily_totals`, the spelling its author will type.
*/
function keySlug(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9_]+/g, '-')
.replace(/^[-_]+|[-_]+$/g, '')
}

/**
* The key a resource is first offered: its name's slug (underscores kept), or the kind when the
* name has no slug characters; prefixed with the kind when the slug starts with a digit, and cut
* to the key length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`.
*/
export function resourceKeyBase(kind: ResourceKind, name: string): string {
const slug = slugify(name)
const slug = keySlug(name)
const base = slug === '' ? kind : /^[a-z]/.test(slug) ? slug : `${kind}-${slug}`
return trimKey(base, MAX_KEY_LENGTH)
}
Expand Down Expand Up @@ -309,7 +321,11 @@ async function readTakenKeys(
and(
eq(workspaceResourceKey.workspaceId, workspaceId),
eq(workspaceResourceKey.kind, kind),
or(...prefixes.map((prefix) => like(workspaceResourceKey.key, `${prefix}%`)))
or(
...prefixes.map((prefix) =>
like(workspaceResourceKey.key, `${escapeLikePattern(prefix)}%`)
)
)
)
)
return new Set(rows.map((row) => row.key))
Expand Down
20 changes: 20 additions & 0 deletions packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,23 @@ describe('sim workflows runs get --select-output', () => {
expect(request.mock.calls.map(([path]) => path)).toEqual([STATE_PATH])
})
})

describe('sim workflows runs get on a paused run', () => {
it('prints the exact resume command beside the run, additively', async () => {
const run = {
runId: RUN_ID,
workflowId: WORKFLOW_ID,
status: 'paused',
paused: { contextId: 'ctx_1', pauseKind: 'human' },
}
answer({ data: run })
const out = stdout()

await get()

expect(JSON.parse(out())).toEqual({
...run,
next: `sim workflows runs resume ${RUN_ID} --workflow ${WORKFLOW_ID} --context ctx_1`,
})
})
})
15 changes: 15 additions & 0 deletions packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ afterEach(() => {

interface RunPayload {
status: string
output?: unknown
paused?: {
contextId?: string | null
pauseKind?: string | null
Expand Down Expand Up @@ -159,6 +160,20 @@ describe('workflows runs wait', () => {
)
})

it('names the same resume command the run record prints in next, from the output links', async () => {
respondWith({
status: 'paused',
output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } },
paused: { pauseKind: 'human', contextId: 'ctx_other' },
})

await wait()

expect(errored.join('\n')).toContain(
'sim workflows runs resume exec_9 --workflow 00000000-0000-4000-8000-00000000000a --context ctx_9'
)
})

it('stops on a pause whose kind the server did not name', async () => {
respondWith({ status: 'paused', paused: { pauseKind: null } })

Expand Down
13 changes: 6 additions & 7 deletions packages/sim-cli/src/commands/protocol/workflow-run-wait.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { sleep } from '@sim/utils/helpers'
import { isRecordLike, toRecordOrNull } from '@sim/utils/object'
import { isRecordLike, toRecord, toRecordOrNull } from '@sim/utils/object'
import { type Command, Option } from 'commander'
import { printError, writeStderr } from '#sim-cli/output/io'
import { hasProgressTerminal, styles } from '#sim-cli/output/presentation'
Expand All @@ -10,6 +10,7 @@ import { STILL_RUNNING_EXIT_CODE } from '../../exit-codes'
import { V2_OPERATIONS } from '../../generated/v2-api'
import { SimApiError } from '../../http/client'
import { apiCommand, type Connection } from '../../runtime/called-operations'
import { resumeCommandFor } from '../../runtime/paused-run'
import { renderResult } from '../../runtime/result'

/**
Expand Down Expand Up @@ -86,7 +87,6 @@ export interface RunSnapshot {
/** `time` resumes itself; `human` and null wait for a person. */
pauseKind: string | null
resumeAt: string | null
contextId: string | null
}

function optionalString(value: unknown): string | null {
Expand Down Expand Up @@ -115,7 +115,6 @@ function readRun(raw: unknown): RunSnapshot {
status: run.status,
pauseKind: paused ? optionalString(paused.pauseKind) : null,
resumeAt: paused ? optionalString(paused.resumeAt) : null,
contextId: paused ? optionalString(paused.contextId) : null,
}
}

Expand Down Expand Up @@ -192,13 +191,13 @@ function explain(
outcome: WaitOutcome,
runId: string,
workflowId: string,
snapshot: RunSnapshot
run: unknown
): string | null {
if (outcome === 'completed') return null
if (outcome === 'failed') return `Run ${runId} failed.`
if (outcome === 'cancelled') return `Run ${runId} was cancelled.`
const context = snapshot.contextId ? ` --context ${snapshot.contextId}` : ''
return `Run ${runId} is paused waiting for input. Resume it: sim workflows runs resume ${runId} --workflow ${workflowId}${context}`
const next = resumeCommandFor(toRecord(run), { runId, workflowId })
return `Run ${runId} is paused waiting for input.${next ? ` Resume it: ${next}` : ''}`
}

/**
Expand Down Expand Up @@ -254,7 +253,7 @@ export async function waitForRun(
if (outcome) {
progress.finish()
renderResult('getWorkflowRun', profile.output, runData(raw), runSpec())
const message = explain(outcome, wait.runId, wait.workflowId, snapshot)
const message = explain(outcome, wait.runId, wait.workflowId, runData(raw))
if (message) printError(styles().red(message))
setSoftExitCode(WAIT_EXIT_CODES[outcome])
return
Expand Down
1 change: 1 addition & 0 deletions packages/sim-cli/src/contract/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2459,6 +2459,7 @@ To read what a block is set to, use \`sim workflows outline\` or \`sim workflows
{ header: 'resume at', path: 'paused.resumeAt', format: 'timestamp' },
{ header: 'blocked on', path: 'paused.blockedOnBlockId' },
{ header: 'pause points', path: 'paused.pausePointCount' },
{ header: 'next', path: 'next' },
{ header: 'error', path: 'error.message' },
],
},
Expand Down
91 changes: 91 additions & 0 deletions packages/sim-cli/src/runtime/paused-run.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest'
import { withResumeNext } from './paused-run'

const paused = {
runId: 'run_top',
workflowId: 'wf_1',
status: 'paused',
output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } },
}

describe('withResumeNext', () => {
it('names the exact resume command, with the pause context and the execution its links name', () => {
expect(withResumeNext('executeWorkflow', paused)).toEqual({
...paused,
next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9',
})
})

it('falls back to the run id, and to the paused record context, when the output names none', () => {
expect(withResumeNext('executeWorkflow', { ...paused, output: null })).toMatchObject({
next: 'sim workflows runs resume run_top --workflow wf_1',
})
expect(
withResumeNext('getWorkflowRun', { ...paused, output: undefined, paused: { contextId: 'c' } })
).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1 --context c' })
})

it('leaves a run that is not paused, another operation and an existing next as they were', () => {
const done = { ...paused, status: 'completed' }
expect(withResumeNext('executeWorkflow', done)).toBe(done)
expect(withResumeNext('listWorkflowRuns', paused)).toBe(paused)
const hinted = { ...paused, next: 'x' }
expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted)
expect(withResumeNext('executeWorkflow', null)).toBeNull()
})

it('reads only the links the server writes, never a record that data or an API response carries', () => {
const decoy = { contextId: 'x; rm -rf ~', executionId: 'y' }
const run = {
...paused,
output: {
data: {
rows: [decoy],
body: { contextId: 'evil', executionId: 'evil_run' },
_resume: paused.output.data._resume,
},
},
}
expect(withResumeNext('executeWorkflow', run)).toMatchObject({
next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9',
})
expect(
withResumeNext('executeWorkflow', {
...paused,
output: { data: { rows: [{ contextId: 'evil', executionId: 'evil_run' }] } },
})
).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1' })
})

it('never prints an id outside the format the server issues', () => {
const hostile = {
...paused,
output: { data: { _resume: { contextId: 'x; rm -rf ~', executionId: '$(id)' } } },
}
expect(withResumeNext('executeWorkflow', hostile)).toMatchObject({
next: 'sim workflows runs resume run_top --workflow wf_1',
})
expect(
withResumeNext('executeWorkflow', { ...paused, workflowId: 'wf; id' })
).not.toHaveProperty('next')
})

it('names one command per pause when several blocks pause together', () => {
const several = {
...paused,
output: {
pausedBlocks: [
{ data: { _resume: { contextId: 'a\u208D0\u208E', executionId: 'exec_9' } } },
{ data: { _resume: { contextId: 'b', executionId: 'exec_9' } } },
],
pauseCount: 2,
},
}
expect(withResumeNext('executeWorkflow', several)).toMatchObject({
next: [
"sim workflows runs resume exec_9 --workflow wf_1 --context 'a\u208D0\u208E'",
'sim workflows runs resume exec_9 --workflow wf_1 --context b',
].join('\n'),
})
})
})
Loading