diff --git a/frontend/src/api/embed/index.ts b/frontend/src/api/embed/index.ts index 95658995..1e541fec 100644 --- a/frontend/src/api/embed/index.ts +++ b/frontend/src/api/embed/index.ts @@ -225,9 +225,11 @@ export async function getEmbedChunkById(channelId: string, token: string, chunkI ) } -export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit = 6) { +export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit?: number) { + // Omit limit to let the channel agent's configured starter count apply. + const qs = typeof limit === 'number' && limit > 0 ? `?limit=${limit}` : '' return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>( - `/api/v1/embed/${channelId}/suggested-questions?limit=${limit}`, + `/api/v1/embed/${channelId}/suggested-questions${qs}`, { headers: { Authorization: `Embed ${token}` } }, ) } diff --git a/frontend/src/stores/settings.ts b/frontend/src/stores/settings.ts index 1f33f963..f4995917 100644 --- a/frontend/src/stores/settings.ts +++ b/frontend/src/stores/settings.ts @@ -418,8 +418,12 @@ export const useSettingsStore = defineStore("settings", { return this.settings.selectedFiles || []; }, - /** Scope for suggested-questions API (KB / file / tag @mentions). */ - getSuggestedQuestionsParams(limit = 6) { + /** + * Scope for suggested-questions API (KB / file / tag @mentions). + * Leave `limit` undefined to let the backend apply the agent's configured + * starter count; pass a number only to request a specific count. + */ + getSuggestedQuestionsParams(limit?: number) { const selectedKBs = this.getSelectedKnowledgeBases(); const selectedFiles = this.getSelectedFiles(); const tags = this.settings.selectedTags || []; diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 6d72d2d5..66ca08cf 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -314,7 +314,7 @@ const fetchSuggestedQuestions = async () => { try { const agentId = useSettingsStoreInstance.selectedAgentId; if (!agentId) return; - const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams(6)); + const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams()); if (fetchId === suggestedQuestionsFetchId) { suggestedQuestions.value = res?.data?.questions || []; } diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue index dc99f2af..8850ec65 100644 --- a/frontend/src/views/creatChat/creatChat.vue +++ b/frontend/src/views/creatChat/creatChat.vue @@ -139,7 +139,7 @@ const fetchSuggestedQuestions = async () => { try { const agentId = settingsStore.selectedAgentId; if (!agentId) return; - const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams(6)); + const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams()); if (fetchId === suggestedQuestionsFetchId) { sqCardsRevealed.value = false; sqRenderKey.value++; diff --git a/frontend/src/views/embed/EmbedChatCore.vue b/frontend/src/views/embed/EmbedChatCore.vue index eb660c46..610a4ea7 100644 --- a/frontend/src/views/embed/EmbedChatCore.vue +++ b/frontend/src/views/embed/EmbedChatCore.vue @@ -315,7 +315,7 @@ const fetchSuggestedQuestions = async () => { } suggestedLoading.value = true try { - const res = await getEmbedSuggestedQuestions(props.channelId, props.token, 6) + const res = await getEmbedSuggestedQuestions(props.channelId, props.token) suggestedQuestions.value = res?.data?.questions || [] } catch { suggestedQuestions.value = [] diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index 0f9e0edf..a7392140 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -23,6 +23,16 @@ var ( ErrAgentNameRequired = errors.New("agent name is required") ) +const ( + // suggestionDefaultLimit is the fallback count when neither the caller nor + // the agent configuration specifies how many suggestions to return. + suggestionDefaultLimit = 6 + // suggestionMaxLimit caps how many suggestions a single request may ask for. + // It bounds the downstream candidate pool (limit*5) so an oversized limit + // cannot turn into an unbounded chunk query. + suggestionMaxLimit = 30 +) + // customAgentService implements the CustomAgentService interface type customAgentService struct { repo interfaces.CustomAgentRepository @@ -497,8 +507,15 @@ func (s *customAgentService) getSuggestedQuestions( limit int, includeCurated bool, ) ([]types.SuggestedQuestion, error) { - if limit <= 0 { - limit = 6 + // A non-positive limit means "unspecified": fall back to the agent's + // configured Starters.Count (below) or the default. An explicit limit is + // authoritative and only bounded by the safety cap. + limitProvided := limit > 0 + if !limitProvided { + limit = suggestionDefaultLimit + } + if limit > suggestionMaxLimit { + limit = suggestionMaxLimit } if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil { @@ -529,7 +546,10 @@ func (s *customAgentService) getSuggestedQuestions( if suggestionConfig == nil || !suggestionConfig.Starters.Enabled { return []types.SuggestedQuestion{}, nil } - if limit > suggestionConfig.Starters.Count { + // Starters.Count is the agent-author default, applied only when the + // caller did not request a specific limit. An explicit limit stays + // authoritative so ?limit=N actually changes how many are returned. + if !limitProvided && suggestionConfig.Starters.Count > 0 { limit = suggestionConfig.Starters.Count } starterMode = suggestionConfig.Starters.Mode diff --git a/internal/application/service/custom_agent_suggestion_limit_test.go b/internal/application/service/custom_agent_suggestion_limit_test.go new file mode 100644 index 00000000..f079bff8 --- /dev/null +++ b/internal/application/service/custom_agent_suggestion_limit_test.go @@ -0,0 +1,103 @@ +package service + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// suggestionLimitAgentRepo returns a single curated-starter agent so the +// suggestion path resolves without touching chunk/KB repositories. +type suggestionLimitAgentRepo struct { + interfaces.CustomAgentRepository + agent *types.CustomAgent +} + +func (r *suggestionLimitAgentRepo) GetAgentByID( + _ context.Context, _ string, _ uint64, +) (*types.CustomAgent, error) { + return r.agent, nil +} + +func newCuratedStarterAgent(count int, items []string) *types.CustomAgent { + return &types.CustomAgent{ + ID: "agent-1", + TenantID: 1, + Config: types.CustomAgentConfig{ + QuestionSuggestions: &types.QuestionSuggestionConfig{ + Starters: types.StarterSuggestionConfig{ + Enabled: true, + Mode: types.SuggestionModeCurated, + Count: count, + Items: items, + }, + }, + }, + } +} + +// TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount is the +// regression test for issue #2238: an explicit limit must be honored instead +// of being clamped down to the agent's configured Starters.Count. +func TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount(t *testing.T) { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"} + svc := &customAgentService{ + repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)}, + } + + got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 10) + require.NoError(t, err) + // Before the fix limit was clamped to Starters.Count (6); now the explicit + // request of 10 is honored. + assert.Len(t, got, 10) +} + +// TestGetSuggestedQuestions_SmallerLimitStillHonored guards the other +// direction: a limit below Starters.Count must also take effect. +func TestGetSuggestedQuestions_SmallerLimitStillHonored(t *testing.T) { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + items := []string{"q1", "q2", "q3", "q4", "q5", "q6"} + svc := &customAgentService{ + repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)}, + } + + got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 2) + require.NoError(t, err) + assert.Len(t, got, 2) +} + +// TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount confirms +// that omitting the limit (<= 0) still uses the agent's configured count. +func TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount(t *testing.T) { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8"} + svc := &customAgentService{ + repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(4, items)}, + } + + got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 0) + require.NoError(t, err) + assert.Len(t, got, 4) +} + +// TestGetSuggestedQuestions_LimitBoundedByMax ensures an oversized limit is +// capped so it cannot inflate the downstream candidate pool without bound. +func TestGetSuggestedQuestions_LimitBoundedByMax(t *testing.T) { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1)) + items := make([]string, 0, 100) + for i := 0; i < 100; i++ { + items = append(items, "q"+string(rune('A'+i%26))+string(rune('0'+i/26))) + } + svc := &customAgentService{ + repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)}, + } + + got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 999) + require.NoError(t, err) + assert.Len(t, got, suggestionMaxLimit) +} diff --git a/internal/application/service/embed_channel.go b/internal/application/service/embed_channel.go index 9f403389..df9986d4 100644 --- a/internal/application/service/embed_channel.go +++ b/internal/application/service/embed_channel.go @@ -322,9 +322,8 @@ func (s *embedChannelService) SuggestedQuestions( if ch == nil || !ch.ShowSuggestedQuestions { return nil, nil } - if limit <= 0 { - limit = 6 - } + // A non-positive limit is forwarded as "unspecified" so GetSuggestedQuestions + // falls back to the agent's configured starter count rather than a fixed 6. kbIDs := s.resolveKnowledgeBaseIDs(ctx, ch) return s.agentService.GetSuggestedQuestions(ctx, ch.AgentID, kbIDs, nil, nil, limit) } diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go index e27acc83..7218388d 100644 --- a/internal/handler/custom_agent.go +++ b/internal/handler/custom_agent.go @@ -563,7 +563,7 @@ func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) { // @Param knowledge_base_ids query string false "知识库ID列表(逗号分隔),覆盖智能体默认配置" // @Param knowledge_ids query string false "知识ID列表(逗号分隔),限定到具体文档" // @Param tag_scopes query string false "带知识库归属的标签范围(JSON)" -// @Param limit query int false "返回数量上限(默认6)" +// @Param limit query int false "返回数量上限(未传时使用智能体配置的开场问题数量,最大30)" // @Success 200 {object} map[string]interface{} "推荐问题列表" // @Failure 400 {object} errors.AppError "请求参数错误" // @Failure 404 {object} errors.AppError "智能体不存在" @@ -608,7 +608,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) { } } - limit := 6 + // limit == 0 signals "unspecified" so the service falls back to the agent's + // configured starter count. A provided value is passed through unchanged and + // bounded by the service's safety cap. + limit := 0 if limitStr := c.Query("limit"); limitStr != "" { if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 { limit = parsed diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go index fa9a25bf..233b38b2 100644 --- a/internal/handler/embed_channel.go +++ b/internal/handler/embed_channel.go @@ -382,13 +382,15 @@ func (h *EmbedChannelHandler) GetEmbedSuggestedQuestions(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"questions": []types.SuggestedQuestion{}}}) return } - limit := 6 + // limit == 0 signals "unspecified" so the channel agent's starter count + // applies. A provided value is honored up to the embed cap. + limit := 0 if raw := c.Query("limit"); raw != "" { if n, err := strconv.Atoi(raw); err == nil && n > 0 { limit = n - } - if limit > 12 { - limit = 12 + if limit > 12 { + limit = 12 + } } } questions, err := h.embedSvc.SuggestedQuestions(c.Request.Context(), ch, limit)