Skip to content

fix: unable to get owner in chat and search - #17244

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:muse
Jul 22, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:muse

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

image image

@Haruko386 Haruko386 added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 22, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 22, 2026
@Haruko386
Haruko386 marked this pull request as draft July 22, 2026 08:33
@Haruko386
Haruko386 marked this pull request as ready for review July 22, 2026 08:33
@Haruko386 Haruko386 added the ci Continue Integration label Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 68c817d0-0918-4205-93cc-6e2f3e08811f

📥 Commits

Reviewing files that changed from the base of the PR and between 49c8941 and d8467f6.

📒 Files selected for processing (3)
  • internal/handler/mcp_server.go
  • internal/service/chat.go
  • internal/service/chat_list_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/chat_list_test.go
  • internal/service/chat.go

📝 Walkthrough

Walkthrough

Chat and search listings now return enriched list-item models, support owner-based filtering, and expose owner nickname and tenant avatar fields. Chat filtering is restricted to accessible tenant memberships, with pagination applied after owner-based retrieval.

Changes

Listing enrichment and owner filtering

Layer / File(s) Summary
List-item models and DAO queries
internal/entity/chat.go, internal/dao/chat.go, internal/entity/search.go, internal/dao/search.go
Chat and search DAOs return enriched list-item types and use Scan for joined query results.
Chat owner filtering and enrichment
internal/handler/chat.go, internal/service/chat.go, internal/handler/mcp_server.go, internal/service/chat_list_test.go
Chat requests pass owner IDs through the service, which filters accessible owners, paginates results, and maps nickname and tenant avatar fields.
Search owner display mapping
internal/handler/search.go, internal/service/search.go, internal/service/search_test.go
Search listings use the shared owner-ID parser and return owner nicknames, tenant-avatar data, and tenant-ID nickname fallbacks.

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

Sequence Diagram(s)

sequenceDiagram
  participant ChatHandler
  participant ChatService
  participant ChatDAO
  ChatHandler->>ChatService: ListChats with ownerIDs
  ChatService->>ChatService: Filter accessible owner IDs
  ChatService->>ChatDAO: ListByOwnerIDs
  ChatDAO-->>ChatService: ChatListItem results
  ChatService-->>ChatHandler: Enriched chat response
Loading
sequenceDiagram
  participant SearchHandler
  participant SearchService
  participant SearchDAO
  SearchHandler->>SearchService: ListSearches with ownerIDs
  SearchService->>SearchDAO: ListByTenantIDs or ListByOwnerIDs
  SearchDAO-->>SearchService: SearchListItem results
  SearchService-->>SearchHandler: Response with nickname and tenant_avatar
Loading

Suggested reviewers: jinhai-cn

Poem

A rabbit hops through lists so bright,
With owner names and avatars light.
Chats find tenants, searches flow,
Empty names fall back below.
Scan brings every field in sight—
Wiggle ears; the rows are right!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 template requires a summary, but this description only says 'As title' and adds screenshots, so the purpose and fix details are too vague. Replace 'As title' with a brief summary of the bug, the fix, and any key behavior changes; keep screenshots as optional context.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: fixing owner retrieval in chat and search.
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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
internal/dao/chat.go (4)

1-1: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Dead OR branch in ListByOwnerIDs's owner filter, duplicated across chat and search DAOs. Both files AND a (tenant_id IN ownerIDs OR tenant_id = userID) clause with a later tenant_id IN ownerIDs clause, which algebraically collapses to just tenant_id IN ownerIDs — the OR ... = userID branch is unreachable in both.

  • internal/dao/chat.go#L119-128: drop the OR dialog.tenant_id = ? branch (and the now-redundant second Where at line 128), collapsing to a single dialog.tenant_id IN ? AND dialog.status = ? clause.
  • internal/dao/search.go#L111-119: apply the same simplification to search.tenant_id IN ? AND search.status = ?.
🤖 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/dao/chat.go` at line 1, In ListByOwnerIDs, simplify the chat DAO
owner filter to one dialog.tenant_id IN ownerIDs condition combined with
dialog.status, removing the OR dialog.tenant_id = userID branch and redundant
second Where; apply the same change to the corresponding search DAO filter using
search.tenant_id and search.status.

Source: Coding guidelines


1-1: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Owner-filtered listing has no DB-level pagination; the full match set is loaded and sliced in Go, in four places. ListByOwnerIDs in both DAOs runs Scan with no Count()/Offset()/Limit(), then the corresponding services compute total := len(...) and manually slice [start:end]. This is unbounded per request for owners/tenants with many chats/searches, unlike the tenant-scoped path which paginates in SQL.

  • internal/dao/chat.go#L109-145: add a Count() call and apply Offset(...).Limit(...) in ListByOwnerIDs, mirroring ListByTenantIDs.
  • internal/dao/search.go#L100-136: apply the same DB-level pagination to ListByOwnerIDs.
  • internal/service/chat.go#L81-152: once the DAO paginates, drop the manual start/end slicing in ListChats.
  • internal/service/search.go#L82-121: drop the equivalent manual slicing in ListSearches.
🤖 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/dao/chat.go` at line 1, Implement database-level pagination for
owner-filtered listings: update ListByOwnerIDs in the chat and search DAOs to
count matching rows and apply Offset and Limit before scanning, matching the
tenant-scoped implementations. Then update ListChats and ListSearches to use the
DAO’s paginated results directly and remove their manual start/end slicing while
preserving the returned total count.

