Skip to content
Closed

1 #3475

Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
680271d
feat(playground): add video size/duration/quality selectors
LJR199887 Mar 27, 2026
988b297
Merge pull request #1 from LJR199887/codex/find-project-purpose
LJR199887 Mar 27, 2026
9db210d
fix(playground): route video models to video endpoint
LJR199887 Mar 28, 2026
f5b1a79
Merge branch 'QuantumNous:main' into main
LJR199887 Mar 28, 2026
6658556
fix(playground): always route video models to video endpoint
LJR199887 Mar 28, 2026
d31fbb6
Merge branch 'main' into codex/find-project-purpose-3vdzr3
LJR199887 Mar 28, 2026
8446231
Merge pull request #2 from LJR199887/codex/find-project-purpose-3vdzr3
LJR199887 Mar 28, 2026
90063cb
fix(playground): use user-authenticated pg video generation endpoint
LJR199887 Mar 28, 2026
2186b57
Merge branch 'main' into codex/find-project-purpose-8t1iot
LJR199887 Mar 28, 2026
8e89b09
Merge pull request #3 from LJR199887/codex/find-project-purpose-8t1iot
LJR199887 Mar 28, 2026
989f667
feat(playground): show video content URL after task creation
LJR199887 Mar 28, 2026
37f5126
Merge branch 'main' into codex/find-project-purpose
LJR199887 Mar 28, 2026
e20c678
Merge pull request #4 from LJR199887/codex/find-project-purpose
LJR199887 Mar 28, 2026
629be09
Revert "Add playground video generation endpoints and UI; wire video …
LJR199887 Mar 28, 2026
b69a41e
Merge pull request #5 from LJR199887/revert-4-codex/find-project-purpose
LJR199887 Mar 28, 2026
8e19212
fix grok video url response
LJR199887 Mar 28, 2026
2933917
avoid duplicate video preview
LJR199887 Mar 28, 2026
df6cb95
add grok video preset options
LJR199887 Mar 28, 2026
37f727c
fix grok video quality request handling
LJR199887 Mar 28, 2026
b1b647d
fix grok 720p video request aliases
LJR199887 Mar 28, 2026
b1a56ec
Fix grok imagine playground image routing
LJR199887 Mar 28, 2026
8671548
Fix playground image relay mode
LJR199887 Mar 28, 2026
3ca517d
Handle empty prompt for grok imagine edit
LJR199887 Mar 28, 2026
ca554ba
Fix grok imagine video endpoint display
LJR199887 Mar 28, 2026
5a65dc4
Merge pull request #6 from LJR199887/codex/fix-grok-video-url
LJR199887 Mar 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 48 additions & 9 deletions controller/playground.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,61 @@ func Playground(c *gin.Context) {
return
}

userId := c.GetInt("id")
if newAPIError = setupPlaygroundTokenContext(c, fmt.Sprintf("playground-%s", relayInfo.UsingGroup), relayInfo.UsingGroup); newAPIError != nil {
return
}

Relay(c, types.RelayFormatOpenAI)
}

// Write user context to ensure acceptUnsetRatio is available
func PlaygroundVideoSubmit(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if newAPIError = setupPlaygroundTokenContext(c, "playground-video", c.GetString("group")); newAPIError != nil {
return
}
RelayTask(c)
}

func PlaygroundVideoFetch(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if newAPIError = setupPlaygroundTokenContext(c, "playground-video-fetch", c.GetString("group")); newAPIError != nil {
return
}
RelayTaskFetch(c)
}
Comment on lines +45 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Reject access-token flows in video playground handlers for parity with Playground.

