Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions apps/web/src/composables/api/useStarterPrompts.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { resolveStarterPromptSet, type StarterPromptSet } from './useStarterPrompts'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ref } from 'vue'
import { resolveStarterPromptSet, useStarterPromptsQuery, type StarterPromptSet } from './useStarterPrompts'

const held: StarterPromptSet = { hash: 'old', items: [{ title: 'Old', prompt: 'Old prompt' }] }
const fresh = { title: 'New', prompt: 'New prompt' }
Expand Down Expand Up @@ -28,3 +29,33 @@ describe('resolveStarterPromptSet', () => {
.toEqual({ hash: '', items: [] })
})
})


const mocks = vi.hoisted(() => ({ refresh: vi.fn(), set: vi.fn() }))
vi.mock('@memohai/sdk', () => ({
getBotsByBotIdStarterPrompts: vi.fn(),
postBotsByBotIdStarterPromptsRefresh: mocks.refresh,
}))
vi.mock('vue-i18n', () => ({ useI18n: () => ({ locale: ref('en') }) }))
vi.mock('@pinia/colada', () => ({
useQuery: () => ({ error: ref(null) }),
useQueryCache: () => ({ getQueryData: () => held, setQueryData: mocks.set, cancelQueries: vi.fn() }),
}))

describe('starter prompt refresh failures', () => {
beforeEach(() => vi.clearAllMocks())

it('retains the structured error and cached prompts, then clears the error after retry', async () => {
const problem = { code: 'internal', status: 500, request_id: 'request-123' }
mocks.refresh.mockRejectedValueOnce(problem)
const query = useStarterPromptsQuery('bot-1')
expect(await query.refresh()).toBe(false)
expect(query.error.value).toEqual(problem)
expect(query.refreshing.value).toBe(false)
expect(mocks.set).not.toHaveBeenCalled()
mocks.refresh.mockResolvedValueOnce({ data: { hash: 'new', items: [fresh] } })
expect(await query.refresh()).toBe(true)
expect(query.error.value).toBeNull()
expect(mocks.set).toHaveBeenCalledWith(['starter-prompts', 'bot-1'], { hash: 'new', items: [fresh] })
})
})
13 changes: 9 additions & 4 deletions apps/web/src/composables/api/useStarterPrompts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ref, toValue, type MaybeRefOrGetter } from 'vue'
import { computed, ref, shallowRef, toValue, watch, type MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
import { useQuery, useQueryCache } from '@pinia/colada'
import {
Expand Down Expand Up @@ -69,28 +69,33 @@ export function useStarterPromptsQuery(botId: MaybeRefOrGetter<string>) {
})

const refreshing = ref(false)
const refreshError = shallowRef<unknown>(null)
watch(() => toValue(botId), () => { refreshError.value = null })
const error = computed(() => refreshError.value ?? query.error.value)
async function refresh(): Promise<boolean> {
const held = queryCache.getQueryData<StarterPromptSet>(key())
refreshing.value = true
refreshError.value = null
try {
const { data } = await postBotsByBotIdStarterPromptsRefresh({
path: { bot_id: toValue(botId) },
body: { locale: locale.value, avoid: held?.items.map(item => item.prompt) ?? [] },
throwOnError: true,
})
if (!data.hash || data.items.length === 0) return false
if (!data.hash || data.items.length === 0) throw new Error('No starter prompts returned')
// A read still in flight answered for the set being replaced; drop it.
queryCache.cancelQueries({ key: key() })
queryCache.setQueryData<StarterPromptSet>(key(), { hash: data.hash, items: data.items })
return true
}
catch {
catch (error) {
refreshError.value = error
return false
}
finally {
refreshing.value = false
}
}

return { ...query, refresh, refreshing }
return { ...query, error, refresh, refreshing }
}
1 change: 1 addition & 0 deletions apps/web/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1870,6 +1870,7 @@
}
},
"chatExamples": {
"dismissError": "Dismiss error",
"noBot": "Create a bot first to try this.",
"createBot": "Create bot",
"tryThese": "Try one of these",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1870,6 +1870,7 @@
}
},
"chatExamples": {
"dismissError": "エラーを閉じる",
"noBot": "試すには、まず Bot を作成してください。",
"createBot": "Bot を作成",
"tryThese": "こんなことを試せます",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -1870,6 +1870,7 @@
}
},
"chatExamples": {
"dismissError": "关闭错误提示",
"noBot": "请先创建一个 Bot 再试试",
"createBot": "创建 Bot",
"tryThese": "试试这些",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// @vitest-environment jsdom
import { createApp, h, nextTick, ref, type Ref } from 'vue'
import { afterEach, expect, it, vi } from 'vitest'

interface QueryState {
data: Ref<{ items: { title: string; prompt: string }[] }>
status: Ref<string>
refreshing: Ref<boolean>
error: Ref<{ code: string; request_id: string }>
refresh: () => Promise<void>
}
const state = vi.hoisted(() => ({} as { query: QueryState; dismissed: Ref<boolean> }))
vi.mock('@/composables/api/useStarterPrompts', () => ({ useStarterPromptsQuery: () => state.query }))
vi.mock('@/components/chat-examples/use-chat-examples-ui', () => ({ useChatExamplesUi: () => ({ welcomeDismissed: state.dismissed }) }))
vi.mock('@/composables/useComposerPrefill', () => ({ useComposerPrefill: () => ({ prefillComposer: vi.fn() }) }))
vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
vi.mock('./starter-prompt-list.vue', () => ({ default: { props: ['rows'], template: '<div data-rows>{{ rows }}</div>' } }))
vi.mock('@felinic/ui', () => ({
Button: { template: '<button><slot /></button>' },
TextButton: { template: '<button><slot /></button>' },
CalloutBanner: {
props: ['dismissLabel', 'description'], emits: ['dismiss'],
template: '<aside>{{ description }}<button v-if="dismissLabel" :aria-label="dismissLabel" @click="$emit(\'dismiss\')">Close</button><slot name="details" /></aside>',
},
}))
import Suggestions from './chat-example-suggestions.vue'

let app: ReturnType<typeof createApp>
let root: HTMLDivElement
afterEach(() => { app?.unmount(); root?.remove() })

it('dismisses only the error, retains retry and prompts, and shows a subsequent failure', async () => {
state.dismissed = ref(false)
state.query = {
data: ref({ items: [{ title: 'Old', prompt: 'Keep this prompt' }] }),
status: ref('success'), refreshing: ref(false), error: ref({ code: 'internal', request_id: 'first' }),
refresh: vi.fn(async () => { state.query.error.value = { code: 'internal', request_id: 'second' } }),
}
root = document.createElement('div')
document.body.append(root)
app = createApp({ render: () => h(Suggestions, { botId: 'bot', composerReplaceable: true }) })
app.config.globalProperties.$t = (key: string) => key
app.mount(root)
const close = root.querySelector<HTMLButtonElement>('aside button')
expect(close).not.toBeNull()
close!.click()
await nextTick()
expect(root.querySelector('aside')).toBeNull()
expect(root.textContent).toContain('Keep this prompt')
expect(state.dismissed.value).toBe(false)
const refresh = [...root.querySelectorAll('button')].find(button => button.textContent === 'chatExamples.refresh')!
refresh.click()
await nextTick()
expect(root.querySelector('aside')?.textContent).toContain('second')
})
38 changes: 31 additions & 7 deletions apps/web/src/pages/home/components/chat-example-suggestions.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { computed } from 'vue'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useEventListener, usePreferredReducedMotion } from '@vueuse/core'
import { X } from 'lucide-vue-next'
import { Button, TextButton, toast } from '@felinic/ui'
import { Button, CalloutBanner, TextButton } from '@felinic/ui'
import { useChatExamplesUi } from '@/components/chat-examples/use-chat-examples-ui'
import { useStarterPromptsQuery } from '@/composables/api/useStarterPrompts'
import { parseMemohError, resolveApiErrorMessage } from '@/utils/api-error'
import { useComposerPrefill } from '@/composables/useComposerPrefill'
import { COMPOSER_PREVIEW_LANDING_MS, type ComposerPreview } from '../composables/useComposerPreview'
import StarterPromptList, { type StarterPromptRow } from './starter-prompt-list.vue'
Expand All @@ -14,8 +15,8 @@ import StarterPromptList, { type StarterPromptRow } from './starter-prompt-list.
* The bot's own starter prompts for this user, under the welcome composer.
* They are always generated, from the bot's name alone when it has nothing
* else yet; while a set is on its way (the first one, or a refresh) the rows
* show a skeleton, and when none could be generated the section stays
* folded away. "Refresh" asks for a different set. Hiding the section is
* show a skeleton, and failures keep a retryable notice with its request ID. With no title
* model configured the section stays folded away. "Refresh" asks for a different set. Hiding the section is
* remembered on this device; while hidden, the composer's context row shows
* the entry that brings it back. Hidden by the welcome column's height tiers
* (style.css) before anything else yields.
Expand All @@ -42,7 +43,7 @@ const { welcomeDismissed } = useChatExamplesUi()
const { prefillComposer } = useComposerPrefill()
const reducedMotion = usePreferredReducedMotion()