119-128: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Dead OR branch in the owner filter.

Line 120's (dialog.tenant_id IN ? OR dialog.tenant_id = ?) is ANDed with line 128's dialog.tenant_id IN ? (same ownerIDs). The combined condition is (A OR B) AND C AND A, which reduces to A AND C — the OR dialog.tenant_id = userID branch never contributes. This looks like leftover from copy-pasting ListByTenantIDs's pattern, where the OR is actually meaningful.

🧹 Proposed fix to remove the dead branch
 	query := DB.Model(&entity.Chat{}).
 		Select(`
 			dialog.*,
 			user.nickname,
 			user.avatar as tenant_avatar
 		`).
 		Joins("LEFT JOIN user ON dialog.tenant_id = user.id").
-		Where("(dialog.tenant_id IN ? OR dialog.tenant_id = ?) AND dialog.status = ?", ownerIDs, userID, "1")
+		Where("dialog.tenant_id IN ? AND dialog.status = ?", ownerIDs, "1")

 	// Apply keyword filter
 	if keywords != "" {
 		query = query.Where("LOWER(dialog.name) LIKE ?", "%"+strings.ToLower(keywords)+"%")
 	}

-	// Filter by owner IDs (additional filter to ensure tenant_id is in ownerIDs)
-	query = query.Where("dialog.tenant_id IN ?", ownerIDs)
-
As per coding guidelines, `**/*` guidance to "Remove dead tests, commented-out code, stale documentation" applies equally to dead SQL predicates.
🤖 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/dao/chat.go` around lines 119 - 128, Remove the redundant “OR
dialog.tenant_id = userID” branch from the owner predicate in the query-building
flow, since the later “dialog.tenant_id IN ownerIDs” filter already constrains
the same column. Preserve the keyword filter, status condition, and ownerIDs
filtering behavior.

Source: Coding guidelines


109-145: 🚀 Performance & Scalability | 🟠 Major

ListByOwnerIDs fetches every matching row before pagination.

Unlike ListByTenantIDs (Count + Offset/Limit at the DB level), ListByOwnerIDs has no Count()/Offset()/Limit() — it scans every row matching the owner filter, then the service slices in memory. For an owner/tenant with many chats this is an unbounded per-request load. This is new code in this PR; worth fixing before it's copied further.

🤖 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/dao/chat.go` around lines 109 - 145, Update ListByOwnerIDs to
perform pagination at the database level, matching ListByTenantIDs: count
matching records separately, apply the request’s offset and limit to the query
before scanning, and return the database count rather than len(chats). Preserve
the existing filters, ordering, and error handling.
internal/dao/search.go (2)

128-134: 🚀 Performance & Scalability | 🟠 Major

Same missing-DB-pagination issue as chat.go's ListByOwnerIDs.

No Count()/Offset()/Limit() here either — all owner-matching searches are loaded before the service slices a page. Pre-existing, but this PR now replicates the pattern into chat listing too — see consolidated comment.

🤖 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/dao/search.go` around lines 128 - 134, Update the search query flow
around the matching-record Scan to apply database-level pagination with Count,
Offset, and Limit before loading results, while retaining the total matching
count separately for pagination metadata. Use the existing pagination inputs and
preserve the current return behavior for query errors.

111-119: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Same dead OR branch as chat.go's ListByOwnerIDs.

Line 111's (search.tenant_id IN ? OR search.tenant_id = ?) is ANDed with line 119's search.tenant_id IN ? (same ownerIDs), making the OR ... = userID branch unreachable. Pre-existing in this file, but now duplicated into internal/dao/chat.go's new ListByOwnerIDs — see consolidated comment.

🤖 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/dao/search.go` around lines 111 - 119, The search query’s owner
filter contains a dead userID OR branch because it is subsequently constrained
by the same ownerIDs set. Update the relevant query construction in the search
listing method to remove the unreachable “OR search.tenant_id = ?” condition and
its userID argument, while retaining the keyword and ownerIDs filtering
behavior.
internal/service/search.go (1)

109-120: 🚀 Performance & Scalability | 🟠 Major

Same manual in-memory pagination pattern duplicated into chat.go.

This pre-existing slicing logic (loads all owner-matching rows, then slices) is now mirrored verbatim in internal/service/chat.go (121-132). See consolidated comment for the shared fix (push pagination to the DB layer in both DAOs).

