diff --git a/e2e/app.spec.ts b/e2e/app.spec.ts index 391f936..9a5c1b8 100644 --- a/e2e/app.spec.ts +++ b/e2e/app.spec.ts @@ -191,3 +191,62 @@ test('chat uses server suggestions and falls back offline', async ({ page.getByRole('button', { name: '解释这个模板的流式架构' }), ).toBeVisible(); }); + +test('invalid product links show a recovery path without requesting detail', async ({ + page, +}) => { + const requests: string[] = []; + page.on('request', (request) => { + if (new URL(request.url()).pathname.startsWith('/api/products/')) + requests.push(request.url()); + }); + for (const id of ['abc', '0', '9007199254740992']) { + await page.goto(`/shop/products/${id}`); + await expect(page.getByRole('alert')).toContainText('商品链接无效'); + await expect( + page.getByRole('link', { name: '返回商品列表' }), + ).toHaveAttribute('href', '/shop'); + } + expect(requests).toEqual([]); + await page.getByRole('link', { name: '返回商品列表' }).click(); + await expect(page).toHaveURL(/\/shop$/); +}); + +test('FastAPI stream finishes correctly and clipboard denial has feedback', async ({ + page, +}) => { + await page.addInitScript(() => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { + writeText: async () => { + throw new DOMException('Denied', 'NotAllowedError'); + }, + }, + }); + }); + await page.route('**/api/ai/chat', (route) => + route.fulfill({ + contentType: 'text/event-stream', + body: + 'data: {"type":"start","id":"fastapi-browser"}\r\n\r\n' + + 'data: {"type":"delta","delta":"FastAPI browser answer"}\r\n\r\n' + + 'data: {"type":"finish","reason":"stop"}\r\n\r\n' + + 'data: {"type":"delta","delta":"STALE TRAILER"}\r\n\r\n', + }), + ); + await page.goto('/ai/chat'); + await page.getByRole('textbox').fill('Hello'); + await page.getByRole('textbox').press('Enter'); + await expect( + page.getByText('FastAPI browser answer', { exact: true }), + ).toBeVisible(); + await expect( + page.getByRole('button', { name: '重新生成', exact: true }), + ).toBeVisible(); + await expect(page.getByText('STALE TRAILER', { exact: false })).toHaveCount( + 0, + ); + await page.getByRole('button', { name: '复制', exact: true }).click(); + await expect(page.getByRole('status')).toContainText('复制失败'); +}); diff --git a/src/composables/useStreamingChat.ts b/src/composables/useStreamingChat.ts index dc5d366..9c87f76 100644 --- a/src/composables/useStreamingChat.ts +++ b/src/composables/useStreamingChat.ts @@ -1,4 +1,10 @@ -import { computed, ref, shallowRef } from 'vue'; +import { + computed, + getCurrentScope, + onScopeDispose, + ref, + shallowRef, +} from 'vue'; import { defaultChatProvider } from '@/services/ai/fetchStreamProvider'; import type { ChatMessage, ChatProvider, ChatUsage } from '@/types/ai'; @@ -21,6 +27,8 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { const conversationId = ref(createId('conversation')); const usage = ref(null); const streaming = computed(() => activeController.value !== null); + let activeAssistant: ChatMessage | undefined; + let disposed = false; const run = async (context: ChatMessage[]) => { messages.value.push(createMessage('assistant', '', 'streaming')); @@ -28,6 +36,7 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { if (!assistant) return; const controller = new AbortController(); activeController.value = controller; + activeAssistant = assistant; error.value = null; usage.value = null; @@ -36,6 +45,8 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { signal: controller.signal, conversationId: conversationId.value, })) { + if (activeController.value !== controller || controller.signal.aborted) + return; if (chunk.type === 'start') conversationId.value = chunk.conversationId; if (chunk.type === 'delta') assistant.content += chunk.delta; if (chunk.type === 'usage') @@ -46,10 +57,11 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { if (chunk.type === 'error') throw new Error(chunk.message); if (chunk.type === 'done') break; } - assistant.status = 'ready'; + if (activeController.value === controller) assistant.status = 'ready'; // catch 参数若命名为 error 会遮蔽外层 error ref,故用 caught 并禁用命名规则 // oxlint-disable-next-line unicorn/catch-error-name } catch (caught) { + if (activeController.value !== controller) return; if (controller.signal.aborted) { assistant.status = 'stopped'; } else { @@ -59,19 +71,36 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { error.value = normalized; } } finally { - if (activeController.value === controller) activeController.value = null; + if (activeController.value === controller) { + activeController.value = null; + activeAssistant = undefined; + } } }; const sendMessage = async (content: string) => { const normalized = content.trim(); - if (!normalized || streaming.value) return; + if (!normalized || streaming.value || disposed) return; const userMessage = createMessage('user', normalized); messages.value.push(userMessage); await run([...messages.value]); }; - const stop = () => activeController.value?.abort(); + const stop = () => { + const controller = activeController.value; + if (!controller) return; + activeController.value = null; + if (activeAssistant) activeAssistant.status = 'stopped'; + activeAssistant = undefined; + controller.abort(); + }; + + if (getCurrentScope()) { + onScopeDispose(() => { + disposed = true; + stop(); + }); + } const findLastMessageIndex = ( predicate: (message: ChatMessage) => boolean, @@ -84,7 +113,7 @@ export function useStreamingChat(provider: ChatProvider = defaultChatProvider) { }; const regenerate = async (assistantId?: string) => { - if (streaming.value) return; + if (streaming.value || disposed) return; const targetIndex = assistantId ? messages.value.findIndex((message) => message.id === assistantId) : findLastMessageIndex((message) => message.role === 'assistant'); diff --git a/src/locales/langs/en-US/common.json b/src/locales/langs/en-US/common.json index 9149399..58c53a8 100644 --- a/src/locales/langs/en-US/common.json +++ b/src/locales/langs/en-US/common.json @@ -140,7 +140,9 @@ "decreaseQuantity": "Decrease quantity", "increaseQuantity": "Increase quantity", "cartAdded": "Added {count} item(s) to your cart", - "checkoutDemo": "Selected {count} item(s); connect your checkout in a real project" + "checkoutDemo": "Selected {count} item(s); connect your checkout in a real project", + "invalidProduct": "This product link is invalid. Please return to the catalog.", + "backProducts": "Back to products" }, "editor": { "editEyebrow": "EDIT PRODUCT", @@ -401,7 +403,8 @@ "How should Vue Query and Pinia divide responsibilities?", "Explain this template's streaming architecture", "Write a Vue 3 composable example" - ] + ], + "copyFailed": "Unable to copy. Please select and copy the text manually." }, "ui": { "eyebrow": "Build-time selection", diff --git a/src/locales/langs/ja-JP/common.json b/src/locales/langs/ja-JP/common.json index 92f447c..b443a0b 100644 --- a/src/locales/langs/ja-JP/common.json +++ b/src/locales/langs/ja-JP/common.json @@ -140,7 +140,9 @@ "decreaseQuantity": "数量を減らす", "increaseQuantity": "数量を増やす", "cartAdded": "{count} 点をカートに追加しました", - "checkoutDemo": "{count} 点を選択しました。実案件では決済フローを接続できます" + "checkoutDemo": "{count} 点を選択しました。実案件では決済フローを接続できます", + "invalidProduct": "商品リンクが無効です。商品一覧に戻ってください。", + "backProducts": "商品一覧に戻る" }, "editor": { "editEyebrow": "商品を編集", @@ -401,7 +403,8 @@ "Vue Query と Pinia の役割分担は?", "このテンプレートのストリーミング設計を説明して", "Vue 3 composable の例を書いて" - ] + ], + "copyFailed": "コピーできませんでした。テキストを選択して手動でコピーしてください。" }, "ui": { "eyebrow": "ビルド時選択", diff --git a/src/locales/langs/zh-CN/common.json b/src/locales/langs/zh-CN/common.json index d224af2..2b0dd9d 100644 --- a/src/locales/langs/zh-CN/common.json +++ b/src/locales/langs/zh-CN/common.json @@ -140,7 +140,9 @@ "decreaseQuantity": "减少数量", "increaseQuantity": "增加数量", "cartAdded": "已将 {count} 件商品加入购物车", - "checkoutDemo": "已选择 {count} 件商品;支付流程可在业务项目中接入" + "checkoutDemo": "已选择 {count} 件商品;支付流程可在业务项目中接入", + "invalidProduct": "商品链接无效,请返回商品列表。", + "backProducts": "返回商品列表" }, "editor": { "editEyebrow": "编辑商品", @@ -401,7 +403,8 @@ "Vue Query 和 Pinia 应该如何分工?", "解释这个模板的流式架构", "写一个 Vue 3 组合式函数示例" - ] + ], + "copyFailed": "复制失败,请选择文本后手动复制。" }, "ui": { "eyebrow": "构建期单选", diff --git a/src/services/ai/fetchStreamProvider.ts b/src/services/ai/fetchStreamProvider.ts index f0c8fde..d5449e9 100644 --- a/src/services/ai/fetchStreamProvider.ts +++ b/src/services/ai/fetchStreamProvider.ts @@ -29,7 +29,9 @@ async function readError(response: Response): Promise { payload = undefined; } return new ApiError( - payload?.msg || `AI request failed (${response.status})`, + payload?.message || + payload?.msg || + `AI request failed (${response.status})`, { kind: 'http', code: payload?.code, diff --git a/src/services/ai/sse.ts b/src/services/ai/sse.ts index 813b2e5..339bdde 100644 --- a/src/services/ai/sse.ts +++ b/src/services/ai/sse.ts @@ -12,8 +12,9 @@ export function parseSseEvent(event: string): ChatChunk | null { if (!value || typeof value !== 'object' || !('type' in value)) throw new Error('Invalid chat stream event'); const chunk = value as Record; - if (chunk.type === 'start' && typeof chunk.conversationId === 'string') { - return { type: 'start', conversationId: chunk.conversationId }; + if (chunk.type === 'start') { + const id = chunk.conversationId ?? chunk.id; + if (typeof id === 'string') return { type: 'start', conversationId: id }; } if (chunk.type === 'delta' && typeof chunk.delta === 'string') return { type: 'delta', delta: chunk.delta }; @@ -28,7 +29,7 @@ export function parseSseEvent(event: string): ChatChunk | null { outputTokens: chunk.outputTokens, }; } - if (chunk.type === 'done') return { type: 'done' }; + if (chunk.type === 'done' || chunk.type === 'finish') return { type: 'done' }; if (chunk.type === 'error' && typeof chunk.message === 'string') return { type: 'error', message: chunk.message }; throw new Error('Unsupported chat stream event'); @@ -40,10 +41,15 @@ export async function* parseSseStream( const reader = stream.getReader(); const decoder = new TextDecoder(); let buffer = ''; + let completed = false; try { while (true) { const { value, done } = await reader.read(); - buffer += decoder.decode(value, { stream: !done }).replace(/\r\n/g, '\n'); + buffer = (buffer + decoder.decode(value, { stream: !done })).replace( + /\r\n/g, + '\n', + ); + if (done) completed = true; let boundary = buffer.indexOf('\n\n'); while (boundary >= 0) { const event = buffer.slice(0, boundary); @@ -57,6 +63,10 @@ export async function* parseSseStream( const finalChunk = parseSseEvent(buffer); if (finalChunk) yield finalChunk; } finally { - reader.releaseLock(); + try { + if (!completed) await reader.cancel().catch(() => undefined); + } finally { + reader.releaseLock(); + } } } diff --git a/src/utils/product.ts b/src/utils/product.ts index 2252f2d..21e37a5 100644 --- a/src/utils/product.ts +++ b/src/utils/product.ts @@ -32,3 +32,9 @@ export function getSafeProductImage(value: string): string { } return '/products/product-placeholder.svg'; } + +export function parseProductId(value: unknown): number | undefined { + if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) return undefined; + const id = Number(value); + return Number.isSafeInteger(id) ? id : undefined; +} diff --git a/src/views/ai/chat.vue b/src/views/ai/chat.vue index 12b29f0..eba7e67 100644 --- a/src/views/ai/chat.vue +++ b/src/views/ai/chat.vue @@ -1,3 +1,111 @@ + + - -