PlaygroundVideoSubmit and PlaygroundVideoFetch currently miss the use_access_token guard that Playground enforces. This introduces inconsistent auth behavior for /pg/video/*.

🔧 Suggested fix
 func PlaygroundVideoSubmit(c *gin.Context) {
 	var newAPIError *types.NewAPIError
 	defer func() {
 		if newAPIError != nil {
 			c.JSON(newAPIError.StatusCode, gin.H{
 				"error": newAPIError.ToOpenAIError(),
 			})
 		}
 	}()
+	if c.GetBool("use_access_token") {
+		newAPIError = types.NewError(errors.New("暂不支持使用 access token"), types.ErrorCodeAccessDenied, types.ErrOptionWithSkipRetry())
+		return
+	}
 	if newAPIError = setupPlaygroundTokenContext(c, "playground-video", c.GetString("group")); newAPIError != nil {
 		return
 	}
 	RelayTask(c)
 }
 
 func PlaygroundVideoFetch(c *gin.Context) {
 	var newAPIError *types.NewAPIError
 	defer func() {
 		if newAPIError != nil {
 			c.JSON(newAPIError.StatusCode, gin.H{
 				"error": newAPIError.ToOpenAIError(),
 			})
 		}
 	}()
+	if c.GetBool("use_access_token") {
+		newAPIError = types.NewError(errors.New("暂不支持使用 access token"), types.ErrorCodeAccessDenied, types.ErrOptionWithSkipRetry())
+		return
+	}
 	if newAPIError = setupPlaygroundTokenContext(c, "playground-video-fetch", c.GetString("group")); newAPIError != nil {
 		return
 	}
 	RelayTaskFetch(c)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func PlaygroundVideoSubmit(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if newAPIError = setupPlaygroundTokenContext(c, "playground-video", c.GetString("group")); newAPIError != nil {
return
}
RelayTask(c)
}
func PlaygroundVideoFetch(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if newAPIError = setupPlaygroundTokenContext(c, "playground-video-fetch", c.GetString("group")); newAPIError != nil {
return
}
RelayTaskFetch(c)
}
func PlaygroundVideoSubmit(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if c.GetBool("use_access_token") {
newAPIError = types.NewError(errors.New("暂不支持使用 access token"), types.ErrorCodeAccessDenied, types.ErrOptionWithSkipRetry())
return
}
if newAPIError = setupPlaygroundTokenContext(c, "playground-video", c.GetString("group")); newAPIError != nil {
return
}
RelayTask(c)
}
func PlaygroundVideoFetch(c *gin.Context) {
var newAPIError *types.NewAPIError
defer func() {
if newAPIError != nil {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}
}()
if c.GetBool("use_access_token") {
newAPIError = types.NewError(errors.New("暂不支持使用 access token"), types.ErrorCodeAccessDenied, types.ErrOptionWithSkipRetry())
return
}
if newAPIError = setupPlaygroundTokenContext(c, "playground-video-fetch", c.GetString("group")); newAPIError != nil {
return
}
RelayTaskFetch(c)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/playground.go` around lines 45 - 73, Add the same "reject
access-token flows" guard to PlaygroundVideoSubmit and PlaygroundVideoFetch as
in Playground: after calling setupPlaygroundTokenContext (and before
RelayTask/RelayTaskFetch), check the request for the use_access_token flag (the
same source Playground uses, e.g., query/header/context key "use_access_token")
and if it's set/true return a NewAPIError (same type/format Playground returns)
so the handlers reject access-token flows consistently.


func setupPlaygroundTokenContext(c *gin.Context, tokenName string, tokenGroup string) *types.NewAPIError {
userId := c.GetInt("id")
userCache, err := model.GetUserCache(userId)
if err != nil {
newAPIError = types.NewError(err, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry())
return
return types.NewError(err, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry())
}
userCache.WriteContext(c)

if tokenGroup == "" {
tokenGroup = c.GetString("group")
}
if tokenGroup == "" {
tokenGroup = userCache.Group
}
tempToken := &model.Token{
UserId: userId,
Name: fmt.Sprintf("playground-%s", relayInfo.UsingGroup),
Group: relayInfo.UsingGroup,
Name: tokenName,
Group: tokenGroup,
}
_ = middleware.SetupContextForToken(c, tempToken)

Relay(c, types.RelayFormatOpenAI)
return nil
}
2 changes: 2 additions & 0 deletions dto/openai_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ type GeneralOpenAIRequest struct {
Input any `json:"input,omitempty"`
Instruction string `json:"instruction,omitempty"`
Size string `json:"size,omitempty"`
Seconds *string `json:"seconds,omitempty"`
Quality *string `json:"quality,omitempty"`
Functions json.RawMessage `json:"functions,omitempty"`
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
Expand Down
2 changes: 2 additions & 0 deletions router/relay-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ func SetRelayRouter(router *gin.Engine) {
playgroundRouter.Use(middleware.UserAuth(), middleware.Distribute())
{
playgroundRouter.POST("/chat/completions", controller.Playground)
playgroundRouter.POST("/video/generations", controller.PlaygroundVideoSubmit)
playgroundRouter.GET("/video/generations/:task_id", controller.PlaygroundVideoFetch)
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify Path2RelayMode handling for /pg/video paths
rg -n 'pg/video' relay/constant/relay_mode.go

# Check if distributor handles /pg/video paths
rg -n 'pg/video' middleware/distributor.go

Repository: QuantumNous/new-api

Length of output: 45


🏁 Script executed:

#!/bin/bash
# First, let's see the context around lines 70-71 in relay-router.go
head -n 85 router/relay-router.go | tail -n 20

Repository: QuantumNous/new-api

Length of output: 929


🏁 Script executed:

#!/bin/bash
# Examine the Path2RelayMode function structure
cat relay/constant/relay_mode.go

Repository: QuantumNous/new-api

Length of output: 5123


🏁 Script executed:

#!/bin/bash
# Check middleware/distributor.go structure and what /pg/ routes it handles
cat middleware/distributor.go | head -n 300

Repository: QuantumNous/new-api

Length of output: 11797


Add relay mode mapping for /pg/video/generations routes.

The /pg/video/generations routes (POST and GET) are registered in relay-router.go but lack corresponding mappings in Path2RelayMode (relay/constant/relay_mode.go). Like other playground routes (/pg/chat/completions, /pg/images/generations), these routes must be explicitly handled to map to RelayModeVideoSubmit and RelayModeVideoFetchByID respectively. Without these mappings, requests to /pg/video/generations will have RelayModeUnknown, causing incorrect routing behavior.

Add the following to Path2RelayMode:

} else if strings.HasPrefix(path, "/pg/video/generations") {
    relayMode = RelayModeVideoSubmit
} else if strings.HasPrefix(path, "/pg/video/generations") && method == http.MethodGet {
    relayMode = RelayModeVideoFetchByID
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@router/relay-router.go` around lines 70 - 71, Path2RelayMode in
relay/constant/relay_mode.go is missing mappings for the playground video
routes; update the Path2RelayMode function to detect paths starting with
"/pg/video/generations" and map GET requests to RelayModeVideoFetchByID and
other methods (POST) to RelayModeVideoSubmit (use strings.HasPrefix(path,
"/pg/video/generations") and method == http.MethodGet for the fetch branch, and
a fallback strings.HasPrefix(...) branch for submit), making sure the GET check
comes before the submit check so GETs resolve to RelayModeVideoFetchByID.

}
relayV1Router := router.Group("/v1")
relayV1Router.Use(middleware.RouteTag("relay"))
Expand Down
61 changes: 61 additions & 0 deletions web/src/components/playground/SettingsPanel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ const SettingsPanel = ({
messages,
}) => {
const { t } = useTranslation();
const isVideoModel =
typeof inputs.model === 'string' && inputs.model.includes('video');
const videoSizeOptions = [
{ label: '1280x720', value: '1280x720' },
{ label: '720x1280', value: '720x1280' },
{ label: '1792x1024', value: '1792x1024' },
{ label: '1024x1792', value: '1024x1792' },
{ label: '1024x1024', value: '1024x1024' },
];
const videoSecondsOptions = [6, 8, 10, 12, 15, 20, 25, 30].map((v) => ({
label: `${v}s`,
value: String(v),
}));
const videoQualityOptions = [
{ label: 'standard', value: 'standard' },
{ label: 'high', value: 'high' },
];
Comment on lines +70 to +73

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Localize the new quality option labels.

standard and high are rendered directly, so they bypass i18next while the rest of the panel is translated.

♻️ Suggested i18n fix
   const videoQualityOptions = [
-    { label: 'standard', value: 'standard' },
-    { label: 'high', value: 'high' },
+    { label: t('标准'), value: 'standard' },
+    { label: t('高质量'), value: 'high' },
   ];
As per coding guidelines, `web/src/**/*.{ts,tsx,js,jsx}`: Frontend i18n: Use `i18next` + `react-i18next` + `i18next-browser-languagedetector`. Translation files in `web/src/i18n/locales/{lang}.json` must be flat JSON with Chinese source strings as keys. Use `useTranslation()` hook and call `t('中文key')` in components.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const videoQualityOptions = [
{ label: 'standard', value: 'standard' },
{ label: 'high', value: 'high' },
];
const videoQualityOptions = [
{ label: t('标准'), value: 'standard' },
{ label: t('高质量'), value: 'high' },
];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/playground/SettingsPanel.jsx` around lines 63 - 66,
videoQualityOptions currently uses raw labels ('standard', 'high') that bypass
i18next; update SettingsPanel.jsx to import/use the useTranslation() hook and
replace those labels with translated strings via t('...') (e.g., t('标准') /
t('高清') or the correct Chinese keys from web/src/i18n/locales/{lang}.json) so
the array becomes [{ label: t('你的中文key1'), value: 'standard' }, ...]; ensure you
reference useTranslation and t in the same component where videoQualityOptions
is defined.