🤖 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/service/search.go` around lines 109 - 120, Replace the in-memory
pagination block in the relevant search service flow with database-level
pagination, and apply the same change to the duplicated logic in chat.go. Update
both DAOs and their callers to pass page and pageSize into the query, returning
only the requested rows while preserving total-count handling and empty results
for out-of-range pages.
🧹 Nitpick comments (1)
internal/service/chat.go (1)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

filterAccessibleChatOwnerIDs and filterAccessibleSearchOwnerIDs are duplicate implementations of the same owner-access-filtering logic. Both trim/dedupe requested owner IDs against an "allowed" set built from userID + GetTenantIDsByUserID(userID). This PR introduces the chat copy verbatim from the pre-existing search helper.

  • internal/service/chat.go#L154-185: extract a single shared helper (e.g., on a common service/util type) and have ChatService call it instead of keeping its own copy.
  • internal/service/search.go#L135-166: have SearchService call the same shared helper, removing its private copy.

As per coding guidelines, **/* direction to "reduce public surface area... and keep refactors centered on the owning abstraction" and to converge duplicate implementations into one path.

🤖 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/service/chat.go` at line 1, Extract the shared owner-access
filtering logic from filterAccessibleChatOwnerIDs and
filterAccessibleSearchOwnerIDs into one private helper on the appropriate common
service or utility abstraction. Update ChatService and SearchService to call
that helper, preserving trimming, deduplication, and the allowed-ID set derived
from userID plus GetTenantIDsByUserID(userID), then remove both private
duplicate implementations.

Source: Coding guidelines

🤖 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 `@internal/service/chat.go`:
- Around line 81-89: Change ChatService.ListChats to accept ownerIDs as a
regular []string parameter, remove the variadic ownerIDs[0] unwrapping and use
the parameter directly, then update all callers that currently omit owner IDs to
pass nil explicitly, matching SearchService.ListSearches.

---

Outside diff comments:
In `@internal/dao/chat.go`:
- Line 1: In ListByOwnerIDs, simplify the chat DAO owner filter to one
dialog.tenant_id IN ownerIDs condition combined with dialog.status, removing the
OR dialog.tenant_id = userID branch and redundant second Where; apply the same
change to the corresponding search DAO filter using search.tenant_id and
search.status.
- Line 1: Implement database-level pagination for owner-filtered listings:
update ListByOwnerIDs in the chat and search DAOs to count matching rows and
apply Offset and Limit before scanning, matching the tenant-scoped
implementations. Then update ListChats and ListSearches to use the DAO’s
paginated results directly and remove their manual start/end slicing while
preserving the returned total count.
- Around line 119-128: Remove the redundant “OR dialog.tenant_id = userID”
branch from the owner predicate in the query-building flow, since the later
“dialog.tenant_id IN ownerIDs” filter already constrains the same column.
Preserve the keyword filter, status condition, and ownerIDs filtering behavior.
- Around line 109-145: Update ListByOwnerIDs to perform pagination at the
database level, matching ListByTenantIDs: count matching records separately,
apply the request’s offset and limit to the query before scanning, and return
the database count rather than len(chats). Preserve the existing filters,
ordering, and error handling.

In `@internal/dao/search.go`:
- Around line 128-134: Update the search query flow around the matching-record
Scan to apply database-level pagination with Count, Offset, and Limit before
loading results, while retaining the total matching count separately for
pagination metadata. Use the existing pagination inputs and preserve the current
return behavior for query errors.
- Around line 111-119: The search query’s owner filter contains a dead userID OR
branch because it is subsequently constrained by the same ownerIDs set. Update
the relevant query construction in the search listing method to remove the
unreachable “OR search.tenant_id = ?” condition and its userID argument, while
retaining the keyword and ownerIDs filtering behavior.

In `@internal/service/search.go`:
- Around line 109-120: Replace the in-memory pagination block in the relevant
search service flow with database-level pagination, and apply the same change to
the duplicated logic in chat.go. Update both DAOs and their callers to pass page
and pageSize into the query, returning only the requested rows while preserving
total-count handling and empty results for out-of-range pages.

---

Nitpick comments:
In `@internal/service/chat.go`:
- Line 1: Extract the shared owner-access filtering logic from
filterAccessibleChatOwnerIDs and filterAccessibleSearchOwnerIDs into one private
helper on the appropriate common service or utility abstraction. Update
ChatService and SearchService to call that helper, preserving trimming,
deduplication, and the allowed-ID set derived from userID plus
GetTenantIDsByUserID(userID), then remove both private duplicate
implementations.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2ccf40a-a729-4deb-b6fb-e9510f61b6d9

📥 Commits

Reviewing files that changed from the base of the PR and between 21e5f00 and 49c8941.

📒 Files selected for processing (10)
  • internal/dao/chat.go
  • internal/dao/search.go
  • internal/entity/chat.go
  • internal/entity/search.go
  • internal/handler/chat.go
  • internal/handler/search.go
  • internal/service/chat.go
  • internal/service/chat_list_test.go
  • internal/service/search.go
  • internal/service/search_test.go

Comment thread internal/service/chat.go Resolved
@JinHai-CN
JinHai-CN merged commit 1d165c7 into infiniflow:main Jul 22, 2026
3 checks passed
This was referenced Jul 23, 2026
@Haruko386
Haruko386 deleted the muse branch July 23, 2026 05:25
@coderabbitai coderabbitai Bot mentioned this pull request Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants