Skip to content

refactor(export): optimize shared task context queries and remove dead code - #2198

Merged
qdaxb merged 8 commits into
wecode-ai:mainfrom
sunnights:fix/hide-kb-context-from-public-outputs
Jul 27, 2026
Merged

qdaxb merged 8 commits into
wecode-ai:mainfrom
sunnights:fix/hide-kb-context-from-public-outputs

Conversation

@sunnights

@sunnights sunnights commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Changes

    • Chat exports no longer include knowledge-base information or related UI indicators.
    • Publicly shared task details now exclude knowledge-base contexts while still including supported attachments and other context types.
    • PDF export rendering has been streamlined to omit knowledge-base cards.
  • Improvements

    • Enhanced export flow messaging with clearer “preparing export” status, font-loading failure feedback, and a retry prompt.
  • Tests

    • Added/updated tests to confirm knowledge-base contexts are filtered out of public shared task responses.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f90fbf8c-38f8-426f-aa69-60f9c3be7338

📥 Commits

Reviewing files that changed from the base of the PR and between f576429 and 35ad221.

📒 Files selected for processing (1)
  • backend/app/services/shared_task.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/app/services/shared_task.py

📝 Walkthrough

Walkthrough

The PR excludes knowledge-base contexts from public shared-task responses and PDF exports, batch-loads remaining contexts, removes PDF knowledge-base rendering and related UI types, and adds coverage for attachment-only serialization. It also adds explicit None return annotations to DOCX-related functions and tests.

Changes

Context and export behavior

