Skip to content

feat: Directly reply to add chart type - #8307

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_chart_type
Dec 4, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_chart_type

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: Directly reply to add chart type

return to_text(value)

def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]:
return [EchartsContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of echarts_reply.py

Potential Issues

  1. uuid_utils.compat as uuid is unusual for a standard library

    • uuid.uuid7() — confirm that the uuid_utils.compat shim actually exposes uuid7(). The stdlib uuid module (even in Python 3.12+) does not have uuid7(). If the compat layer doesn't provide it, this will fail at runtime with AttributeError.
    • Consider whether uuid_utils is a declared dependency in pyproject.toml/requirements.txt.
  2. json.dumps may raise on non-serializable values

    • If value is a dict/list containing datetime, Decimal, sets, custom objects, etc., json.dumps will throw TypeError. Given this is chart data coming from workflow variables, types like datetime are plausible.
    • Suggest a default= fallback (e.g., default=str) or wrap in try/except and fall back to to_text(value).
  3. No type annotations on method signatures

    • support(self, content_type: str) -> bool is annotated, but get_answer(self, node, value) and to_content_list(...) have untyped node, value, answer.
    • answer: str and node: Node return type List[Content] would improve readability and static checking, consistent with support.
  4. Unused import concern / coupling

    • Verify NodeInfo, Position, Status, EchartsContent, to_text are all actually needed (they appear to be). No dead imports obvious, but json is imported unconditionally even though the textual path doesn't need it (minor).
  5. Header comment inconsistency

    • Docstring says @date:2026/12/4 while the diff header shows 2026/12/4 — fine, but mixed full-width colon (:) and ASCII : in the docstring tags (@Author: vs @file:). Cosmetic consistency suggestion.
  6. Magic string "ECHARTS"

    • Repeated verbatim; if other handlers use the same pattern this is acceptable, but consider an enum/shared constant to avoid typos across handlers.
  7. to_content_list always reports Status.SUCCESS

    • Confirm this is intentional. EchartsReply producing SUCCESS regardless of input seems acceptable since rendering is client-side, but worth double-checking no error propagation is expected here.
  8. on the springboard: str(uuid.uuid7()) twice? No — called once per invocation, fine.

Optimization Suggestions

  • Add a serialization guard:
    def get_answer(self, node, value):
        if isinstance(value, (dict, list)):
            try:
                return json.dumps(value, ensure_ascii=False, default=str)
            except TypeError:
                return to_text(value)
        return to_text(value)
  • Add type hints to get_answer (value: Any -> str, node: Node), to_content_list (answer: str) to match the style used in support.
  • Optionally make the JSON serializer configurable (separators, indent) if humans may inspect raw output.
  • Consider moving the ECharts content-type literal to a shared constant.
  • Ensure uuid_utils is pinned in dependencies; alternatively use from uuid import uuid4 for broad compatibility if v7 semantics aren't required.

Overall the file is small and clean; the main risks are uuid7 availability and JSON-serialization exceptions for non-JSON-native workflow variables.

@shaohuzhang1
shaohuzhang1 merged commit 8935e04 into v3 Dec 4, 2026
3 of 4 checks passed
chunk.status or prev.status,
chunk.node_info or prev.node_info,
chunk.position or prev.position,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: EchartsAggregator

Potential Issues

1. chunk.id or prev.id — ID overwrite semantics

The aggregation picks chunk.id whenever it's truthy, which means the last chunk's id wins. If ContentAggregator downstream logic relies on stable identity (e.g., deduplication, keying), this may cause instability across chunks. If id should remain constant for the whole aggregated message, use prev.id or chunk.id. Confirm intent.

Suggestion: Make the precedence explicit and document it:

return EchartsContent(
    id=prev.id or chunk.id,          # keep original identity if id is meant to be stable
    content=(prev.content or "") + (chunk.content or ""),
    ...
)

2. Positional constructor arguments are fragile

EchartsContent(...) is called positionally, relying on field order of a dataclass/namedtuple. Any future reordering of fields silently breaks aggregation. Use keyword arguments.

3. Fields are dropped / not handled

Only id, content, status, node_info, position are aggregated. If EchartsContent has other fields (timestamps, metadata, error info, done/is_end flags), they are silently discarded from chunk. Verify all relevant fields are carried over.

4. prev is None branch returns chunk by reference

Returning the incoming chunk directly means the caller receives an object aliased with the input. If either side mutates later, state can leak. If EchartsContent is immutable (frozen dataclass / namedtuple) this is fine; otherwise consider copying.

5. status or prev.status precedence

Like id, later status wins. That's usually correct for streaming, but make sure a partial status ("running") doesn't override a terminal one ("success"). Consider explicit status-merge logic if status is an enum with severity/terminal states (e.g., never downgrade DONE → RUNNING).

6. String concatenation in a loop — O(n²) risk

If aggregate is invoked once per chunk in a stream, (prev.content or "") + (chunk.content or "") rebuilds the full buffer each time → quadratic behavior on large outputs. For typical chat payloads it's fine, but for large charts/long streams, accumulate into a list/buffer and join at the end.

Optimization: store chunks in a list and join lazily, or use ''.join in a finalizer step.

7. Docstring mentions <echarts_rander> — typo

"rander" is likely "render". Also the docstring claims "按顺序拼接内容块" (concatenate content blocks in order), which matches content handling — good, but ensure tags/separators are not required between chunks (e.g., a chunk split mid-</echarts_render> fully qualified tag boundary). Mid-tag splits just work with plain concatenation only if the tag stream itself is being reassembled here — confirm the renderer tolerates arbitrary split points.

8. Missing type hints robustness

prev: EchartsContent yet the code checks prev is None. The signature should be prev: EchartsContent | None = None (or Optional) to match reality, unless the ABC contract forbids None.

9. No regressions tests visible

No unit tests in the diff. Add coverage for: first-chunk (prev=None), empty content, mixed None status/node_info, and multi-chunk concatenation.

10. Encoding/coding declaration

# coding=utf-8 is redundant in Python 3 (UTF-8 is the default). Harmless, but could be removed for consistency with PEP 3120.

Minor / Style

  • Import ordering: application.workflow.message.aggregator... before struct... is fine, but check project isort config.
  • File header @file: uses a full-width colon (:); cosmetic inconsistency with @project: / @date:.

Summary of Recommended Changes

def aggregate(self, prev: Optional[EchartsContent], chunk: EchartsContent) -> EchartsContent:
    if prev is None:
        return chunk
    return EchartsContent(
        id=chunk.id or prev.id,
        content=(prev.content or "") + (chunk.content or ""),
        status=chunk.status or prev.status,
        node_info=chunk.node_info or prev.node_info,
        position=chunk.position or prev.position,
    )

Plus: confirm field completeness, add tests, and consider buffered concatenation for large streams.

@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_chart_type branch December 4, 2026 11:03
def to_dict(self):
result = super().to_dict()
result["content"] = self.content
return result

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's my review:

Potential Issues

  1. Inconsistent state handling: self.content is set before super().__init__(). If the parent constructor raises an exception, self.content is still partially initialized. More importantly, if the base class's to_dict() or other logic relies on a content attribute, ordering matters. Consider calling super().__init__() first, then assigning.

  2. content not validated/typed strictly: The type hint says str, but there's no validation. If callers pass None or a dict (some ECharts payloads are objects), it silently propagates. Consider validating or documenting expected format (JSON string vs. dict).

  3. Mutating shared state in to_dict: Assuming super().to_dict() returns a fresh dict this is fine, but if it ever returns a cached/shared reference, you'd be mutating it. Worth confirming the parent contract.

  4. Missing Optional/defaults: No defaults for status, node_info, position — callers must always supply them. Fine if intentional, but consider keyword-only args for readability given the positional _id, content.

  5. No __slots__ (minor): If many instances exist and the base supports it, adding __slots__ = ('content',) reduces memory.

  6. No repr/equality: Minor; depends on base class behavior.

Style/Optimization Suggestions

  • Move super().__init__() before self.content = content for safer initialization ordering.
  • Add a docstring to __init__ and to_dict explaining the content field's expected format (raw JSON string of ECharts option).
  • Consider making content a property or validating it's valid JSON if the frontend requires it.
  • The file header date/naming with full-width colon (@file:) is inconsistent — use ASCII :.
  • Add unit tests verifying to_dict() output contains both parent keys and content.

Summary: The main actionable items are the init-order concern and the lack of validation/documentation around content. Everything else is minor.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant