@@ -16,14 +16,14 @@ import { CohereClientV2, CohereError, type Cohere } from "cohere-ai";
1616import { withFaultFixture } from "../helpers/misbehavior-server.js" ;
1717import { describe , it , expect , beforeAll , afterAll } from "vitest" ;
1818import type { ServerInstance } from "../../server.js" ;
19- import { extractShape , triangulate , formatDriftReport } from "./schema.js" ;
2019import {
21- httpPost ,
22- httpPostRaw ,
23- parseDataOnlySSE ,
24- startDriftServer ,
25- stopDriftServer ,
26- } from "./helpers.js" ;
20+ extractShape ,
21+ triangulate ,
22+ compareSSESequences ,
23+ formatDriftReport ,
24+ type SSEEventShape ,
25+ } from "./schema.js" ;
26+ import { httpPost , httpPostRaw , startDriftServer , stopDriftServer } from "./helpers.js" ;
2727import {
2828 COHERE_BASE_URL ,
2929 COHERE_K5_NO_GENERATION ,
@@ -86,17 +86,81 @@ function cohereChatResponseShape() {
8686}
8787
8888/**
89- * Minimal Cohere /v2/chat streaming chunk shape .
89+ * Minimal Cohere /v2/chat streaming event shapes, one per text-stream event type .
9090 */
91- function cohereChatStreamChunkShape ( ) {
92- return extractShape ( {
93- id : "chat-abc123" ,
94- type : "content-delta" ,
95- delta : {
96- message : {
97- content : { text : "Hel" } ,
91+ function cohereChatStreamEventShapes ( ) : SSEEventShape [ ] {
92+ const events : { type : string ; data : object } [ ] = [
93+ {
94+ type : "message-start" ,
95+ data : {
96+ id : "chat-abc123" ,
97+ type : "message-start" ,
98+ delta : {
99+ message : { role : "assistant" , content : [ ] , tool_plan : "" , tool_calls : [ ] , citations : [ ] } ,
100+ } ,
101+ } ,
102+ } ,
103+ {
104+ type : "content-start" ,
105+ data : {
106+ type : "content-start" ,
107+ index : 0 ,
108+ delta : { message : { content : { type : "text" } } } ,
109+ } ,
110+ } ,
111+ {
112+ type : "content-delta" ,
113+ data : {
114+ type : "content-delta" ,
115+ index : 0 ,
116+ delta : { message : { content : { text : "Hel" } } } ,
117+ } ,
118+ } ,
119+ { type : "content-end" , data : { type : "content-end" , index : 0 } } ,
120+ {
121+ type : "message-end" ,
122+ data : {
123+ type : "message-end" ,
124+ delta : {
125+ finish_reason : "COMPLETE" ,
126+ usage : {
127+ billed_units : { input_tokens : 10 , output_tokens : 5 } ,
128+ tokens : { input_tokens : 10 , output_tokens : 5 } ,
129+ } ,
130+ } ,
98131 } ,
99132 } ,
133+ ] ;
134+ return events . map ( ( e ) => ( { type : e . type , dataShape : extractShape ( e . data ) } ) ) ;
135+ }
136+
137+ /**
138+ * Parse a Cohere v2 SSE body. Every frame is `event: <type>` + `data: <json>`
139+ * whose JSON `type` equals the event name; a final `data: [DONE]` sentinel is
140+ * allowed and dropped. Any other frame throws, so a framing change is loud
141+ * instead of silently parsing to an empty list.
142+ */
143+ function parseCohereSSE ( body : string ) : { type : string ; data : Record < string , unknown > } [ ] {
144+ const frames = body
145+ . replace ( / \r \n / g, "\n" )
146+ . split ( "\n\n" )
147+ . filter ( ( frame ) => frame . trim ( ) !== "" ) ;
148+ if ( frames . at ( - 1 ) === "data: [DONE]" ) frames . pop ( ) ;
149+ return frames . map ( ( frame ) => {
150+ const lines = frame . split ( "\n" ) ;
151+ if ( lines . length !== 2 || ! lines [ 0 ] . startsWith ( "event: " ) || ! lines [ 1 ] . startsWith ( "data: " ) ) {
152+ throw new Error ( `Unsupported Cohere SSE frame: ${ JSON . stringify ( frame ) } ` ) ;
153+ }
154+ const type = lines [ 0 ] . slice ( "event: " . length ) ;
155+ const data : unknown = JSON . parse ( lines [ 1 ] . slice ( "data: " . length ) ) ;
156+ if ( data === null || typeof data !== "object" || Array . isArray ( data ) ) {
157+ throw new Error ( `Cohere SSE data is not an object: ${ JSON . stringify ( frame ) } ` ) ;
158+ }
159+ const record = data as Record < string , unknown > ;
160+ if ( record . type !== type ) {
161+ throw new Error ( `Cohere SSE event name ${ type } != data.type ${ String ( record . type ) } ` ) ;
162+ }
163+ return { type, data : record } ;
100164 } ) ;
101165}
102166
@@ -382,7 +446,6 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
382446 }
383447 const model = resolved . model ;
384448
385- const sdkChunkShape = cohereChatStreamChunkShape ( ) ;
386449 const messages = [ { role : "user" , content : "Say hello" } ] ;
387450
388451 const [ realRes , mockRes ] = await Promise . all ( [
@@ -413,59 +476,92 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
413476 }
414477
415478 expect ( realRes . status ) . toBe ( 200 ) ;
416- expect ( mockRes . status ) . toBeLessThan ( 500 ) ;
479+ expect ( mockRes . status ) . toBe ( 200 ) ;
480+
481+ const realEvents = parseCohereSSE ( realRes . body ) ;
482+ const mockEvents = parseCohereSSE ( mockRes . body ) ;
483+ expect ( realEvents . length , "Real API returned no SSE events" ) . toBeGreaterThan ( 0 ) ;
484+ expect ( mockEvents . length , "Mock returned no SSE events" ) . toBeGreaterThan ( 0 ) ;
485+
486+ const realEnd = realEvents . at ( - 1 ) ;
487+ if (
488+ realEnd ?. type === "message-end" &&
489+ isCohereNoGenerationStreamEnd (
490+ cohereRecord ( realEnd . data . delta ) ,
491+ COHERE_SHAPE_LEG_NO_GENERATION ,
492+ )
493+ ) {
494+ // Upstream generated nothing: a 200 stream whose message-end is
495+ // finish_reason ERROR with empty usage. No success terminal to compare.
496+ expect (
497+ realEvents . some ( ( e ) => e . type === "content-start" ) ,
498+ "content before no-generation terminal" ,
499+ ) . toBe ( false ) ;
500+ ctx . skip (
501+ cohereNoGenerationSkipReason ( [
502+ { errorType : "NO_VALID_RESPONSE_GENERATED" , id : cohereString ( realEvents [ 0 ] . data . id ) } ,
503+ ] ) ,
504+ ) ;
505+ return ;
506+ }
417507
418- if ( mockRes . status === 200 ) {
419- // Parse SSE chunks from both responses
420- const realChunks = parseDataOnlySSE ( realRes . body ) ;
421- const mockChunks = parseDataOnlySSE ( mockRes . body ) ;
422-
423- if ( realChunks . length > 0 && mockChunks . length > 0 ) {
424- // Compare first chunk shape (content-delta)
425- const realChunkShape = extractShape ( realChunks [ 0 ] ) ;
426- const mockChunkShape = extractShape ( mockChunks [ 0 ] ) ;
427-
428- const diffs = triangulate ( sdkChunkShape , realChunkShape , mockChunkShape ) ;
429- const report = formatDriftReport (
430- "Cohere /v2/chat (streaming first chunk)" ,
431- diffs ,
432- "cohere-chat" ,
433- ) ;
508+ for ( const [ side , events ] of [
509+ [ "real" , realEvents ] ,
510+ [ "mock" , mockEvents ] ,
511+ ] as const ) {
512+ expect ( events [ 0 ] . type , `${ side } stream must open with message-start` ) . toBe ( "message-start" ) ;
513+ expect ( events . at ( - 1 ) ?. type , `${ side } stream must close with message-end` ) . toBe ( "message-end" ) ;
514+ }
434515
435- expect (
436- diffs . filter ( ( d ) => d . severity === "critical" ) ,
437- report ,
438- ) . toEqual ( [ ] ) ;
439-
440- // Also compare the LAST chunk shape (has finish_reason, usage)
441- const sdkLastChunkShape = extractShape ( {
442- id : "chat-abc123" ,
443- type : "message-end" ,
444- delta : {
445- finish_reason : "COMPLETE" ,
446- usage : {
447- billed_units : { input_tokens : 10 , output_tokens : 5 } ,
448- tokens : { input_tokens : 10 , output_tokens : 5 } ,
449- } ,
450- } ,
451- } ) ;
516+ const diffs = compareSSESequences (
517+ cohereChatStreamEventShapes ( ) ,
518+ realEvents . map ( ( e ) => ( { type : e . type , dataShape : extractShape ( e . data ) } ) ) ,
519+ mockEvents . map ( ( e ) => ( { type : e . type , dataShape : extractShape ( e . data ) } ) ) ,
520+ ) ;
521+ const report = formatDriftReport ( "Cohere /v2/chat (streaming events)" , diffs , "cohere-chat" ) ;
452522
453- const realLastShape = extractShape ( realChunks [ realChunks . length - 1 ] ) ;
454- const mockLastShape = extractShape ( mockChunks [ mockChunks . length - 1 ] ) ;
523+ expect (
524+ diffs . filter ( ( d ) => d . severity === "critical" ) ,
525+ report ,
526+ ) . toEqual ( [ ] ) ;
527+ } ) ;
528+ } ) ;
455529
456- const lastDiffs = triangulate ( sdkLastChunkShape , realLastShape , mockLastShape ) ;
457- const lastReport = formatDriftReport (
458- "Cohere /v2/chat (streaming last chunk)" ,
459- lastDiffs ,
460- "cohere-chat" ,
461- ) ;
530+ describe ( "parseCohereSSE" , ( ) => {
531+ it ( "parses recorded live event: + data: frames and drops the [DONE] sentinel" , async ( ) => {
532+ const body = (
533+ await readFile ( new URL ( "./fixtures/cohere-k5-stream.sse" , import . meta. url ) )
534+ ) . toString ( ) ;
535+ const events = parseCohereSSE ( body ) ;
536+ expect ( events . length ) . toBeGreaterThan ( 2 ) ;
537+ expect ( events [ 0 ] . type ) . toBe ( "message-start" ) ;
538+ expect ( events . at ( - 1 ) ?. type ) . toBe ( "message-end" ) ;
539+ for ( const e of events ) expect ( e . data . type ) . toBe ( e . type ) ;
540+ } ) ;
462541
463- expect (
464- lastDiffs . filter ( ( d ) => d . severity === "critical" ) ,
465- lastReport ,
466- ) . toEqual ( [ ] ) ;
467- }
468- }
542+ it ( "parses aimock's stream as a non-empty event list" , async ( ) => {
543+ const res = await httpPost ( `${ instance . url } /v2/chat` , {
544+ model : "command-a-03-2025" ,
545+ messages : [ { role : "user" , content : "Say hello" } ] ,
546+ stream : true ,
547+ } ) ;
548+ expect ( res . status ) . toBe ( 200 ) ;
549+ const events = parseCohereSSE ( res . body ) ;
550+ expect ( events . map ( ( e ) => e . type ) ) . toEqual ( [
551+ "message-start" ,
552+ "content-start" ,
553+ "content-delta" ,
554+ "content-end" ,
555+ "message-end" ,
556+ ] ) ;
557+ } ) ;
558+
559+ it ( "rejects frames it does not understand instead of dropping them" , ( ) => {
560+ expect ( ( ) => parseCohereSSE ( 'data: {"type":"message-start"}\n\n' ) ) . toThrow ( / U n s u p p o r t e d / ) ;
561+ expect ( ( ) => parseCohereSSE ( 'event: content-end\ndata: {"type":"content-start"}\n\n' ) ) . toThrow (
562+ / e v e n t n a m e / ,
563+ ) ;
564+ expect ( ( ) => parseCohereSSE ( "event: content-end\ndata: [1]\n\n" ) ) . toThrow ( / n o t a n o b j e c t / ) ;
469565 } ) ;
470566} ) ;
471567
@@ -954,7 +1050,7 @@ function readCohereK5(
9541050 }
9551051 }
9561052 const delta = cohereRecord ( events . at ( - 1 ) ?. delta ) ;
957- if ( options . live && isCohereNoGenerationStreamEnd ( delta ) ) {
1053+ if ( options . live && isCohereNoGenerationStreamEnd ( delta , COHERE_K5_NO_GENERATION ) ) {
9581054 assert . equal ( calls . length , 0 , "tool before no-generation terminal" ) ;
9591055 assert . equal ( contentCount , 0 , "content before no-generation terminal" ) ;
9601056 return {
0 commit comments