From 333769df1b68cca7f1d38355f05227a7aafcecd3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 03:55:26 -0800 Subject: [PATCH 1/2] fix(workflow-code): release review follow-ups for type-check suppression, failure attribution and error ports - source check: a type error in a file still as the last get or apply wrote it is left out only when that file had it then, checked by a second tsc run against workspace.d.ts as that get or apply left it (only when such an error exists and the declarations changed) - summary marker encodes each code point, so names past the BMP never share a marker - exit 6 in the workspace guide names tables and where each kind is unlocked - the workflow loop help chains the test run with --input, as the primer does - v2 log detail and the status read share one run-failure reader: a workflow-returned finalOutput.error is no longer taken as the run's error - a block without an error port has no error output, so is an undeclared input - v2 log failure descriptions - resource-keys race tests start the competing claim only after the held insert --- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../docs/workflows/code/diagnostics.mdx | 2 +- .../docs/content/docs/workflows/code/edit.mdx | 2 +- .../docs/workflows/code/exit-codes.mdx | 2 +- apps/docs/openapi-v2-logs.json | 4 +- .../sim/app/api/v2/logs/[runId]/route.test.ts | 42 ++++++ apps/sim/app/api/v2/logs/[runId]/route.ts | 15 +- apps/sim/lib/api/contracts/v2/logs.ts | 4 +- .../logs/execution/trace-spans/trace-spans.ts | 2 +- .../lib/workflows/executor/execution-state.ts | 12 +- .../executor/execution-status.test.ts | 27 ++++ .../workflows/executor/execution-status.ts | 19 +-- .../lib/workflows/executor/failure-message.ts | 31 +++++ .../workspaces/resource-keys.integration.ts | 14 +- .../src/commands/protocol/source-check.ts | 34 ++++- .../src/commands/protocol/source-dir/index.ts | 3 + .../commands/protocol/source-dir/written.ts | 29 +++- .../protocol/source-exit-codes.test.ts | 19 ++- .../commands/protocol/source-exit-codes.ts | 14 +- .../protocol/source-loop-help.test.ts | 11 ++ .../src/commands/protocol/source-loop-help.ts | 2 +- .../src/commands/protocol/source-tree.ts | 46 +++++-- .../src/commands/protocol/source-types.ts | 124 +++++++++++++++-- .../src/commands/protocol/source-ui.test.ts | 9 ++ .../src/commands/protocol/source-ui.ts | 2 +- .../protocol/workflow-source-check.ts | 10 +- .../protocol/workspace-source-check.ts | 3 + .../commands/protocol/workspace-source-dir.ts | 26 ++++ .../protocol/workspace-source-get.test.ts | 128 +++++++++++++++++- .../workflow-code/src/catalog/activity.ts | 12 +- packages/workflow-code/src/compile/SYNTAX.md | 2 +- .../workflow-code/src/compile/checks.test.ts | 19 +++ 34 files changed, 576 insertions(+), 101 deletions(-) create mode 100644 apps/sim/lib/workflows/executor/failure-message.ts create mode 100644 packages/sim-cli/src/commands/protocol/source-loop-help.test.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 6ee11de2671..a8d4c90eb38 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8718,7 +8718,7 @@ sim workflows source check [options] -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. @@ -10101,7 +10101,7 @@ sim workspaces source check [options] -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 67558d48f85..cb40387b707 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1512,7 +1512,7 @@ sim workflows source check [options] -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 7f50eb3c1f1..785bf582b8b 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ sim workspaces source check [options] -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index 8d9c4159afe..cbd3060b1e0 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -196,7 +196,7 @@ Saving the workflow draft. | Code | Meaning | | --- | --- | -| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. | +| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). | | `W_TYPES_UNCHECKED` | The type check did not run: TypeScript could not be installed (offline, or no `npm`) or did not start. The other findings stand; pass `--no-types` to skip it. | ### Workspace source diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index 346615110a9..5a637b6a2c2 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -31,7 +31,7 @@ sim workflows source check --dir ./support-triage `check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. -Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it, where the dry run decides. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once; offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. +Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them), where the dry run decides; one that another file's edit causes there is reported. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once; offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. ## 3. See what changed diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx index 5fde9f37d5b..5b16b21f531 100644 --- a/apps/docs/content/docs/workflows/code/exit-codes.mdx +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -53,7 +53,7 @@ The table for the kind of directory you work in. Both are built from the table ` | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another resource holds (`E_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workspaces source get --dir `, reapply your edit there, dry-run, apply | - | `6` | A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead | Ask someone to unlock it in the workflow builder | + | `6` | A resource is locked (`E_APPLY_LOCKED`): a workflow or its folder, or a table; a locked block exits 1 instead | Ask someone to unlock it: a workflow in the workflow builder, a table in its settings (the finding's hint names which) | | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | | `8` | `sim workspaces source apply` stopped part-way: what was written is saved into the directory | Apply again until it exits 0 | | `9` | Still rate limited (HTTP 429) after the CLI's retries (up to 6, at most a minute apart); nothing more was written | Wait a minute and run the same command again | diff --git a/apps/docs/openapi-v2-logs.json b/apps/docs/openapi-v2-logs.json index fbbf1bd5205..046b37bb072 100644 --- a/apps/docs/openapi-v2-logs.json +++ b/apps/docs/openapi-v2-logs.json @@ -1680,7 +1680,7 @@ "type": "null" } ], - "description": "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's leads with the line and code that threw." + "description": "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's error leads with the line and code that threw." }, "errorMessage": { "anyOf": [ @@ -1691,7 +1691,7 @@ "type": "null" } ], - "description": "A Function block's thrown message alone, which is the text to reply with; null for any other block." + "description": "The failed block's declared `errorMessage` output (Function blocks today): the thrown message alone, which is the text to reply with. Null for any other block." } }, "required": ["blockId", "blockName", "blockType", "error", "errorMessage"], diff --git a/apps/sim/app/api/v2/logs/[runId]/route.test.ts b/apps/sim/app/api/v2/logs/[runId]/route.test.ts index 93755f497d5..4833b786ca6 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.test.ts @@ -194,6 +194,8 @@ describe('GET /api/v2/logs/[runId]', () => { children: [failedBlock('a', 'Agent A'), failedBlock('b', 'Agent B')], }, ], + finalizationPath: 'force_failed', + completionFailure: 'Agent B: timeout', finalOutput: { error: 'Agent B: timeout' }, }, }) @@ -291,6 +293,8 @@ describe('GET /api/v2/logs/[runId]', () => { output: { error: 'Score failed' }, }, ], + finalizationPath: 'force_failed', + completionFailure: 'upstream returned 500', finalOutput: { error: 'upstream returned 500' }, }, }) @@ -302,6 +306,44 @@ describe('GET /api/v2/logs/[runId]', () => { expect((await response.json()).data.failure).toBeNull() }) + /** + * A run whose status comes from a block's error keeps the workflow's own `finalOutput`, which + * can hold an `error` field of its own: that is the workflow's data, not the run's error. + */ + it('names the failed block of a run whose workflow output holds an error field of its own', async () => { + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'span-fn', + blockId: 'block-fn', + name: 'Score', + type: 'function', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.010Z', + endTime: '2026-08-06T00:00:00.020Z', + output: { error: 'Line 1 - boom' }, + }, + ], + finalizationPath: 'completed', + finalOutput: { error: 'no matching customer' }, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toMatchObject({ + blockId: 'block-fn', + blockName: 'Score', + error: 'Line 1 - boom', + }) + }) + it('reports no failure for a run whose trace has none', async () => { const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { params: Promise.resolve({ runId: 'run-1' }), diff --git a/apps/sim/app/api/v2/logs/[runId]/route.ts b/apps/sim/app/api/v2/logs/[runId]/route.ts index 30762139643..780972b2af6 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.ts @@ -1,4 +1,3 @@ -import { isRecordLike } from '@sim/utils/object' import { type CostLedger, traceSpansSchema } from '@/lib/api/contracts/logs' import { type V2LogDetail, v2GetLogContract, v2LogStatusSchema } from '@/lib/api/contracts/v2/logs' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' @@ -7,6 +6,7 @@ import { getPublicLog } from '@/lib/logs/application/get-public-log' import { logOperations } from '@/lib/logs/application/operations' import { findTraceFailure, withSpanDurationMs } from '@/lib/logs/execution/trace-spans/trace-spans' import { projectLogFiles } from '@/lib/logs/files' +import { runFailureMessage } from '@/lib/workflows/executor/failure-message' export const revalidate = 0 @@ -27,17 +27,6 @@ function buildCostProjection( return null } -/** The error string a run recorded for itself, when it recorded one. */ -function runErrorOf(executionData: Record): string | undefined { - const { error, finalOutput } = executionData - const candidates = [ - error, - isRecordLike(error) ? error.message : undefined, - isRecordLike(finalOutput) ? finalOutput.error : undefined, - ] - return candidates.find((value): value is string => typeof value === 'string' && value !== '') -} - /** * Where a failed run failed. The run's own error names the block when several failed in the same * instant; one that names none of them yields no failure rather than an unrelated block, as the @@ -45,7 +34,7 @@ function runErrorOf(executionData: Record): string | undefined */ function failureOf(status: string, executionData: Record): V2LogDetail['failure'] { if (status !== 'failed') return null - return findTraceFailure(executionData.traceSpans, runErrorOf(executionData)) + return findTraceFailure(executionData.traceSpans, runFailureMessage(executionData)) } /** diff --git a/apps/sim/lib/api/contracts/v2/logs.ts b/apps/sim/lib/api/contracts/v2/logs.ts index e19c51ed5ee..0ae94581507 100644 --- a/apps/sim/lib/api/contracts/v2/logs.ts +++ b/apps/sim/lib/api/contracts/v2/logs.ts @@ -261,13 +261,13 @@ export const v2LogDetailSchema = z .string() .nullable() .describe( - "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's leads with the line and code that threw." + "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's error leads with the line and code that threw." ), errorMessage: z .string() .nullable() .describe( - "A Function block's thrown message alone, which is the text to reply with; null for any other block." + "The failed block's declared `errorMessage` output (Function blocks today): the thrown message alone, which is the text to reply with. Null for any other block." ), }) .nullable() diff --git a/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts b/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts index 68bcd1fcdbc..f56f2d8e732 100644 --- a/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts +++ b/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts @@ -300,7 +300,7 @@ export function findFailedTraceBlock(spans: unknown, runError?: string): FailedT export interface TraceFailure extends FailedTraceBlock { /** The block's error as recorded: a Function's leads with the line and code that threw. */ error: string | null - /** A Function's thrown message alone, null for any other block. */ + /** The block's declared `errorMessage` output (a Function's thrown message alone), else null. */ errorMessage: string | null } diff --git a/apps/sim/lib/workflows/executor/execution-state.ts b/apps/sim/lib/workflows/executor/execution-state.ts index 91547af2bc7..cea3262c0be 100644 --- a/apps/sim/lib/workflows/executor/execution-state.ts +++ b/apps/sim/lib/workflows/executor/execution-state.ts @@ -4,6 +4,7 @@ import { filterUndefined, isRecordLike } from '@sim/utils/object' import { and, desc, eq, or, sql } from 'drizzle-orm' import { getBaseUrl } from '@/lib/core/utils/urls' import { materializeExecutionData, TRACE_STORE_REF_KEY } from '@/lib/logs/execution/trace-store' +import { forceFailedMessage } from '@/lib/workflows/executor/failure-message' import { buildResumeUiUrl } from '@/executor/constants' import type { SerializableExecutionState } from '@/executor/execution/types' import type { PausePoint } from '@/executor/types' @@ -232,17 +233,10 @@ export async function getHumanPauseResumeUrl( return waitsOnPerson ? buildResumeUiUrl(getBaseUrl(), workflowId, executionId) : null } -/** - * The message an error finalization (`force_failed`) stored as the run's `finalOutput.error`. - * Any other run's `finalOutput.error` is the workflow's own data, not a failure message. - */ +/** A terminal run's failure message: its own `error`, else {@link forceFailedMessage}. */ function readFailureMessage(executionData: Record): string | undefined { if (typeof executionData.error === 'string') return executionData.error - if (executionData.finalizationPath !== 'force_failed') return undefined - const { finalOutput } = executionData - return isRecordLike(finalOutput) && typeof finalOutput.error === 'string' - ? finalOutput.error - : undefined + return forceFailedMessage(executionData) } /** Loads a terminal workflow result only when its server-persisted Copilot binding matches. */ diff --git a/apps/sim/lib/workflows/executor/execution-status.test.ts b/apps/sim/lib/workflows/executor/execution-status.test.ts index 6fe2d592dc0..cfe3eb0a21c 100644 --- a/apps/sim/lib/workflows/executor/execution-status.test.ts +++ b/apps/sim/lib/workflows/executor/execution-status.test.ts @@ -778,6 +778,33 @@ describe('getWorkflowExecutionStatus once a pause has settled', () => { }, }) }) + + it.each([ + [ + 'the message an error finalization recorded', + { + finalizationPath: 'force_failed', + completionFailure: 'Lookup: upstream returned 500', + finalOutput: { error: 'Lookup: upstream returned 500' }, + }, + 'Lookup: upstream returned 500', + ], + [ + "no error from a workflow output's own error field", + { finalizationPath: 'completed', finalOutput: { error: 'no matching customer' } }, + null, + ], + ])('reports as a failed run its error %s', async (_, recorded, error) => { + queueFailedRunWithOpenPause({ 'wait-five': FAILED_TIME_POINT }) + mockMaterializeForDisplayWithBlockOutputs.mockResolvedValue({ + executionData: { ...recorded, traceSpans: [] }, + blockOutputs: new Map(), + }) + + const projected = await getProjectedWorkflowExecutionStatus(input) + + expect(projected?.status).toMatchObject({ status: 'failed', error }) + }) }) describe('readPausedRunPoints cap', () => { diff --git a/apps/sim/lib/workflows/executor/execution-status.ts b/apps/sim/lib/workflows/executor/execution-status.ts index 9461c9e98ac..51bcbf9ca8a 100644 --- a/apps/sim/lib/workflows/executor/execution-status.ts +++ b/apps/sim/lib/workflows/executor/execution-status.ts @@ -25,6 +25,7 @@ import { WORKFLOW_EXECUTION_JOB_ID_PREFIX, } from '@/lib/workflows/executor/execution-job-ids' import { normalizePausePoints } from '@/lib/workflows/executor/execution-state' +import { runFailureMessage } from '@/lib/workflows/executor/failure-message' import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' import { namePausePoints, pauseBaseBlockId } from '@/lib/workflows/executor/pause-block-names' import { getAutomaticResumeWaitingMetadata } from '@/lib/workflows/executor/paused-execution-metadata' @@ -42,9 +43,7 @@ import type { PauseInputField, PausePoint, ResumeStatus } from '@/executor/types type LogStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' interface ExecutionDataShape { - finalOutput?: { error?: string } & Record - error?: { message?: string } | string - completionFailure?: string + finalOutput?: unknown traceSpans?: unknown } @@ -88,18 +87,6 @@ function isSettledPausePoint(point: PausePoint): boolean { return point.resumeStatus === 'resumed' || point.resumeStatus === 'failed' } -function extractError(executionData: unknown): string | null { - if (!executionData || typeof executionData !== 'object') return null - const data = executionData as ExecutionDataShape - if (typeof data.error === 'string') return data.error - if (data.error && typeof data.error === 'object' && typeof data.error.message === 'string') { - return data.error.message - } - if (typeof data.finalOutput?.error === 'string') return data.finalOutput.error - if (typeof data.completionFailure === 'string') return data.completionFailure - return null -} - function extractJobFinalOutput(output: unknown): unknown | null { if (!output || typeof output !== 'object' || !('output' in output)) return null return (output as Record).output ?? null @@ -603,7 +590,7 @@ async function readWorkflowExecutionStatus( ) const executionData = materialized.executionData as ExecutionDataShape - const error = status === 'failed' ? extractError(executionData) : null + const error = status === 'failed' ? (runFailureMessage(executionData) ?? null) : null const finalOutput = includeOutput && status === 'completed' && executionData diff --git a/apps/sim/lib/workflows/executor/failure-message.ts b/apps/sim/lib/workflows/executor/failure-message.ts new file mode 100644 index 00000000000..ed77ee185e7 --- /dev/null +++ b/apps/sim/lib/workflows/executor/failure-message.ts @@ -0,0 +1,31 @@ +import { isRecordLike } from '@sim/utils/object' + +/** + * The message an error finalization (`force_failed`) stored as the run's `finalOutput.error`. + * Any other run's `finalOutput.error` is the workflow's own data, not a failure message. + */ +export function forceFailedMessage(executionData: Record): string | undefined { + if (executionData.finalizationPath !== 'force_failed') return undefined + const { finalOutput } = executionData + return isRecordLike(finalOutput) && typeof finalOutput.error === 'string' + ? finalOutput.error + : undefined +} + +/** + * The error a failed run recorded for itself, as the run log and status reads report it: its own + * `error` (a string, or an object with a `message`), the failure its completion recorded + * (`completionFailure`), else {@link forceFailedMessage}. Undefined when it recorded none, as a + * run whose status comes from a block's error alone does. + */ +export function runFailureMessage(executionData: unknown): string | undefined { + if (!isRecordLike(executionData)) return undefined + const { error, completionFailure } = executionData + const candidates = [ + error, + isRecordLike(error) ? error.message : undefined, + completionFailure, + forceFailedMessage(executionData), + ] + return candidates.find((value): value is string => typeof value === 'string' && value !== '') +} diff --git a/apps/sim/lib/workspaces/resource-keys.integration.ts b/apps/sim/lib/workspaces/resource-keys.integration.ts index 3b3797f3ccd..eafedf63025 100644 --- a/apps/sim/lib/workspaces/resource-keys.integration.ts +++ b/apps/sim/lib/workspaces/resource-keys.integration.ts @@ -67,9 +67,12 @@ async function keyRows(wsId: string, kind: ResourceKind, resourceId: string) { /** * Holds a transaction open with one uncommitted key row, so a concurrent writer that collides on - * a unique index blocks on it. Resolves `committed` once the row is committed. + * a unique index blocks on it. Resolves `inserted` once the row is written (start the competing + * write only then, or it can commit first; it rejects as `committed` does when the write fails) + * and `committed` once the row is committed. */ function holdUncommittedKey(row: { key: string; resourceId: string }): { + inserted: Promise committed: Promise commit: () => void } { @@ -77,6 +80,10 @@ function holdUncommittedKey(row: { key: string; resourceId: string }): { const released = new Promise((resolve) => { commit = resolve }) + let markInserted = () => {} + const inserted = new Promise((resolve) => { + markInserted = resolve + }) const committed = db.transaction(async (tx) => { const now = new Date() await tx.insert(workspaceResourceKey).values({ @@ -90,9 +97,10 @@ function holdUncommittedKey(row: { key: string; resourceId: string }): { createdAt: now, updatedAt: now, }) + markInserted() await released }) - return { committed, commit } + return { inserted: Promise.race([inserted, committed]), committed, commit } } /** Waits until some backend is blocked on a lock while writing `workspace_resource_key`. */ @@ -423,6 +431,7 @@ describe('workspace resource keys against PostgreSQL', () => { await insertTable(holder, workspaceId, 'Race Holder', at(50)) await insertTable(claimant, workspaceId, 'Race Claimant', at(51)) const held = holdUncommittedKey({ key: 'race-leads', resourceId: holder }) + await held.inserted const claim = claimResourceKey({ workspaceId, @@ -451,6 +460,7 @@ describe('workspace resource keys against PostgreSQL', () => { const id = generateId() await insertTable(id, workspaceId, 'Race Allocated', at(52)) const held = holdUncommittedKey({ key: 'race-allocated', resourceId: id }) + await held.inserted const claim = claimResourceKey({ workspaceId, diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 636a60d0332..951e27fef13 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -40,13 +40,20 @@ import type { Command } from 'commander' import { setSoftExitCode } from '../../embed-context' import { SourceDirError } from './local-errors' import { printProtocolResult } from './result' -import { digest, readFolderWritten, readSourceText } from './source-dir' +import { + digest, + readFolderWritten, + readSourceText, + unchangedTexts, + type Written, +} from './source-dir' import { STRICT_FINDINGS } from './source-strict' import { cachedCatalog, cachedSourceCatalog, type LocalDeclarations, refreshTsconfigs, + workspaceTypesText, } from './source-tree' import type { TypeCheck } from './source-types' import { type Diagnostic, findingsOutput } from './source-ui' @@ -58,6 +65,7 @@ import { readWorkspaceDeclarations, WORKSPACE_TREE, type WorkspaceDeclarations, + writtenLocalDeclarations, } from './workspace-source-dir' /** @@ -540,6 +548,30 @@ export function withWorkflowInputs( return { ...local, workflows } } +/** + * `workspace.d.ts` as the last get or apply (`written`) left the workspace directory `root`: the + * kept manifest, what the files that write recorded declare, and the `workflowInputs` of each + * workflow whose `workflow.ts` is unchanged since. A workflow edited since keeps its stored inputs + * (none without a kept manifest), so an error its edit causes in another workflow is not taken + * for one that workflow's printed source already had. + */ +export async function writtenWorkspaceTypes( + root: string, + workflowInputs: ReadonlyMap, + written: Written +): Promise { + const unchanged = await unchangedTexts( + root, + [...workflowInputs.keys()].map(workflowEntry), + written.digests + ) + const inputs = new Map([...workflowInputs].filter(([key]) => unchanged.has(workflowEntry(key)))) + return workspaceTypesText( + root, + withWorkflowInputs(await writtenLocalDeclarations(root, written), inputs) + ) +} + /** * Compiles one workflow source directory offline against `catalog`, with the workspace's * declarations when the directory sits in a workspace directory, and returns its findings with diff --git a/packages/sim-cli/src/commands/protocol/source-dir/index.ts b/packages/sim-cli/src/commands/protocol/source-dir/index.ts index b71036d9cee..21569e286f8 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/index.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/index.ts @@ -58,8 +58,11 @@ export { readFolderWritten, readWritten, recordedStats, + SOURCE_CACHE_DIR, + SOURCE_CACHE_IGNORE, type StatDigest, sameFileStat, + unchangedTexts, type Written, writtenFiles, writtenRecord, diff --git a/packages/sim-cli/src/commands/protocol/source-dir/written.ts b/packages/sim-cli/src/commands/protocol/source-dir/written.ts index 604926b9e04..324a0197c3f 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/written.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/written.ts @@ -18,9 +18,11 @@ import { orphanedCodeFiles, SOURCE_WRITTEN_FILE } from './layout' * which names this machine's files (device, inode, times) and so is never committed. The folder * ignores itself (`.sim/cache/.gitignore`), whatever the repository's own `.gitignore` says. */ -const SOURCE_CACHE_DIR = '.sim/cache' +export const SOURCE_CACHE_DIR = '.sim/cache' const SOURCE_STATS_FILE = `${SOURCE_CACHE_DIR}/stats.json` -const SOURCE_CACHE_IGNORE_FILE = `${SOURCE_CACHE_DIR}/.gitignore` + +/** The cache folder's own `.gitignore`, written with any file the CLI keeps there. */ +export const SOURCE_CACHE_IGNORE = [`${SOURCE_CACHE_DIR}/.gitignore`, '*\n'] as const /** * What identifies a file's bytes without reading them, taken when its digest was: the file (device @@ -133,11 +135,7 @@ export function writtenFiles(written: Written): Array ) if (stats.length === 0) return files const cache: StatsRecord = { version: 1, stats: sortedByPath(Object.fromEntries(stats)) } - return [ - ...files, - [SOURCE_STATS_FILE, `${JSON.stringify(cache, null, 2)}\n`], - [SOURCE_CACHE_IGNORE_FILE, '*\n'], - ] + return [...files, [SOURCE_STATS_FILE, `${JSON.stringify(cache, null, 2)}\n`], SOURCE_CACHE_IGNORE] } /** What the CLI recorded for its last write, empty when it recorded nothing. */ @@ -203,6 +201,23 @@ export async function editedFiles( }) } +/** The texts of those of `paths` still as the CLI last wrote them (`written`), by path. */ +export async function unchangedTexts( + dir: string, + paths: readonly string[], + written: Written['digests'] +): Promise> { + const texts = await mapWithConcurrency(paths, FILE_CONCURRENCY, (path) => + readSourceText(dir, path) + ) + return new Map( + paths.flatMap((path, index) => { + const text = texts[index] + return text !== null && written[path] === digest(text) ? [[path, text] as const] : [] + }) + ) +} + /** * The source files a write of `answer` would destroy edits in: a file it replaces or prunes whose * text on disk is neither what the CLI last wrote there nor what it is about to write. diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts index 13d1991b456..890c9533bc3 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import * as exitCodes from '../../exit-codes' -import { sourceExitCodesHelp } from './source-exit-codes' +import { sourceExitCodesHelp, sourceExitCodesTable } from './source-exit-codes' import { WORKFLOW_TREE } from './workflow-dir' import { WORKSPACE_TREE } from './workspace-source-dir' @@ -27,6 +27,23 @@ describe('the exit-code tables an agent or a reader relies on', () => { }) }) +describe('the locked row of a directory guide', () => { + const lockedRow = (prefix: Parameters[0]) => + sourceExitCodesTable(prefix) + .split('\n') + .find((row) => row.startsWith(`| ${exitCodes.SOURCE_LOCKED_EXIT_CODE} |`)) + + it('says where a workspace apply unlocks each kind of resource it can find locked', () => { + expect(lockedRow('sim workspaces source')).toMatch(/a table\b.*a table in its settings/) + expect(lockedRow('sim workspaces source')).toContain('a workflow in the workflow builder') + }) + + it('sends a workflow apply to the workflow builder', () => { + expect(lockedRow('sim workflows source')).toContain('unlock it in the workflow builder') + expect(lockedRow('sim workflows source')).not.toContain('table') + }) +}) + describe('the exit codes a get names in its --help', () => { it.each(['workflows source get', 'workspaces source get'] as const)( '%s names exit 13 for a missing or refused login', diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 9ecdbb61c59..70bc16a50bf 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -99,9 +99,17 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo }, { code: SOURCE_LOCKED_EXIT_CODE, - meaning: - 'A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead', - next: 'Ask someone to unlock it in the workflow builder', + ...(prefix === 'sim workspaces source' + ? { + meaning: + 'A resource is locked (`E_APPLY_LOCKED`): a workflow or its folder, or a table; a locked block exits 1 instead', + next: "Ask someone to unlock it: a workflow in the workflow builder, a table in its settings (the finding's hint names which)", + } + : { + meaning: + 'A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead', + next: 'Ask someone to unlock it in the workflow builder', + }), help: { 'workflows source apply': 'the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK)', diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts new file mode 100644 index 00000000000..25f8c1c48a5 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { WORKFLOW_SOURCE_LOOP_HELP } from './source-loop-help' +import { sourcePrimer } from './source-primer' + +describe('the edit loop of sim workflows source --help', () => { + it('chains the same test run the primer does', () => { + const primerRun = sourcePrimer('workflow').match(/&& (sim workflows run [^`]+)`/)?.[1] + expect(primerRun).toBeDefined() + expect(WORKFLOW_SOURCE_LOOP_HELP).toContain(`&& ${primerRun}`) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index f1ddf2d5e8e..00aa7dda37a 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -36,7 +36,7 @@ ${loopRows([ ['edit ./wf/workflow.ts', 'every file first, then the one command below'], ['sim workflows source check --dir ./wf', 'compile + types: each error as file:line:column'], [' && sim workflows source apply --dir ./wf --yes', 'save the draft (it re-checks)'], - [' && sim workflows run --manual', 'test the saved draft'], + [" && sim workflows run --manual --input '{…}'", 'test the saved draft'], ])} Run those three as one chained command: a non-zero exit stops it at the first failure, and the next step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 77a1043f3d6..2a634c36d10 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -56,7 +56,8 @@ import { import { AGENTS_POINTER_MARKER, agentsPointer, type PrimerKind, primerFor } from './source-primer' import { shellWord } from './source-ui' -const TSCONFIG_FILE = 'tsconfig.json' +/** The CLI's `tsconfig.json`, which a check type-checks the directory with. */ +export const TSCONFIG_FILE = 'tsconfig.json' /** Where agents look first: the nearest `AGENTS.md` above the file they edit. */ const ROOT_AGENTS_FILE = 'AGENTS.md' /** @@ -373,6 +374,33 @@ export async function loadWorkspaceTypes( } } +/** + * The stored manifest the last get kept beside `workspace.d.ts`: `null` when it kept none (the get + * could not list the workspace's resources), `undefined` when the file does not parse. + */ +async function readKeptManifest(dir: string): Promise { + const manifest = await readSourceText(dir, WORKSPACE_MANIFEST_FILE) + if (manifest === null) return null + try { + const parsed: unknown = JSON.parse(manifest) + return isRecordLike(parsed) ? parsed : undefined + } catch { + return undefined + } +} + +/** + * `workspace.d.ts` for the kept stored manifest and `local`, as {@link refreshWorkspaceTypes} + * would write it, without writing it; `null` for no file. A manifest that does not parse counts + * as none kept. + */ +export async function workspaceTypesText( + dir: string, + local: LocalDeclarations +): Promise { + return workspaceTypesFrom((await readKeptManifest(dir)) ?? null, local)?.text ?? null +} + /** * Regenerates `workspace.d.ts` from the stored manifest the last get kept beside it and what the * directory declares now (`local`), so a check types a key added since without a request. Without @@ -381,21 +409,11 @@ export async function loadWorkspaceTypes( * not parse leaves the file as it is. */ export async function refreshWorkspaceTypes(dir: string, local: LocalDeclarations): Promise { - const [manifest, current] = await Promise.all([ - readSourceText(dir, WORKSPACE_MANIFEST_FILE), + const [stored, current] = await Promise.all([ + readKeptManifest(dir), readSourceText(dir, WORKSPACE_TYPES_FILE), ]) - let stored: WorkspaceManifest | null = null - if (manifest !== null) { - let parsed: unknown - try { - parsed = JSON.parse(manifest) - } catch { - return - } - if (!isRecordLike(parsed)) return - stored = parsed - } + if (stored === undefined) return const types = workspaceTypesFrom(stored, local) if (types === null) { if (current !== null) await updateSourceDir(dir, { write: [], remove: [WORKSPACE_TYPES_FILE] }) diff --git a/packages/sim-cli/src/commands/protocol/source-types.ts b/packages/sim-cli/src/commands/protocol/source-types.ts index e83b0977469..e5b507538aa 100644 --- a/packages/sim-cli/src/commands/protocol/source-types.ts +++ b/packages/sim-cli/src/commands/protocol/source-types.ts @@ -10,9 +10,10 @@ import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' import { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { dirname, join, posix } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' +import { generateShortId } from '@sim/utils/id' import { codeFrame } from '@sim/workflow-code' import { SOURCE_TYPESCRIPT_VERSION } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' @@ -20,7 +21,17 @@ import { configDir } from '../../config/paths' import { embedStore } from '../../embed-context' import { childProcessEnv } from '../../environment' import { printError } from '../../output/io' -import { digest, FILE_CONCURRENCY, readSourceText, readWritten } from './source-dir' +import { + digest, + FILE_CONCURRENCY, + readSourceText, + readWritten, + SOURCE_CACHE_DIR, + SOURCE_CACHE_IGNORE, + updateSourceDir, + type Written, +} from './source-dir' +import { TSCONFIG_FILE, WORKSPACE_TYPES_FILE } from './source-tree' import type { Diagnostic } from './source-ui' /** The `--types` / `--no-types` pair: absent runs the type check. */ @@ -31,8 +42,9 @@ export interface TypesOptions { /** What both check commands' help says of the type check. */ export const TYPES_HELP = `Then it type-checks the directory with TypeScript ${SOURCE_TYPESCRIPT_VERSION} (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message -starting with TypeScript's code; one on a line the compile already reports an error on, or in a -file still as the last get or apply wrote it, is left out. The first check installs that release +starting with TypeScript's code. One is left out on a line the compile already reports an error +on, and in a file still as the last get or apply wrote it when that file had the same error then +(against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check.` @@ -256,16 +268,17 @@ export interface TypeCheck { } /** - * Runs the pinned tsc over `root`'s `tsconfig.json` and returns its errors; a {@link - * TypesUnavailable} when it cannot be installed, does not start, or stops without saying why. + * Runs the pinned tsc over `root`'s `tsconfig.json` (or `project`, a config under `root`) and + * returns its errors, each file relative to `root`; a {@link TypesUnavailable} when it cannot be + * installed, does not start, or stops without saying why. */ -async function tscErrors(root: string): Promise> { +async function tscErrors(root: string, project = '.'): Promise> { const tsc = await installedTsc() const finished = await run( 'TypeScript', process.execPath, // --noEmit: a tsconfig.json the person wrote may emit, and a check writes nothing. - [tsc, '-p', '.', '--pretty', 'false', '--noEmit'], + [tsc, '-p', project, '--pretty', 'false', '--noEmit'], { cwd: root, } @@ -291,20 +304,96 @@ async function tscErrors(root: string): Promise`) resolve. + */ +async function errorsWithWorkspaceTypes( + root: string, + types: string | null +): Promise { + const id = generateShortId() + const typesFile = `${SOURCE_CACHE_DIR}/workspace-${id}.d.ts` + const project = `${SOURCE_CACHE_DIR}/tsconfig-${id}.json` + const fromCache = (path: string) => posix.relative(SOURCE_CACHE_DIR, path) + const typesFiles = types === null ? [] : [[typesFile, types] as const] + const tsconfig = { + extends: fromCache(TSCONFIG_FILE), + exclude: [fromCache(WORKSPACE_TYPES_FILE)], + files: typesFiles.map(([path]) => fromCache(path)), + } + const written = [project, ...typesFiles.map(([path]) => path)] + await updateSourceDir(root, { + write: [ + SOURCE_CACHE_IGNORE, + [project, `${JSON.stringify(tsconfig, null, 2)}\n`], + ...typesFiles, + ], + }) + try { + return (await tscErrors(root, project)).located + } catch (error) { + // A run that fails says nothing of the earlier errors, so none is taken as one. + if (error instanceof TypesUnavailable) return [] + throw error + } finally { + await updateSourceDir(root, { write: [], remove: written }) + } +} + +/** + * Which of `errors`, each in a file still as the last get or apply wrote it, that file already had + * then: all of them when the declarations are as that get or apply left them, else those a second + * run against `writtenTypes` (`workspace.d.ts` as it was) reports too. A workflow file depends on + * the declarations alone, never on another workflow file, so an error of an unchanged file that + * the edited declarations alone cause is kept. + */ +async function errorsAsWritten( + root: string, + errors: readonly LocatedTscError[], + written: Written | null, + writtenTypes: ((written: Written) => Promise) | undefined +): Promise> { + const all = new Set(errors.map(errorKey)) + if (errors.length === 0 || written === null || writtenTypes === undefined) return all + const [types, current] = await Promise.all([ + writtenTypes(written), + readSourceText(root, WORKSPACE_TYPES_FILE), + ]) + if (types === current) return all + const before = new Set((await errorsWithWorkspaceTypes(root, types)).map(errorKey)) + return new Set([...all].filter((key) => before.has(key))) +} + /** * Type-checks the source directory `root` with its `tsconfig.json`, unless `enabled` is false * (`--no-types`). `scope` (a folder under `root`, such as `workflows//`) keeps only that * folder's errors, with files relative to it, as a check of one workflow folder of a workspace * reports them. Two kinds of type error are left out: one on a line where `compiled` (the * compile's findings) already has an error, the same mistake, which the compile says better; and - * one in a file still as the last get or apply wrote it (`.sim/written.json`), printed source the - * server accepted, where the declarations can lag (a block the workspace's catalog withholds from - * the caller while a stored workflow holds it). An embedded run reads files through its host, + * one that a file still as the last get or apply wrote it (`.sim/written.json`) had then: printed + * source the server accepted, where the declarations can lag (a block the workspace's catalog + * withholds from the caller while a stored workflow holds it). A workspace directory's check + * regenerates `workspace.d.ts` from the files, so `writtenTypes` gives the file as that get or + * apply left it, and an error of an unchanged file is left out only when it occurs against that + * too; without it the declarations are as written. An embedded run reads files through its host, * which no subprocess can, so it does not type-check. */ export async function typeCheck( root: string, - options: { enabled: boolean; scope?: string; compiled: readonly Diagnostic[] } + options: { + enabled: boolean + scope?: string + compiled: readonly Diagnostic[] + writtenTypes?: (written: Written) => Promise + } ): Promise { if (!options.enabled || embedStore.getStore()) return { checked: false, findings: [] } let errors: Awaited> @@ -346,14 +435,21 @@ export async function typeCheck( return [file, { text, printed }] as const }) ) + const asWritten = await errorsAsWritten( + root, + located.filter(({ file }) => sources.get(file)?.printed), + written, + options.writtenTypes + ) const findings: Diagnostic[] = errors.project.map((message) => ({ code: 'E_TYPE', severity: 'error', message, })) - for (const { file, line, column, message } of located) { + for (const error of located) { + const { file, line, column, message } = error const source = sources.get(file) - if (source?.printed) continue + if (asWritten.has(errorKey(error))) continue findings.push({ code: 'E_TYPE', severity: 'error', diff --git a/packages/sim-cli/src/commands/protocol/source-ui.test.ts b/packages/sim-cli/src/commands/protocol/source-ui.test.ts index 0a7ef8dffa6..543ca8e146f 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.test.ts @@ -7,6 +7,15 @@ describe('summaryMarker', () => { expect(summaryMarker('a b')).not.toBe(summaryMarker('a-b')) }) + it('gives directories whose names differ only past the Basic Multilingual Plane different markers', () => { + expect(summaryMarker('ws-😀')).not.toBe(summaryMarker('ws-🚀')) + expect(summaryMarker('ws-😀')).toBe('') + }) + + it('encodes a name inside the Basic Multilingual Plane byte by byte', () => { + expect(summaryMarker('café 数据')).toBe('') + }) + it('never carries a double hyphen, which would end the comment', () => { expect(summaryMarker('a--b>c')).not.toContain('--b') expect(summaryMarker('a--b>c')).toMatch(/^$/) diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index a7cd975a019..7aab45a7def 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -336,7 +336,7 @@ export function errorBullets(errors: ReadonlyArray): string[] { /** The first line of a summary file for `dir`: stable per directory (every character outside `A-Za-z0-9._/` percent-encoded, so two names never share one and no `--` ends the comment). */ export function summaryMarker(dir: string): string { const name = relative(process.cwd(), dir) || '.' - const encoded = name.replace(/[^A-Za-z0-9._/]/g, (char) => + const encoded = name.replace(/[^A-Za-z0-9._/]/gu, (char) => [...Buffer.from(char)] .map((byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`) .join('') diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index 062deea4b05..752cc471f74 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -15,6 +15,7 @@ import { strictHelp, strictMode, withWorkflowInputs, + writtenWorkspaceTypes, } from './source-check' import { absoluteDirOption, @@ -22,6 +23,7 @@ import { directoryWorkspace, readSourceJson, readStarterWorkspace, + type Written, workspaceFolderOf, } from './source-dir' import { @@ -127,8 +129,14 @@ export function attachWorkflowSourceCheck(source: Command): void { } const types = await typeCheck(workspace ? workspace.root : options.dir, { enabled: options.types !== false, - ...(workspace ? { scope: `${KIND_DIRS.workflow}/${workspace.key}/` } : {}), compiled: findings, + ...(workspace && declarations + ? { + scope: `${KIND_DIRS.workflow}/${workspace.key}/`, + writtenTypes: (written: Written) => + writtenWorkspaceTypes(workspace.root, declarations.workflowInputs, written), + } + : {}), }) reportCheck( profile.output, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index f9f4b97ca01..a82b989f686 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -19,6 +19,7 @@ import { strictMode, withWorkflowInputs, workspaceWorkflowKeys, + writtenWorkspaceTypes, } from './source-check' import { absoluteDirOption, @@ -177,6 +178,8 @@ export function attachWorkspaceSourceCheck(source: Command): void { const types = await typeCheck(options.dir, { enabled: options.types !== false, compiled: findings, + writtenTypes: (written) => + writtenWorkspaceTypes(options.dir, declarations.workflowInputs, written), }) reportCheck( profile.output, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 7aa25517a77..df96931e14b 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -72,6 +72,7 @@ import { SOURCE_STAGING_PREFIX, SOURCE_STORED_EDGES_FILE, type StatDigest, + unchangedTexts, type Written, } from './source-dir' import { sourceExitCodesTable } from './source-exit-codes' @@ -250,6 +251,31 @@ export function localDeclarations(files: Readonly>): Loca return declared } +/** + * What the workspace directory `root` declared as the last get or apply wrote it: the paths that + * write recorded (`written`), each folder kind's keys from them, and a root file's names only + * while its text is unchanged since; an edited one's earlier text is gone, so it declares none. + */ +export async function writtenLocalDeclarations( + root: string, + written: Written +): Promise { + const files: Record = {} + for (const path of Object.keys(written.digests)) { + if (kindOfPath(path) !== null) files[path] = '' + } + const rootFiles = APPLY_ORDER.filter(isFileKind) + .map((kind) => KIND_DIRS[kind]) + .filter((file) => Object.hasOwn(files, file)) + const unchanged = await unchangedTexts(root, rootFiles, written.digests) + for (const file of rootFiles) { + const text = unchanged.get(file) + if (text === undefined) delete files[file] + else files[file] = text + } + return localDeclarations(files) +} + /** * The keys `files` (path → text) declare for `kind`: a root file's entries, or the resources its * folder's paths group into. `null` for a root file that is absent or does not read, whose keys diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 03d8adc4522..1a2bad199d3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -1,4 +1,4 @@ -import { execFileSync } from 'node:child_process' +import { execFileSync, spawn } from 'node:child_process' import { createHash } from 'node:crypto' import { existsSync, @@ -25,6 +25,10 @@ import { blobBytes, blobDigests } from './workspace-source-blobs' import { kindFolders } from './workspace-source-dir' vi.mock('../../context', async () => (await import('../../test/context-mock')).contextMock) +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, spawn: vi.fn(actual.spawn) } +}) const { mockRequest: request, mockRequestRaw: requestRaw } = contextMockFns const SOURCE_PATH = '/api/v2/workspaces/ws_local/source' @@ -1434,6 +1438,128 @@ describe('the type check of workspaces source check', () => { expect(existsSync(join(dir, 'workflows/save/workflow.js'))).toBe(false) }) + describe('a type error in a file still as the get wrote it', () => { + const workflowSource = (...lines: string[]) => + [ + '// @sim-sdk 1', + "import { childWorkflow, runWorkflow, trigger, workflow } from '@sim/workflow-sdk'", + "export default workflow('W', {}, () => {", + ...lines.map((line) => ` ${line}`), + '})', + '', + ].join('\n') + const child = (type: string) => + workflowSource(`trigger.start('Start', { inputFormat: { count: '${type}' } })`) + const PARENT = workflowSource( + "const start = trigger.start('Start', {})", + "const call = runWorkflow('Call', { workflowId: childWorkflow('child'), inputMapping: { count: 5 } })", + 'start.to(call)' + ) + /** The resource listing of a workspace whose stored child takes `count` as `type`. */ + const manifestWith = (type: string) => ({ + workspaceId: 'ws_local', + tables: [], + knowledgeBases: [], + credentials: [], + workflows: [ + { key: 'child', inputs: [{ name: 'count', type }] }, + { key: 'parent', inputs: [] }, + ], + skills: [], + customTools: [], + mcpServers: [], + env: [], + truncated: false, + }) + const tscRuns = () => + vi + .mocked(spawn) + .mock.calls.filter(([, args]) => String(args?.[0]).endsWith(join('bin', 'tsc'))).length + + beforeEach(() => { + vi.mocked(spawn).mockClear() + }) + + it.each([ + ['workspaces', 'a kept resource listing', true], + ['workspaces', 'no resource listing', false], + ['workflows', 'a kept resource listing', true], + ['workflows', 'no resource listing', false], + ])( + "reports one another file's edit caused, after a %s check with %s", + async (command, _listing, listed) => { + serve( + { + 'workflows/child/workflow.ts': child('number'), + 'workflows/parent/workflow.ts': PARENT, + }, + { kinds: ['workflow'], ...(listed ? { manifest: manifestWith('number') } : {}) } + ) + await get() + writeFileSync(join(dir, 'workflows/child/workflow.ts'), child('boolean')) + + if (command === 'workspaces') await runWorkspaceSource('check', dir) + else await runWorkflowSourceCheck(join(dir, 'workflows/parent')) + + const file = command === 'workspaces' ? 'workflows/parent/workflow.ts' : 'workflow.ts' + expect(result().diagnostics).toEqual([ + expect.objectContaining({ + code: 'E_TYPE', + file, + line: 5, + message: expect.stringMatching(/^TS2322: Type 'number' is not assignable/), + }), + ]) + expect(process.exitCode).toBe(1) + expect(tscRuns()).toBe(2) + } + ) + + it.each([ + ['a kept resource listing', true], + ['no resource listing', false], + ])( + 'leaves out one the server accepted, on a fresh get with %s, running tsc once', + async (_listing, listed) => { + serve( + { + 'workflows/child/workflow.ts': child('boolean'), + 'workflows/parent/workflow.ts': PARENT, + }, + { kinds: ['workflow'], ...(listed ? { manifest: manifestWith('boolean') } : {}) } + ) + await get() + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ + checked: ['compile', 'types'], + errors: 0, + diagnostics: [], + }) + expect(tscRuns()).toBe(1) + expect(typecheckDirectory()).toContain('TS2322') + } + ) + + it('leaves out one under a block the catalog withholds when an edit elsewhere changes the declarations', async () => { + serveWorkflow('router', ROUTER, ['start', 'isurgent', 'policy', 'logticket'], CATALOG.hash) + await get() + expect(typecheckDirectory()).toContain('workflows/router/workflow.ts') + mkdirSync(join(dir, 'workflows/extra'), { recursive: true }) + writeFileSync( + join(dir, 'workflows/extra/workflow.ts'), + workflowSource("trigger.start('Start', { inputFormat: { note: 'string' } })") + ) + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ checked: ['compile', 'types'], errors: 0, diagnostics: [] }) + expect(tscRuns()).toBe(2) + expect(readdirSync(join(dir, '.sim/cache'))).toEqual(['.gitignore']) + }) + }) + it('skips the type check with --no-types', async () => { serve({ 'tables/leads.ts': LEADS }) await get() diff --git a/packages/workflow-code/src/catalog/activity.ts b/packages/workflow-code/src/catalog/activity.ts index 2b9d99af4e3..d9069f01ee7 100644 --- a/packages/workflow-code/src/catalog/activity.ts +++ b/packages/workflow-code/src/catalog/activity.ts @@ -118,22 +118,26 @@ export function blockOutputSchemas( * every block (`BlockExecutor`'s `errorOutput`), or one of the `errorOutputs` its catalog entry * declares (a Function's `errorMessage`). Each is text, read exactly where `error` is. */ -function isErrorOutputName(block: CatalogBlock | undefined, name: string): boolean { - return name === 'error' || (block?.errorOutputs?.includes(name) ?? false) +function isErrorOutputName(block: CatalogBlock, name: string): boolean { + return name === 'error' || (block.errorOutputs?.includes(name) ?? false) } /** * The failure output a path names (`x.error`, or a Function's `x.errorMessage`; * `isErrorOutputName`): what a failed block outputs when an error edge (`x.onError(y)`) leaves it, * which the executor returns as the block's output instead of failing the run - * (`BlockExecutor`'s `errorOutput`). Any other block fails the run, so nothing reads it. + * (`BlockExecutor`'s `errorOutput`). Any other block fails the run, so nothing reads it. A block + * with no error port (a Start trigger) has none, so on it the path is an ordinary output. */ export function errorOutputOf( block: CatalogBlock | undefined, segments: readonly RefSegment[] ): string | null { const [first] = segments - return segments.length === 1 && first?.kind === 'name' && isErrorOutputName(block, first.name) + return block?.graph.errorPort === true && + segments.length === 1 && + first?.kind === 'name' && + isErrorOutputName(block, first.name) ? first.name : null } diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index eb7b02d2241..040f06423f5 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -548,5 +548,5 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | Code | Meaning | |---|---| -| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. | +| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). | | `W_TYPES_UNCHECKED` | The type check did not run: TypeScript could not be installed (offline, or no `npm`) or did not start. The other findings stand; pass `--no-types` to skip it. | diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 0bf9c401d57..2f17a5583ab 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -747,6 +747,25 @@ describe('hints that name the fix', () => { expect(unknown?.hint).toBe('Wire call.onError() and read call.error in the handler.') }) + it('reads as an undeclared input, since a Start trigger has no error port', () => { + const result = run( + [ + START, + "const next = api('Next', { url: 'https://x', body: { why: start.error } })", + 'start.to(next)', + ].join('\n') + ) + expect(findings(result, 'W_OUTPUT_PATH_UNDECLARED').map(({ message }) => message)).toEqual([ + 'Start declares no input error: its inputFormat declares none.', + ]) + expect(findings(result, 'W_JSON_REF_UNTYPED').map(({ message }) => message)).toEqual([ + expect.stringContaining(''), + ]) + expect(JSON.stringify(result.workflow?.blocks.next?.params.body)).not.toContain( + '\\"\\"' + ) + }) + it('reads a Function error output where x.error reads, and nowhere else', () => { const body = (wiring: string) => [ From 45214ceadc0bee5030fc39cd26026c391cb4636e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 04:23:31 -0800 Subject: [PATCH 2/2] fix(workflow-code): a table declaration edited since the last write types from the kept manifest in the type check's base --- .../commands/protocol/workspace-source-dir.ts | 24 ++++---- .../protocol/workspace-source-get.test.ts | 56 +++++++++++++++++++ 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index df96931e14b..94339d5287a 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -253,8 +253,10 @@ export function localDeclarations(files: Readonly>): Loca /** * What the workspace directory `root` declared as the last get or apply wrote it: the paths that - * write recorded (`written`), each folder kind's keys from them, and a root file's names only - * while its text is unchanged since; an edited one's earlier text is gone, so it declares none. + * write recorded (`written`), each folder kind's keys from them. A file `workspace.d.ts` reads + * its types from (a root file, a table's declaration) counts only while its text is unchanged + * since: an edited one's earlier text is gone, so it declares nothing, and a table it declared + * types from the kept manifest instead. */ export async function writtenLocalDeclarations( root: string, @@ -264,14 +266,16 @@ export async function writtenLocalDeclarations( for (const path of Object.keys(written.digests)) { if (kindOfPath(path) !== null) files[path] = '' } - const rootFiles = APPLY_ORDER.filter(isFileKind) - .map((kind) => KIND_DIRS[kind]) - .filter((file) => Object.hasOwn(files, file)) - const unchanged = await unchangedTexts(root, rootFiles, written.digests) - for (const file of rootFiles) { - const text = unchanged.get(file) - if (text === undefined) delete files[file] - else files[file] = text + const rootFiles = new Set(APPLY_ORDER.filter(isFileKind).map((kind) => KIND_DIRS[kind])) + const typedFrom = Object.keys(files).filter( + (path) => + rootFiles.has(path) || (kindOfPath(path) === 'table' && path.endsWith(DECLARATION_EXTENSION)) + ) + const unchanged = await unchangedTexts(root, typedFrom, written.digests) + for (const path of typedFrom) { + const text = unchanged.get(path) + if (text === undefined) delete files[path] + else if (rootFiles.has(path)) files[path] = text } return localDeclarations(files) } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 1a2bad199d3..5bc46ed3478 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -1515,6 +1515,62 @@ describe('the type check of workspaces source check', () => { } ) + it.each([ + ['a kept resource listing', true], + ['no resource listing', false], + ])("reports one a table declaration's edit caused, with %s", async (_listing, listed) => { + const table = (type: string) => + [ + '// @sim-sdk 1', + "import { column, defineTable } from '@sim/workflow-sdk/workspace'", + `export default defineTable({ name: 'leads', columns: { score: column.${type}() } })`, + '', + ].join('\n') + serve( + { + 'tables/leads.ts': table('number'), + 'workflows/save/workflow.ts': [ + '// @sim-sdk 1', + "import { table, trigger, workflow } from '@sim/workflow-sdk'", + "export default workflow('Save', {}, () => {", + " const start = trigger.start('Start', {})", + " const save = table.insertRow('Save', { tableId: table('leads'), data: { score: 5 } })", + ' start.to(save)', + '})', + '', + ].join('\n'), + }, + { + kinds: ['table', 'workflow'], + ...(listed + ? { + manifest: { + ...manifestWith('number'), + workflows: [{ key: 'save', inputs: [] }], + tables: [ + { + key: 'leads', + id: 'tbl-1', + name: 'leads', + columns: [{ name: 'score', type: 'number' }], + }, + ], + }, + } + : {}), + } + ) + await get() + writeFileSync(join(dir, 'tables/leads.ts'), table('boolean')) + + await runWorkspaceSource('check', dir) + + expect(result().diagnostics).toEqual([ + expect.objectContaining({ code: 'E_TYPE', file: 'workflows/save/workflow.ts', line: 5 }), + ]) + expect(process.exitCode).toBe(1) + }) + it.each([ ['a kept resource listing', true], ['no resource listing', false],