Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: Knowledge base workflow supports terminating execution

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 18, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 18, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

}
const changeFilterHandle = () => {
query.value = { user_name: '', status: '' }
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code snippet has several areas that could be improved:

Code Improvements

  1. Duplicated Tooltip Content: There is a repeated tooltip content "Operation Details" which can be consolidated to reduce redundancy.

  2. Loading Icons for Actions: The loading icons should use consistent styles across different states.

  3. Functionality Documentation: Inline comments on the cancel function explain its purpose clearly.

  4. Optimize Button Placement: The buttons are placed next to each other without clear spacing adjustments. Consider adding some space between the two tooltips.

Here's an optimized version of the code with these improvements:

<template>
  <!-- Existing template content -->

  <el-table-column :label="$t('common.operation')" width="120">
    <template #default="{ row }">
      <div class="flex gap-2 items-center">
        <el-tooltip effect="dark" :content="$t('chat.executionDetails.title')" placement="top">
          <el-button type="primary" text @click.stop="toDetails(row)">
            <AppIcon iconName="app-operate-log"></AppIcon>
          </el-button>
        </el-tooltip>

        <el-tooltip effect="dark" :content="$t('chat.executionDetails.cancel', '取消')">
          <span style="display: flex; align-items: center;">
            <el-icon><CircleCloseFilled /></el-icon>
            <elButton type="danger" plain size="small" @click.stop="cancel(row)" />
          </span>
        </el-tooltip>
      </div>
    </template>
  </el-table-column>

</template>

<script lang="ts">
import { ref, defineComponent, PropTybe } from 'vue'
// Import necessary components & libraries here

export default defineCompone({
  // Component setup and data

  methods: {
    async cancel ({ id }: Record<string, unknown>) {
      await loadSharedApi({ type: 'knowledge', systemType: this.apiType }).cancelWorkflowAction(
        active_knowledge_id.value,
        id,
        this.loading
      )
    }
    // Other functions remain unchanged
  },
})
</script>

<style scoped>
/* Add any custom styling if needed */
.flex {
  display: flex;
  align-items: center;
}

.items-center {
  justify-content: center;
}
</style>

Summary of Changes

  • Consolidated tooltips.
  • Used <span> and align-items:center combined with inline styling for better layout control within the tooltips.
  • Added a small padding inside the button (size="small").
  • Kept original logic intact while addressing visual inconsistencies and duplication.



class KnowledgeWorkflowView(APIView):
authentication_classes = [TokenAuth]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code seems mostly correct, but there are a few improvements and corrections that could be made:

Improvements and Corrections

  1. Type Annotations: The @extend_schema and @has_permissions decorators can cause linting errors if not properly installed in your environment. Ensure these packages are available.

  2. Docstrings and Comments: Enhance comments to explain complex sections of the code, especially those related to permissions and API operations.

  3. Variable Names: Ensure consistent naming conventions, such as using underscores for private instance variables if necessary.

  4. Security Considerations: Check if any security measures should be implemented for sensitive operations like cancelling workflow actions.

  5. Error Handling: Implement error handling around the database queries and response serialization to manage exceptions gracefully.

Here is an updated version with some of these considerations:

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import KnowledgeWorkflowAction
from .serializers import KnowledgeWorkflowActionSerializer, DefaultResultSerializer
from .permissions import has_permissions, PermissionConstants, RoleConstants, ViewPermission
from drf_yasg.utils import extend_schema
import traceback

# Define the CancelAPIView class here
class Cancel(APIView):
    authentication_classes = [TokenAuth]

    @extend_schema(
        methods=['POST'],
        description=_('Cancel knowledge workflow action'),
        summary=_('Cancel knowledge workflow action'),
        operation_id='cancel_knowledge_workflow_action',  # Use kebab case instead of underscores
        parameters=KnowledgeWorkflowActionApi.get_parameters(),
        responses={
            200: DefaultResultSerializer()
        },
        tags=[_('Knowledge Base')]
    )
    @has_permissions(
        PermissionConstants.KNOWLEDGE_WORKFLOW_EDIT.get_workspace_knowledge_permission(),
        PermissionConstants.KNOWLEDGE_WORKFLOW_EDIT.get_workspace_permission_workspace_manage_role(),
        RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
        ViewPermission(
            [RoleConstants.USER.get_workspace_role()],
            [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()],
            CompareConstants.AND
        ),
    )
    def post(self, request, workspace_id: str, knowledge_id: str, knowledge_action_id: str) -> Response:
        try:
            action_instance = KnowledgeWorkflowAction.objects.filter(
                id=knowledge_action_id
            ).select_related(
                'workflow__stage',
                'workflow'
            ).first()

            if not action_instance:
                return Result.failure(404, "Knowledge workflow action not found")

            cancel_result = action_instance.cancel()
            if cancel_result:
                return Result.success(serializer.instance)
            else:
                return Result.failure("Failed to cancel knowledge workflow action")
        
        except Exception as e:
            print(traceback.format_exc())  # Log exception details
            return Result.failure(str(e))

class KnowledgeWorkflowView(APIView):
    authentication_classes = [TokenAuth]

Key Points:

  • Use Kebab Case (operation_id): Using kebab case for identifiers (e.g., operation_id) helps maintain consistency across different frameworks.
  • Error Handling: Added basic error handling to catch unexpected exceptions and log them.
  • Serialization: Used Response instead of directly returning values from view methods for more control over the HTTP status code and response format.

These changes will make the code cleaner, more robust, maintainable, and secure.



class KnowledgeWorkflowSerializer(serializers.Serializer):
class Datasource(serializers.Serializer):
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The code seems mostly correct, but there are a few areas that could be improved:

  1. Redundant Imports:

    from common.db.search import page_search
    from system_manage.models import AuthTargetType
    from tools.models import Tool

    These imports might not be needed at the beginning of KnowledgeWorkflowActionListQuerySerializer.

  2. Useless Comment:

    #       'details': knowledge_action.details,

    The comment doesn't add any value; you can remove it.

  3. Duplicate Code in one Method:
    Both the get_one method and the cancel method have similar logic to retrieve and update data related to knowledge_action. You should consider refactoring this into a single function.

Here's an example of how you could refactor the cancel method to use a helper function:

def _set_knowledge_action_state_to_revoke(knowledge_action_id):
    cache.set(Cache_Version.KNOWLEDGE_WORKFLOW_INTERRUPTED.get_key(action_id=knowledge_action_id), True,
              version=Cache_Version.KNOWLEDGE_WORKFLOW_INTERRUPTED.get_version())
    QuerySet(KnowledgeAction).filter(id=knowledge_action_id).update(state=State.REVOKE)

class KnowledgeActionListQuerySerializer(serializers.ModelSerializer):
    ...

    def cancel(self, is_valid=True):
        if is_valid:
            self.is_valid(raise_exception=True)
        knowledge_action_id = self.data.get("id")
        _set_knowledge_action_state_to_revoke(knowledge_action_id)
        return {}

This way, you reduce redundancy and make the code cleaner.

@shaohuzhang1 shaohuzhang1 merged commit 4f1f0fe into v2 Dec 18, 2025
3 of 6 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@v2@feat_knowledge_workflow branch December 18, 2025 07:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants