Skip to content

Commit fff8456

Browse files
authored
fix(workflow-code): keep mixed upload lists in the upload member and share the resource resolver with corpus tests (#10734)
- valueKindMatches('upload') now accepts file() nodes, so a list mixing a workspace file and an uploaded object compiles into the upload member instead of the pair's text twin - extract the pure resolver (keys, files by path, uploadOf, skills) into resource-resolver.ts; loadResourceKeyResolver and CORPUS_RESOURCES both build on it - add stored workspace-file upload cases for every file-upload field to the round-trip corpus
1 parent 8493e04 commit fff8456

8 files changed

Lines changed: 214 additions & 64 deletions

File tree

‎apps/sim/lib/workflows/code/corpus/fixtures.test-helpers.ts‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ import {
3434
generateRegistryCorpus,
3535
} from '@/lib/workflows/code/corpus'
3636
import { workflowStateArbitrary } from '@/lib/workflows/code/corpus/proof'
37-
import { CORPUS_SKILL } from '@/lib/workflows/code/corpus/values'
37+
import { CORPUS_SKILL, CORPUS_WORKSPACE_UPLOAD } from '@/lib/workflows/code/corpus/values'
38+
import { resourceKeyResolver } from '@/lib/workflows/code/resource-resolver'
3839
import type { WorkflowState } from '@/stores/workflows/workflow/types'
3940

4041
interface FixtureState {
@@ -116,17 +117,20 @@ function inCorpusWorkspace(value: string): boolean {
116117
}
117118

118119
/**
119-
* The workspace the round-trip harness resolves resources in: every resource the corpus stores
120-
* (`corpus-*`: credentials, tables, knowledge bases, workflows, skills…) under a key equal to its
121-
* id, so selector fields print as `credential('…')`, `table('…')` and the like and write back
122-
* through the resolver. A deleted resource (`*-deleted`) and any id from outside the corpus stay
123-
* unresolved, as they would in a workspace that lacks them.
120+
* The workspace the round-trip harness resolves resources in, through the server's own
121+
* `resourceKeyResolver`: every resource the corpus stores (`corpus-*`: credentials, tables,
122+
* knowledge bases, workflows, skills…) under a key equal to its id, so selector fields print as
123+
* `credential('…')`, `table('…')` and the like and write back through the resolver, and the one
124+
* workspace file corpus uploads pick ({@link CORPUS_WORKSPACE_UPLOAD}), named by its path. A deleted
125+
* resource (`*-deleted`) and any id from outside the corpus stay unresolved, as they would in a
126+
* workspace that lacks them.
124127
*/
125-
export const CORPUS_RESOURCES: ResourceKeyResolver = {
126-
toKey: (_kind, id) => (inCorpusWorkspace(id) ? id : null),
127-
toId: (_kind, key) => (inCorpusWorkspace(key) ? key : null),
128-
nameOf: (kind, id) => (kind === 'skill' && id === CORPUS_SKILL.id ? CORPUS_SKILL.name : null),
129-
}
128+
export const CORPUS_RESOURCES: ResourceKeyResolver = resourceKeyResolver({
129+
keyOf: (_kind, id) => (inCorpusWorkspace(id) ? id : null),
130+
idOf: (_kind, key) => (inCorpusWorkspace(key) ? key : null),
131+
skillName: (id) => (id === CORPUS_SKILL.id ? CORPUS_SKILL.name : null),
132+
files: [CORPUS_WORKSPACE_UPLOAD],
133+
})
130134

131135
export interface ProofSubject {
132136
id: string
@@ -217,8 +221,7 @@ export function caseSubject(corpusCase: CorpusCase): ProofSubject {
217221
* states from `ROUNDTRIP_CORPUS_EXTRA_DIR`, and fast-check workflows, each in the shape the
218222
* normalized tables store.
219223
*/
220-
export function corpusSubjects(): ProofSubject[] {
221-
const generated = generateRegistryCorpus()
224+
export function corpusSubjects(generated = generateRegistryCorpus()): ProofSubject[] {
222225
const extraDir = process.env.ROUNDTRIP_CORPUS_EXTRA_DIR
223226
const corpus: ProofSubject[] = (
224227
process.env.ROUNDTRIP_CORPUS_FULL === '1'

‎apps/sim/lib/workflows/code/corpus/generate.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,11 @@ import {
3737
} from '@/lib/workflows/code/corpus/blocks'
3838
import { createSeededRandom, type SeededRandom } from '@/lib/workflows/code/corpus/random'
3939
import {
40+
CORPUS_DELETED_UPLOAD,
4041
CORPUS_START_NAME,
4142
CORPUS_TEXT,
4243
CORPUS_VARIABLE_NAME,
44+
CORPUS_WORKSPACE_UPLOAD,
4345
resolveOptions,
4446
} from '@/lib/workflows/code/corpus/values'
4547
import { hasTriggerCapability } from '@/lib/workflows/triggers/utils'
@@ -65,6 +67,7 @@ type CorpusCaseKind =
6567
| 'agent-tools'
6668
| 'legacy-scalars'
6769
| 'stored-shapes'
70+
| 'stored-uploads'
6871

6972
export interface CorpusCase {
7073
/** Stable and unique: `<kind>:<block type>:<detail>`. */
@@ -86,6 +89,8 @@ export interface CorpusCase {
8689
* value the editor no longer writes in that shape but stored workflows hold (`storedShapeCases`).
8790
*/
8891
storedQuirk?: 'implicit-branch-handle' | 'legacy-scalar-text' | 'legacy-stored-value'
92+
/** Set on `stored-uploads` cases: the upload field holding the picked workspace file. */
93+
upload?: { blockId: string; subBlockId: string }
8994
}
9095

9196
interface CorpusOptions {
@@ -1323,6 +1328,39 @@ export function generateReapplyCorpus(options: CorpusOptions = {}): CorpusCase[]
13231328
})
13241329
}
13251330

1331+
/**
1332+
* The registry corpus's file-upload fields holding workspace files instead of files uploaded in
1333+
* place: for each block type and upload field, the first registry case that fills it, with a
1334+
* single upload holding {@link CORPUS_WORKSPACE_UPLOAD} and a multiple one also holding
1335+
* {@link CORPUS_DELETED_UPLOAD}, which stays verbatim beside it.
1336+
*/
1337+
export function generateStoredUploadCorpus(cases: CorpusCase[]): CorpusCase[] {
1338+
const seen = new Set<string>()
1339+
const uploads: CorpusCase[] = []
1340+
for (const corpusCase of cases) {
1341+
for (const block of Object.values(corpusCase.state.blocks)) {
1342+
for (const [subBlockId, subBlock] of Object.entries(block.subBlocks ?? {})) {
1343+
const id = `stored-uploads:${block.type}:${subBlockId}`
1344+
if (subBlock?.type !== 'file-upload' || subBlock.value == null || seen.has(id)) continue
1345+
seen.add(id)
1346+
const state = structuredClone(corpusCase.state)
1347+
const value: unknown = Array.isArray(subBlock.value)
1348+
? [CORPUS_WORKSPACE_UPLOAD, CORPUS_DELETED_UPLOAD]
1349+
: CORPUS_WORKSPACE_UPLOAD
1350+
state.blocks[block.id].subBlocks[subBlockId].value = value as typeof subBlock.value
1351+
uploads.push({
1352+
...corpusCase,
1353+
id,
1354+
kind: 'stored-uploads',
1355+
state,
1356+
upload: { blockId: block.id, subBlockId },
1357+
})
1358+
}
1359+
}
1360+
}
1361+
return uploads
1362+
}
1363+
13261364
/** A stored edge every save drops (`validateEdges`), which source must leave out. */
13271365
interface DroppedEdgeCase {
13281366
id: string

‎apps/sim/lib/workflows/code/corpus/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ export {
55
generateDroppedEdgeCorpus,
66
generateReapplyCorpus,
77
generateRegistryCorpus,
8+
generateStoredUploadCorpus,
89
} from './generate'
910
export { CORPUS_TEXT, CORPUS_TEXT_MARKERS } from './values'

‎apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@ import {
3333
printWorkflow,
3434
} from '@sim/workflow-code'
3535
import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registry-catalog.test-helpers'
36-
import { generateDroppedEdgeCorpus, generateReapplyCorpus } from '@/lib/workflows/code/corpus'
36+
import {
37+
generateDroppedEdgeCorpus,
38+
generateReapplyCorpus,
39+
generateRegistryCorpus,
40+
generateStoredUploadCorpus,
41+
} from '@/lib/workflows/code/corpus'
3742
import {
3843
CORPUS_RESOURCES,
3944
caseSubject,
@@ -48,13 +53,16 @@ import {
4853
assertNoopIdentity,
4954
createProofReport,
5055
executionParity,
56+
findDifferences,
5157
idempotence,
5258
type OracleResult,
5359
type ProofProperty,
5460
reportPathVariable,
5561
} from '@/lib/workflows/code/corpus/proof'
62+
import { CORPUS_WORKSPACE_UPLOAD } from '@/lib/workflows/code/corpus/values'
5663
import { createMaterializeHooks } from '@/lib/workflows/code/materialize-hooks'
5764
import { hasWorkflowChanged } from '@/lib/workflows/comparison/compare'
65+
import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path'
5866
import { Serializer } from '@/serializer'
5967
import { validateEdges } from '@/stores/workflows/workflow/edge-validation'
6068
import type { WorkflowState } from '@/stores/workflows/workflow/types'
@@ -73,7 +81,16 @@ const hooks = createMaterializeHooks()
7381
/** Properties that serialize the original, which an unknown block type makes throw. */
7482
const SERIALIZING_PROPERTIES: ReadonlySet<ProofProperty> = new Set(['P2', 'O2'])
7583

76-
const subjects: ProofSubject[] = corpusSubjects()
84+
const registryCorpus = generateRegistryCorpus()
85+
86+
/** Upload fields holding a picked workspace file, one per block type and field. */
87+
const uploadCases = generateStoredUploadCorpus(registryCorpus)
88+
const uploadSubjects: ProofSubject[] = uploadCases.map(caseSubject)
89+
90+
const subjects: ProofSubject[] = [...corpusSubjects(registryCorpus), ...uploadSubjects]
91+
92+
/** The `file(...)` path of the workspace file the upload subjects pick. */
93+
const CORPUS_FILE_PATH = workspaceFileSourcePath(CORPUS_WORKSPACE_UPLOAD)
7794

7895
/** Subjects only the re-apply property judges (`generateReapplyCorpus`). */
7996
const reapplySubjects: ProofSubject[] = generateReapplyCorpus().map(caseSubject)
@@ -393,6 +410,31 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => {
393410
corpusBudgetMs(subjects.length, PROPERTY_BUDGET_MS)
394411
)
395412

413+
it('writes a picked workspace file back as the object the picker stored', () => {
414+
expect(uploadSubjects.map((subject) => subject.id)).toContain(
415+
'stored-uploads:agent:attachmentFiles'
416+
)
417+
const failures: string[] = []
418+
uploadCases.forEach(({ upload }, index) => {
419+
const subject = uploadSubjects[index]
420+
if (!upload) throw new Error(`${subject.id} names no upload field`)
421+
if (!sourceRun(subject).printed.files[0].text.includes(`file('${CORPUS_FILE_PATH}')`)) {
422+
failures.push(`${subject.id}: not printed as file()`)
423+
return
424+
}
425+
const created = materialized(compiledOrThrow(sourceRun(subject).compiled))
426+
const storedBlock = subject.state.blocks[upload.blockId]
427+
const createdBlock = Object.values(created.blocks).find(
428+
(block) => block.name === storedBlock.name
429+
)
430+
const stored = storedBlock.subBlocks[upload.subBlockId].value
431+
const written = createdBlock?.subBlocks[upload.subBlockId]?.value
432+
const differences = findDifferences(stored, written)
433+
if (differences.length > 0) failures.push(`${subject.id}: ${JSON.stringify(differences)}`)
434+
})
435+
expect(failures).toEqual([])
436+
})
437+
396438
describe.each(generateDroppedEdgeCorpus())('a stored edge every save drops: $id', (c) => {
397439
const subject: ProofSubject = { id: c.id, blockTypes: [], state: c.state }
398440
const kept = { ...c.state, edges: c.state.edges.filter((edge) => edge.id !== c.edgeId) }

‎apps/sim/lib/workflows/code/corpus/values.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,31 @@ export const CORPUS_VARIABLE_NAME = 'corpusNote'
2323
*/
2424
export const CORPUS_SKILL = { id: 'corpus-skill', key: 'corpus-skill', name: 'Corpus skill' }
2525

26+
/**
27+
* A workspace file a corpus upload field picked, stored as the editor's workspace file picker
28+
* writes it (`handleSelectWorkspaceFile`). The round-trip harness holds this file, so the upload
29+
* lifts to `file('Corpus reports/q3 report.pdf')` and writes back through `uploadOf`.
30+
*/
31+
export const CORPUS_WORKSPACE_UPLOAD = {
32+
name: 'q3 report.pdf',
33+
path: '/api/files/serve/workspace%2Fcorpus%2Fq3-report.pdf?context=workspace',
34+
key: 'workspace/corpus/q3-report.pdf',
35+
size: 2048,
36+
type: 'application/pdf',
37+
id: 'corpus-file',
38+
folderPath: 'Corpus reports',
39+
}
40+
41+
/** A picked workspace file since deleted: it resolves nowhere, so the upload stays verbatim. */
42+
export const CORPUS_DELETED_UPLOAD = {
43+
name: 'gone.csv',
44+
path: '/api/files/serve/workspace%2Fcorpus%2Fgone.csv?context=workspace',
45+
key: 'workspace/corpus/gone.csv',
46+
size: 64,
47+
type: 'text/csv',
48+
id: 'corpus-file-deleted',
49+
}
50+
2651
/** The markers every free-text corpus string carries. */
2752
export const CORPUS_TEXT_MARKERS = [
2853
'<start.input>',
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type { Json, ResourceKeyResolver, ResourceKind } from '@sim/workflow-code'
2+
import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace/file-manager'
3+
import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills'
4+
import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path'
5+
6+
/** The fields of a live workspace file a resolver reads. */
7+
type ResolvableFile = Pick<
8+
WorkspaceFileRecord,
9+
'id' | 'key' | 'name' | 'path' | 'size' | 'type' | 'folderPath'
10+
>
11+
12+
/** The resources one resolver answers for, however they were loaded. */
13+
interface ResolvedResources {
14+
/** The key bound to a live keyed resource's id, `null` when none (never asked about files). */
15+
keyOf(kind: ResourceKind, id: string): string | null
16+
/** The live keyed resource a key names, `null` when none (never asked about files). */
17+
idOf(kind: ResourceKind, key: string): string | null
18+
/** The current name of a resolved workspace skill, `null` when unknown. */
19+
skillName(id: string): string | null
20+
/** The live workspace files a `file(...)` path or a stored upload object may name. */
21+
files: Iterable<ResolvableFile>
22+
}
23+
24+
/** What a file-upload field stores for a workspace file, as the editor's workspace file picker writes it. */
25+
function uploadedFile(file: ResolvableFile): Json {
26+
return {
27+
name: file.name,
28+
path: file.path,
29+
key: file.key,
30+
size: file.size,
31+
type: file.type,
32+
id: file.id,
33+
...(file.folderPath ? { folderPath: file.folderPath } : {}),
34+
}
35+
}
36+
37+
/**
38+
* The {@link ResourceKeyResolver} over `resolved`: keyed kinds through `keyOf`/`idOf`, a workspace
39+
* file by its source path (`file('docs/a.pdf')`) from the id or storage key a stored upload object
40+
* carries, and back to the object the picker stores (`uploadOf`). Built-in skills answer
41+
* `isBuiltin`, and a resolved skill's name comes from `skillName`.
42+
*
43+
* The server's `loadResourceKeyResolver` and the round-trip test resolvers both build on this, so
44+
* a test resolver cannot drift from production semantics.
45+
*/
46+
export function resourceKeyResolver(resolved: ResolvedResources): ResourceKeyResolver {
47+
const filesByPath = new Map<string, ResolvableFile>()
48+
for (const file of resolved.files) {
49+
const path = workspaceFileSourcePath(file)
50+
if (path !== null) filesByPath.set(path, file)
51+
}
52+
const pathByStored = new Map(
53+
[...filesByPath].flatMap(([path, file]) => [
54+
[file.id, path],
55+
[file.key, path],
56+
])
57+
)
58+
return {
59+
toKey: (kind, id) =>
60+
kind === 'file' ? (pathByStored.get(id) ?? null) : resolved.keyOf(kind, id),
61+
toId: (kind, key) =>
62+
kind === 'file' ? (filesByPath.get(key)?.id ?? null) : resolved.idOf(kind, key),
63+
nameOf: (kind, id) => (kind === 'skill' ? resolved.skillName(id) : null),
64+
isBuiltin: (kind, id) => kind === 'skill' && isBuiltinSkillId(id),
65+
uploadOf: (path) => {
66+
const file = filesByPath.get(path)
67+
return file ? uploadedFile(file) : null
68+
},
69+
}
70+
}

0 commit comments

Comments
 (0)