Layer / File(s) Summary
Public shared-task context filtering
backend/app/services/shared_task.py, backend/tests/services/test_shared_task_prompt_sanitization.py
Public shared-task retrieval batch-loads non-knowledge-base contexts and tests that attachment contexts remain while knowledge-base contexts are omitted.
PDF export payload contracts
frontend/src/utils/pdf/types.ts, frontend/src/utils/pdf/index.ts, frontend/src/features/tasks/components/share/ExportSelectModal.tsx, frontend/src/i18n/locales/*/chat.json
PDF and selectable message payloads no longer include knowledge-base data, the selection indicator is removed, and export locale strings no longer define the knowledge-base count label.
PDF message rendering cleanup
frontend/src/utils/pdf/renderers/message.ts
Knowledge-base card helpers and their rendering calls are removed for both user and AI messages.

Explicit return annotations

Layer / File(s) Summary
DOCX return annotations
backend/app/services/export/docx_generator.py, backend/tests/services/test_docx_generator_fonts.py, backend/tests/services/test_docx_generator_prompt_sanitization.py
The DOCX header helper and related tests now explicitly declare None return types.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • wecode-ai/Wegent#2187: Changes the same public shared-task context path to exclude knowledge-base contexts and updates corresponding tests.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: shared task query optimization and removal of export-related dead code.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
backend/app/services/export/docx_generator.py (1)

151-151: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add -> None return annotations to new functions.

  • backend/app/services/export/docx_generator.py#L151-L151: annotate _add_document_header.
  • backend/tests/services/test_docx_generator_fonts.py#L32-L32: annotate test_normal_style_defines_latin_and_east_asian_fonts.
  • backend/tests/services/test_docx_generator_fonts.py#L50-L50: annotate test_inline_code_uses_monospace_latin_and_document_cjk_font.
  • backend/tests/services/test_docx_generator_prompt_sanitization.py#L77-L77: annotate test_knowledge_base_context_not_written_to_document.

As per coding guidelines, Python code must use type hints.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/export/docx_generator.py` at line 151, Add explicit ->
None return annotations to _add_document_header and the three listed test
functions: test_normal_style_defines_latin_and_east_asian_fonts and
test_inline_code_uses_monospace_latin_and_document_cjk_font in
backend/tests/services/test_docx_generator_fonts.py, and
test_knowledge_base_context_not_written_to_document in
backend/tests/services/test_docx_generator_prompt_sanitization.py.

Source: Coding guidelines

backend/app/services/shared_task.py (1)

828-838: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider batching the per-subtask context query.

This query runs once per subtask inside the loop (N+1), on a public/unauthenticated endpoint. The function already batches user lookups via sender_ids/user_name_map a few lines above (Lines 815-825) — the same pattern (single IN query + group by subtask_id) could be applied here to avoid repeated round-trips as subtask counts grow.

♻️ Sketch of batched context fetch
+        subtask_ids = [sub.id for sub in subtasks]
+        contexts_by_subtask: dict[int, list] = {}
+        if subtask_ids:
+            all_contexts = (
+                db.query(SubtaskContext)
+                .filter(
+                    SubtaskContext.subtask_id.in_(subtask_ids),
+                    SubtaskContext.context_type != ContextType.KNOWLEDGE_BASE.value,
+                )
+                .all()
+            )
+            for ctx in all_contexts:
+                contexts_by_subtask.setdefault(ctx.subtask_id, []).append(ctx)
+
         for sub in subtasks:
-            # Knowledge base contexts are runtime metadata and are not public.
-            contexts = (
-                db.query(SubtaskContext)
-                .filter(
-                    SubtaskContext.subtask_id == sub.id,
-                    SubtaskContext.context_type != ContextType.KNOWLEDGE_BASE.value,
-                )
-                .all()
-            )
+            contexts = contexts_by_subtask.get(sub.id, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/shared_task.py` around lines 828 - 838, Replace the
per-subtask SubtaskContext query inside the public_subtasks loop with one
batched query using all subtask IDs and the existing knowledge-base exclusion,
then group the fetched contexts by subtask_id and reuse that mapping while
constructing public_subtasks. Preserve the current behavior for subtasks with no
matching contexts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/tests/services/test_shared_task_prompt_sanitization.py`:
- Around line 121-174: Update
test_keeps_attachments_and_filters_knowledge_base_contexts so the SubtaskContext
records reference a persisted Subtask row, using the mock subtask’s actual
persisted identifier when available. Ensure the test database flush succeeds
with foreign-key enforcement enabled while preserving the existing attachment
and knowledge-base context assertions.

---

Nitpick comments:
In `@backend/app/services/export/docx_generator.py`:
- Line 151: Add explicit -> None return annotations to _add_document_header and
the three listed test functions:
test_normal_style_defines_latin_and_east_asian_fonts and
test_inline_code_uses_monospace_latin_and_document_cjk_font in
backend/tests/services/test_docx_generator_fonts.py, and
test_knowledge_base_context_not_written_to_document in
backend/tests/services/test_docx_generator_prompt_sanitization.py.

In `@backend/app/services/shared_task.py`:
- Around line 828-838: Replace the per-subtask SubtaskContext query inside the
public_subtasks loop with one batched query using all subtask IDs and the
existing knowledge-base exclusion, then group the fetched contexts by subtask_id
and reuse that mapping while constructing public_subtasks. Preserve the current
behavior for subtasks with no matching contexts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 36689d34-62ed-4620-b28b-f580e4d79cbb

📥 Commits

Reviewing files that changed from the base of the PR and between af997cf and 6f0f7ab.

📒 Files selected for processing (12)
  • backend/app/services/export/docx_generator.py
  • backend/app/services/shared_task.py
  • backend/tests/services/test_docx_generator_fonts.py
  • backend/tests/services/test_docx_generator_prompt_sanitization.py
  • backend/tests/services/test_shared_task_prompt_sanitization.py
  • frontend/src/features/tasks/components/message/MessagesArea.tsx
  • frontend/src/features/tasks/components/share/ExportSelectModal.tsx
  • frontend/src/i18n/locales/en/chat.json
  • frontend/src/i18n/locales/zh-CN/chat.json
  • frontend/src/utils/pdf/index.ts
  • frontend/src/utils/pdf/renderers/message.ts
  • frontend/src/utils/pdf/types.ts
💤 Files with no reviewable changes (4)
  • frontend/src/utils/pdf/index.ts
  • frontend/src/i18n/locales/en/chat.json
  • frontend/src/i18n/locales/zh-CN/chat.json
  • frontend/src/utils/pdf/types.ts

@sunnights sunnights changed the title Fix/hide kb context from public outputs refactor(export): 清理知识库导出死代码 Jul 24, 2026
@sunnights sunnights changed the title refactor(export): 清理知识库导出死代码 refactor(export): Optimize shared task context queries and remove dead code Jul 24, 2026
@sunnights sunnights changed the title refactor(export): Optimize shared task context queries and remove dead code refactor(export): optimize shared task context queries and remove dead code Jul 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/app/services/shared_task.py`:
- Line 827: Update the type annotation for contexts_by_subtask_id in the
surrounding task-processing function so Dict is defined before use: import Dict
from typing, or replace it with the supported built-in generic syntax. Ensure
the module no longer triggers Ruff F821.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 30eeff89-1797-464b-9fc9-73253da5adaf

📥 Commits

Reviewing files that changed from the base of the PR and between 6f0f7ab and f576429.

📒 Files selected for processing (5)
  • backend/app/services/export/docx_generator.py
  • backend/app/services/shared_task.py
  • backend/tests/services/test_docx_generator_fonts.py
  • backend/tests/services/test_docx_generator_prompt_sanitization.py
  • backend/tests/services/test_shared_task_prompt_sanitization.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/tests/services/test_docx_generator_fonts.py
  • backend/tests/services/test_shared_task_prompt_sanitization.py

Comment thread backend/app/services/shared_task.py Resolved
@qdaxb
qdaxb merged commit d2d6fa0 into wecode-ai:main Jul 27, 2026
27 checks passed
duzeng pushed a commit to duzeng/Wegent that referenced this pull request Jul 27, 2026
…d code (wecode-ai#2198)

* fix(export): 隐藏导出和公开分享中的知识库上下文

* fix(export): 统一 DOCX 中英文导出字体

* refactor(export): 清理 PDF 知识库导出死代码

* fix(export): 完善公开分享知识库上下文过滤

* refactor(export): 优化公开分享上下文查询

* fix(export): 修复公开分享上下文类型注解

---------

Co-authored-by: axb <qindi@staff.weibo.com>
cocowh added a commit to cocowh/Wegent that referenced this pull request Aug 4, 2026
Resolve conflicts between the DingTalk external-knowledge feature and
upstream capability/permission refactors (wecode-ai#2311, wecode-ai#2348, wecode-ai#2285, wecode-ai#2198).

Co-Authored-By: Claude <noreply@anthropic.com>
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.

2 participants