Skip to content

[Bug] Code node: extractFunctionParams mis-parses destructured JavaScript params (the node's own default template) and multi-line signatures #44045

Closed

Description

@Yueliup

Self Checks

  • I have read the Contributing Guide and Language Policy.
  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.

Dify version

1.17.1 (web/package.json), reproduced on main @ c64d906

Cloud or Self Hosted

Cloud, Self Hosted (Source)

Steps to reproduce

extractFunctionParams in web/app/components/workflow/nodes/code/code-parser.ts is the only thing that derives the Code node's input variable list from the user's code. Its single production caller is web/app/components/workflow/nodes/code/panel.tsx:

// panel.tsx
const handleGeneratedCode = (value: string) => {
  const params = extractFunctionParams(value, inputs.code_language)
  const codeNewInput = params.map((p) => ({ variable: p, value_selector: [] }))
  const returnTypes = extractReturnType(value, inputs.code_language)
  handleCodeAndVarsChange(value, codeNewInput, returnTypes)
}

handleGeneratedCode is the editor's onGenerated callback, so it runs whenever the user applies AI-generated / AI-modified code in the Code node panel (CodeEditor → Base → CodeGeneratorButton → GetCodeGeneratorResModal.onFinished → onGenerated(res.modified)). Note that the "modify" branch on the backend (LLM_MODIFY_CODE_SYSTEM in api/core/llm_generator/prompts.py, reached from instruction_modify_workflow whenever current != code_template) sends the user's own code to the model and returns it back with only the requested change — so whatever signature the user wrote is preserved and then re-parsed here.

Two legitimate main signature shapes are mis-parsed:

1. Destructured JavaScript parameters. The JavaScript Code node's own default template is destructured — api/core/helper/code_executor/javascript/javascript_code_provider.py:

@classmethod
@override
def get_default_code(cls) -> str:
    return dedent(
        """
        function main({arg1, arg2}) {
            return {
                result: arg1 + arg2
            }
        }
        """
    )

This is not a stylistic choice: api/core/helper/code_executor/javascript/javascript_transformer.py runs the user code with

var output_obj = main(inputs_obj)

i.e. a single object argument, so destructuring is the required form in JavaScript. The panel itself agrees — use-config.ts (handleSyncFunctionSignature) writes function main({...}), and the existing fixtures in __tests__/use-config.spec.ts and __tests__/panel.spec.tsx all use function main({ foo }).

2. Multi-line parameter lists, e.g. a formatted Python signature:

def main(
    arg1: str,
    arg2: str,
) -> dict:
    return {"result": arg1}

Standalone reproduction with Node 22 (function body copied verbatim from main):

FAIL  JS default template (destructured)
      expected: [arg1, arg2]
      actual  : [{arg1, arg2}]
PASS  Python default template
PASS  JS single-line, plain params
FAIL  Python multi-line signature
      expected: [arg1, arg2]
      actual  : []
FAIL  JS multi-line signature
      expected: [arg1, arg2]
      actual  : []

3 failing case(s)

Root cause in code-parser.ts:

const patterns: Record<Exclude<CodeLanguage, typeof CodeLanguage.json>, RegExp> = {
  [CodeLanguage.python3]: /def\s+main\s*\((.*?)\)/,
  [CodeLanguage.javascript]: /function\s+main\s*\((.*?)\)/,
}
  • (.*?) cannot match a newline (there is no s flag), so any signature that wraps yields [].
  • Even on a single line, the captured group is never unwrapped from the destructuring braces, so {arg1, arg2} is split into {arg1 and arg2}.

✔️ Expected Behavior

extractFunctionParams should return ['arg1', 'arg2'] for the Code node's own JavaScript default template, and ['arg1', 'arg2'] for a multi-line signature, in both languages. Existing single-line behaviour must not change.

A minimal fix is to allow newlines in the capture and to strip one surrounding destructuring brace pair:

const patterns: Record<Exclude<CodeLanguage, typeof CodeLanguage.json>, RegExp> = {
  [CodeLanguage.python3]: /def\s+main\s*\(([\s\S]*?)\)/,
  [CodeLanguage.javascript]: /function\s+main\s*\(([\s\S]*?)\)/,
}
// ...
if (match?.[1]) {
  // The JavaScript `main` is invoked as `main(inputs_obj)`, so its parameters are
  // usually written as a single destructuring pattern: `function main({ arg1, arg2 })`.
  const rawParams = match[1].trim().replace(/^\{([\s\S]*)\}$/, '$1')
  // ...then split/filter as before
}

❌ Actual Behavior

  • Destructured JavaScript parameters (function main({arg1, arg2}) — the shape the Code node ships with): extractFunctionParams returns ['{arg1', 'arg2}'], and those two malformed strings are written straight into the node's input variables by handleCodeAndVarsChange, replacing the correct arg1 / arg2 entries. The input-variable list then shows {arg1 and arg2}, and the variable-to-value mapping for the node is broken.
  • Multi-line signatures (either language): extractFunctionParams returns []. Because handleCodeAndVarsChange assigns draft.variables = codeNewInput unconditionally, the node's existing input variables are silently deleted when the AI-modified code is applied.
  • Neither case is covered by __tests__/code-parser.spec.ts: SAMPLE_CODES contains no multi-line signature sample and no destructured-parameter sample, which is why this went unnoticed.

Activity

  1. added
    review: low
    on Oct 14, 2026
  2. dosubot commented on Oct 14, 2026

    @dosubot

    Hi @Yueliup! I'm Dosu and I'm helping the Dify team.

    One additional detail for triage: applying AI-generated code rebuilds every input with value_selector: [], even when parameter parsing succeeds. The handler then replaces both the input list and output definitions. Correct parameter names alone therefore do not preserve existing upstream bindings. [1] [2]

    As a temporary workaround, edit or paste code directly into the editor rather than applying it through the AI-generation flow. Ordinary editor changes use handleCodeChange, which updates only draft.code, leaving input and output configuration intact. If the inputs have already been replaced, restore their names and upstream selections in the input-variable list. [3] [4] [5]

    Keep the JavaScript object-argument signature when doing this. Switching to positional parameters to satisfy the parser would not match the runner, which calls main(inputs_obj). [6]

    To reply, just mention @dosu.


    Share context across your team and agents. Try Dosu.

    Leave Feedback Learn about dify with Dosu

  3. Yueliup commented on Oct 14, 2026

    @Yueliup
    ContributorAuthor

    Thanks @dosubot — that is correct and worth separating out.

    Scope of #44046: the parser. extractFunctionParams could not read two legitimate main signatures, so it produced ['{arg1', 'arg2}'] for the JavaScript default template and [] for any wrapped signature. That is a self-contained defect with a clear expected value, and the PR fixes it plus adds regression cases.

    The point you raise is a different defect on a different line: handleGeneratedCode in panel.tsx builds every regenerated input with value_selector: [], so upstream bindings are dropped even when the parameter names are parsed correctly. Fixing that means deciding what should happen to a selector when a parameter survives regeneration (keep it) versus when it disappears or changes type (drop it), which is a behaviour change rather than a parsing fix — so it is deliberately left out of this PR to keep the diff reviewable.

    Tracked as a follow-up rather than silently bundled: if a maintainer would prefer both in one change, I am happy to extend #44046 instead.

    One note on the workaround for anyone reading this later: keeping the object-argument form is not just a parser convenience — javascript_transformer.py calls main(inputs_obj), so a positional function main(arg1, arg2) does not receive the node's inputs at all. The destructured form is the only correct JavaScript signature, which is why the parser has to accept it rather than the other way round.

  4. dosubot commented on Oct 14, 2026

    @dosubot

    Thanks for clarifying. The parser and selector-preservation concerns are separate: handleGeneratedCode creates empty selectors independently of parameter extraction, so correcting the parsed names does not preserve bindings. My earlier note was a follow-up concern, not a reason to expand your parser PR. [1]

    One precision for future readers: the runner requires a single-object argument contract, not destructuring specifically. function main(inputs) can also work by reading inputs.arg1 and inputs.arg2. With function main(arg1, arg2), the first parameter receives the entire inputs object and the second receives undefined, not the two configured values. The shipped destructured signature should remain supported. [2]

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about dify

  5. Stream29 commented on Oct 15, 2026

    @Stream29
    Contributor

    Reproduced both cases via Generate → Apply → Confirm on self-hosted Dify 1.17.1:

    • JavaScript function main({arg1, arg2}) produced input names {arg1 and arg2}.
    • Wrapping a Python signature with the same two parameters across multiple lines removed both inputs (variables: []).

    Both were visible in the editor and persisted in the autosaved draft.

    I stubbed only the generator response with valid code; parsing, Apply and persistence were unchanged.

    Screenshots

    JavaScript — after Apply

    JavaScript — after Apply

    Python multiline signature — after Apply

    Python multiline signature — after Apply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    review: low

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions