mirror of
https://github.com/sunniejs/vue-h5-template.git
synced 2026-12-02 05:43:38 +08:00
fix: 完善聊天流清理与商品详情状态
This commit is contained in:
parent
9ac24512ea
commit
c0e5bccc35
@ -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('复制失败');
|
||||
});
|
||||
|
||||
@ -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<ChatUsage | null>(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');
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -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": "ビルド時選択",
|
||||
|
||||
@ -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": "构建期单选",
|
||||
|
||||
@ -29,7 +29,9 @@ async function readError(response: Response): Promise<ApiError> {
|
||||
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,
|
||||
|
||||
@ -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<string, unknown>;
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -1,3 +1,111 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onScopeDispose,
|
||||
shallowRef,
|
||||
useTemplateRef,
|
||||
watch,
|
||||
} from 'vue';
|
||||
import ChatComposer from '@/components/ai/ChatComposer.vue';
|
||||
import SafeMarkdown from '@/components/ai/SafeMarkdown.vue';
|
||||
import SvgIcon from '@/components/common/SvgIcon.vue';
|
||||
import { useQuery } from '@tanstack/vue-query';
|
||||
import { getChatSuggestions } from '@/api/modules/ai';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useStreamingChat } from '@/composables/useStreamingChat';
|
||||
import { useVisualViewport } from '@/composables/useVisualViewport';
|
||||
|
||||
const router = useRouter();
|
||||
const { t, tm, locale } = useI18n();
|
||||
const { messages, streaming, error, sendMessage, stop, regenerate, clear } =
|
||||
useStreamingChat();
|
||||
const { viewportHeight } = useVisualViewport();
|
||||
const messageList = useTemplateRef<HTMLElement>('messageList');
|
||||
const showScrollButton = shallowRef(false);
|
||||
const copiedId = shallowRef('');
|
||||
const copyNotice = shallowRef('');
|
||||
let copyVersion = 0;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const resetCopy = () => {
|
||||
copyVersion += 1;
|
||||
clearTimeout(copyTimer);
|
||||
copiedId.value = '';
|
||||
copyNotice.value = '';
|
||||
};
|
||||
onScopeDispose(resetCopy);
|
||||
const clearChat = () => {
|
||||
resetCopy();
|
||||
showScrollButton.value = false;
|
||||
clear();
|
||||
};
|
||||
const suggestionsQuery = useQuery({
|
||||
queryKey: computed(() => ['ai-suggestions', locale.value]),
|
||||
queryFn: ({ signal }) =>
|
||||
getChatSuggestions(
|
||||
locale.value,
|
||||
signal,
|
||||
import.meta.env.VITE_AI_API_BASE_URL || '/api/ai',
|
||||
),
|
||||
retry: false,
|
||||
staleTime: 300_000,
|
||||
});
|
||||
const prompts = computed(() =>
|
||||
suggestionsQuery.data.value?.length
|
||||
? suggestionsQuery.data.value
|
||||
: (tm('common.ai.prompts') as string[]),
|
||||
);
|
||||
const pageStyle = computed(() => ({
|
||||
height: viewportHeight.value ? `${viewportHeight.value}px` : '100dvh',
|
||||
}));
|
||||
const isNearBottom = () => {
|
||||
const element = messageList.value;
|
||||
return (
|
||||
!element ||
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight < 160
|
||||
);
|
||||
};
|
||||
const scrollToBottom = (behavior: ScrollBehavior = 'auto') =>
|
||||
void nextTick(() =>
|
||||
messageList.value?.scrollTo({
|
||||
top: messageList.value.scrollHeight,
|
||||
behavior,
|
||||
}),
|
||||
);
|
||||
const updateScrollState = () => {
|
||||
showScrollButton.value = !isNearBottom();
|
||||
};
|
||||
const send = (content: string) => {
|
||||
void sendMessage(content);
|
||||
scrollToBottom();
|
||||
};
|
||||
const copyMessage = async (id: string, content: string) => {
|
||||
resetCopy();
|
||||
const version = copyVersion;
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
if (version !== copyVersion) return;
|
||||
copiedId.value = id;
|
||||
} catch {
|
||||
if (version !== copyVersion) return;
|
||||
copyNotice.value = t('common.ai.copyFailed');
|
||||
}
|
||||
copyTimer = setTimeout(resetCopy, 1200);
|
||||
};
|
||||
watch(
|
||||
[
|
||||
() => messages.value.length,
|
||||
() => messages.value[messages.value.length - 1]?.content,
|
||||
streaming,
|
||||
],
|
||||
() => {
|
||||
if (!showScrollButton.value) scrollToBottom();
|
||||
},
|
||||
{ flush: 'post' },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="chat-page" :style="pageStyle">
|
||||
<header class="chat-header">
|
||||
@ -12,7 +120,11 @@
|
||||
<strong>{{ t('common.ai.assistant') }}</strong
|
||||
><span><i /> {{ t('common.ai.status') }}</span>
|
||||
</div>
|
||||
<button type="button" :aria-label="t('common.ai.newChat')" @click="clear">
|
||||
<button
|
||||
type="button"
|
||||
:aria-label="t('common.ai.newChat')"
|
||||
@click="clearChat"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</header>
|
||||
@ -104,6 +216,7 @@
|
||||
↓
|
||||
</button>
|
||||
<footer class="composer-area">
|
||||
<p v-if="copyNotice" role="status">{{ copyNotice }}</p>
|
||||
<ChatComposer :streaming="streaming" @send="send" @stop="stop" /><small>{{
|
||||
t('common.ai.disclaimer')
|
||||
}}</small>
|
||||
@ -111,79 +224,6 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';
|
||||
import { useQuery } from '@tanstack/vue-query';
|
||||
import { getChatSuggestions } from '@/api/modules/ai';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useStreamingChat } from '@/composables/useStreamingChat';
|
||||
import { useVisualViewport } from '@/composables/useVisualViewport';
|
||||
|
||||
const router = useRouter();
|
||||
const { t, tm, locale } = useI18n();
|
||||
const { messages, streaming, error, sendMessage, stop, regenerate, clear } =
|
||||
useStreamingChat();
|
||||
const { viewportHeight } = useVisualViewport();
|
||||
const messageList = useTemplateRef<HTMLElement>('messageList');
|
||||
const showScrollButton = ref(false);
|
||||
const copiedId = ref('');
|
||||
const suggestionsQuery = useQuery({
|
||||
queryKey: computed(() => ['ai-suggestions', locale.value]),
|
||||
queryFn: ({ signal }) =>
|
||||
getChatSuggestions(
|
||||
locale.value,
|
||||
signal,
|
||||
import.meta.env.VITE_AI_API_BASE_URL || '/api/ai',
|
||||
),
|
||||
retry: false,
|
||||
staleTime: 300_000,
|
||||
});
|
||||
const prompts = computed(() =>
|
||||
suggestionsQuery.data.value?.length
|
||||
? suggestionsQuery.data.value
|
||||
: (tm('common.ai.prompts') as string[]),
|
||||
);
|
||||
const pageStyle = computed(() => ({
|
||||
height: viewportHeight.value ? `${viewportHeight.value}px` : '100dvh',
|
||||
}));
|
||||
const isNearBottom = () => {
|
||||
const element = messageList.value;
|
||||
return (
|
||||
!element ||
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight < 160
|
||||
);
|
||||
};
|
||||
const scrollToBottom = (behavior: ScrollBehavior = 'auto') =>
|
||||
void nextTick(() =>
|
||||
messageList.value?.scrollTo({
|
||||
top: messageList.value.scrollHeight,
|
||||
behavior,
|
||||
}),
|
||||
);
|
||||
const updateScrollState = () => {
|
||||
showScrollButton.value = !isNearBottom();
|
||||
};
|
||||
const send = (content: string) => {
|
||||
void sendMessage(content);
|
||||
scrollToBottom();
|
||||
};
|
||||
const copyMessage = async (id: string, content: string) => {
|
||||
await navigator.clipboard.writeText(content);
|
||||
copiedId.value = id;
|
||||
window.setTimeout(() => {
|
||||
copiedId.value = '';
|
||||
}, 1200);
|
||||
};
|
||||
watch(
|
||||
messages,
|
||||
() => {
|
||||
if (!showScrollButton.value) scrollToBottom();
|
||||
},
|
||||
{ deep: true, flush: 'post' },
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-page {
|
||||
position: fixed;
|
||||
|
||||
@ -1,6 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
import FavoriteButton from '@/components/shop/FavoriteButton.vue';
|
||||
import { useUserStore } from '@/store/modules/user';
|
||||
import { computed, shallowRef, watch } from 'vue';
|
||||
import { useQuery } from '@tanstack/vue-query';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router';
|
||||
import { getProduct } from '@/api/modules/products';
|
||||
import { useCartStore } from '@/store/modules/cart';
|
||||
import {
|
||||
formatProductPrice,
|
||||
getLocalizedText,
|
||||
getSafeProductImage,
|
||||
parseProductId,
|
||||
} from '@/utils/product';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { locale, t } = useI18n();
|
||||
const cart = useCartStore();
|
||||
const user = useUserStore();
|
||||
const productId = computed(() => parseProductId(route.params.id));
|
||||
const productQuery = useQuery({
|
||||
queryKey: computed(() => ['products', productId.value]),
|
||||
queryFn: ({ signal }) => {
|
||||
if (productId.value === undefined) throw new Error('Invalid product ID');
|
||||
return getProduct(productId.value, signal);
|
||||
},
|
||||
enabled: computed(() => productId.value !== undefined),
|
||||
});
|
||||
const product = computed(() => productQuery.data.value);
|
||||
const name = computed(() =>
|
||||
product.value ? getLocalizedText(product.value.name, locale.value) : '',
|
||||
);
|
||||
const subtitle = computed(() =>
|
||||
product.value ? getLocalizedText(product.value.subtitle, locale.value) : '',
|
||||
);
|
||||
const description = computed(() =>
|
||||
product.value
|
||||
? getLocalizedText(product.value.description, locale.value)
|
||||
: '',
|
||||
);
|
||||
const quantity = shallowRef(1);
|
||||
const actionMessage = shallowRef('');
|
||||
watch(productId, () => {
|
||||
quantity.value = 1;
|
||||
actionMessage.value = '';
|
||||
});
|
||||
const available = computed(
|
||||
() =>
|
||||
!!product.value &&
|
||||
product.value.stock > 0 &&
|
||||
product.value.status === 'on_sale',
|
||||
);
|
||||
watch(
|
||||
() => product.value?.stock,
|
||||
(stock) => {
|
||||
if (stock !== undefined)
|
||||
quantity.value = Math.max(1, Math.min(quantity.value, stock));
|
||||
},
|
||||
);
|
||||
const addToCart = () => {
|
||||
if (!product.value || !available.value) return;
|
||||
cart.add(product.value, quantity.value);
|
||||
actionMessage.value = t('common.shop.detail.cartAdded', {
|
||||
count: quantity.value,
|
||||
});
|
||||
};
|
||||
const showBuyAction = () => {
|
||||
if (!available.value) return;
|
||||
actionMessage.value = t('common.shop.detail.checkoutDemo', {
|
||||
count: quantity.value,
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="product-detail">
|
||||
<div v-if="productQuery.isPending.value" class="detail-state">
|
||||
<div v-if="productId === undefined" class="detail-state" role="alert">
|
||||
<p>{{ t('common.shop.detail.invalidProduct') }}</p>
|
||||
<RouterLink to="/shop">{{
|
||||
t('common.shop.detail.backProducts')
|
||||
}}</RouterLink>
|
||||
</div>
|
||||
<div v-else-if="productQuery.isPending.value" class="detail-state">
|
||||
{{ t('common.global.loading') }}
|
||||
</div>
|
||||
<div
|
||||
@ -13,7 +95,7 @@
|
||||
{{ t('common.global.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
<template v-else-if="product">
|
||||
<template v-else-if="product && productId !== undefined">
|
||||
<section class="product-media">
|
||||
<img :src="getSafeProductImage(product.coverUrl)" :alt="name" /><button
|
||||
type="button"
|
||||
@ -77,6 +159,7 @@
|
||||
<button
|
||||
type="button"
|
||||
:aria-label="t('common.shop.detail.decreaseQuantity')"
|
||||
:disabled="!available || quantity <= 1"
|
||||
@click="quantity = Math.max(1, quantity - 1)"
|
||||
>
|
||||
−</button
|
||||
@ -84,14 +167,24 @@
|
||||
><button
|
||||
type="button"
|
||||
:aria-label="t('common.shop.detail.increaseQuantity')"
|
||||
:disabled="!available || quantity >= product.stock"
|
||||
@click="quantity = Math.min(product.stock, quantity + 1)"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" @click="addToCart">
|
||||
{{ t('common.shop.detail.addCart') }}</button
|
||||
><button class="buy" type="button" @click="showBuyAction">
|
||||
<button type="button" :disabled="!available" @click="addToCart">
|
||||
{{
|
||||
available
|
||||
? t('common.shop.detail.addCart')
|
||||
: t('common.shop.status.sold_out')
|
||||
}}</button
|
||||
><button
|
||||
class="buy"
|
||||
type="button"
|
||||
:disabled="!available"
|
||||
@click="showBuyAction"
|
||||
>
|
||||
{{ t('common.shop.detail.buyNow') }}
|
||||
</button>
|
||||
</footer>
|
||||
@ -99,62 +192,6 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import FavoriteButton from '@/components/shop/FavoriteButton.vue';
|
||||
import { useUserStore } from '@/store/modules/user';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useQuery } from '@tanstack/vue-query';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { getProduct } from '@/api/modules/products';
|
||||
import { useCartStore } from '@/store/modules/cart';
|
||||
import {
|
||||
formatProductPrice,
|
||||
getLocalizedText,
|
||||
getSafeProductImage,
|
||||
} from '@/utils/product';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { locale, t } = useI18n();
|
||||
const cart = useCartStore();
|
||||
const user = useUserStore();
|
||||
const productId = computed(() => Number(route.params.id));
|
||||
const productQuery = useQuery({
|
||||
queryKey: computed(() => ['products', productId.value]),
|
||||
queryFn: ({ signal }) => getProduct(productId.value, signal),
|
||||
enabled: computed(
|
||||
() => Number.isInteger(productId.value) && productId.value > 0,
|
||||
),
|
||||
});
|
||||
const product = computed(() => productQuery.data.value);
|
||||
const name = computed(() =>
|
||||
product.value ? getLocalizedText(product.value.name, locale.value) : '',
|
||||
);
|
||||
const subtitle = computed(() =>
|
||||
product.value ? getLocalizedText(product.value.subtitle, locale.value) : '',
|
||||
);
|
||||
const description = computed(() =>
|
||||
product.value
|
||||
? getLocalizedText(product.value.description, locale.value)
|
||||
: '',
|
||||
);
|
||||
const quantity = ref(1);
|
||||
const actionMessage = ref('');
|
||||
const addToCart = () => {
|
||||
if (!product.value) return;
|
||||
cart.add(product.value, quantity.value);
|
||||
actionMessage.value = t('common.shop.detail.cartAdded', {
|
||||
count: quantity.value,
|
||||
});
|
||||
};
|
||||
const showBuyAction = () => {
|
||||
actionMessage.value = t('common.shop.detail.checkoutDemo', {
|
||||
count: quantity.value,
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.product-detail {
|
||||
min-height: 100%;
|
||||
@ -336,6 +373,11 @@ dd {
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.purchase-bar button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.quantity button {
|
||||
min-height: var(--touch-target);
|
||||
color: var(--color-text);
|
||||
|
||||
90
tests/components/ChatPage.test.ts
Normal file
90
tests/components/ChatPage.test.ts
Normal file
@ -0,0 +1,90 @@
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import ChatPage from '@/views/ai/chat.vue';
|
||||
|
||||
vi.mock('@/api/modules/ai', () => ({
|
||||
getChatSuggestions: vi.fn().mockResolvedValue(['Say hello']),
|
||||
}));
|
||||
vi.mock('@/services/ai/fetchStreamProvider', () => ({
|
||||
defaultChatProvider: {
|
||||
async *chat() {
|
||||
yield { type: 'delta', delta: 'Hello Vue' };
|
||||
yield { type: 'done' };
|
||||
},
|
||||
},
|
||||
}));
|
||||
const clients: QueryClient[] = [];
|
||||
enableAutoUnmount(afterEach);
|
||||
beforeEach(() =>
|
||||
vi
|
||||
.mocked(navigator.clipboard.writeText)
|
||||
.mockReset()
|
||||
.mockResolvedValue(undefined),
|
||||
);
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
clients.splice(0).forEach((client) => client.clear());
|
||||
});
|
||||
async function render() {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
clients.push(client);
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [{ path: '/ai/chat', component: ChatPage }],
|
||||
});
|
||||
await router.push('/ai/chat');
|
||||
const wrapper = mount(ChatPage, {
|
||||
global: { plugins: [router, [VueQueryPlugin, { queryClient: client }]] },
|
||||
});
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('Say hello'));
|
||||
await wrapper.get('.suggestions button').trigger('click');
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
describe('chat clipboard feedback', () => {
|
||||
it('handles clipboard denial and clears its feedback', async () => {
|
||||
const wrapper = await render();
|
||||
vi.useFakeTimers();
|
||||
vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(
|
||||
new Error('permission denied'),
|
||||
);
|
||||
await wrapper.get('.message-actions button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.get('[role="status"]').text()).toContain('复制失败');
|
||||
await vi.advanceTimersByTimeAsync(1200);
|
||||
expect(wrapper.find('[role="status"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not show a late copy result after starting a new conversation', async () => {
|
||||
const wrapper = await render();
|
||||
let finish!: () => void;
|
||||
vi.mocked(navigator.clipboard.writeText).mockReturnValueOnce(
|
||||
new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
await wrapper.get('.message-actions button').trigger('click');
|
||||
await wrapper.get('.chat-header button:last-child').trigger('click');
|
||||
finish();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.conversation').exists()).toBe(false);
|
||||
expect(wrapper.find('[role="status"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('已复制');
|
||||
});
|
||||
|
||||
it('copies the assistant text and restores the action label', async () => {
|
||||
const wrapper = await render();
|
||||
vi.useFakeTimers();
|
||||
await wrapper.get('.message-actions button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('Hello Vue');
|
||||
expect(wrapper.get('.message-actions button').text()).toBe('已复制');
|
||||
await vi.advanceTimersByTimeAsync(1200);
|
||||
expect(wrapper.get('.message-actions button').text()).toBe('复制');
|
||||
});
|
||||
});
|
||||
130
tests/components/ProductDetail.test.ts
Normal file
130
tests/components/ProductDetail.test.ts
Normal file
@ -0,0 +1,130 @@
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
|
||||
import { createPinia } from 'pinia';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import ProductDetail from '@/views/shop/detail.vue';
|
||||
import { getProduct } from '@/api/modules/products';
|
||||
import type { Product } from '@/api/modules/products';
|
||||
import { useCartStore } from '@/store/modules/cart';
|
||||
|
||||
vi.mock('@/api/modules/products', () => ({ getProduct: vi.fn() }));
|
||||
const clients: QueryClient[] = [];
|
||||
enableAutoUnmount(afterEach);
|
||||
beforeEach(() =>
|
||||
vi
|
||||
.mocked(getProduct)
|
||||
.mockReset()
|
||||
.mockImplementation(async (id) => ({ ...product, id })),
|
||||
);
|
||||
afterEach(() => clients.splice(0).forEach((client) => client.clear()));
|
||||
|
||||
const product: Product = {
|
||||
id: 1,
|
||||
sku: 'TEST-1',
|
||||
name: { 'zh-CN': '测试商品', 'en-US': 'Test product', 'ja-JP': 'テスト商品' },
|
||||
subtitle: { 'zh-CN': '测试', 'en-US': 'Test', 'ja-JP': 'テスト' },
|
||||
description: { 'zh-CN': '测试', 'en-US': 'Test', 'ja-JP': 'テスト' },
|
||||
category: 'digital',
|
||||
brand: 'Test',
|
||||
coverUrl: '/products/product-placeholder.svg',
|
||||
priceCents: 9900,
|
||||
originalPriceCents: 12_900,
|
||||
stock: 3,
|
||||
sales: 0,
|
||||
rating: 5,
|
||||
status: 'on_sale',
|
||||
featured: false,
|
||||
createdAt: new Date(0).toISOString(),
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
async function render(path: string) {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/shop/products/:id?', component: ProductDetail },
|
||||
{ path: '/shop', component: { template: '<div>Shop</div>' } },
|
||||
],
|
||||
});
|
||||
await router.push(path);
|
||||
const pinia = createPinia();
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
clients.push(client);
|
||||
const wrapper = mount(ProductDetail, {
|
||||
global: {
|
||||
plugins: [router, pinia, [VueQueryPlugin, { queryClient: client }]],
|
||||
stubs: { FavoriteButton: true },
|
||||
},
|
||||
});
|
||||
return { wrapper, router, cart: useCartStore(pinia) };
|
||||
}
|
||||
|
||||
describe('product detail route and purchase state', () => {
|
||||
it.each(['', '0', '-1', '1.5', '1e2', 'abc', '9007199254740992'])(
|
||||
'rejects invalid ID %s without a request or an endless loading state',
|
||||
async (id) => {
|
||||
const { wrapper } = await render(`/shop/products/${id}`);
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain('商品链接无效');
|
||||
expect(wrapper.get('a').attributes('href')).toBe('/shop');
|
||||
expect(getProduct).not.toHaveBeenCalled();
|
||||
expect(wrapper.find('.purchase-bar').exists()).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('resets quantity and confirmation when the route reuses the page', async () => {
|
||||
const { wrapper, router, cart } = await render('/shop/products/1');
|
||||
await vi.waitFor(() =>
|
||||
expect(wrapper.find('.purchase-bar').exists()).toBe(true),
|
||||
);
|
||||
await wrapper.get('button[aria-label="增加数量"]').trigger('click');
|
||||
await wrapper.get('.purchase-bar > button').trigger('click');
|
||||
expect(cart.itemCount).toBe(2);
|
||||
expect(wrapper.get('[role="status"]').text()).toContain('2');
|
||||
await router.push('/shop/products/2');
|
||||
await vi.waitFor(() =>
|
||||
expect(getProduct).toHaveBeenLastCalledWith(2, expect.any(AbortSignal)),
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(wrapper.find('.quantity span').text()).toBe('1'),
|
||||
);
|
||||
expect(wrapper.find('[role="status"]').exists()).toBe(false);
|
||||
await wrapper.get('.purchase-bar > button').trigger('click');
|
||||
expect(
|
||||
cart.lines.map(({ product: item, quantity }) => [item.id, quantity]),
|
||||
).toEqual([
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('disables purchases when there is no stock', async () => {
|
||||
vi.mocked(getProduct).mockResolvedValueOnce({
|
||||
...product,
|
||||
stock: 0,
|
||||
status: 'sold_out',
|
||||
});
|
||||
const { wrapper, cart } = await render('/shop/products/1');
|
||||
await vi.waitFor(() =>
|
||||
expect(wrapper.find('.purchase-bar').exists()).toBe(true),
|
||||
);
|
||||
for (const button of wrapper.findAll('.purchase-bar button'))
|
||||
expect(button.attributes('disabled')).toBeDefined();
|
||||
expect(wrapper.get('.quantity span').text()).toBe('1');
|
||||
expect(cart.lines).toEqual([]);
|
||||
});
|
||||
|
||||
it('lets the user retry a failed detail request', async () => {
|
||||
vi.mocked(getProduct).mockRejectedValueOnce(new Error('offline'));
|
||||
const { wrapper } = await render('/shop/products/1');
|
||||
await vi.waitFor(() =>
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true),
|
||||
);
|
||||
await wrapper.get('[role="alert"] button').trigger('click');
|
||||
await flushPromises();
|
||||
await vi.waitFor(() => expect(wrapper.find('h1').text()).toBe('测试商品'));
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -1,5 +1,5 @@
|
||||
import { effect, stop } from 'vue';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { effect, effectScope, stop } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { useStreamingChat } from '@/composables/useStreamingChat';
|
||||
import type { ChatProvider } from '@/types/ai';
|
||||
|
||||
@ -89,4 +89,112 @@ describe('useStreamingChat', () => {
|
||||
);
|
||||
expect(chat.streaming.value).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['stop', 'clear'] as const)(
|
||||
'%s detaches a late provider before starting a new conversation',
|
||||
async (action) => {
|
||||
let releaseOld!: () => void;
|
||||
let releaseNew!: () => void;
|
||||
const oldGate = new Promise<void>((resolve) => {
|
||||
releaseOld = resolve;
|
||||
});
|
||||
const newGate = new Promise<void>((resolve) => {
|
||||
releaseNew = resolve;
|
||||
});
|
||||
let attempts = 0;
|
||||
let oldSignal: AbortSignal | undefined;
|
||||
const chat = useStreamingChat({
|
||||
async *chat(_messages, options) {
|
||||
if (++attempts === 1) {
|
||||
oldSignal = options?.signal;
|
||||
await oldGate;
|
||||
yield { type: 'start', conversationId: 'stale-conversation' };
|
||||
yield { type: 'usage', inputTokens: 999, outputTokens: 999 };
|
||||
throw new Error('Late failure');
|
||||
}
|
||||
yield { type: 'start', conversationId: 'new-conversation' };
|
||||
yield { type: 'delta', delta: 'New ' };
|
||||
await newGate;
|
||||
yield { type: 'delta', delta: 'response' };
|
||||
},
|
||||
});
|
||||
const oldRequest = chat.sendMessage('Old question');
|
||||
chat[action]();
|
||||
expect(oldSignal?.aborted).toBe(true);
|
||||
expect(chat.streaming.value).toBe(false);
|
||||
expect(chat.messages.value[chat.messages.value.length - 1]?.status).toBe(
|
||||
action === 'clear' ? undefined : 'stopped',
|
||||
);
|
||||
const newRequest = chat.sendMessage('New question');
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
chat.messages.value[chat.messages.value.length - 1]?.content,
|
||||
).toBe('New '),
|
||||
);
|
||||
releaseOld();
|
||||
await oldRequest;
|
||||
expect(chat.conversationId.value).toBe('new-conversation');
|
||||
expect(chat.usage.value).toBeNull();
|
||||
expect(chat.error.value).toBeNull();
|
||||
expect(chat.streaming.value).toBe(true);
|
||||
releaseNew();
|
||||
await newRequest;
|
||||
expect(chat.messages.value[chat.messages.value.length - 1]?.content).toBe(
|
||||
'New response',
|
||||
);
|
||||
expect(chat.messages.value[chat.messages.value.length - 1]?.status).toBe(
|
||||
'ready',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('ignores a late rejection after clear', async () => {
|
||||
let fail!: (reason: Error) => void;
|
||||
const pendingFailure = new Promise<void>((_resolve, reject) => {
|
||||
fail = reject;
|
||||
});
|
||||
const chat = useStreamingChat({
|
||||
async *chat() {
|
||||
await pendingFailure;
|
||||
yield { type: 'done' };
|
||||
},
|
||||
});
|
||||
const pending = chat.sendMessage('Hello');
|
||||
chat.clear();
|
||||
fail(new Error('stale error'));
|
||||
await pending;
|
||||
expect(chat.messages.value).toEqual([]);
|
||||
expect(chat.error.value).toBeNull();
|
||||
});
|
||||
|
||||
it('aborts on scope disposal and prevents further requests', async () => {
|
||||
const scope = effectScope();
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let signal: AbortSignal | undefined;
|
||||
const chat = scope.run(() =>
|
||||
useStreamingChat({
|
||||
async *chat(_messages, options) {
|
||||
signal = options?.signal;
|
||||
await gate;
|
||||
yield { type: 'delta', delta: 'late' };
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!chat) throw new Error('Unable to create chat scope');
|
||||
const pending = chat.sendMessage('Hello');
|
||||
scope.stop();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
release();
|
||||
await pending;
|
||||
await chat.sendMessage('After leaving');
|
||||
await chat.regenerate();
|
||||
expect(chat.messages.value).toHaveLength(2);
|
||||
expect(chat.messages.value[chat.messages.value.length - 1]?.content).toBe(
|
||||
'',
|
||||
);
|
||||
expect(chat.streaming.value).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@ -70,4 +70,26 @@ describe('fetchStreamChatProvider', () => {
|
||||
});
|
||||
expect(onUnauthorized).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('preserves the FastAPI message and trace on a failed request', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () =>
|
||||
Response.json(
|
||||
{
|
||||
code: 429,
|
||||
message: 'Too many requests',
|
||||
data: null,
|
||||
},
|
||||
{ status: 429, headers: { 'X-Request-ID': 'fastapi-trace' } },
|
||||
),
|
||||
),
|
||||
);
|
||||
const provider = new FetchStreamChatProvider('/api/ai/chat');
|
||||
await expect(provider.chat([]).next()).rejects.toMatchObject({
|
||||
message: 'Too many requests',
|
||||
status: 429,
|
||||
requestId: 'fastapi-trace',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { parseSseEvent, parseSseStream } from '@/services/ai/sse';
|
||||
|
||||
describe('sSE parser', () => {
|
||||
@ -54,4 +54,60 @@ describe('sSE parser', () => {
|
||||
{ type: 'done' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('accepts FastAPI events across UTF-8 and CRLF byte boundaries', async () => {
|
||||
const data = new TextEncoder().encode(
|
||||
'data: {"type":"start","id":"fastapi-id"}\r\n\r\n' +
|
||||
'data: {"type":"delta","delta":"你好、Vue"}\r\n\r\n' +
|
||||
'data: {"type":"finish","reason":"stop"}\r\n\r\n',
|
||||
);
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (const byte of data) controller.enqueue(Uint8Array.of(byte));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const chunks = [];
|
||||
for await (const chunk of parseSseStream(stream)) chunks.push(chunk);
|
||||
expect(chunks).toEqual([
|
||||
{ type: 'start', conversationId: 'fastapi-id' },
|
||||
{ type: 'delta', delta: '你好、Vue' },
|
||||
{ type: 'done' },
|
||||
]);
|
||||
expect(stream.locked).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['early return', 'invalid event'])(
|
||||
'cancels the transport after %s',
|
||||
async (scenario) => {
|
||||
const cancel = vi.fn();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(
|
||||
new TextEncoder().encode(
|
||||
scenario === 'early return'
|
||||
? 'data: {"type":"delta","delta":"Hi"}\n\n'
|
||||
: 'data: {"type":"unknown"}\n\n',
|
||||
),
|
||||
);
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const events = parseSseStream(stream)[Symbol.asyncIterator]();
|
||||
let failure: unknown;
|
||||
try {
|
||||
await events.next();
|
||||
await events.return?.();
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
expect(failure instanceof Error ? failure.message : undefined).toBe(
|
||||
scenario === 'invalid event'
|
||||
? 'Unsupported chat stream event'
|
||||
: undefined,
|
||||
);
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(stream.locked).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user