Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-08 15:36:47 +08:00
commit a2931e0095
37 files changed
+1790 -126

No files matched your search

@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
approveOrderProfileTestSuite,
confirmOrderProfileBlindTestReviews,
@@ -36,7 +37,7 @@ const router = useRouter();
const message = useMessage();
const { t } = useI18n();
const profileId = Number(route.params.profileId);
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const suite = ref<OrderProfileTestSuite | null>(null);
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
const selectedSampleKey = ref('');
@@ -11,6 +11,7 @@ import { useI18n } from 'vue-i18n';
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
@@ -33,7 +34,7 @@ const tables = ref<Array<{ table_id: string; page_no: number; row_count: number;
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
const documentId = ref(0);
const tableId = ref('');
const browserSessionId = crypto.randomUUID();
const browserSessionId = createRandomUuid();
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
@@ -140,7 +141,7 @@ async function finish(enterEditor: boolean): Promise<void> {
document_id: documentId.value,
main_table_id: tableId.value,
browser_session_id: browserSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
};
const profile = await completeOrderDocumentProfileWizard(payload);
message.success(t('admin.shippingOrderProfiles.created'));
@@ -21,6 +21,7 @@ import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { BusinessError } from "@/shared/api/client";
import { useMessage } from "@/shared/composables/useMessage";
import { createRandomUuid } from "@/shared/utils/id";
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
import {
authorizeOrderProfilePreviewPages,
@@ -218,7 +219,7 @@ const documentAnchorNotice = ref('');
const history = ref<OrderProfileCanvasRegion[][]>([]);
const future = ref<OrderProfileCanvasRegion[][]>([]);
const editLeaseToken = ref<string | null>(null);
const editorSessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const editorSessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const compactEditor = ref(false);
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
@@ -1820,7 +1821,7 @@ const save = async (automatic = false) => {
expected_lock_version: existingProfile.lock_version,
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value || '',
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
...(adapterPayload.splitRuleConfirmationTokens
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
: {}),
@@ -2139,7 +2140,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
await decideOrderDocumentProfileSuggestion(active.value.id, {
suggestion_id: item.id, suggestion_checksum: item.checksum, suggestion_summary: item.summary, decision,
adjustment_summary: adjustmentSummary,
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: crypto.randomUUID(),
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: createRandomUuid(),
});
if (decision !== 'rejected') {
checkpoint();
@@ -2758,7 +2759,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
const acquireEditLease = async (profileId: number): Promise<void> => {
const lease = await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: editorSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
editLeaseToken.value = lease.lease_token;
startLeaseRenewal();
@@ -2774,7 +2775,7 @@ const renewEditLease = async (): Promise<void> => {
const lease = await renewOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
editLeaseToken.value = lease.lease_token;
} catch (error) {
@@ -2961,7 +2962,7 @@ const recoverEditLease = async (confirmTakeover = false) => {
try {
const lease = await acquireOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
confirm_takeover: confirmTakeover,
});
editLeaseToken.value = lease.lease_token;
@@ -3124,7 +3125,7 @@ onBeforeUnmount(() => {
void releaseOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
}
});
@@ -10,6 +10,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
acquireOrderDocumentProfileEditLease,
confirmOrderProfilePublishCheck,
@@ -31,7 +32,7 @@ const runs = ref<OrderProfileValidationRun[]>([]);
const report = ref<OrderProfilePublishCheckReport | null>(null);
const confirmed = ref<string[]>([]);
const busy = ref(false);
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const leaseToken = ref('');
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
@@ -92,7 +93,7 @@ async function ensureLease(): Promise<boolean> {
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) {
@@ -121,7 +122,7 @@ async function createReport(): Promise<void> {
overlap_validation_run_id: overlapRun.value?.id,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
confirmed.value = [];
await loadRuns();
@@ -141,7 +142,7 @@ async function publish(): Promise<void> {
confirmed_warning_keys: confirmed.value,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
await router.replace({
name: 'AdminShippingOrderDocumentProfileVersionDetail',
@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import { getShippingOrderSchemaVersion } from '@/features/admin/api/shipping-order-schema.api';
import {
acquireOrderDocumentProfileEditLease,
@@ -42,7 +43,7 @@ const leaseToken = ref('');
const profile = ref<ShippingOrderDocumentProfile | null>(null);
const sample = ref<OrderProfileBoundSample | null>(null);
const fieldNames = ref(new Map<string, string>());
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
const raw = sampleRun.value?.summary?.validation_evidence;
@@ -206,7 +207,7 @@ async function ensureLease(): Promise<boolean> {
if (leaseToken.value) return true;
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId, operation_id: crypto.randomUUID(),
browser_session_id: sessionId, operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) { report(error); return false; }
@@ -221,7 +222,7 @@ async function validateCurrentDraft(): Promise<void> {
}
executing.value = true;
try {
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() });
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: createRandomUuid() });
await runOrderProfileInstantCheck(profileId, payload());
await runOrderProfileCurrentSample(profileId, { ...payload(), sample_binding_id: sample.value.id });
await loadRuns();
@@ -10,6 +10,7 @@ import { computed, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
previewOrderProfileSampleXfaSplitRules,
} from '@/features/admin/api/shipping-order-document-profile.api';
@@ -97,9 +98,10 @@ const showUnsavedConfirmBanner = computed(() => (
/**
* 生成 seg-/rule-/stage- 前缀的客户端 UUID(无连字符)。
* HTTP 非安全上下文亦可用(经 createRandomUuid 降级)。
*/
function newClientId(prefix: 'seg' | 'rule' | 'stage'): string {
return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`;
return `${prefix}-${createRandomUuid().replace(/-/g, '')}`;
}
/**
@@ -1,6 +1,9 @@
/**
* features/chat/components/ChatMessageList.vue
* 消息列表主区域:滚动容器、欢迎页、消息气泡与思考中占位。
* 用途:消息列表主区域(滚动容器、欢迎页、气泡与思考中占位)。
* 依赖:ChatMessageBubble、各类进度卡、chat.types。
* 逻辑:按 shouldRenderMessage 过滤;货代抽取卡按 run / upload_batch / client_submission 去重只留最后一张;
* 用户气泡在下方已有抽取进度卡时对附件启用 summaryOnly,避免与进度卡重复堆文件明细。
*/
<script setup lang="ts">
import type { Ref } from 'vue';
@@ -84,7 +87,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
/** 同一 Run / 上传批次 / 提交幂等键只展示最后一张状态卡,避免历史恢复造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
@@ -102,7 +105,12 @@ const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: numbe
|| current.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
if (!runIdentity && !batchIdentity) return false;
const submissionIdentity = String(
payload.shipping_order_extraction_client_submission_id
|| current.shipping_order_extraction_state.clientSubmissionId
|| '',
).trim();
if (!runIdentity && !batchIdentity && !submissionIdentity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
@@ -119,8 +127,14 @@ const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: numbe
|| candidate.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
const candidateSubmissionIdentity = String(
candidatePayload.shipping_order_extraction_client_submission_id
|| candidate.shipping_order_extraction_state.clientSubmissionId
|| '',
).trim();
return Boolean(
(batchIdentity && candidateBatchIdentity === batchIdentity)
|| (submissionIdentity && candidateSubmissionIdentity === submissionIdentity)
|| (runIdentity && candidateRunIdentity === runIdentity),
);
});
@@ -139,6 +153,20 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
}
return true;
};
/**
* 用户消息与下一轮用户输入之间,是否已有货代订单抽取进度卡。
* 核心逻辑:有进度卡时附件区只留摘要,文件明细交给进度卡展示。
*/
const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number): boolean => {
for (let i = index + 1; i < items.length; i += 1) {
const candidate = items[i];
if (!candidate) continue;
if (candidate.role === 'user') break;
if (candidate.shipping_order_extraction_state) return true;
}
return false;
};
</script>
<template>
@@ -180,6 +208,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
:shipping-handlers="shippingHandlers"
:training-handlers="trainingHandlers"
:compact-shipping-progress="compactShippingProgress"
:attachment-summary-only="hasFollowingShippingProgressCard(messages, index)"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@@ -1,22 +1,82 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.spec.ts
* 用途:校验已发送附件分层展示(chip / 摘要折叠 / 进度卡并存只留摘要)。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:覆盖 ≤3 chip、>3 摘要可展开、summaryOnly 不可展开。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import type { ChatMessageAttachment } from '../../types/chat.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
attachment: {
summaryCount: '{count} 个附件',
expandList: '展开附件列表',
collapseList: '收起附件列表',
},
},
},
},
});
const makeAttachments = (count: number): ChatMessageAttachment[] =>
Array.from({ length: count }, (_, index) => ({
name: `file-${index + 1}.eml`,
type: 'document' as const,
source: 'local' as const,
size: 1024 * (index + 1),
extension: 'eml',
}));
describe('ChatMessageAttachmentList', () => {
it('keeps many sent attachments in a single horizontally scrollable row', () => {
it('renders compact chips when there are at most three attachments', () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: {
attachments: [
{ name: 'one.eml', type: 'document', source: 'local', size: 1024, extension: 'eml' },
{ name: 'two.eml', type: 'document', source: 'local', size: 2048, extension: 'eml' },
{ name: 'three.eml', type: 'document', source: 'local', size: 3072, extension: 'eml' },
],
},
props: { attachments: makeAttachments(3) },
global: { plugins: [i18n] },
});
const list = wrapper.get('[data-testid="chat-message-attachment-list"]');
expect(list.classes()).toContain('overflow-x-auto');
expect(list.classes()).toContain('flex-nowrap');
expect(wrapper.findAll('article')).toHaveLength(3);
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(true);
expect(wrapper.findAll('[data-testid="chat-message-attachment-chip"]')).toHaveLength(3);
expect(wrapper.find('[data-testid="chat-message-attachment-summary"]').exists()).toBe(false);
});
it('collapses many attachments into a summary that expands into a scrollable list', async () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: { attachments: makeAttachments(5) },
global: { plugins: [i18n] },
});
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
expect(summary.text()).toContain('5 个附件');
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
await summary.trigger('click');
const expanded = wrapper.get('[data-testid="chat-message-attachment-expanded"]');
expect(expanded.classes()).toContain('max-h-40');
expect(expanded.findAll('article')).toHaveLength(5);
});
it('keeps only the summary when a shipping progress card follows the message', async () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: {
attachments: makeAttachments(2),
summaryOnly: true,
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(false);
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
expect(summary.text()).toContain('2 个附件');
await summary.trigger('click');
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
});
});
@@ -1,18 +1,49 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.vue
* 用途:在用户消息中展示已发送附件快照。
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
* 用途:在用户消息中分层展示已发送附件快照(少文件 chip / 多文件摘要折叠)。
* 依赖:lucide 图标、vue-i18n、attachmentCard.utils、chat.types。
* 逻辑:ChatMessageBubble 传入附件与 summaryOnly;≤3 用紧凑 chip,>3 默认摘要条可展开纵向列表;
* 下方已有货代进度卡时 summaryOnly=true,只留摘要避免与进度卡重复。
*/
<script setup lang="ts">
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronUp, FileAudio, FileImage, FileText, FileVideo, Link2, Paperclip } from 'lucide-vue-next';
import { formatAttachmentSize } from '../../utils/attachmentCard.utils';
import type { ChatMessageAttachment } from '../../types/chat.types';
const { attachments } = defineProps<{
/** 超过该数量后默认折叠为摘要条,避免气泡内横排大卡。 */
const CHIP_LIMIT = 3;
/** 展开列表内部最大高度(约 4~5 行)。 */
const EXPANDED_LIST_MAX_HEIGHT_CLASS = 'max-h-40';
const props = defineProps<{
attachments: ChatMessageAttachment[];
/** 下方已有货代进度卡时为 true:只显示摘要,不展开明细。 */
summaryOnly?: boolean;
}>();
const { t } = useI18n();
const expanded = ref(false);
const attachmentCount = computed(() => props.attachments.length);
const useChips = computed(() => !props.summaryOnly && attachmentCount.value > 0 && attachmentCount.value <= CHIP_LIMIT);
const useCollapsibleSummary = computed(() => !props.summaryOnly && attachmentCount.value > CHIP_LIMIT);
const showSummaryBar = computed(() => Boolean(props.summaryOnly) || useCollapsibleSummary.value);
const totalSizeLabel = computed(() => {
let total = 0;
let known = 0;
for (const item of props.attachments) {
if (typeof item.size === 'number' && Number.isFinite(item.size) && item.size >= 0) {
total += item.size;
known += 1;
}
}
if (!known) return '';
return formatAttachmentSize(total);
});
/** 根据附件来源与业务类型选择只读消息卡片图标。 */
function attachmentIcon(attachment: ChatMessageAttachment) {
if (attachment.source === 'remote') return Link2;
@@ -29,35 +60,104 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
if (attachment.source === 'remote') return 'URL';
return attachment.type.toUpperCase().slice(0, 5);
}
/** 切换多附件摘要的展开/收起;summaryOnly 时不可展开。 */
function toggleExpanded() {
if (props.summaryOnly) return;
expanded.value = !expanded.value;
}
</script>
<template>
<div
v-if="attachments.length > 0"
v-if="attachmentCount > 0"
data-testid="chat-message-attachment-list"
class="mb-2 flex w-full flex-nowrap justify-end gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
class="mb-2 w-full"
>
<article
v-for="(attachment, attachmentIndex) in attachments"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex h-[68px] w-[250px] shrink-0 items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900"
:title="attachment.name"
<!-- ≤3:紧凑 chip,宽度自适应 -->
<div
v-if="useChips"
data-testid="chat-message-attachment-chips"
class="flex w-full flex-wrap justify-end gap-1.5"
>
<div
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
<article
v-for="(attachment, attachmentIndex) in props.attachments"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex h-10 max-w-[220px] items-center gap-2 rounded-lg border border-white/25 bg-white/95 px-2.5 text-slate-800 shadow-sm dark:border-white/10 dark:bg-slate-900/90 dark:text-slate-100"
:title="attachment.name"
data-testid="chat-message-attachment-chip"
>
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
<span class="mt-0.5 max-w-8 truncate text-[8px] font-bold leading-none">
{{ attachmentBadge(attachment) }}
</span>
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
{{ formatAttachmentSize(attachment.size) }}
<div
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-semibold leading-tight">{{ attachment.name }}</div>
<div class="mt-0.5 flex items-center gap-1 text-[10px] leading-none text-slate-500 dark:text-slate-400">
<span>{{ attachmentBadge(attachment) }}</span>
<span v-if="attachment.size !== undefined">· {{ formatAttachmentSize(attachment.size) }}</span>
</div>
</div>
</article>
</div>
<!-- >3 或货代进度卡并存:摘要条 -->
<div v-else-if="showSummaryBar" class="flex w-full flex-col items-end gap-1.5">
<button
type="button"
data-testid="chat-message-attachment-summary"
class="inline-flex max-w-full items-center gap-2 rounded-lg border border-white/25 bg-white/15 px-3 py-2 text-left text-white transition hover:bg-white/20"
:class="props.summaryOnly ? 'cursor-default' : 'cursor-pointer'"
:aria-expanded="props.summaryOnly ? undefined : expanded"
:aria-controls="props.summaryOnly || !expanded ? undefined : 'chat-message-attachment-expanded'"
:aria-label="props.summaryOnly
? t('chat.attachment.summaryCount', { count: attachmentCount })
: (expanded ? t('chat.attachment.collapseList') : t('chat.attachment.expandList'))"
@click="toggleExpanded"
>
<Paperclip class="h-3.5 w-3.5 shrink-0 opacity-90" aria-hidden="true" />
<span class="truncate text-xs font-semibold">
{{ t('chat.attachment.summaryCount', { count: attachmentCount }) }}
</span>
<span v-if="totalSizeLabel" class="shrink-0 text-[11px] opacity-80">· {{ totalSizeLabel }}</span>
<component
:is="expanded ? ChevronUp : ChevronDown"
v-if="!props.summaryOnly"
class="h-3.5 w-3.5 shrink-0 opacity-80"
aria-hidden="true"
/>
</button>
<div
v-if="useCollapsibleSummary && expanded"
id="chat-message-attachment-expanded"
data-testid="chat-message-attachment-expanded"
class="w-full max-w-sm overflow-y-auto rounded-xl border border-white/20 bg-white/95 p-1.5 shadow-sm dark:bg-slate-900/95"
:class="EXPANDED_LIST_MAX_HEIGHT_CLASS"
>
<article
v-for="(attachment, attachmentIndex) in props.attachments"
:key="`expanded-${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex items-center gap-2 rounded-lg px-2 py-1.5 text-slate-800 dark:text-slate-100"
:title="attachment.name"
>
<div
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-semibold">{{ attachment.name }}</div>
<div class="mt-0.5 text-[10px] text-slate-500 dark:text-slate-400">
<span>{{ attachmentBadge(attachment) }}</span>
<span v-if="attachment.size !== undefined"> · {{ formatAttachmentSize(attachment.size) }}</span>
</div>
</div>
</article>
</div>
</article>
</div>
</div>
</template>
@@ -3,6 +3,7 @@
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
* 用户附件区支持 summaryOnly:下方已有抽取进度卡时只显示附件摘要。
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
*/
<script setup lang="ts">
@@ -60,6 +61,7 @@ const {
handlers,
leaveHandlers,
shippingHandlers,
attachmentSummaryOnly = false,
} = defineProps<{
message: ChatMessage;
index: number;
@@ -74,6 +76,8 @@ const {
shippingHandlers: ShippingMessageHandlers;
trainingHandlers: TrainingHandlers;
compactShippingProgress?: boolean;
/** 下方已有货代进度卡时,用户气泡附件只显示摘要。 */
attachmentSummaryOnly?: boolean;
}>();
const emit = defineEmits<{
@@ -729,6 +733,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<ChatMessageAttachmentList
v-if="message.attachments?.length"
:attachments="message.attachments"
:summary-only="attachmentSummaryOnly"
/>
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
</template>
@@ -409,6 +409,167 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
expect(api.getRun).toHaveBeenCalledWith('SNER-LATEST', expect.any(AbortSignal));
harness.runs.stopPolling();
});
it('restores the submission primary instead of a newer sibling Run without client_submission_id', async () => {
const sibling = Object.assign(run({
run_no: 'SNER-SIBLING',
conversation_id: 'conv-1',
status: 'processing',
created_at: '2026-09-07T11:25:47Z',
}), { client_submission_id: null, upload_batch_id: null });
const primary = Object.assign(run({
run_no: 'SNER-PRIMARY',
conversation_id: 'conv-1',
status: 'processing',
created_at: '2026-09-07T10:54:34Z',
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
// 模拟后端会话短列表:sibling 虽更新,但 primary 排前(或至少出现在列表中)。
api.listRuns.mockResolvedValue({ items: [sibling, primary] });
api.getRun.mockResolvedValue(primary);
const harness = createHarness();
harness.conversationId.value = 'conv-1';
await harness.runs.restoreForConversation('conv-1');
expect(api.getRun).toHaveBeenCalledWith('SNER-PRIMARY', expect.any(AbortSignal));
expect(harness.runs.getActiveRunNo()).toBe('SNER-PRIMARY');
expect(harness.messages.value.filter((item) => item.shipping_order_extraction_state)).toHaveLength(1);
expect(harness.messages.value[0]?.payload).toMatchObject({
order_extraction_run_no: 'SNER-PRIMARY',
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
});
harness.runs.stopPolling();
});
it('keeps an existing primary progress card instead of upserting a sibling on restore', async () => {
const primary = Object.assign(run({
run_no: 'SNER-PRIMARY',
conversation_id: 'conv-1',
status: 'partially_completed',
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
const sibling = Object.assign(run({
run_no: 'SNER-SIBLING',
conversation_id: 'conv-1',
status: 'partially_completed',
}), { client_submission_id: null, upload_batch_id: null });
api.listRuns.mockResolvedValue({ items: [sibling] });
api.getRun.mockResolvedValue(primary);
const harness = createHarness();
harness.conversationId.value = 'conv-1';
harness.messages.value = [{
role: 'assistant',
type: 'text',
content: '',
local_id: 'existing-primary-card',
shipping_order_extraction_state: {
status: 'partially_completed',
runNo: 'SNER-PRIMARY',
clientSubmissionId: 'SUB-ONCE',
uploadBatchId: null,
summary: {
totalDocuments: 22,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 15,
reviewRequiredDocuments: 7,
failedDocuments: 0,
cancelledDocuments: 0,
candidateCount: 0,
},
availableActions: [],
terminal: true,
refreshFailed: false,
},
payload: {
formId: 'shipping-order-extraction-run:SNER-PRIMARY',
order_extraction_run_no: 'SNER-PRIMARY',
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
},
}];
await harness.runs.restoreForConversation('conv-1');
// sibling 不在已有卡列表命中时,仍应直拉已有卡 run_no,而不是 list[0] sibling。
expect(api.getRun).toHaveBeenCalledWith('SNER-PRIMARY', expect.any(AbortSignal));
expect(harness.messages.value.filter((item) => item.shipping_order_extraction_state)).toHaveLength(1);
expect(harness.messages.value[0]?.payload?.order_extraction_run_no).toBe('SNER-PRIMARY');
});
it('prunes an orphan sibling progress card when restoring a submission primary', async () => {
const primary = Object.assign(run({
run_no: 'SNER-PRIMARY',
conversation_id: 'conv-1',
status: 'partially_completed',
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
api.listRuns.mockResolvedValue({ items: [primary] });
api.getRun.mockResolvedValue(primary);
const harness = createHarness();
harness.conversationId.value = 'conv-1';
harness.messages.value = [
{
role: 'assistant',
type: 'text',
content: '',
local_id: 'primary-card',
shipping_order_extraction_state: {
status: 'partially_completed',
runNo: 'SNER-PRIMARY',
clientSubmissionId: 'SUB-ONCE',
summary: {
totalDocuments: 1,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 1,
reviewRequiredDocuments: 0,
failedDocuments: 0,
cancelledDocuments: 0,
candidateCount: 0,
},
availableActions: [],
terminal: true,
refreshFailed: false,
},
payload: {
formId: 'shipping-order-extraction-run:SNER-PRIMARY',
order_extraction_run_no: 'SNER-PRIMARY',
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
},
},
{
role: 'assistant',
type: 'text',
content: '',
local_id: 'orphan-sibling-card',
shipping_order_extraction_state: {
status: 'partially_completed',
runNo: 'SNER-SIBLING',
summary: {
totalDocuments: 1,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 1,
reviewRequiredDocuments: 0,
failedDocuments: 0,
cancelledDocuments: 0,
candidateCount: 0,
},
availableActions: [],
terminal: true,
refreshFailed: false,
},
payload: {
formId: 'shipping-order-extraction-run:SNER-SIBLING',
order_extraction_run_no: 'SNER-SIBLING',
},
},
];
await harness.runs.restoreForConversation('conv-1');
const cards = harness.messages.value.filter((item) => item.shipping_order_extraction_state);
expect(cards).toHaveLength(1);
expect(cards[0]?.payload?.order_extraction_run_no).toBe('SNER-PRIMARY');
});
});
@@ -7,6 +7,7 @@
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
* 会话恢复锚定 submission primary(client_submission_id)或已有进度卡,禁止 sibling Run 再写第二张卡。
*/
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
import {
@@ -72,6 +73,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
submissionOrdinal: run.submission_ordinal ?? null,
composerContextId: run.composer_context_id || null,
uploadBatchId: run.upload_batch_id || null,
clientSubmissionId: run.client_submission_id || null,
runNo: run.run_no,
sourceRunNo: run.reparse?.source_run_no || null,
supersedingRunNo: run.reparse?.superseding_run_no || null,
@@ -268,6 +270,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
/**
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
* 核心逻辑:按 formId / run_no / upload_batch_id / client_submission_id 合并;
* 同一次提交的 sibling(无 submission 键)不得因 run_no 不同再建第二张卡。
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
* @returns 当前会话内原位更新后的助手状态消息。
*/
@@ -278,6 +282,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const formId = `shipping-order-extraction-run:${run.run_no}`;
const state = mapOrderExtractionRunToMessageState(run);
const uploadBatchId = String(run.upload_batch_id || '').trim();
const clientSubmissionId = String(run.client_submission_id || '').trim();
const stateCards = options.messages.value.filter((item) => {
if (item.role !== 'assistant') return false;
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
@@ -286,9 +291,15 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|| item.shipping_order_extraction_state?.uploadBatchId
|| '',
).trim();
const cardSubmissionId = String(
payload.shipping_order_extraction_client_submission_id
|| item.shipping_order_extraction_state?.clientSubmissionId
|| '',
).trim();
return payload.formId === formId
|| payload.order_extraction_run_no === run.run_no
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId);
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId)
|| Boolean(clientSubmissionId && cardSubmissionId === clientSubmissionId);
});
let message = stateCards.find((item) => {
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
@@ -313,6 +324,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
formId,
order_extraction_run_no: run.run_no,
shipping_order_extraction_upload_batch_id: run.upload_batch_id || null,
shipping_order_extraction_client_submission_id: run.client_submission_id || null,
shipping_order_extraction_state: state,
order_extraction_reparse: run.reparse || null,
shipping_order_extraction_review: reviewAttachments || [],
@@ -673,7 +685,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
}));
};
/** 刷新或进入既有会话时恢复最新 Run 状态卡;活动 Run 继续轮询。右侧 Workflow 面板由独立投影恢复。 */
/**
* 刷新或进入既有会话时恢复最新进度卡。
* 核心逻辑:优先锚定已有消息中的 Run 卡;否则取列表中的 submission primary
* (client_submission_id 非空)。禁止按 created_at 最新的 sibling 再建第二张卡。
* 活动 Run 继续轮询;右侧 Workflow 面板由独立投影恢复。
*/
const restoreForConversation = async (conversationId: string): Promise<void> => {
clearActiveRun();
try {
@@ -681,9 +698,39 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const request = createRequestController(generation);
const { items } = await listWorkspaceShippingOrderExtractionRuns(conversationId, 20, request.signal).finally(request.release);
if (options.conversationId.value !== conversationId) return;
const latest = items[0];
if (!latest) return;
const displayRun = await getWorkspaceShippingOrderExtractionRun(latest.run_no, request.signal);
if (!items.length) return;
// [STEP 1] 已有进度卡优先:历史消息中的 primary 卡可能不在短列表窗口内。
const existingCardRunNos: string[] = [];
for (const message of options.messages.value) {
if (!message.shipping_order_extraction_state) continue;
const payload = message.payload && typeof message.payload === 'object'
? message.payload as Record<string, unknown>
: {};
const runNo = String(
payload.order_extraction_run_no
|| message.shipping_order_extraction_state.runNo
|| '',
).trim();
if (runNo) existingCardRunNos.push(runNo);
}
// [STEP 2] 选择恢复锚点:已有卡 → submission primary → 列表首项(后端会话列表已 primary 优先)。
const preferredFromExisting = items.find((item) => existingCardRunNos.includes(item.run_no));
const preferredPrimary = items.find((item) => Boolean(String(item.client_submission_id || '').trim()));
const existingOnlyRunNo = !preferredFromExisting && existingCardRunNos.length
? existingCardRunNos[existingCardRunNos.length - 1]
: '';
const selectedRunNo = String(
preferredFromExisting?.run_no
|| preferredPrimary?.run_no
|| existingOnlyRunNo
|| items[0]?.run_no
|| '',
).trim();
if (!selectedRunNo) return;
const displayRun = await getWorkspaceShippingOrderExtractionRun(selectedRunNo, request.signal);
if (options.conversationId.value !== conversationId) return;
activeRunNo = displayRun.run_no;
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
@@ -691,11 +738,42 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
: await refreshTerminalFacts(displayRun);
if (options.conversationId.value !== conversationId) return;
await upsertRunMessage(displayRun, reviewAttachments);
// [STEP 3] 清掉同会话里无 submission/batch 键的孤儿 sibling 卡(历史误写),避免两张进度并排。
// 有独立 client_submission_id 或 upload_batch_id 的卡保留(另一次真实提交)。
const preferredRunNo = String(displayRun.run_no || '').trim();
const preferredSubmissionId = String(displayRun.client_submission_id || '').trim();
if (preferredRunNo && preferredSubmissionId) {
options.messages.value = options.messages.value.filter((message) => {
if (!message.shipping_order_extraction_state) return true;
const payload = message.payload && typeof message.payload === 'object'
? message.payload as Record<string, unknown>
: {};
const runNo = String(
payload.order_extraction_run_no
|| message.shipping_order_extraction_state.runNo
|| '',
).trim();
if (!runNo || runNo === preferredRunNo) return true;
const batchId = String(
payload.shipping_order_extraction_upload_batch_id
|| message.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
const submissionId = String(
payload.shipping_order_extraction_client_submission_id
|| message.shipping_order_extraction_state.clientSubmissionId
|| '',
).trim();
if (submissionId && submissionId !== preferredSubmissionId) return true;
if (batchId) return true;
return false;
});
}
await acknowledgeTerminalRunWhenVisible(displayRun);
options.onWorkflowRefresh?.();
if (options.conversationId.value !== conversationId) return;
if (ACTIVE_RUN_STATUSES.has(displayRun.status)) {
beginPolling(latest.run_no, 1000);
beginPolling(displayRun.run_no, 1000);
}
} catch {
// 会话历史仍可正常使用;下一次进入会话或手动刷新时重新恢复 Run。
@@ -6,6 +6,7 @@
* 会话多任务聚合阶段 0(2026-08-03):ShippingChatFocusState /
* ShippingOrderExtractionState 增加 userTaskNo、submissionOrdinal、
* composerContextId;与 shipping.api.types 提交 DTO 对齐。
* 2026-09-07:ShippingOrderExtractionState 增加 clientSubmissionId,供恢复锚定 primary。
*/
import type { LeaveAgentOption } from './leave.types';
import type { ShippingTaskUiState } from './shipping.api.types';
@@ -159,6 +160,8 @@ export interface ShippingOrderExtractionState {
composerContextId?: string | null;
/** 同一次文件选择的聊天卡聚合键;绝不参与业务写入或任务路由。 */
uploadBatchId?: string | null;
/** 客户端提交幂等键;仅 submission primary 有值,供恢复时锚定进度卡。 */
clientSubmissionId?: string | null;
/** Run 版本谱系;由后端投影,供历史消息只读隔离。 */
runNo?: string | null;
sourceRunNo?: string | null;
@@ -1896,6 +1896,8 @@ export interface ShippingOrderExtractionRunListItem {
conversation_id: string;
status: ShippingOrderExtractionRunStatus;
phase: string;
/** 仅 submission primary 有值;sibling 为空。会话恢复应优先选有此字段的 Run。 */
client_submission_id?: string | null;
summary: ShippingOrderExtractionRunSummary;
progress_version?: number | null;
last_activity_at?: string | null;
@@ -1992,6 +1994,8 @@ export interface ShippingOrderExtractionRun {
intake_nos: string[];
/** 同一次文件选择的展示聚合键;不是 user_task_no,不能用于业务写入。 */
upload_batch_id?: string | null;
/** 仅 submission primary 有值;sibling Run 为空。 */
client_submission_id?: string | null;
schema_version_id: number;
schema_version?: number | null;
schema_checksum?: string | null;
+4 -1
View File
@@ -33,7 +33,10 @@
"remoteDisabled": "This app does not support URL attachments",
"unsupportedRemote": "Unsupported URL attachment type",
"remoteTypeDisabled": "This app does not support this URL attachment type: {type}",
"missingUploadId": "The upload service did not return a file identifier"
"missingUploadId": "The upload service did not return a file identifier",
"summaryCount": "{count} attachments",
"expandList": "Expand attachment list",
"collapseList": "Collapse attachment list"
},
"agentId": "Agent ID:",
"loadingAgent": "Loading agent...",
+4 -1
View File
@@ -33,7 +33,10 @@
"remoteDisabled": "แอปนี้ไม่รองรับไฟล์แนบจาก URL",
"unsupportedRemote": "ไม่รองรับประเภทไฟล์แนบจาก URL",
"remoteTypeDisabled": "แอปนี้ไม่รองรับไฟล์แนบ URL ประเภท: {type}",
"missingUploadId": "บริการอัปโหลดไม่ได้ส่งคืนรหัสไฟล์"
"missingUploadId": "บริการอัปโหลดไม่ได้ส่งคืนรหัสไฟล์",
"summaryCount": "ไฟล์แนบ {count} รายการ",
"expandList": "ขยายรายการไฟล์แนบ",
"collapseList": "ยุบรายการไฟล์แนบ"
},
"agentId": "รหัสตัวแทน:",
"loadingAgent": "กำลังโหลดตัวแทน...",
+4 -1
View File
@@ -33,7 +33,10 @@
"remoteDisabled": "当前应用不支持 URL 附件",
"unsupportedRemote": "不支持的 URL 附件类型",
"remoteTypeDisabled": "当前应用不支持该类型 URL 附件:{type}",
"missingUploadId": "上传服务未返回文件标识"
"missingUploadId": "上传服务未返回文件标识",
"summaryCount": "{count} 个附件",
"expandList": "展开附件列表",
"collapseList": "收起附件列表"
},
"agentId": "应用 ID:",
"loadingAgent": "正在加载应用...",
+4 -1
View File
@@ -33,7 +33,10 @@
"remoteDisabled": "目前應用程式不支援 URL 附件",
"unsupportedRemote": "不支援的 URL 附件類型",
"remoteTypeDisabled": "目前應用程式不支援此類型 URL 附件:{type}",
"missingUploadId": "上傳服務未回傳檔案識別碼"
"missingUploadId": "上傳服務未回傳檔案識別碼",
"summaryCount": "{count} 個附件",
"expandList": "展開附件列表",
"collapseList": "收起附件列表"
},
"agentId": "應用 ID:",
"loadingAgent": "正在加載應用...",
+34
View File
@@ -0,0 +1,34 @@
/**
* shared/utils/id.test.ts
* 用途:校验 createRandomUuid 在缺少 randomUUID 时仍可生成可用 ID。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createRandomUuid } from './id';
describe('createRandomUuid', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('uses crypto.randomUUID when available', () => {
// 断言:安全上下文走原生 API。
vi.stubGlobal('crypto', {
randomUUID: () => '11111111-2222-4333-8444-555555555555',
});
expect(createRandomUuid()).toBe('11111111-2222-4333-8444-555555555555');
});
it('falls back when randomUUID is missing (HTTP non-secure context)', () => {
// 断言:模拟内网 HTTP,无 randomUUID 也不抛错,且返回非空串。
vi.stubGlobal('crypto', {
getRandomValues: (bytes: Uint8Array) => {
for (let i = 0; i < bytes.length; i += 1) bytes[i] = i;
return bytes;
},
});
const value = createRandomUuid();
expect(value).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
);
});
});
+29
View File
@@ -0,0 +1,29 @@
/**
* shared/utils/id.ts
* 用途:生成客户端随机 ID(会话号、operation_id、幂等键等)。
* 依赖:Web Crypto(优先);无安全上下文时回退到 getRandomValues / Math.random。
* 逻辑:HTTP 内网(如 192.168.x)不是 secure context,`crypto.randomUUID` 不可用,
* 直接调用会在 Vue setup 阶段抛 TypeError 导致白屏;统一走本工具避免分叉。
*/
/**
* 生成 UUID 风格随机串;优先 `crypto.randomUUID`,HTTP 等非安全上下文自动降级。
* 核心逻辑:secure context 用原生 API;否则用 getRandomValues 拼 RFC4122 v4;再不行用时间戳+随机。
* @returns 形如 `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` 的字符串(降级路径不保证密码学强度)
*/
export function createRandomUuid(): string {
const webCrypto = globalThis.crypto;
if (webCrypto && typeof webCrypto.randomUUID === 'function') {
return webCrypto.randomUUID();
}
if (webCrypto && typeof webCrypto.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
webCrypto.getRandomValues(bytes);
// noUncheckedIndexedAccess 下 Uint8Array 下标为 number | undefined
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
return `fallback-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
}