const { data: starterSet, status: starterStatus, refresh: refreshStarterSet, refreshing } = useStarterPromptsQuery(() => props.botId)
const { data: starterSet, status: starterStatus, refresh: refreshStarterSet, refreshing, error: starterError } = useStarterPromptsQuery(() => props.botId)

/** The generated rows, or null while a set is on its way (skeleton). */
const rows = computed<StarterPromptRow[] | null>(() => {
Expand All @@ -58,11 +59,19 @@ const rows = computed<StarterPromptRow[] | null>(() => {
/** Whether the composer is currently showing the preview. */
const previewShown = computed(() => props.composerReplaceable && preview.value !== null)

const visible = computed(() => !welcomeDismissed.value && (rows.value === null || rows.value.length > 0))
const visible = computed(() => !welcomeDismissed.value && (rows.value === null || rows.value.length > 0 || !!starterError.value))
const errorDismissed = ref(false)
/** Dismissal belongs to one failure on one bot, never to future attempts. */
watch([() => props.botId, starterError], () => { errorDismissed.value = false })
const errorMessage = computed(() => starterError.value
? resolveApiErrorMessage(starterError.value, t('chatExamples.refreshFailed'))
: '')
const requestId = computed(() => parseMemohError(starterError.value)?.requestId)

async function refresh() {
errorDismissed.value = false
preview.value = null
if (!(await refreshStarterSet())) toast.error(t('chatExamples.refreshFailed'))
await refreshStarterSet()
}

function setPreview(prompt: string | null) {
Expand Down Expand Up @@ -141,6 +150,21 @@ async function select(row: StarterPromptRow) {
</Button>
</div>
</div>
<CalloutBanner
v-if="starterError && !refreshing && !errorDismissed"
tone="destructive"
size="sm"
:description="errorMessage"
:dismiss-label="$t('chatExamples.dismissError')"
@dismiss="errorDismissed = true"
>
<template
v-if="requestId"
#details
>
{{ $t('common.requestId') }}: {{ requestId }}
</template>
</CalloutBanner>
<StarterPromptList
:rows="rows"
:enter-hint="composerReplaceable"
Expand Down
39 changes: 19 additions & 20 deletions internal/agent/application/service_starter_prompts.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ type StarterPromptsRequest struct {
}

// StarterPromptsResult is either Unchanged (the client's set still matches
// the material) or a fresh set with its Hash. A set the model could not
// produce comes back with an empty Hash and no Items; the client shows its
// generic examples and asks again next time.
// the material) or a fresh set with its Hash. No configured title model
// yields an empty set; generation failures are returned as errors so callers
// can retain cached suggestions and offer a diagnosable retry.
type StarterPromptsResult struct {
Unchanged bool
Hash string
Expand Down Expand Up @@ -126,50 +126,49 @@ func (s *Service) StarterPrompts(ctx context.Context, req StarterPromptsRequest)
prompt += starterPromptsAvoidSection(avoid)
key += "\x00refresh\x00" + strings.Join(avoid, "\x00")
}
value, _, _ := s.starterPromptFlights.Do(key, func() (any, error) {
return s.generateStarterPrompts(context.WithoutCancel(ctx), req.BotID, ownerUserID, prompt), nil
value, err, _ := s.starterPromptFlights.Do(key, func() (any, error) {
return s.generateStarterPrompts(context.WithoutCancel(ctx), req.BotID, ownerUserID, prompt)
})
if err != nil {
return StarterPromptsResult{}, err
}
items, _ := value.([]StarterPrompt)
if len(items) == 0 {
return StarterPromptsResult{Items: []StarterPrompt{}}, nil
}
return StarterPromptsResult{Hash: hash, Items: items}, nil
}

// generateStarterPrompts runs the title model on prompt. Every failure, from
// a missing title model to unparsable output, yields nil: the caller treats
// that as "no suggestions this time".
func (s *Service) generateStarterPrompts(ctx context.Context, botID, ownerUserID, prompt string) []StarterPrompt {
// generateStarterPrompts leaves suggestions absent when no title model is configured.
// Operational failures propagate to the HTTP boundary for safe, correlated errors.
func (s *Service) generateStarterPrompts(ctx context.Context, botID, ownerUserID, prompt string) ([]StarterPrompt, error) {
logger := s.logger.With(slog.String("bot_id", botID))
account, err := s.accountService.Get(ctx, ownerUserID)
if err != nil {
logger.WarnContext(ctx, "starter prompts: load owner account failed", slog.Any("error", err))
return nil
return nil, errs.Wrap(err, "load starter prompt owner account")
}
modelID := strings.TrimSpace(account.TitleModelID)
if modelID == "" {
logger.DebugContext(ctx, "starter prompts: no title model configured")
return nil
return nil, nil
}
model, provider, err := s.fetchChatModel(ctx, modelID)
if err != nil {
logger.WarnContext(ctx, "starter prompts: resolve title model failed", slog.Any("error", err))
return nil
return nil, errs.Wrap(err, "resolve starter prompt title model")
}
return s.completeStarterPrompts(ctx, logger, ownerUserID, model, provider, prompt)
return s.completeStarterPrompts(ctx, ownerUserID, model, provider, prompt)
}

func (s *Service) completeStarterPrompts(ctx context.Context, logger *slog.Logger, ownerUserID string, model models.GetResponse, provider sqlc.Provider, prompt string) []StarterPrompt {
func (s *Service) completeStarterPrompts(ctx context.Context, ownerUserID string, model models.GetResponse, provider sqlc.Provider, prompt string) ([]StarterPrompt, error) {
text, err := s.generateWithTitleModel(ctx, "agent.starter_prompts", ownerUserID, model, provider, prompt)
if err != nil {
logger.WarnContext(ctx, "starter prompts: generation failed", slog.Any("error", err))
return nil
return nil, errs.Wrap(err, "generate starter prompts")
}
items := parseStarterPrompts(text)
if len(items) == 0 {
logger.WarnContext(ctx, "starter prompts: model output had no usable items", slog.Int("output_len", len(text)))
return nil, errs.New("starter prompt model output had no usable items")
}
return items
return items, nil
}

// collectStarterPromptMaterial reads everything the suggestions depend on.
Expand Down
47 changes: 46 additions & 1 deletion internal/agent/application/service_starter_prompts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package application

import (
"context"
"errors"
"io"
"log/slog"
"net/http"
Expand Down Expand Up @@ -278,11 +279,55 @@ func TestCompleteStarterPromptsParsesModelOutput(t *testing.T) {

svc := &Service{logger: slog.New(slog.DiscardHandler)}
provider := sqlc.Provider{ClientType: "openai-completions", Config: []byte(`{"base_url":"` + server.URL + `","api_key":"k"}`)}
items := svc.completeStarterPrompts(context.Background(), svc.logger, "user-1", models.GetResponse{ModelID: "m"}, provider, "PROMPT-MARKER")
items, err := svc.completeStarterPrompts(context.Background(), "user-1", models.GetResponse{ModelID: "m"}, provider, "PROMPT-MARKER")
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].Title != "查攻略" || items[0].Prompt != "帮我找一份神庙攻略" {
t.Fatalf("completeStarterPrompts() = %+v", items)
}
if !strings.Contains(gotBody, "PROMPT-MARKER") {
t.Fatalf("request body did not carry the prompt: %s", gotBody)
}
}

type unavailableStarterAccountStore struct{ dbstore.AccountStore }

func (unavailableStarterAccountStore) GetByUserID(context.Context, string) (dbstore.AccountRecord, error) {
return dbstore.AccountRecord{}, errors.New("PRIVATE account lookup failure")
}

func TestStarterPromptsReturnsGenerationSetupFailure(t *testing.T) {
svc, _ := newStarterPromptService(t, "")
svc.accountService = accounts.NewService(nil, unavailableStarterAccountStore{})
_, err := svc.StarterPrompts(context.Background(), starterRequest(""))
if err == nil {
t.Fatal("generation setup failure was swallowed as an empty successful response")
}
}

func TestStarterPromptGenerationFailuresAreReturned(t *testing.T) {
for _, tc := range []struct {
name string
status int
body string
}{
{"quota exhausted", http.StatusPaymentRequired, `{"error":{"message":"PRIVATE diagnostic", "type":"insufficient_quota"}}`},
{"unusable output", http.StatusOK, `{"id":"r","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"No suggestions"},"finish_reason":"stop"}]}`},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tc.status)
_, _ = w.Write([]byte(tc.body))
}))
defer server.Close()
svc := &Service{logger: slog.New(slog.DiscardHandler)}
provider := sqlc.Provider{ClientType: "openai-completions", Config: []byte(`{"base_url":"` + server.URL + `","api_key":"k"}`)}
items, err := svc.completeStarterPrompts(context.Background(), "user-1", models.GetResponse{ModelID: "m"}, provider, "test")
if err == nil || len(items) != 0 {
t.Fatalf("got items=%v, err=%v; want a diagnosable failure", items, err)
}
})
}
}
Loading