const currentConfig = {
inputs,
Expand Down Expand Up @@ -200,6 +217,50 @@ const SettingsPanel = ({
/>
</div>

{/* 视频参数(仅视频模型显示) */}
{isVideoModel && (
<div className={customRequestMode ? 'opacity-50' : ''}>
<div className='space-y-4'>
<div>
<Typography.Text strong className='text-sm'>
{t('视频尺寸')}
</Typography.Text>
<Select
className='!rounded-lg mt-2'
optionList={videoSizeOptions}
value={inputs.videoSize}
onChange={(value) => onInputChange('videoSize', value)}
disabled={customRequestMode}
/>
</div>
<div>
<Typography.Text strong className='text-sm'>
{t('视频时长')}
</Typography.Text>
<Select
className='!rounded-lg mt-2'
optionList={videoSecondsOptions}
value={inputs.videoSeconds}
onChange={(value) => onInputChange('videoSeconds', value)}
disabled={customRequestMode}
/>
</div>
<div>
<Typography.Text strong className='text-sm'>
{t('视频质量')}
</Typography.Text>
<Select
className='!rounded-lg mt-2'
optionList={videoQualityOptions}
value={inputs.videoQuality}
onChange={(value) => onInputChange('videoQuality', value)}
disabled={customRequestMode}
/>
</div>
</div>
</div>
)}

{/* 流式输出开关 */}
<div className={customRequestMode ? 'opacity-50' : ''}>
<div className='flex items-center justify-between'>
Expand Down
4 changes: 4 additions & 0 deletions web/src/constants/playground.constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export const DEBUG_TABS = {
// ========== API 相关常量 ==========
export const API_ENDPOINTS = {
CHAT_COMPLETIONS: '/pg/chat/completions',
VIDEO_GENERATIONS: '/pg/video/generations',
USER_MODELS: '/api/user/models',
USER_GROUPS: '/api/user/self/groups',
};
Expand All @@ -94,6 +95,9 @@ export const DEFAULT_CONFIG = {
stream: true,
imageEnabled: false,
imageUrls: [''],
videoSize: '1280x720',
videoSeconds: '10',
videoQuality: 'standard',
},
parameterEnabled: {
temperature: true,
Expand Down
15 changes: 15 additions & 0 deletions web/src/helpers/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,21 @@ export const buildApiPayload = (
}
});

const isVideoModel =
typeof inputs.model === 'string' && inputs.model.includes('video');
if (isVideoModel) {
payload.stream = false;
if (inputs.videoSize) {
payload.size = inputs.videoSize;
}
if (inputs.videoSeconds) {
payload.seconds = String(inputs.videoSeconds);
}
if (inputs.videoQuality) {
payload.quality = inputs.videoQuality;
}
}

return payload;
};

Expand Down
125 changes: 119 additions & 6 deletions web/src/hooks/playground/useApiRequest.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,78 @@ export const useApiRequest = (
saveMessages,
) => {
const { t } = useTranslation();
const isVideoGenerationPayload = useCallback((payload) => {
const model = payload?.model;
return typeof model === 'string' && model.includes('video');
}, []);

const getTextFromMessageContent = useCallback((content) => {
if (typeof content === 'string') {
return content;
}
if (!Array.isArray(content)) {
return '';
}
const textParts = content
.filter((item) => item?.type === 'text')
.map((item) => item?.text || '')
.filter(Boolean);
return textParts.join('\n');
}, []);

const getImageFromMessageContent = useCallback((content) => {
if (!Array.isArray(content)) {
return '';
}
const imageItem = content.find((item) => item?.type === 'image_url');
if (!imageItem) {
return '';
}
const imageURL = imageItem.image_url;
if (typeof imageURL === 'string') {
return imageURL;
}
return imageURL?.url || '';
}, []);

const buildVideoRequestPayload = useCallback(
(payload) => {
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
const lastUserMessage = [...messages]
.reverse()
.find((m) => m?.role === 'user');
const prompt = getTextFromMessageContent(lastUserMessage?.content);
const image = getImageFromMessageContent(lastUserMessage?.content);

return {
model: payload.model,
prompt,
seconds: payload.seconds,
size: payload.size,
quality: payload.quality,
...(image ? { image } : {}),
};
},
[getImageFromMessageContent, getTextFromMessageContent],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don't drop extra reference images on the video path.

buildVideoRequestPayload() only keeps the first image_url, but the playground input is plural and relay/common/relay_info.go:666-677 already has both Image and Images. Any additional reference image is silently lost here.

🧩 One way to preserve multi-image input
-  const getImageFromMessageContent = useCallback((content) => {
-    if (!Array.isArray(content)) {
-      return '';
-    }
-    const imageItem = content.find((item) => item?.type === 'image_url');
-    if (!imageItem) {
-      return '';
-    }
-    const imageURL = imageItem.image_url;
-    if (typeof imageURL === 'string') {
-      return imageURL;
-    }
-    return imageURL?.url || '';
-  }, []);
+  const getImagesFromMessageContent = useCallback((content) => {
+    if (!Array.isArray(content)) {
+      return [];
+    }
+    return content
+      .filter((item) => item?.type === 'image_url')
+      .map((item) => {
+        const imageURL = item.image_url;
+        return typeof imageURL === 'string' ? imageURL : imageURL?.url || '';
+      })
+      .filter(Boolean);
+  }, []);
 
   const buildVideoRequestPayload = useCallback(
     (payload) => {
       const messages = Array.isArray(payload?.messages) ? payload.messages : [];
       const lastUserMessage = [...messages]
         .reverse()
         .find((m) => m?.role === 'user');
       const prompt = getTextFromMessageContent(lastUserMessage?.content);
-      const image = getImageFromMessageContent(lastUserMessage?.content);
+      const images = getImagesFromMessageContent(lastUserMessage?.content);
 
       return {
         model: payload.model,
         prompt,
         seconds: payload.seconds,
         size: payload.size,
         quality: payload.quality,
-        ...(image ? { image } : {}),
+        ...(images.length === 1 ? { image: images[0] } : {}),
+        ...(images.length > 1 ? { images } : {}),
       };
     },
-    [getImageFromMessageContent, getTextFromMessageContent],
+    [getImagesFromMessageContent, getTextFromMessageContent],
   );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const getImageFromMessageContent = useCallback((content) => {
if (!Array.isArray(content)) {
return '';
}
const imageItem = content.find((item) => item?.type === 'image_url');
if (!imageItem) {
return '';
}
const imageURL = imageItem.image_url;
if (typeof imageURL === 'string') {
return imageURL;
}
return imageURL?.url || '';
}, []);
const buildVideoRequestPayload = useCallback(
(payload) => {
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
const lastUserMessage = [...messages]
.reverse()
.find((m) => m?.role === 'user');
const prompt = getTextFromMessageContent(lastUserMessage?.content);
const image = getImageFromMessageContent(lastUserMessage?.content);
return {
model: payload.model,
prompt,
seconds: payload.seconds,
size: payload.size,
quality: payload.quality,
...(image ? { image } : {}),
};
},
[getImageFromMessageContent, getTextFromMessageContent],
const getImagesFromMessageContent = useCallback((content) => {
if (!Array.isArray(content)) {
return [];
}
return content
.filter((item) => item?.type === 'image_url')
.map((item) => {
const imageURL = item.image_url;
return typeof imageURL === 'string' ? imageURL : imageURL?.url || '';
})
.filter(Boolean);
}, []);
const buildVideoRequestPayload = useCallback(
(payload) => {
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
const lastUserMessage = [...messages]
.reverse()
.find((m) => m?.role === 'user');
const prompt = getTextFromMessageContent(lastUserMessage?.content);
const images = getImagesFromMessageContent(lastUserMessage?.content);
return {
model: payload.model,
prompt,
seconds: payload.seconds,
size: payload.size,
quality: payload.quality,
...(images.length === 1 ? { image: images[0] } : {}),
...(images.length > 1 ? { images } : {}),
};
},
[getImagesFromMessageContent, getTextFromMessageContent],
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/playground/useApiRequest.jsx` around lines 62 - 95,
buildVideoRequestPayload currently calls getImageFromMessageContent which
returns only a single image_url, dropping any additional reference images;
change the logic to collect all image_url items from the message content and
preserve them in the payload (e.g., produce an images array), while optionally
keeping the single image property for backward compatibility. Update
getImageFromMessageContent (or add a new helper like
getImagesFromMessageContent) to return an array of image URLs from content items
with type === 'image_url', and modify buildVideoRequestPayload to set both image
(first URL) and images (full array) or at least images when multiple exist so
the relay/common/relay_info.go consumer (Image and Images) receives all
references.

);

const resolveEndpointAndPayload = useCallback(
(payload) => {
if (isVideoGenerationPayload(payload)) {
return {
endpoint: API_ENDPOINTS.VIDEO_GENERATIONS,
requestPayload: buildVideoRequestPayload(payload),
forceNonStream: true,
};
}
return {
endpoint: API_ENDPOINTS.CHAT_COMPLETIONS,
requestPayload: payload,
forceNonStream: false,
};
},
[buildVideoRequestPayload, isVideoGenerationPayload],
);

// 处理消息自动关闭逻辑的公共函数
const applyAutoCollapseLogic = useCallback(
Expand Down Expand Up @@ -174,9 +246,10 @@ export const useApiRequest = (
// 非流式请求
const handleNonStreamRequest = useCallback(
async (payload) => {
const { endpoint, requestPayload } = resolveEndpointAndPayload(payload);
setDebugData((prev) => ({
...prev,
request: payload,
request: requestPayload,
timestamp: new Date().toISOString(),
response: null,
sseMessages: null, // 非流式请求清除 SSE 消息
Expand All @@ -185,13 +258,13 @@ export const useApiRequest = (
setActiveDebugTab(DEBUG_TABS.REQUEST);

try {
const response = await fetch(API_ENDPOINTS.CHAT_COMPLETIONS, {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'New-Api-User': getUserIdFromLocalStorage(),
},
body: JSON.stringify(payload),
body: JSON.stringify(requestPayload),
});

if (!response.ok) {
Expand Down Expand Up @@ -228,6 +301,38 @@ export const useApiRequest = (
}));
setActiveDebugTab(DEBUG_TABS.RESPONSE);

if (
endpoint === API_ENDPOINTS.VIDEO_GENERATIONS ||
data.object === 'video' ||
data.task_id
) {
const summary = [
`${t('视频任务已创建')}`,
`task_id: ${data.task_id || data.id || '-'}`,
`status: ${data.status || '-'}`,
`seconds: ${data.seconds || requestPayload.seconds || '-'}`,
`size: ${data.size || requestPayload.size || '-'}`,
].join('\n');
Comment on lines +454 to +468

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Localize the new video task summary fields.

Only the headline goes through t(). The field labels in the assistant message will still render as raw English.

♻️ Suggested i18n fix
           const summary = [
             `${t('视频任务已创建')}`,
-            `task_id: ${data.task_id || data.id || '-'}`,
-            `status: ${data.status || '-'}`,
-            `seconds: ${data.seconds || requestPayload.seconds || '-'}`,
-            `size: ${data.size || requestPayload.size || '-'}`,
+            `${t('任务 ID')}: ${data.task_id || data.id || '-'}`,
+            `${t('状态')}: ${data.status || '-'}`,
+            `${t('视频时长')}: ${data.seconds || requestPayload.seconds || '-'}`,
+            `${t('视频尺寸')}: ${data.size || requestPayload.size || '-'}`,
           ].join('\n');
As per coding guidelines, `web/src/**/*.{ts,tsx,js,jsx}`: Frontend i18n: Use `i18next` + `react-i18next` + `i18next-browser-languagedetector`. Translation files in `web/src/i18n/locales/{lang}.json` must be flat JSON with Chinese source strings as keys. Use `useTranslation()` hook and call `t('中文key')` in components.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const summary = [
`${t('视频任务已创建')}`,
`task_id: ${data.task_id || data.id || '-'}`,
`status: ${data.status || '-'}`,
`seconds: ${data.seconds || requestPayload.seconds || '-'}`,
`size: ${data.size || requestPayload.size || '-'}`,
].join('\n');
const summary = [
`${t('视频任务已创建')}`,
`${t('任务 ID')}: ${data.task_id || data.id || '-'}`,
`${t('状态')}: ${data.status || '-'}`,
`${t('视频时长')}: ${data.seconds || requestPayload.seconds || '-'}`,
`${t('视频尺寸')}: ${data.size || requestPayload.size || '-'}`,
].join('\n');
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/playground/useApiRequest.jsx` around lines 309 - 315, The
summary string currently only localizes the headline via t() while the field
labels (task_id, status, seconds, size) remain raw English; update the component
in useApiRequest.jsx to use the useTranslation() hook and wrap each label in
t('...') with Chinese keys matching our flat locale JSON (e.g., t('任务ID'),
t('状态'), t('秒'), t('大小')), then build the summary using those t(...) calls (keep
the existing headline t('视频任务已创建') and the same fallbacks like data.task_id ||
data.id || '-'); ensure the keys you use exist in
web/src/i18n/locales/{lang}.json.

setMessage((prevMessage) => {
const newMessages = [...prevMessage];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage?.status === MESSAGE_STATUS.LOADING) {
const autoCollapseState = applyAutoCollapseLogic(
lastMessage,
true,
);
newMessages[newMessages.length - 1] = {
...lastMessage,
content: summary,
status: MESSAGE_STATUS.COMPLETE,
...autoCollapseState,
};
}
return newMessages;
});
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if (data.choices?.[0]) {
const choice = data.choices[0];
let content = choice.message?.content || '';
Expand Down Expand Up @@ -285,7 +390,14 @@ export const useApiRequest = (
});
}
},
[setDebugData, setActiveDebugTab, setMessage, t, applyAutoCollapseLogic],
[
resolveEndpointAndPayload,
setDebugData,
setActiveDebugTab,
setMessage,
t,
applyAutoCollapseLogic,
],
);

// SSE请求
Expand Down Expand Up @@ -500,13 +612,14 @@ export const useApiRequest = (
// 发送请求
const sendRequest = useCallback(
(payload, isStream) => {
if (isStream) {
const { forceNonStream } = resolveEndpointAndPayload(payload);
if (isStream && !forceNonStream) {
handleSSE(payload);
} else {
handleNonStreamRequest(payload);
}
},
[handleSSE, handleNonStreamRequest],
[resolveEndpointAndPayload, handleSSE, handleNonStreamRequest],
);

return {
Expand Down