Repository navigation
feat: Workflow supports file type output #8301
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+2,917
−104
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from types import SimpleNamespace | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| from django.test import SimpleTestCase | ||
|
|
||
| from application.workflow.content_type import ContentType | ||
| from application.workflow.message.aggregator.aggregation_manager import AggregationManager | ||
| from application.workflow.message.struct.file_content import FileContent | ||
| from application.workflow.nodes.reply_node.handle.impl.file_reply import to_file_id_list | ||
| from application.workflow.nodes.reply_node.reply_node import ReplyNode, get_reply_handle | ||
| from application.workflow.status import Status | ||
| from common.exception.app_exception import AppUnauthorizedFailed | ||
|
|
||
| FILE_A = "019a0000-0000-7000-8000-0000000000a1" | ||
| FILE_B = "019a0000-0000-7000-8000-0000000000b1" | ||
| WORKFLOW_PARAMS = {"root_user_id": "019a0000-0000-7000-8000-0000000000aa"} | ||
|
|
||
|
|
||
| def _reply_node(node_params, reference_value=None): | ||
| node = ReplyNode.__new__(ReplyNode) | ||
| node.data = {} | ||
| node.context = {} | ||
| node.workflow_manage = MagicMock() | ||
| node.workflow_manage.get_reference_field.return_value = reference_value | ||
| node.workflow_manage.generate_prompt.side_effect = lambda prompt: prompt | ||
| node.get_parameters = lambda: node_params | ||
| node.get_workflow_parameters = lambda: WORKFLOW_PARAMS | ||
| node.get_node_id = lambda: "reply" | ||
| node.get_node_name = lambda: "Reply" | ||
| node.write_context = lambda key, value: node.context.__setitem__(key, value) | ||
| return node | ||
|
|
||
|
|
||
| def _stored_file(file_id): | ||
| return SimpleNamespace(id=file_id, file_name=f"{file_id[-2:]}.png", file_size=10) | ||
|
|
||
|
|
||
| class FileIdListTest(SimpleTestCase): | ||
| def test_accepts_file_objects_urls_and_ids_in_order_without_duplicates(self): | ||
| value = [{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"url": f"./oss/file/{FILE_B}"}, FILE_A] | ||
| self.assertEqual(to_file_id_list(value), [FILE_A, FILE_B]) | ||
|
|
||
| def test_accepts_rendered_text(self): | ||
| self.assertEqual(to_file_id_list(str([{"file_id": FILE_A}])), [FILE_A]) | ||
| self.assertEqual(to_file_id_list(f'["{FILE_A}", "{FILE_B}"]'), [FILE_A, FILE_B]) | ||
| self.assertEqual(to_file_id_list(f"{FILE_A}, ./oss/file/{FILE_B}"), [FILE_A, FILE_B]) | ||
|
|
||
| def test_empty_values(self): | ||
| self.assertEqual(to_file_id_list(None), []) | ||
| self.assertEqual(to_file_id_list(""), []) | ||
| self.assertEqual(to_file_id_list([{"name": "no-id"}]), []) | ||
|
|
||
|
|
||
| class ReplyFileTest(SimpleTestCase): | ||
| def test_unknown_content_type_falls_back_to_text(self): | ||
| self.assertTrue(get_reply_handle("UNKNOWN").support("TEXT")) | ||
|
|
||
| @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") | ||
| def test_file_reply_reads_metadata_from_authorized_files(self, get_authorized_file): | ||
| get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id) | ||
| node = _reply_node( | ||
| {"reply_type": "referencing", "fields": ["image", "image"], "content_type": "FILE", "is_result": True}, | ||
| reference_value=[{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"file_id": FILE_B}], | ||
| ) | ||
| node.execute() | ||
|
|
||
| self.assertEqual( | ||
| [call.args for call in get_authorized_file.call_args_list], | ||
| [(FILE_A, WORKFLOW_PARAMS), (FILE_B, WORKFLOW_PARAMS)], | ||
| ) | ||
| expected = [ | ||
| {"file_id": FILE_A, "name": "a1.png", "url": f"./oss/file/{FILE_A}", "size": 10}, | ||
| {"file_id": FILE_B, "name": "b1.png", "url": f"./oss/file/{FILE_B}", "size": 10}, | ||
| ] | ||
| self.assertEqual(node.context["answer"], expected) | ||
| (message,) = [call.args[0] for call in node.workflow_manage.write.call_args_list] | ||
| self.assertIsInstance(message, FileContent) | ||
| self.assertEqual(message.to_dict()["file_list"], expected) | ||
|
|
||
| @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") | ||
| def test_file_reply_rejects_unauthorized_file(self, get_authorized_file): | ||
| get_authorized_file.side_effect = AppUnauthorizedFailed(403, "No permission to access") | ||
| node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": True}) | ||
| with self.assertRaises(AppUnauthorizedFailed): | ||
| node.execute() | ||
| node.workflow_manage.write.assert_not_called() | ||
|
|
||
| @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") | ||
| def test_file_reply_hidden_when_not_result(self, get_authorized_file): | ||
| get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id) | ||
| node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": False}) | ||
| node.execute() | ||
| self.assertEqual(len(node.context["answer"]), 1) | ||
| node.workflow_manage.write.assert_not_called() | ||
|
|
||
| def test_file_contents_aggregate_by_id(self): | ||
| manager = AggregationManager() | ||
| manager.aggregate(FileContent("1", [{"file_id": FILE_A, "name": "a.png"}], Status.RUNNING, None, None)) | ||
| manager.aggregate( | ||
| FileContent( | ||
| "1", | ||
| [{"file_id": FILE_B, "name": "b.pdf"}, {"file_id": FILE_A, "name": "a2.png"}], | ||
| Status.SUCCESS, | ||
| None, | ||
| None, | ||
| ) | ||
| ) | ||
| (content,) = manager.get_contents() | ||
| self.assertEqual(content["type"], ContentType.FILE.value) | ||
| self.assertEqual(content["status"], Status.SUCCESS.value) | ||
| self.assertEqual([file["name"] for file in content["file_list"]], ["a2.png", "b.pdf"]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
apps/application/workflow/message/aggregator/impl/file_aggregator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| # coding=utf-8 | ||
| """ | ||
| @project: MaxKB | ||
| @file: file_aggregator.py | ||
| @date:2026/12/4 | ||
| @desc: FileContent 聚合器 | ||
| """ | ||
|
|
||
| from application.workflow.message.aggregator.content_aggregator import ContentAggregator | ||
| from application.workflow.message.struct.file_content import FileContent | ||
|
|
||
|
|
||
| def _file_key(file: dict): | ||
| return file.get("file_id") or file.get("url") | ||
|
|
||
|
|
||
| class FileAggregator(ContentAggregator[FileContent]): | ||
| """ | ||
| 文件内容聚合器 | ||
| 按顺序追加文件,file_id(无则 url)相同的文件后到覆盖先到 | ||
| """ | ||
|
|
||
| def aggregate(self, prev: FileContent, chunk: FileContent) -> FileContent: | ||
| if prev is None: | ||
| return chunk | ||
| file_list = list(prev.file_list) | ||
| key_to_index = {_file_key(file): index for index, file in enumerate(file_list) if _file_key(file)} | ||
| for file in chunk.file_list: | ||
| key = _file_key(file) | ||
| if key and key in key_to_index: | ||
| file_list[key_to_index[key]] = file | ||
| else: | ||
| if key: | ||
| key_to_index[key] = len(file_list) | ||
| file_list.append(file) | ||
| result = FileContent(prev.id, file_list, prev.status, prev.node_info, prev.position) | ||
| self.merge_base_fields(prev, chunk, result) | ||
| return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # coding=utf-8 | ||
| """ | ||
| @project: MaxKB | ||
| @Author:虎虎 | ||
| @file: file_content.py | ||
| @date:2026/12/4 | ||
| @desc: 文件内容,前端按文件类型渲染(图片预览、音视频播放、其他文件下载) | ||
| """ | ||
|
|
||
| from typing import Dict, List, Optional | ||
|
|
||
| from application.workflow.content_type import ContentType | ||
| from application.workflow.message.struct.content import Content, NodeInfo, Position | ||
| from application.workflow.status import Status | ||
|
|
||
|
|
||
| class FileContent(Content): | ||
| """ | ||
| file_list 中每一项: | ||
| file_id: 文件 id | ||
| name: 文件名(前端据扩展名决定图标与渲染方式) | ||
| url: 访问地址 | ||
| size: 文件大小(字节,可选) | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| _id, | ||
| file_list: Optional[List[Dict]], | ||
| status: Status, | ||
| node_info: NodeInfo, | ||
| position: Position, | ||
| **kwargs, | ||
| ): | ||
| self.file_list = list(file_list or []) | ||
| super().__init__(_id, status, ContentType.FILE, node_info, position, **kwargs) | ||
|
|
||
| def to_dict(self): | ||
| result = super().to_dict() | ||
| result["file_list"] = self.file_list | ||
| return result |
Empty file.
Empty file.
98 changes: 98 additions & 0 deletions
98
apps/application/workflow/nodes/reply_node/handle/impl/file_reply.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| # coding=utf-8 | ||
| """ | ||
| @project: MaxKB | ||
| @Author:虎虎 | ||
| @file: file_reply.py | ||
| @date:2026/12/4 | ||
| @desc: 文件回复:按 file_id 鉴权后从文件表取文件名与大小,前端按扩展名渲染 | ||
| """ | ||
|
|
||
| import ast | ||
| import json | ||
| import re | ||
| from typing import List | ||
|
|
||
| import uuid_utils.compat as uuid | ||
|
|
||
| from application.workflow.file_access import get_authorized_file | ||
| from application.workflow.message.struct.content import Content, NodeInfo, Position | ||
| from application.workflow.message.struct.file_content import FileContent | ||
| from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle | ||
| from application.workflow.status import Status | ||
|
|
||
| OSS_FILE_PREFIX = "/oss/file/" | ||
|
|
||
|
|
||
| def _parse_text(text: str): | ||
| """回复文本可能是 JSON、Python 字面量(模板渲染列表/字典)或以逗号、空白分隔的 file_id / 文件地址""" | ||
| text = text.strip() | ||
| if not text: | ||
| return [] | ||
| for parse in (json.loads, ast.literal_eval): | ||
| try: | ||
| parsed = parse(text) | ||
| except (ValueError, SyntaxError): | ||
| continue | ||
| if not isinstance(parsed, str): | ||
| return parsed | ||
| return [token for token in re.split(r"[\s,]+", text) if token] | ||
|
|
||
|
|
||
| def _token_to_file_id(token: str): | ||
| token = token.strip() | ||
| if OSS_FILE_PREFIX in token: | ||
| token = token.split(OSS_FILE_PREFIX, 1)[1].split("?", 1)[0].split("/", 1)[0] | ||
| return token or None | ||
|
|
||
|
|
||
| def to_file_id_list(value): | ||
| """ | ||
| 把回复值归一化为 file_id 列表(保持顺序、去重)。 | ||
| 支持 file_id、./oss/file/{file_id} 地址、带 file_id/url 的文件对象,以及它们组成的列表或其文本形式。 | ||
| """ | ||
| file_id_list = [] | ||
|
|
||
| def collect(item): | ||
| if item is None: | ||
| return | ||
| if isinstance(item, (list, tuple)): | ||
| for child in item: | ||
| collect(child) | ||
| elif isinstance(item, dict): | ||
| if item.get("file_id"): | ||
| collect(str(item.get("file_id"))) | ||
| elif isinstance(item.get("url"), str): | ||
| collect(item.get("url")) | ||
| elif isinstance(item, str): | ||
| file_id = _token_to_file_id(item) | ||
| if file_id and file_id not in file_id_list: | ||
| file_id_list.append(file_id) | ||
|
|
||
| collect(_parse_text(value) if isinstance(value, str) else value) | ||
| return file_id_list | ||
|
|
||
|
|
||
| class FileReply(ReplyBaseHandle): | ||
| def support(self, content_type: str) -> bool: | ||
| return content_type == "FILE" | ||
|
|
||
| def get_answer(self, node, value): | ||
| workflow_params = node.get_workflow_parameters() | ||
| file_list = [] | ||
| for file_id in to_file_id_list(value): | ||
| # 与图片理解等节点一致:只允许发起者本人或根资源的文件,无权限直接拒绝 | ||
| file = get_authorized_file(file_id, workflow_params) | ||
| file_list.append( | ||
| { | ||
| "file_id": str(file.id), | ||
| "name": file.file_name, | ||
| "url": f"./oss/file/{file.id}", | ||
| "size": file.file_size, | ||
| } | ||
| ) | ||
| return file_list | ||
|
|
||
| def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: | ||
| if not answer: | ||
| return [] | ||
| return [FileContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Overall, the tests are clear and mostly well-isolated. I do not see syntax errors or obvious failing assertions, but there are several brittleness/coverage/security-adjacent concerns.
Potential issues
String vs enum inconsistency
Elsewhere the code uses
ContentType.FILE.value, implyingContentTypeis an enum. Ifsupport()expects aContentType, passing"TEXT"may be incorrect or only work accidentally. Prefer:or use
ContentType.TEXTconsistently depending on the API contract.The test encourages overly permissive text parsing
This requires support for Python
repr-style input in addition to JSON and comma-separated IDs. If the implementation useseval, that is a security problem. Even withast.literal_eval, it broadens the accepted format unnecessarily.evalis used.Brittle extraction of the written message
This implicitly assumes exactly one positional call. Use:
This gives clearer failure messages.
Manual
ReplyNode.__new__construction is brittleThis bypasses
__init__and will break ifReplyNodegains required attributes or initialization logic. Consider a small factory using mocks, or at least keep all required attributes in one place and assert they exist.get_authorized_fileside effect is signature-sensitiveIf production code later calls it with keyword arguments or extra arguments, the test fails for an uninteresting reason. Prefer:
Alternatively keep the strict signature if that is intentionally part of the contract.
Global mutable
WORKFLOW_PARAMSIf production code mutates the dict, tests can leak state. Return a copy from
get_workflow_parameters:or use an immutable mapping.
Incomplete failure-path assertions
In
test_file_reply_rejects_unauthorized_file, you assert thatwritewas not called, but not that no partial context was written. If authorization fails after adding one file, you could leak partial state. Add:or assert the expected empty/unchanged state.
Weak assertion in
test_file_reply_hidden_when_not_resultThis does not verify content or hidden behavior. Assert the exact answer and that
writewas not called. Also consider testing an empty file list foris_result=False.Aggregation order assumption may be brittle
This assumes that replacing an existing
file_idpreserves its original position. If that is a required contract, keep it; otherwise assert on a set or document the ordering requirement.Missing edge cases
Useful additions:
is_result=True.file_id.root_user_idor invalid workflow params.Minor optimization suggestions
@patch(...)onReplyFileTestto avoid repeating the decorator.test_accepts_rendered_text, usesubTestfor each format so failures identify the exact format.test_file_contents_aggregate_by_idinto a separateFileContentAggregationTestclass since it does not testReplyNode.assertTrue(get_reply_handle("UNKNOWN").support(...))with an assertion on the handler type if the fallback behavior is the real intent.No blocking issue is apparent, but I would prioritize the enum/string consistency, the overly broad text parsing test, and stronger failure-path assertions.