2026-10-16 15:30:10 +08:00
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
2026-10-20 10:04:17 +08:00
import { assistantSkippedResults } from '../../src/utils/business-assistant.js'
2026-10-16 15:30:10 +08:00
import { assistantFileError , assistantPrepareAttachment , assistantSheetSelection , assistantAttachmentSource , assistantOutgoingMessage , assistantFollowScroll , isAssistantConversationBusy , assistantSessionRevision , assistantDuration , assistantImageCandidates , assistantImageViewerIndex , isAssistantExpired , isAssistantPending , canConfirmAssistantDraft , assistantOption , assistantRowsSignature , assistantDraftCounts , assistantTimeline , assistantHasUnlinkedPendingDraft , assistantDraftStatus , assistantPendingRowLabel , assistantReferenceConditions , assistantResultTable , assistantDisplayValue } from '../../src/utils/business-assistant.js'
const readyDraft = { id : 'draft-1' , version : 2 , status : 'WAIT_CONFIRM' , ready : true , expiresAt : '2099-01-01T00:00:00' , rows : [ { _rowId : '1' , quantity : 2 } ] }
test ( 'elapsed display distinguishes actual duration from missing data and uses whole seconds while waiting' , ( ) => {
for ( const value of [ undefined , null , '' , '1960' , - 1 , NaN , Infinity ] ) assert . equal ( assistantDuration ( value ) , '' )
assert . equal ( assistantDuration ( 0 ) , '0 秒' )
assert . equal ( assistantDuration ( 1960 ) , '1.96 秒' )
assert . equal ( assistantDuration ( 1960 , true ) , '1 秒' )
assert . equal ( assistantDuration ( 65000 ) , '1 分 5 秒' )
assert . equal ( assistantDuration ( 180450 , true ) , '3 分 0 秒' )
} )
test ( 'chat shows live request waiting and server reply duration without inventing elapsed times for historical messages' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /entry.message.delivery === 'SENDING'[^\n]+now - Date.parse\(entry.message.createdAt\)/ )
assert . match ( main , /entry.message.role === 'assistant' && assistantDuration\(entry.message.elapsedMs\)/ )
assert . match ( main , /entry.message.delivery === 'FAILED' && assistantDuration\(entry.message.clientWaitedMs\)/ )
assert . doesNotMatch ( main , /elapsedMs\s*\|\|/ )
assert . match ( main , /setInterval\([^\n]+1000\)/ )
assert . match ( main , /onBeforeUnmount\([^\n]+clearInterval\(timer\)/ )
} )
test ( 'outgoing bubble freezes only selected worksheet metadata and does not copy private preview paths' , ( ) => {
const files = [ { id : 'excel' , name : '采购.xlsx' , type : 'excel' , selectedSheetIndexes : [ 1 ] , sheets : [ { index : 0 , name : '总表' , rowCount : 101 } , { index : 1 , name : '子表' , rowCount : 50 } ] , previewUrl : 'blob:private' } , { id : 'image' , name : '单据.png' , type : 'image' , path : '/private' , previewUrl : 'blob:private-image' } ]
const message = assistantOutgoingMessage ( 'local-1' , '登记到货' , files , '2026-10-15T10:00:00Z' )
assert . equal ( message . delivery , 'SENDING' )
assert . equal ( message . role , 'user' )
assert . equal ( message . content , '登记到货' )
assert . deepEqual ( message . attachments [ 0 ] . sheetIndexes , [ 1 ] )
assert . equal ( message . attachments [ 0 ] . rowCount , 50 )
assert . deepEqual ( message . attachments [ 1 ] , { id : 'image' , name : '单据.png' , type : 'image' } )
files [ 0 ] . sheets [ 1 ] . name = '后来更改'
assert . equal ( message . attachments [ 0 ] . sheets [ 0 ] . name , '子表' )
assert . deepEqual ( assistantOutgoingMessage ( 'retry' , '' , [ { ... message . attachments [ 0 ] } ] ) . attachments [ 0 ] . sheetIndexes , [ 1 ] )
} )
test ( 'pending user message is appended without taking ownership of a previous confirmation card' , ( ) => {
const pending = assistantOutgoingMessage ( 'pending' , '新请求' , [ ] )
const session = { draft : readyDraft , messages : [ { id : 'previous' , role : 'assistant' , draftId : readyDraft . id } ] }
const entries = assistantTimeline ( session , pending )
assert . equal ( entries . length , 2 )
assert . equal ( entries [ 0 ] . draft . id , readyDraft . id )
assert . equal ( entries [ 1 ] . message . id , 'pending' )
assert . equal ( entries [ 1 ] . draft , null )
assert . equal ( entries [ 1 ] . active , false )
assert . equal ( session . messages . length , 1 )
} )
test ( 'chat follows content growth but stops following after scrolling up until the reader returns to the bottom' , ( ) => {
const metrics = ( top , height = 1000 ) => ( { scrollTop : top , scrollHeight : height , clientHeight : 300 } )
assert . equal ( assistantFollowScroll ( metrics ( 700 , 1400 ) , 700 , true ) , true )
assert . equal ( assistantFollowScroll ( metrics ( 500 ) , 700 , true ) , false )
assert . equal ( assistantFollowScroll ( metrics ( 500 , 1400 ) , 500 , false ) , false )
assert . equal ( assistantFollowScroll ( metrics ( 800 , 1400 ) , 500 , false ) , false )
assert . equal ( assistantFollowScroll ( metrics ( 1080 , 1400 ) , 800 , false ) , true )
} )
test ( 'only the explicit concurrent-message rejection is considered not sent' , ( ) => {
assert . equal ( isAssistantConversationBusy ( new Error ( '上一条消息仍在处理中,请稍候' ) ) , true )
assert . equal ( isAssistantConversationBusy ( '上一条消息仍在处理中,请稍候' ) , true )
for ( const error of [ new Error ( 'timeout' ) , new Error ( '模型处理失败' ) , new Error ( '请求处理中断' ) , null ] ) assert . equal ( isAssistantConversationBusy ( error ) , false )
const previous = { id : 's1' , messages : [ { id : 'a1' , role : 'assistant' , content : '上次结果' } ] }
assert . equal ( assistantSessionRevision ( previous ) , assistantSessionRevision ( { ... previous , draft : { version : 9 } , updatedAt : 'later' } ) )
assert . notEqual ( assistantSessionRevision ( previous ) , assistantSessionRevision ( { ... previous , messages : [ ... previous . messages , { id : 'a2' , content : '新结果' } ] } ) )
assert . notEqual ( assistantSessionRevision ( previous ) , assistantSessionRevision ( { ... previous , id : 's2' } ) )
} )
test ( 'recovery controls stay outside the scrolling conversation and allow editing a rejected concurrent message' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /<section v-if="allowed && assistant.needsRefresh && !sessionLoading && !resumePrompt" class="assistant-recovery"/ )
assert . match ( main , /@click="recoverConversation"/ )
assert . match ( main , /\(assistant.needsRefresh && !assistant.remoteBusy\)/ )
assert . match ( main , /entry.message.delivery === 'NOT_SENT' \? '尚未发送'/ )
assert . match ( main , /获取最新结果/ )
const recovery = main . slice ( main . indexOf ( 'async function recoverConversation()' ) , main . indexOf ( 'async function resumeSession(' ) )
assert . doesNotMatch ( recovery , /assistant.send|retryMessage|\.execute\(/ )
} )
test ( 'reference controls and their source conditions share one vertical root rather than a table-cell flex row' , ( ) => {
const field = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantField.vue' , import . meta . url ) , 'utf8' )
assert . match ( field , /<template>\s*<div class="assistant-field">/ )
assert . match ( field , /<small v-if="referenceConditions.length"[\s\S]*?<\/div>\s*<\/template>/ )
assert . match ( field , /\.assistant-field\s*\{[^}]*display: flex;[^}]*flex-direction: column;[^}]*width: 100%;[^}]*min-width: 0;/ )
assert . match ( field , /\.assistant-field > \*\s*\{ flex-shrink: 0; \}/ )
} )
test ( 'send scrolls after synchronous outgoing feedback, not after waiting for the model response' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
const api = readFileSync ( new URL ( '../../src/api/warehouse/assistant.js' , import . meta . url ) , 'utf8' )
assert . match ( main , /const request = send\(\)[\s\S]+?await nextTick\(\)[\s\S]+?scrollToEnd\(\)[\s\S]+?await request/ )
assert . match ( main , /@scroll="onConversationScroll"/ )
assert . match ( main , /if \(!followLatest.value\) return/ )
assert . match ( main , /assistantTimeline\(assistant.session, assistant.pendingMessage, assistant.catalog\)/ )
assert . match ( main , /retryRecognition\(entry.message.id\)/ )
assert . match ( api , /sendAssistantMessage[^\n]+timeout: 210000/ )
} )
test ( 'assistant attachment limits match server-supported types and reject empty or oversized files' , ( ) => {
for ( const name of [ 'photo.PNG' , 'note.jpg' , 'note.jpeg' , 'purchase.xls' , 'purchase.xlsx' ] ) assert . equal ( assistantFileError ( { name , size : 100 } ) , '' )
for ( const file of [ { name : 'program.exe' , size : 100 } , { name : 'note.webp' , size : 100 } , { name : 'empty.xlsx' , size : 0 } , { name : 'huge.jpg' , size : 10 * 1024 * 1024 + 1 } ] ) assert . ok ( assistantFileError ( file ) )
} )
test ( 'only a single-sheet workbook is automatically selected, never a multi-sheet summary' , ( ) => {
const multi = { id : 'multi' , type : 'excel' , name : '采购.xlsx' , sheets : [ { index : 0 , name : '总表' , rowCount : 101 } , { index : 1 , name : '子表2' , rowCount : 50 } , { index : 2 , name : '子表3' , rowCount : 51 } ] }
assert . deepEqual ( assistantPrepareAttachment ( multi ) . selectedSheetIndexes , [ ] )
assert . deepEqual ( assistantPrepareAttachment ( { ... multi , sheets : [ multi . sheets [ 1 ] ] } ) . selectedSheetIndexes , [ 1 ] )
assert . equal ( assistantPrepareAttachment ( { id : 'image' , type : 'image' } ) . selectedSheetIndexes , undefined )
const selected = assistantSheetSelection ( [ { ... multi , selectedSheetIndexes : [ 1 ] } ] )
assert . equal ( selected . valid , true )
assert . equal ( selected . rowCount , 50 )
assert . deepEqual ( selected . selections , [ { id : 'multi' , sheetIndexes : [ 1 ] } ] )
assert . equal ( multi . sheets . length , 3 )
} )
test ( 'Excel row limit sums only selected nonempty rows including headers across all files, not images' , ( ) => {
const excel = ( id , count ) => ( { id , type : 'excel' , name : ` ${ id } .xlsx ` , selectedSheetIndexes : [ 0 ] , sheets : [ { index : 0 , name : 'Sheet1' , rowCount : count } ] } )
const boundary = assistantSheetSelection ( [ excel ( 'one' , 50 ) , excel ( 'two' , 50 ) , { type : 'image' , rowCount : 999 } ] )
assert . equal ( boundary . valid , true )
assert . equal ( boundary . rowCount , 100 )
assert . equal ( boundary . excelCount , 2 )
assert . equal ( boundary . sheetCount , 2 )
const exceeded = assistantSheetSelection ( [ excel ( 'one' , 50 ) , excel ( 'two' , 51 ) ] )
assert . equal ( exceeded . valid , false )
assert . equal ( exceeded . rowCount , 101 )
assert . match ( exceeded . errors . find ( error => error . id === null ) . message , /超过 100 行/ )
assert . equal ( assistantSheetSelection ( [ { ... excel ( 'dedup' , 50 ) , selectedSheetIndexes : [ 0 , 0 ] } ] ) . rowCount , 50 )
} )
test ( 'missing sheet selection, empty sheets, unknown indexes and invalid row metadata block sending' , ( ) => {
const file = { id : 'excel' , name : '采购.xlsx' , type : 'excel' , sheets : [ { index : 0 , name : 'Sheet1' , rowCount : 50 } ] , selectedSheetIndexes : [ 0 ] }
assert . match ( assistantSheetSelection ( [ { ... file , selectedSheetIndexes : [ ] } ] ) . errors [ 0 ] . message , /请选择/ )
assert . match ( assistantSheetSelection ( [ { ... file , sheets : [ ] } ] ) . errors [ 0 ] . message , /未读取到工作表/ )
assert . match ( assistantSheetSelection ( [ { ... file , selectedSheetIndexes : [ 99 ] } ] ) . errors [ 0 ] . message , /选择已失效/ )
assert . match ( assistantSheetSelection ( [ { ... file , sheets : [ { index : 0 , name : '空表' , rowCount : 0 } ] } ] ) . errors [ 0 ] . message , /工作表为空/ )
assert . match ( assistantSheetSelection ( [ { ... file , selectedSheetIndexes : [ ] , sheets : [ { index : 0 , name : '空表1' , rowCount : 0 } , { index : 1 , name : '空表2' , rowCount : 0 } ] } ] ) . errors [ 0 ] . message , /所有工作表为空/ )
assert . equal ( assistantSheetSelection ( [ { ... file , sheets : [ { index : 0 , name : '异常' , rowCount : - 1 } ] } ] ) . valid , false )
assert . equal ( assistantSheetSelection ( [ ] ) . valid , true )
} )
test ( 'conversation attachment sources name only sheets frozen for that message' , ( ) => {
const file = { id : 'excel' , type : 'excel' , name : '采购.xlsx' , sheetIndexes : [ 1 ] , sheets : [ { index : 0 , name : '总表' , rowCount : 101 } , { index : 1 , name : '子表2' , rowCount : 50 } ] }
assert . equal ( assistantAttachmentSource ( file ) , '采购.xlsx · 工作表: 子表2( 50 行)' )
assert . equal ( assistantAttachmentSource ( { ... file , sheetIndexes : [ ] } ) , '采购.xlsx' )
assert . equal ( assistantAttachmentSource ( { type : 'image' , name : '到货单.png' } ) , '到货单.png' )
} )
test ( 'sheet selector is inline in attachment card and invalid selection disables send' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
const attachments = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantAttachments.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /!assistant.attachmentSelection.valid/ )
assert . match ( main , /assistantAttachmentSource\(file\)/ )
assert . match ( attachments , /multiple filterable clearable/ )
assert . match ( attachments , /包含表头;图片不计入/ )
assert . match ( attachments , /未选工作表不会读取/ )
assert . doesNotMatch ( attachments , /<el-dialog|v-html/ )
} )
test ( 'image viewer accepts only identified images and never trusts paths or remote preview URLs from metadata' , ( ) => {
const files = [ { id : 'a' , type : 'image' , name : '到货单.png' , path : '/private/a' , previewUrl : 'https://untrusted.example/a' } , { id : 'a' , type : 'image' } , { id : 'sheet' , type : 'excel' } , { type : 'image' } , { id : 'b' , type : 'image' , name : '明细.jpg' } ]
assert . deepEqual ( assistantImageCandidates ( files ) , [ { id : 'a' , type : 'image' , name : '到货单.png' } , { id : 'b' , type : 'image' , name : '明细.jpg' } ] )
assert . equal ( assistantImageViewerIndex ( assistantImageCandidates ( files ) , 'b' ) , 1 )
assert . equal ( assistantImageViewerIndex ( assistantImageCandidates ( files ) , 'missing' ) , 0 )
} )
test ( 'historical and uploaded image buttons open a native isolated viewer, including after thumbnail release' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
const attachments = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantAttachments.vue' , import . meta . url ) , 'utf8' )
const viewer = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantImageViewer.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /@click.stop="openSourceImage\(entry.message.attachments, file.id\)"/ )
assert . match ( main , /@preview="openUploadedImage"/ )
assert . match ( main , /if \(!open\) assistant.releaseImagePreviews\(\)/ )
assert . match ( attachments , /<button v-if="file.type === 'image'"/ )
assert . match ( viewer , /<el-image-viewer/ )
assert . match ( viewer , /teleported show-progress/ )
assert . match ( viewer , /#viewer-error/ )
assert . doesNotMatch ( viewer , /executeDraft|\.execute\(|v-html|window.open/ )
} )
test ( 'image viewer toolbar uses named keyboard-accessible buttons for zoom, rotation, switching and close' , ( ) => {
const viewer = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantImageViewer.vue' , import . meta . url ) , 'utf8' )
assert . match ( viewer , /#toolbar="\{ actions, prev, next, reset, activeIndex \}"/ )
for ( const label of [ '上一张' , '缩小' , '放大' , '原尺寸或适应窗口' , '向左旋转' , '向右旋转' , '下一张' , '关闭预览' ] ) {
assert . match ( viewer , new RegExp ( ` <button[^ \\ n]+type="button"[^ \\ n]+aria-label=" ${ label } " ` ) )
}
assert . match ( viewer , /:close-on-press-escape="true"/ )
assert . match ( viewer , /:focus-visible/ )
} )
test ( 'only the latest ready editable draft can be manually confirmed' , ( ) => {
assert . equal ( canConfirmAssistantDraft ( readyDraft ) , true )
for ( const context of [ { busy : true } , { dirty : true } , { allowed : false } , { now : Date . parse ( '2100-01-01' ) } ] ) assert . equal ( canConfirmAssistantDraft ( readyDraft , context ) , false )
for ( const change of [ { id : '' } , { version : null } , { ready : false } , { permissionDenied : true } , { readOnly : true } , { status : 'SUCCEEDED' } , { status : 'CANCELLED' } , { status : 'EXECUTING' } , { status : 'EXPIRED' } ] ) assert . equal ( canConfirmAssistantDraft ( { ... readyDraft , ... change } ) , false )
assert . equal ( canConfirmAssistantDraft ( { ... readyDraft , status : 'PARTIAL' } ) , true )
} )
test ( 'expiry handles server date strings and milliseconds without changing business time' , ( ) => {
const now = Date . parse ( '2026-10-15T12:00:00' )
assert . equal ( isAssistantExpired ( { expiresAt : '2026-10-15 11:59:59' } , now ) , true )
assert . equal ( isAssistantExpired ( { expiresAt : now } , now ) , true )
assert . equal ( isAssistantExpired ( { expiresAt : '2026-10-15T12:00:01' } , now ) , false )
assert . equal ( isAssistantPending ( { status : 'NEEDS_REVIEW' } ) , true )
assert . equal ( isAssistantPending ( { status : 'EXPIRED' } ) , true )
assert . equal ( isAssistantPending ( null ) , false )
} )
test ( 'draft change detection ignores server-only labels but catches value, row and BOM changes' , ( ) => {
const rows = [ { _rowId : '1' , quantity : 1 , itemId : 3 , _labels : { itemId : '物品' } , _errors : [ ] } ]
assert . equal ( assistantRowsSignature ( rows ) , assistantRowsSignature ( [ { itemId : 3 , quantity : 1 , _rowId : '1' , _labels : { itemId : '不同标签' } , _errors : [ '校验中' ] } ] ) )
assert . notEqual ( assistantRowsSignature ( rows ) , assistantRowsSignature ( [ { ... rows [ 0 ] , quantity : 2 } ] ) )
assert . notEqual ( assistantRowsSignature ( rows ) , assistantRowsSignature ( [ { ... rows [ 0 ] , _rowId : '2' } ] ) )
assert . notEqual ( assistantRowsSignature ( [ { lines : [ { itemId : 3 , unitQuantity : 1 } ] } ] ) , assistantRowsSignature ( [ { lines : [ { itemId : 3 , unitQuantity : 2 } ] } ] ) )
} )
test ( 'candidate identifiers preserve numeric IDs and dictionary labels' , ( ) => {
assert . equal ( assistantOption ( { id : 7 , name : '电机' } ) . value , 7 )
assert . equal ( assistantOption ( { value : '个' , label : '个' } ) . value , '个' )
assert . equal ( assistantOption ( { value : 0 , label : '立项' } ) . value , 0 )
} )
test ( 'partial completion counts do not suggest retrying successful rows' , ( ) => {
2026-10-20 10:04:17 +08:00
assert . deepEqual ( assistantDraftCounts ( { rows : [ { } , { } , { } ] , results : [ { status : 'SUCCEEDED' } , { status : 'FAILED' } , { status : 'FAILED' } ] } ) , { total : 3 , succeeded : 1 , skipped : 0 , failed : 2 } )
} )
test ( 'explicitly skipped quotation rows stay visible and are not counted as successful price changes' , ( ) => {
const draft = { rows : [ { _rowId : 'a' } , { _rowId : 'b' , _sourceText : '水冷一体管, 4× 29.2元' } ] , results : [ { rowId : 'a' , status : 'SUCCEEDED' , data : { } } , { rowId : 'b' , status : 'SUCCEEDED' , data : { skipped : true } } ] }
assert . deepEqual ( assistantDraftCounts ( draft ) , { total : 2 , succeeded : 1 , skipped : 1 , failed : 0 } )
assert . deepEqual ( assistantSkippedResults ( draft ) , [ { rowId : 'b' , label : '水冷一体管, 4× 29.2元' } ] )
const card = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantConversationCard.vue' , import . meta . url ) , 'utf8' )
assert . match ( card , /本次已跳过,未更正/ )
assert . ok ( card . indexOf ( 'v-for="item in skippedResults"' ) < card . indexOf ( 'v-if="active || expanded"' ) )
} )
test ( 'internal reference prices have their own paged before-after preview rather than a cost-price table' , ( ) => {
const preview = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantReferencePricePreview.vue' , import . meta . url ) , 'utf8' )
const draft = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantDraft.vue' , import . meta . url ) , 'utf8' )
for ( const label of [ '物品名称' , '规格型号' , '当前报价' , '原实际单价' , '新实际单价' , '原实际金额' , '新实际金额' ] ) assert . ok ( preview . includes ( label ) )
assert . match ( preview , /不修改报价及成本/ )
assert . match ( preview , /:total="rows.length"/ )
assert . match ( draft , /_referencePricePreview/ )
const rows = Array . from ( { length : 34 } , ( ) => ( { } ) )
assert . equal ( assistantDraftCounts ( { action : 'purchase.referencePrice' , rows : [ { _referencePricePreview : rows } ] } ) . total , 34 )
assert . deepEqual ( assistantDraftCounts ( { action : 'purchase.referencePrice' , rows : [ { _referencePricePreview : rows } ] , results : [ { status : 'SUCCEEDED' , data : { changed : 13 , rows } } ] } ) , { total : 34 , succeeded : 13 , skipped : 21 , failed : 0 } )
2026-10-16 15:30:10 +08:00
} )
test ( 'draft and row statuses distinguish missing information and cancelled work' , ( ) => {
assert . deepEqual ( assistantDraftStatus ( { status : 'WAIT_CONFIRM' , ready : false } ) , { label : '待补充' , type : 'warning' } )
assert . equal ( assistantDraftStatus ( { status : 'WAIT_CONFIRM' , ready : true } ) . label , '待确认' )
assert . equal ( assistantDraftStatus ( { status : 'CANCELLED' , ready : false } ) . label , '已取消' )
assert . equal ( assistantPendingRowLabel ( { status : 'CANCELLED' , ready : false } ) , '已取消' )
assert . equal ( assistantPendingRowLabel ( { status : 'CANCELLED' , ready : true } ) , '已取消' )
assert . equal ( assistantPendingRowLabel ( { status : 'WAIT_CONFIRM' , ready : false } ) , '待校验' )
} )
test ( 'unmatched references display only supplied source conditions with Chinese labels' , ( ) => {
const source = { keyword : '测试螺丝' , spec : 'M6× 20' , brand : '测试牌' , supplierName : '测试供应商' , batchNo : 'P261001' , projectName : '机器人项目' }
assert . deepEqual ( assistantReferenceConditions ( source ) , [
{ label : '名称' , value : '测试螺丝' } , { label : '规格型号' , value : 'M6× 20' } , { label : '品牌' , value : '测试牌' } ,
{ label : '供应商' , value : '测试供应商' } , { label : '采购批次' , value : 'P261001' } , { label : '项目' , value : '机器人项目' }
] )
assert . deepEqual ( assistantReferenceConditions ( { keyword : '测试支架' , spec : 'L型' , brand : '测试牌' , supplierName : ' ' , projectName : null , _snapshot : 'private' , unknown : 'hidden' } ) , [
{ label : '名称' , value : '测试支架' } , { label : '规格型号' , value : 'L型' } , { label : '品牌' , value : '测试牌' }
] )
assert . deepEqual ( assistantReferenceConditions ( { name : '电机' , brand : { bad : 'shape' } } ) , [ { label : '名称' , value : '电机' } ] )
for ( const value of [ null , 27 , '电机' , [ ] ] ) assert . deepEqual ( assistantReferenceConditions ( value ) , [ ] )
} )
test ( 'query results retain server Chinese headings and do not coerce zero to missing data' , ( ) => {
assert . deepEqual ( assistantResultTable ( { columns : [ { key : 'quantity' , label : '库存数量' } ] , rows : [ { quantity : 0 } ] } ) , { columns : [ { key : 'quantity' , label : '库存数量' } ] , rows : [ { quantity : 0 } ] } )
assert . equal ( assistantDisplayValue ( 0 ) , '0' )
assert . equal ( assistantDisplayValue ( false ) , '否' )
assert . equal ( assistantResultTable ( { recordId : 1 } ) , null )
} )
test ( 'assistant is globally mounted; AI text is not rendered as executable HTML or nested dialogs' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
const layout = readFileSync ( new URL ( '../../src/layout/index.vue' , import . meta . url ) , 'utf8' )
const home = readFileSync ( new URL ( '../../src/views/businessHome/index.vue' , import . meta . url ) , 'utf8' )
assert . match ( layout , /<business-assistant\s*\/>/ )
assert . match ( main , /\{\{ assistantResponseText\(entry.message\) \|\|/ )
assert . doesNotMatch ( main , /v-html|<el-dialog/ )
assert . match ( main , /max-width: 768px/ )
assert . doesNotMatch ( home , /<inventory-assistant/ )
assert . match ( main , /需求可以分几次补充/ )
assert . match ( main , /由你核对后再执行/ )
assert . match ( main , /不确定怎么操作,直接问我就好/ )
} )
test ( 'timeline keeps cancelled cards before later conversation rather than appending them at the end' , ( ) => {
const draft = { id : 'arrival-1' , status : 'CANCELLED' , rows : [ { quantity : 12 } , { quantity : 3 } ] }
const session = { draft , messages : [
{ id : 'u1' , role : 'user' , content : '登记到货' } ,
{ id : 'a1' , role : 'assistant' , content : '请核对' , draftId : 'arrival-1' , draft : { ... draft , status : 'WAIT_CONFIRM' } } ,
{ id : 'u2' , role : 'user' , content : '你好' } ,
{ id : 'a2' , role : 'assistant' , content : '你好,需要什么帮助?' }
] }
const timeline = assistantTimeline ( session )
assert . deepEqual ( timeline . map ( entry => entry . message . id ) , [ 'u1' , 'a1' , 'u2' , 'a2' ] )
assert . equal ( timeline [ 1 ] . draft . status , 'CANCELLED' )
assert . equal ( timeline [ 1 ] . active , false )
assert . equal ( timeline [ 3 ] . draft , null )
} )
test ( 'current edits and execution results replace only their owning message card' , ( ) => {
const previous = { id : 'old' , status : 'SUCCEEDED' , readOnly : true , rows : [ { } ] , results : [ { status : 'SUCCEEDED' , data : { rows : [ { old : true } ] } } ] }
const current = { id : 'new' , version : 3 , status : 'PARTIAL' , rows : [ { quantity : 4 } ] , results : [ { status : 'SUCCEEDED' , data : { rows : [ { current : true } ] } } ] }
const timeline = assistantTimeline ( { draft : current , messages : [
{ role : 'assistant' , draftId : 'old' , draft : previous } ,
{ role : 'assistant' , draftId : 'new' , draft : { ... current , version : 1 , results : [ ] } }
] } )
assert . equal ( timeline [ 0 ] . active , false )
assert . deepEqual ( timeline [ 0 ] . draft . results , previous . results )
assert . equal ( timeline [ 1 ] . active , true )
assert . equal ( timeline [ 1 ] . draft . version , 3 )
assert . deepEqual ( timeline [ 1 ] . draft . results , current . results )
} )
test ( 'unlinked legacy draft is never rendered globally or guessed onto small talk' , ( ) => {
const messages = [ { id : 'hello' , role : 'assistant' , content : '你好' } ]
const timeline = assistantTimeline ( { draft : { id : 'legacy' , status : 'CANCELLED' } , messages } )
assert . equal ( timeline . length , 1 )
assert . equal ( timeline [ 0 ] . message . id , 'hello' )
assert . equal ( timeline [ 0 ] . draft , null )
assert . equal ( timeline [ 0 ] . active , false )
assert . equal ( messages . length , 1 )
assert . deepEqual ( assistantTimeline ( { draft : { id : 'orphan-pending' , status : 'WAIT_CONFIRM' , ready : true } , messages : [ ] } ) , [ ] )
} )
test ( 'naturally trimmed completed or cancelled cards never display an orphan warning; pending cards stay protected' , ( ) => {
const messages = [ { id : 'recent-user' , role : 'user' , content : '你好' } , { id : 'recent-assistant' , role : 'assistant' , content : '你好' } ]
for ( const status of [ 'CANCELLED' , 'SUCCEEDED' , 'FAILED' ] ) {
const session = { draft : { id : 'old-card' , status , readOnly : true } , messages }
assert . equal ( assistantHasUnlinkedPendingDraft ( session ) , false )
assert . ok ( assistantTimeline ( session ) . every ( entry => entry . draft === null ) )
}
for ( const status of [ 'WAIT_CONFIRM' , 'NEEDS_REVIEW' , 'PARTIAL' , 'EXPIRED' ] ) {
const draft = { id : 'current-card' , status }
assert . equal ( assistantHasUnlinkedPendingDraft ( { draft , messages } ) , true )
assert . equal ( assistantHasUnlinkedPendingDraft ( { draft , messages : [ ... messages , { id : 'owner' , role : 'assistant' , draftId : draft . id } ] } ) , false )
}
assert . equal ( assistantHasUnlinkedPendingDraft ( null ) , false )
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /const orphanDraft = computed\(\(\) => assistantHasUnlinkedPendingDraft\(assistant.session, assistant.catalog\)\)/ )
assert . match ( main , /const canOperateDraft = computed\(\(\) => !orphanDraft.value && pending.value/ )
} )
test ( 'timeline trusts only explicit matching assistant ownership and cannot enable denied or readonly cards' , ( ) => {
const draft = { id : 7 , status : 'WAIT_CONFIRM' , ready : true , permissionDenied : true }
const timeline = assistantTimeline ( { draft , messages : [
{ role : 'user' , draftId : 7 } ,
{ role : 'assistant' , draftId : 7 , draft : { id : 7 , rows : [ { secret : 'outdated' } ] } } ,
{ role : 'assistant' , draftId : 7 } ,
{ role : 'assistant' , draftId : 'x' , draft : { id : 'different' } }
] } )
assert . equal ( timeline [ 0 ] . draft , null )
assert . equal ( timeline [ 1 ] . draft . permissionDenied , true )
assert . equal ( timeline [ 1 ] . draft . rows , undefined )
assert . equal ( timeline [ 1 ] . active , false )
assert . equal ( timeline [ 2 ] . draft , null )
assert . equal ( timeline [ 3 ] . draft , null )
assert . equal ( assistantTimeline ( { draft : { ... draft , permissionDenied : false , readOnly : true } , messages : [ { role : 'assistant' , draftId : 7 } ] } ) [ 0 ] . active , false )
assert . deepEqual ( assistantTimeline ( null ) , [ ] )
} )
test ( 'chat cards render inside messages, history expands inline, and both sides use their own avatar' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
const card = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantConversationCard.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /v-for="entry in timeline"[\s\S]*?<assistant-conversation-card[\s\S]*?<\/article>/ )
assert . doesNotMatch ( main , /<assistant-draft|<assistant-results/ )
assert . match ( main , /user.avatar \|\| defaultAvatar : assistantAvatar/ )
assert . match ( main , /business-assistant-avatar.png/ )
assert . match ( main , /v-if="canOperateDraft && !sessionLoading && !resumePrompt"/ )
assert . match ( main , /const canOperateDraft = computed\(\(\) => !orphanDraft.value/ )
assert . match ( main , /v-if="orphanDraft"/ )
assert . match ( main , /缺少对应的对话消息,暂不展示或执行/ )
assert . match ( card , /v-if="!active"[\s\S]*?expanded = !expanded/ )
assert . match ( card , /:read-only="!active"/ )
assert . match ( card , /<assistant-results[^>]+:results="draft.results"/ )
assert . doesNotMatch ( card , /v-html|<el-dialog/ )
} )
test ( 'user logout clears assistant before request and finally, stale responses are ignored' , ( ) => {
const user = readFileSync ( new URL ( '../../src/store/modules/user.js' , import . meta . url ) , 'utf8' )
const store = readFileSync ( new URL ( '../../src/store/modules/businessAssistant.js' , import . meta . url ) , 'utf8' )
assert . match ( user , /logOut\(\)\s*\{\s*useBusinessAssistantStore\(\).resetLocal\(\)/ )
assert . match ( user , /finally\(\(\) => useBusinessAssistantStore\(\).resetLocal\(\)\)/ )
assert . match ( store , /if \(generation !== this.generation\) return null/ )
assert . doesNotMatch ( store , /localStorage|sessionStorage/ )
assert . match ( store , /if \(kind === 'execute'\) this.uncertain = true/ )
} )
test ( 'reference fields never allow creating new dictionary values, BOM edits use inline rows' , ( ) => {
const field = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantField.vue' , import . meta . url ) , 'utf8' )
const lines = readFileSync ( new URL ( '../../src/components/BusinessAssistant/AssistantLines.vue' , import . meta . url ) , 'utf8' )
assert . doesNotMatch ( field , /allow-create/ )
assert . match ( field , /field.type === 'select'/ )
assert . match ( lines , /lines.itemId/ )
assert . match ( lines , /lines.childBomId/ )
assert . doesNotMatch ( lines , /<el-dialog|JSON.stringify/ )
} )
test ( 'assistant error recovery remains visible and reopening revalidates without silently discarding edits' , ( ) => {
const main = readFileSync ( new URL ( '../../src/components/BusinessAssistant/index.vue' , import . meta . url ) , 'utf8' )
assert . match ( main , /watch\(\(\) => assistant.open,[\s\S]+?await refreshState\(\)/ )
assert . match ( main , /if \(dirty.value && !assistant.accessDenied\)[^\n]+resumePrompt.value = true/ )
assert . match ( main , /放弃修改并刷新/ )
assert . match ( main , /校验并刷新/ )
assert . match ( main , /await assistant.load\(true\)/ )
assert . match ( main , /@click="refreshState"/ )
assert . doesNotMatch ( main , /v-if="!assistant.loaded \|\| assistant.uncertain"/ )
assert . match ( main , /hasEntryPermission.value && !assistant.accessDenied/ )
} )
test ( 'assistant private image JSON errors preserve authorization codes' , async ( ) => {
const source = readFileSync ( new URL ( '../../src/api/warehouse/assistant.js' , import . meta . url ) , 'utf8' )
const key = ` __assistantBlobTest_ ${ Math . random ( ) . toString ( 36 ) . slice ( 2 ) } `
globalThis [ key ] = async options => {
assert . equal ( options . assistantRequest , true )
return new Blob ( [ JSON . stringify ( { code : 403 , msg : '无访问权限' } ) ] , { type : 'application/json' } )
}
2026-10-20 10:04:17 +08:00
const module = await import ( ` data:text/javascript, ${ encodeURIComponent ( source . replace ( "import service from '@/utils/request'" , ` const service = globalThis. ${ key } ` ) . replace ( "from '@/utils/resumable-upload'" , ` from ' ${ new URL ( '../../src/utils/resumable-upload.js' , import . meta . url ) . href } ' ` ) . replace ( "import {getToken} from '@/utils/auth'" , "const getToken=()=>''" ) ) } # ${ key } ` )
2026-10-16 15:30:10 +08:00
delete globalThis [ key ]
await assert . rejects ( module . getAssistantAttachmentImage ( 'image-1' ) , error => error . code === 403 && error . message === '无访问权限' )
const request = readFileSync ( new URL ( '../../src/utils/request.js' , import . meta . url ) , 'utf8' )
assert . match ( request , /res.config.assistantRequest && \[401, 403\].includes\(Number\(code\)\)/ )
assert . match ( request , /error.code = Number\(code\)/ )
} )