Skip to content

feat(go-api): Implement BulkDeleteChats Go API and fix ListChats - #16157

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat-delete-chat-clean
Jun 22, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat-delete-chat-clean

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Description

  • Bulk Delete Chats: Implemented Go endpoint DELETE /api/v1/chats supporting bulk delete by ids, delete_all flag, and backward-compatible chat_id body payload (with tenant-ownership security checks).
  • Bug Fix: Fixed a parameter swap in Go ListChats handler to properly exclude soft-deleted chats.

Verification & Testing

  • Verified API behavioral parity with Python using manual curl tests.
  • Successfully ran and passed backend unit tests:
    • internal/handler/chat_test.go
    • internal/service/chat_delete_test.go

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 17, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 17, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 17, 2026 10:57
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 17, 2026 10:57
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Two new HTTP DELETE endpoints and their backing service methods are added for soft-deleting chats. The service enforces ownership via tenant ID matching, deduplicates IDs in batch operations, supports a delete_all flag to expand to all user-owned chats, and returns partial-success payloads with error tracking. The handler layer maps authorization errors to a specific response code while other errors map to a data-error code. Tests cover both service and handler layers using in-memory SQLite.

Changes

Chat soft-delete (single and bulk)

Layer / File(s) Summary
Service contracts and deletion logic
internal/service/chat.go, internal/service/chat_delete_test.go
BulkDeleteChatsRequest struct and checkDuplicateChatIDs dedup helper are defined. getOwnedValidChat enforces ownership by matching chat tenant ID to user ID and validating status is "valid". DeleteChat soft-deletes a single owned chat by setting status to "invalid", returning a "no authorization" error when the user does not own the chat. BulkDeleteChats expands delete_all to fetch all valid chats for the user, deduplicates IDs, and attempts deletion with per-item error tracking and combined success/error response. Service tests assert non-owner rejection with unchanged status, tenant isolation under DeleteAll, and partial-success/error reporting for duplicate and missing IDs.
HTTP handlers and router wiring
internal/router/router.go, internal/handler/chat.go, internal/handler/chat_test.go
Two DELETE routes are registered: DELETE /api/v1/chats for bulk deletion and DELETE /api/v1/chats/:chat_id for single deletion. DeleteChat handler validates chat_id and maps a "no authorization" error string to CodeAuthenticationError; all other errors map to CodeDataError. BulkDeleteChats handler handles empty/missing request body with early success exit, provides a single-delete fallback when ChatID is provided without IDs or DeleteAll, and formats partial-success messages from result error list and success count. Handler tests validate success and partial-success response shapes using an in-memory SQLite DB. Router reflow preserves existing workspace and dataset commit route definitions.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Router
  participant ChatHandler
  participant ChatService
  participant DB

  rect rgba(70, 130, 180, 0.5)
    note over Client,DB: DELETE /api/v1/chats/:chat_id
    Client->>Router: DELETE /chats/:chat_id (auth token)
    Router->>ChatHandler: DeleteChat(c *gin.Context)
    ChatHandler->>ChatService: DeleteChat(userID, chatID)
    ChatService->>DB: find chat where id=chatID, status=valid
    DB-->>ChatService: chat or error
    ChatService->>DB: update status="invalid"
    DB-->>ChatService: ok
    ChatService-->>ChatHandler: nil or "no authorization" error
    ChatHandler-->>Client: 200 {code, data: true/false}
  end

  rect rgba(34, 139, 34, 0.5)
    note over Client,DB: DELETE /api/v1/chats (bulk)
    Client->>Router: DELETE /chats (JSON body: IDs/DeleteAll)
    Router->>ChatHandler: BulkDeleteChats(c *gin.Context)
    ChatHandler->>ChatService: BulkDeleteChats(userID, req)
    ChatService->>DB: optionally fetch all valid chats for userID
    loop each deduped chatID
      ChatService->>DB: ownership check + status update
    end
    ChatService-->>ChatHandler: map[success_count, errors] or error
    ChatHandler-->>Client: 200 {code, data: result, message}
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~28 minutes

Suggested labels

size:M

Suggested reviewers

  • Haruko386

Poem

🐇 Hop hop, the chats must go,
A soft delete with status low.
delete_all? No worries, friend —
Only your chats meet their end.
Partial success, errors tracked,
The rabbit's got your data's back! 🗑️

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description is missing the required 'Type of change' section from the template, which should clearly identify whether this is a bug fix, new feature, or both. Add the 'Type of change' section to the description and select the appropriate checkbox(es) to clarify that this includes both a new feature (BulkDeleteChats) and a bug fix (ListChats).
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title mentions 'BulkDeleteChats' and 'ListChats fix', which align with the main changes (bulk delete feature and ListChats bug fix), though the 'fix ListChats' part is only briefly mentioned in the description and not reflected in the raw summary.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 17, 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.

🧹 Nitpick comments (1)
internal/handler/chat.go (1)

400-405: 💤 Low value

Minor: Pluralization in partial success message.

The message uses "chats" regardless of count, resulting in grammatically incorrect "1 chats" when success_count is 1. Consider handling singular vs plural for better user experience.

♻️ Suggested fix
 message := "success"
 if errorsList, ok := result["errors"].([]string); ok && len(errorsList) > 0 {
 	if successCount, ok := result["success_count"].(int); ok {
-		message = "Partially deleted " + strconv.Itoa(successCount) + " chats with " + strconv.Itoa(len(errorsList)) + " errors"
+		chatWord := "chats"
+		if successCount == 1 {
+			chatWord = "chat"
+		}
+		errorWord := "errors"
+		if len(errorsList) == 1 {
+			errorWord = "error"
+		}
+		message = "Partially deleted " + strconv.Itoa(successCount) + " " + chatWord + " with " + strconv.Itoa(len(errorsList)) + " " + errorWord
 	}
 }
🤖 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 `@internal/handler/chat.go` around lines 400 - 405, The message string
construction in the chat handler needs to handle proper pluralization for
grammatically correct output. When building the "Partially deleted" message,
check both the successCount value and the length of errorsList to determine
whether to use singular or plural forms of "chat" and "error". Specifically, if
successCount equals 1, use "chat" instead of "chats", and if len(errorsList)
equals 1, use "error" instead of "errors". Apply conditional logic to select the
appropriate word form based on the respective counts before constructing the
final message string.
🤖 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.

Nitpick comments:
In `@internal/handler/chat.go`:
- Around line 400-405: The message string construction in the chat handler needs
to handle proper pluralization for grammatically correct output. When building
the "Partially deleted" message, check both the successCount value and the
length of errorsList to determine whether to use singular or plural forms of
"chat" and "error". Specifically, if successCount equals 1, use "chat" instead
of "chats", and if len(errorsList) equals 1, use "error" instead of "errors".
Apply conditional logic to select the appropriate word form based on the
respective counts before constructing the final message string.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 268c9309-8389-462a-9890-2c450538b6c8

📥 Commits

Reviewing files that changed from the base of the PR and between cb2e061 and 3ba1d4f.

📒 Files selected for processing (5)
  • internal/handler/chat.go
  • internal/handler/chat_test.go
  • internal/router/router.go
  • internal/service/chat.go
  • internal/service/chat_delete_test.go

@codecov

codecov Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (69dbc44) to head (b05844e).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16157   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Harry-Hz-Zhang Harry-Hz-Zhang changed the title feat: Implement BulkDeleteChats Go API and fix ListChats parameter sw… feat(go-api): Implement BulkDeleteChats Go API and fix ListChats Jun 18, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@JinHai-CN
JinHai-CN merged commit 2856cde into infiniflow:main Jun 22, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants