Skip to content

Commit ce74554

Browse files
authored
fix(workflow-code): name workspace files by path in file() references (#10545)
* fix(workflow-code): name workspace files by path in file() references file('<folder>/<name>') now resolves the workspace file at that path and writes the object the editor's file picker stores (storage key and file id), a stored workspace file prints back as file('<path>'), and the source resources manifest and workspace.d.ts list file paths. * fix(workflow-code): resolve file() paths as written and keep them from withheld callers * fix(workflow-code): report a malformed file() path as an unknown file * fix(workflow-code): gate file() paths on files.use, match names as written, and report truncation exactly - a path the stored workflow does not already hold resolves only for a caller whose group allows Files; any other caller gets the unknown-file finding a missing path gets - resolve file() paths by exact name and folder path instead of the VFS reference parser, so files named content or meta.json inside a folder resolve - read file pages until the manifest cap is filled so files no path names cannot hide a truncated list - document the quoted file('docs/report.pdf') form in the manifest description * chore(workflow-sdk): regenerate core text after rebase
1 parent c6da82e commit ce74554

36 files changed

Lines changed: 607 additions & 249 deletions

File tree

‎apps/docs/content/docs/cli/reference.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8604,7 +8604,7 @@ API request and response schemas: [getSourceCatalog](/api-reference/catalog/getS
86048604

86058605
### sim workflows source resources
86068606

8607-
List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name
8607+
List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name
86088608

86098609
```bash
86108610
sim workflows source resources

‎apps/docs/content/docs/cli/workflows.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1636,7 +1636,7 @@ Prints a builder in brief (an example call, the required params with types, the
16361636

16371637
Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once).
16381638

1639-
### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name
1639+
### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name
16401640

16411641
```bash
16421642
sim workflows source resources

‎apps/docs/content/docs/workflows/code/directory.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ A resource's key is its file or folder name, and a workflow names it by that key
6161
- `mcp/<key>.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A new host or path in `url` replaces the server; a new query string updates it in place. A workflow: `mcp('<key>').tool('<name>')`.
6262
- `tables/<key>.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '<unique column>' }` keeps the rows equal to `tables/<key>.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('<key>')`.
6363
- `knowledge/<key>/knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge/<key>/docs/`, one file per document, flat. A workflow: `knowledgeBase('<key>')`. Connector-synced documents are never part of source.
64-
- `files/<path>`: every file is one workspace file at that folder path; no declaration.
64+
- `files/<path>`: every file is one workspace file at that folder path; no declaration. A workflow: `file('<path>')` (the path under `files/`), as a file-upload field's value.
6565
- `workflows/<key>/`: one workflow each, exactly a `sim workflows source get --dir` directory (`workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`).
6666
- `deployments/<workflow key>.ts`: `defineDeployment({ live: 'draft' | 'pinned', api?: { public? }, chat? })` deploys `workflows/<workflow key>/`, so its schedule, webhook, API and chat triggers run. `live: 'draft'` publishes the draft whenever it differs from the live version; `'pinned'` never redeploys and says when the draft differs. A chat password is `env.NAME` (or `stored()` to keep the stored one); chat outputs name a block by its name. Removing the file undeploys the workflow (needs `--allow-delete`). Deploying needs workspace admin, never a workspace API key. MCP publishing is not part of source.
6767

‎apps/docs/content/docs/workflows/code/syntax.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,14 +165,14 @@ The optional third argument holds what belongs to the block, not to its settings
165165

166166
### Resource helpers
167167

168-
A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply.
168+
A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A file's key is its folder path and name, so the same source names the file at that path in any workspace it is applied to. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply.
169169

170170
| Form | Stands for |
171171
| --- | --- |
172172
| `credential('key')` | A saved credential |
173173
| `table('key')` | A workspace table |
174174
| `knowledgeBase('key')` | A knowledge base |
175-
| `file('path')` | A workspace file |
175+
| `file('folder/name.pdf')` | A workspace file, by its folder path and name; a file field's value, or an item of a multi-file field's list |
176176
| `folder('key')` | A workspace folder |
177177
| `childWorkflow('key')` | A workflow, for `runWorkflow`; `.asTool()` in a `tools` list |
178178
| `customTool('key')` | A custom tool, in a `tools` list |

‎apps/docs/openapi-v2-workflows.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6887,6 +6887,7 @@
68876887
"tools": ["create_issue", "list_issues"]
68886888
}
68896889
],
6890+
"files": ["contracts/acme.pdf"],
68906891
"env": ["CRM_KEY"],
68916892
"truncated": false
68926893
}
@@ -23925,6 +23926,13 @@
2392523926
},
2392623927
"description": "MCP servers, oldest first."
2392723928
},
23929+
"files": {
23930+
"type": "array",
23931+
"items": {
23932+
"type": "string"
23933+
},
23934+
"description": "Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
23935+
},
2392823936
"env": {
2392923937
"type": "array",
2393023938
"items": {
@@ -23946,6 +23954,7 @@
2394623954
"skills",
2394723955
"customTools",
2394823956
"mcpServers",
23957+
"files",
2394923958
"env",
2395023959
"truncated"
2395123960
],
@@ -24029,6 +24038,7 @@
2402924038
"tools": ["create_issue", "list_issues"]
2403024039
}
2403124040
],
24041+
"files": ["contracts/acme.pdf"],
2403224042
"env": ["CRM_KEY"],
2403324043
"truncated": false
2403424044
}

‎apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ const manifest = {
6262
skills: [{ key: 'triage', id: 'skl_1', name: 'Triage' }],
6363
customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'Lookup order' }],
6464
mcpServers: [{ key: 'github', id: 'mcp-1', name: 'GitHub', tools: ['create_issue'] }],
65+
files: ['contracts/acme.pdf'],
6566
env: ['CRM_KEY'],
6667
truncated: false,
6768
}

‎apps/sim/lib/api/contracts/v2/openapi/source-resources.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ const SOURCE_RESOURCES_EXAMPLE = {
4040
mcpServers: [
4141
{ key: 'github', id: 'mcp-1a2b3c4d', name: 'GitHub', tools: ['create_issue', 'list_issues'] },
4242
],
43+
files: ['contracts/acme.pdf'],
4344
env: ['CRM_KEY'],
4445
truncated: false,
4546
}

‎apps/sim/lib/api/contracts/v2/source-resources.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,11 @@ const sourceResourcesSchema = z
108108
.describe('An MCP server the workspace consumes: `mcp(key)`.')
109109
)
110110
.describe('MCP servers, oldest first.'),
111+
files: z
112+
.array(z.string())
113+
.describe(
114+
"Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
115+
),
111116
env: z
112117
.array(z.string())
113118
.describe(

‎apps/sim/lib/uploads/contexts/workspace/file-manager.ts‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -767,9 +767,6 @@ export async function commitFileCreateInTx(
767767
return inserted
768768
}
769769

770-
/** Writes that commit with a new workspace file: run in its create transaction, given its id. */
771-
export type WorkspaceFileCreateHook = (tx: DbTransaction, fileId: string) => Promise<void>
772-
773770
/**
774771
* Upload a file to workspace-scoped storage
775772
*/
@@ -785,11 +782,6 @@ export async function uploadWorkspaceFile(
785782
exactName?: boolean
786783
secretProvenance?: WorkspaceFileSecretProvenance
787784
notifyWorkspaceChange?: boolean
788-
/**
789-
* Runs inside the create's transaction once the file row is inserted, so what it writes
790-
* commits or rolls back with the file.
791-
*/
792-
withinCreate?: WorkspaceFileCreateHook
793785
}
794786
): Promise<UploadedWorkspaceFileRecord> {
795787
logger.info(`Uploading workspace file: ${fileName} for workspace ${workspaceId}`)
@@ -867,7 +859,6 @@ export async function uploadWorkspaceFile(
867859
secretProvenance: options?.secretProvenance,
868860
})
869861
const usage = await accounting.mutation.applyDelta(effectiveBuffer.length)
870-
await options?.withinCreate?.(tx, inserted.id)
871862
return { inserted, updatedUsage: usage, billing: accounting.billing }
872863
})
873864

@@ -2495,31 +2486,39 @@ async function listWorkspaceFileCandidates(
24952486
}
24962487

24972488
/**
2498-
* Live workspace files by id, by storage key, and by reference (resolved as
2489+
* Live workspace files by id, by storage key, by exact name in any folder (`names`, taken as
2490+
* written rather than as a VFS path), and by reference (resolved as
24992491
* {@link findListedWorkspaceFiles} resolves it), from one read and one folder-path hydration.
25002492
* `files` holds each match once, oldest upload first. Another workspace's ids and keys, deleted
25012493
* files, chat uploads, and owned files never match.
25022494
*/
25032495
export async function lookupActiveWorkspaceFiles(
25042496
workspaceId: string,
2505-
lookup: { ids: readonly string[]; keys: readonly string[]; references: readonly string[] }
2497+
lookup: {
2498+
ids: readonly string[]
2499+
keys: readonly string[]
2500+
names?: readonly string[]
2501+
references: readonly string[]
2502+
}
25062503
): Promise<{ files: WorkspaceFileRecord[]; references: Map<string, WorkspaceFileRecord | null> }> {
2507-
if (lookup.ids.length + lookup.keys.length + lookup.references.length === 0) {
2504+
const names = new Set(lookup.names)
2505+
if (lookup.ids.length + lookup.keys.length + names.size + lookup.references.length === 0) {
25082506
return { files: [], references: new Map() }
25092507
}
25102508
const byReference = referenceCandidates(lookup.references)
25112509
const candidates = await listWorkspaceFileCandidates(workspaceId, {
25122510
ids: [...lookup.ids, ...byReference.ids],
25132511
keys: lookup.keys,
2514-
leafNames: byReference.leafNames,
2512+
leafNames: [...byReference.leafNames, ...[...names].map(normalizeDisplaySegment)],
25152513
})
25162514
const references = resolveListedReferences(candidates, lookup.references)
25172515
const ids = new Set(lookup.ids)
25182516
const keys = new Set(lookup.keys)
25192517
const resolved = new Set([...references.values()].map((file) => file?.id))
25202518
return {
25212519
files: candidates.filter(
2522-
(file) => ids.has(file.id) || keys.has(file.key) || resolved.has(file.id)
2520+
(file) =>
2521+
ids.has(file.id) || keys.has(file.key) || names.has(file.name) || resolved.has(file.id)
25232522
),
25242523
references,
25252524
}

‎apps/sim/lib/workflows/application/read-source-resources.integration.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
userTableDefinitions,
2525
workspace,
2626
workspaceEnvironment,
27+
workspaceFiles,
2728
} from '@sim/db/schema'
2829
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
2930
import {
@@ -34,6 +35,7 @@ import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/featur
3435
import { generateId } from '@sim/utils/id'
3536
import { eq, inArray } from 'drizzle-orm'
3637
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
38+
import { MAX_MANIFEST_RESOURCES_PER_KIND } from '@/lib/api/contracts/v2/source-resources'
3739
import { readSourceResources } from '@/lib/workflows/application/read-source-resources'
3840

3941
vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
@@ -204,6 +206,16 @@ describe('source resources manifest', () => {
204206
createdBy: tokenOwnerId,
205207
},
206208
])
209+
await db.insert(workspaceFiles).values({
210+
id: generateId(),
211+
key: `workspace/${workspaceId}/plan.md`,
212+
userId: adminId,
213+
workspaceId,
214+
context: 'workspace',
215+
originalName: 'plan.md',
216+
contentType: 'text/markdown',
217+
sizeBytes: 7,
218+
})
207219
await db.insert(workspaceEnvironment).values({
208220
id: generateId(),
209221
workspaceId,
@@ -494,6 +506,21 @@ describe('source resources manifest', () => {
494506
expect(manifest.tables.map((table) => table.name)).toEqual(['leads'])
495507
})
496508

509+
it('lists workspace files by path, and omits them when the caller’s group hides the Files tab', async () => {
510+
const visible = await readSourceResources.execute({
511+
principal: session(readerId),
512+
input: { workspaceId },
513+
})
514+
expect(visible.files).toEqual(['plan.md'])
515+
await withholdInGroup({ hideFilesTab: true })
516+
const manifest = await readSourceResources.execute({
517+
principal: session(readerId),
518+
input: { workspaceId },
519+
})
520+
expect(manifest.files).toEqual([])
521+
expect(manifest.tables.map((table) => table.name)).toEqual(['leads'])
522+
})
523+
497524
it('omits env names for a workspace API key, which the secrets listing denies', async () => {
498525
const manifest = await readSourceResources.execute({
499526
principal: workspaceKey(),
@@ -502,4 +529,36 @@ describe('source resources manifest', () => {
502529
expect(manifest.env).toEqual([])
503530
})
504531
})
532+
533+
it('marks the files section truncated when a file no path names sits among the first page', async () => {
534+
const before = Date.now() - 60 * 60 * 1000
535+
const rows = Array.from({ length: MAX_MANIFEST_RESOURCES_PER_KIND + 1 }, (_, index) => ({
536+
id: generateId(),
537+
key: `workspace/${workspaceId}/bulk-${index}`,
538+
userId: adminId,
539+
workspaceId,
540+
context: 'workspace',
541+
originalName: index === 0 ? 'a/b.txt' : `bulk-${index}.txt`,
542+
contentType: 'text/plain',
543+
sizeBytes: 1,
544+
uploadedAt: new Date(before + index),
545+
}))
546+
await db.insert(workspaceFiles).values(rows)
547+
try {
548+
const manifest = await readSourceResources.execute({
549+
principal: session(adminId),
550+
input: { workspaceId },
551+
})
552+
expect(manifest.files).toHaveLength(MAX_MANIFEST_RESOURCES_PER_KIND)
553+
expect(manifest.files).not.toContain('plan.md')
554+
expect(manifest.truncated).toBe(true)
555+
} finally {
556+
await db.delete(workspaceFiles).where(
557+
inArray(
558+
workspaceFiles.id,
559+
rows.map((row) => row.id)
560+
)
561+
)
562+
}
563+
})
505564
})

0 commit comments

Comments
 (0)