Compare commits

...

20 Commits

Author SHA1 Message Date
stringadmin 13893bc3a9 Merge remote-tracking branch 'origin/master' into codex/generation-task-reliability
# Conflicts:
#	src/components/AppShell.tsx
2026-06-05 18:38:08 +08:00
stringadmin 5bdeac20fb Merge pull request 'feat: 个人中心仪表盘视觉打磨与交互优化' (#21) from feat/profile-dashboard-polish into master
Reviewed-on: #21
2026-06-05 10:29:24 +00:00
ludan bbc705c8d9 feat: 个人中心仪表盘视觉打磨与交互优化
本次提交对个人中心(Profile Dashboard)进行了全面的 UI/UX 升级:

## AppShell 导航修复
- 修复浮动导航栏显示逻辑:移除未登录状态下多余的 session 判断条件,确保登录页不显示导航

## ProfilePage 功能增强
- 新增面板标题、描述和计数变量,动态展示不同面板(代表作/服务器项目/我的资产/社区审核)的上下文信息
- 背景图更换按钮增加 aria-label 无障碍支持,文字使用独立 span 便于移动端隐藏
- 积分与任务切换按钮拆分为标签+数值结构,信息层级更清晰
- 账号摘要卡片新增套餐名称和已完成任务数展示
- 操作按钮(工作台/社区/退出登录)包裹至 actions 容器,统一布局管理
- 主面板标签页文字包裹 span,支持响应式隐藏

## profile.css 滚动模型调整
- Dashboard 视图改用页面自然滚动,替代嵌套区域滚动,避免双滚动条问题

## dark-green.css 主题样式(约 1160 行新增)
- 背景图与头像区域:毛玻璃按钮、头像环绿边光晕、hover 编辑覆盖层
- 个性签名:圆角胶囊展示态 + 编辑态双向布局,状态提示条
- 账号卡片:标签按钮网格化布局、积分摘要面板、套餐标签
- 操作按钮组:主按钮渐变绿色、次要按钮低对比、退出按钮红色警示
- 内容标签页:胶囊切换 + 计数徽章,激活态绿边高亮
- 列表卡片:hover 微上浮 + 绿色边框过渡,空状态虚线面板
- 多轮视觉迭代:从 graphite 灰调到最终 black+green 参考色调
- 响应式适配:移动端头像环缩小、背景按钮圆形、标签页紧凑排列
- 页面级滚动:让 body 自然滚动,取消 content 内部滚动容器
2026-06-05 18:28:10 +08:00
stringadmin 0d136d8622 perf: reduce chained array traversal 2026-06-05 18:27:08 +08:00
stringadmin d09e5e673e refactor: extract canvas marking popover 2026-06-05 18:19:24 +08:00
stringadmin d68064f529 refactor: share canvas mention textarea 2026-06-05 18:15:29 +08:00
stringadmin 31046eae58 refactor: extract canvas text prompt composer 2026-06-05 18:08:16 +08:00
stringadmin ef05667caa refactor: extract canvas derived state 2026-06-05 18:01:48 +08:00
stringadmin b8b3b8f137 perf: memoize derived render data 2026-06-05 17:35:54 +08:00
stringadmin 6060705345 perf: split page css from main bundle 2026-06-05 17:19:38 +08:00
stringadmin 53f6a02377 fix: reduce store rerenders and cleanup timers 2026-06-05 17:04:01 +08:00
stringadmin 9999e516ae fix: improve generation task reliability 2026-06-05 16:43:02 +08:00
stringadmin 796162de4d Merge pull request 'chore: re-upload current web project code' (#19) from reupload/current-web-20260605 into master
Reviewed-on: #19
2026-06-05 08:13:56 +00:00
stringadmin aebe0ff827 chore: re-upload current web project code 2026-06-05 16:08:47 +08:00
stringadmin c113d82844 Merge pull request 'feat: 实现全局响应式布局,适配不同设备、不同屏幕、不同分辨率' (#17) from feat/responsive-layout into master
Merge PR 17 feat responsive-layout
2026-06-05 07:21:29 +00:00
stringadmin 2129b29dfe Merge pull request 'Feat/profile account polish' (#16) from feat/profile-account-polish into master
Reviewed-on: #16
2026-06-05 06:58:37 +00:00
stringadmin d36d46836f merge: resolve EcommercePage.tsx conflict, integrate master into profile-account-polish
Keep master's EcommercePage.tsx (has more complete upload logic from prior conflict resolution). Accept all other master changes including canvas tool panels, task lifecycle, and workbench updates.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-05 14:05:39 +08:00
ludan b17a978e9e Merge origin/master: 保留电商上传优化版,接入master新增面板组件
冲突解决:EcommercePage.tsx 保留本地版本(上传预览大图+缩略图切换交互)
master新增:6个独立面板组件、图片校验工具、视频工作区增强、CSS更新
2026-06-05 10:34:19 +08:00
ludan 6d68ab02bb feat: 个人中心账户摘要区重构、主题色调对齐电商
【账户摘要区重构】
- 新增 profile-page__account-summary 双列网格布局(主信息 + 右侧指标)
- 主信息区(account-summary-main):显示账号名/任务概览
- 指标区(account-summary-metric):品牌绿色数字展示积分/完成数,左侧分隔线
- 任务概览改为"X 个任务"更自然的表达方式
- 替代旧 upload-card--meta/meta-item 类名体系

【主题色调对齐】
- 个人中心页面背景、侧边栏、卡片统一为电商同款平坦暗色
- 移除 box-shadow 深度阴影,使用 var(--bg-panel)/var(--bg-inset) Token
- Tab 切换按钮透明背景,选中态品牌绿边框+浅绿背景
- 统计卡片/简介/Bio/媒体预览卡片统一边框与背景色
- 媒体徽章、分享按钮、头像环去除阴影
2026-06-04 18:06:43 +08:00
ludan 2b65206b84 feat: 电商克隆上传交互升级、视频模型选择器图标
【电商克隆 - 商品图上传交互重构】
- 新增上传预览大图区(clone-ai-upload-preview-wrap),点击缩略图可切换预览
- 选中缩略图增加 is-active 绿色边框高亮
- 预览区显示商品图编号 + 尺寸/比例/格式信息(formatProductImageSpec)
- 上传区到达 7 张上限时显示"已达上限"、阻止拖拽上传、输入框禁用
- 上传图片自动异步读取尺寸(width/height),无需等待上传完成即可展示
- 已上传素材区重构为列表头(标题+计数)+ 缩略图栈式布局
- 缩略图增加序号角标(1-7),删除按钮独立于缩略图下方
- selectedProductImageId 状态自动管理:删除/新增时自动切换到有效图片

【工作台 - 视频模型选择器图标】
- 新增 VIDEO_MODEL_ICON_URLS 映射(HappyHorse/Pixverse/Vidu/Wan/Kling)
- SelectChip 组件在 chipId=video-model 时显示模型品牌图标
- getVideoModelIconUrl 支持中英文模糊匹配

【样式】
- ecommerce.css: 预览区/素材栈/缩略图选中态/上限态完整样式
- dark-green.css: 主题层微调
2026-06-04 17:27:40 +08:00
60 changed files with 2329 additions and 1508 deletions
+2 -2
View File
@@ -42,9 +42,9 @@ assertNoMatch(
/dashscope\.aliyuncs\.com|\/dashscope-api\b|Bearer\s+sk-/i, /dashscope\.aliyuncs\.com|\/dashscope-api\b|Bearer\s+sk-/i,
); );
assertMatch("image generation must go through the app API", generationClient, /buildApiUrl\("ai\/image"\)/); assertMatch("image generation must go through the app API", generationClient, /buildApiUrl\("ai\/image"\)/);
assertMatch("video generation must go through the app API", generationClient, /buildApiUrl\("ai\/video"\)/); assertMatch("video generation must go through the app API", generationClient, /serverRequest<\{ taskId: string \}>\("ai\/video"/);
assertMatch("binary uploads must go through the app OSS API", generationClient, /buildApiUrl\("oss\/upload-binary"\)/); assertMatch("binary uploads must go through the app OSS API", generationClient, /buildApiUrl\("oss\/upload-binary"\)/);
assertMatch("URL uploads must go through the app OSS API", generationClient, /buildApiUrl\("oss\/upload-by-url"\)/); assertMatch("URL uploads must go through the app OSS API", generationClient, /serverRequest<\{ url: string; signedUrl\?: string; ossKey\?: string \}>\("oss\/upload-by-url"/);
assertMatch( assertMatch(
"ecommerce video history must durable-copy media before saving", "ecommerce video history must durable-copy media before saving",
ecommerceVideoService, ecommerceVideoService,
+138 -49
View File
@@ -15,6 +15,7 @@ import {
WalletOutlined, WalletOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import ErrorBoundary from "./components/ErrorBoundary"; import ErrorBoundary from "./components/ErrorBoundary";
import { reportError } from "./utils/errorReporting"; import { reportError } from "./utils/errorReporting";
import { initNotificationPermission } from "./utils/generationNotifier"; import { initNotificationPermission } from "./utils/generationNotifier";
@@ -126,6 +127,27 @@ const VIEW_KEYS = new Set<WebViewKey>([
]); ]);
const PUBLIC_VIEW_SET = new Set<WebViewKey>(["home", "login", "community", "more", "dialogGenerator", "userAgreement", "privacyPolicy", "not-found"]); const PUBLIC_VIEW_SET = new Set<WebViewKey>(["home", "login", "community", "more", "dialogGenerator", "userAgreement", "privacyPolicy", "not-found"]);
const LEGACY_PAGE_STYLE_VIEWS = new Set<WebViewKey>([
"login",
"workbench",
"canvas",
"community",
"communityReview",
"communityCaseAdd",
"assets",
"ecommerce",
"ecommerceHub",
"digitalHuman",
"characterMix",
"more",
]);
let legacyPageStylesPromise: Promise<unknown> | null = null;
function loadLegacyPageStyles(): Promise<unknown> {
legacyPageStylesPromise ??= import("./styles/pages/legacy-pages.css");
return legacyPageStylesPromise;
}
function normalizeViewKey(rawView: string): WebViewKey { function normalizeViewKey(rawView: string): WebViewKey {
const normalized = const normalized =
@@ -233,61 +255,122 @@ function App() {
const canvasAutoOpenedRecentRef = useRef(false); const canvasAutoOpenedRecentRef = useRef(false);
// Session store // Session store
const session = useSessionStore((s) => s.session); const {
const loginPromptOpen = useSessionStore((s) => s.loginPromptOpen); session,
const pendingAction = useSessionStore((s) => s.pendingAction); loginPromptOpen,
const sessionReplacedOpen = useSessionStore((s) => s.sessionReplacedOpen); pendingAction,
const sessionReplacedMessage = useSessionStore((s) => s.sessionReplacedMessage); sessionReplacedOpen,
const setSession = useSessionStore((s) => s.setSession); sessionReplacedMessage,
const openLoginPrompt = useSessionStore((s) => s.openLoginPrompt); setSession,
const closeLoginPrompt = useSessionStore((s) => s.closeLoginPrompt); openLoginPrompt,
const showSessionReplaced = useSessionStore((s) => s.showSessionReplaced); closeLoginPrompt,
const hideSessionReplaced = useSessionStore((s) => s.hideSessionReplaced); showSessionReplaced,
const clearSessionState = useSessionStore((s) => s.clearSession); hideSessionReplaced,
clearSession: clearSessionState,
} = useSessionStore(useShallow((s) => ({
session: s.session,
loginPromptOpen: s.loginPromptOpen,
pendingAction: s.pendingAction,
sessionReplacedOpen: s.sessionReplacedOpen,
sessionReplacedMessage: s.sessionReplacedMessage,
setSession: s.setSession,
openLoginPrompt: s.openLoginPrompt,
closeLoginPrompt: s.closeLoginPrompt,
showSessionReplaced: s.showSessionReplaced,
hideSessionReplaced: s.hideSessionReplaced,
clearSession: s.clearSession,
})));
// Project store // Project store
const projects = useProjectStore((s) => s.projects); const {
const projectsLoaded = useProjectStore((s) => s.projectsLoaded); projects,
const canvasWorkflow = useProjectStore((s) => s.canvasWorkflow); projectsLoaded,
const currentCanvasProjectId = useProjectStore((s) => s.currentCanvasProjectId); canvasWorkflow,
const pendingDeleteProject = useProjectStore((s) => s.pendingDeleteProject); currentCanvasProjectId,
const deleteProjectSubmitting = useProjectStore((s) => s.deleteProjectSubmitting); pendingDeleteProject,
const setProjects = useProjectStore((s) => s.setProjects); deleteProjectSubmitting,
const setProjectsLoaded = useProjectStore((s) => s.setProjectsLoaded); setProjects,
const setCanvasWorkflow = useProjectStore((s) => s.setCanvasWorkflow); setProjectsLoaded,
const setCurrentCanvasProjectId = useProjectStore((s) => s.setCurrentCanvasProjectId); setCanvasWorkflow,
const openDeleteProjectModal = useProjectStore((s) => s.openDeleteProject); setCurrentCanvasProjectId,
const closeDeleteProjectModal = useProjectStore((s) => s.closeDeleteProject); openDeleteProject: openDeleteProjectModal,
const setDeleteProjectSubmitting = useProjectStore((s) => s.setDeleteProjectSubmitting); closeDeleteProject: closeDeleteProjectModal,
const clearProjectState = useProjectStore((s) => s.clearProjectState); setDeleteProjectSubmitting,
clearProjectState,
} = useProjectStore(useShallow((s) => ({
projects: s.projects,
projectsLoaded: s.projectsLoaded,
canvasWorkflow: s.canvasWorkflow,
currentCanvasProjectId: s.currentCanvasProjectId,
pendingDeleteProject: s.pendingDeleteProject,
deleteProjectSubmitting: s.deleteProjectSubmitting,
setProjects: s.setProjects,
setProjectsLoaded: s.setProjectsLoaded,
setCanvasWorkflow: s.setCanvasWorkflow,
setCurrentCanvasProjectId: s.setCurrentCanvasProjectId,
openDeleteProject: s.openDeleteProject,
closeDeleteProject: s.closeDeleteProject,
setDeleteProjectSubmitting: s.setDeleteProjectSubmitting,
clearProjectState: s.clearProjectState,
})));
// Task store // Task store
const tasks = useTaskStore((s) => s.tasks); const {
const appendTask = useTaskStore((s) => s.appendTask); tasks,
const mergeServerTasks = useTaskStore((s) => s.mergeServerTasks); appendTask,
const clearTasks = useTaskStore((s) => s.clearTasks); mergeServerTasks,
clearTasks,
} = useTaskStore(useShallow((s) => ({
tasks: s.tasks,
appendTask: s.appendTask,
mergeServerTasks: s.mergeServerTasks,
clearTasks: s.clearTasks,
})));
// App store // App store
const usage = useAppStore((s) => s.usage); const {
const runtimeNotifications = useAppStore((s) => s.runtimeNotifications); usage,
const serverNotifications = useAppStore((s) => s.serverNotifications); runtimeNotifications,
const activeView = useAppStore((s) => s.activeView); serverNotifications,
const workspaceExpanded = useAppStore((s) => s.workspaceExpanded); activeView,
const imageWorkbenchTool = useAppStore((s) => s.imageWorkbenchTool); workspaceExpanded,
const pendingEcommerceTemplate = useAppStore((s) => s.pendingEcommerceTemplate); imageWorkbenchTool,
const backendHealth = useAppStore((s) => s.backendHealth); pendingEcommerceTemplate,
const setUsage = useAppStore((s) => s.setUsage); backendHealth,
const pushNotification = useAppStore((s) => s.pushNotification); setUsage,
const setRuntimeNotifications = useAppStore((s) => s.setRuntimeNotifications); pushNotification,
const setServerNotifications = useAppStore((s) => s.setServerNotifications); setRuntimeNotifications,
const setView = useAppStore((s) => s.setView); setServerNotifications,
const setWorkspaceExpanded = useAppStore((s) => s.setWorkspaceExpanded); setView,
const setImageWorkbenchTool = useAppStore((s) => s.setImageWorkbenchTool); setWorkspaceExpanded,
const setPendingEcommerceTemplate = useAppStore((s) => s.setPendingEcommerceTemplate); setImageWorkbenchTool,
const setBackendHealth = useAppStore((s) => s.setBackendHealth); setPendingEcommerceTemplate,
const markNotificationRead = useAppStore((s) => s.markNotificationRead); setBackendHealth,
const markAllNotificationsRead = useAppStore((s) => s.markAllNotificationsRead); markNotificationRead,
const clearAppState = useAppStore((s) => s.clearAppState); markAllNotificationsRead,
clearAppState,
} = useAppStore(useShallow((s) => ({
usage: s.usage,
runtimeNotifications: s.runtimeNotifications,
serverNotifications: s.serverNotifications,
activeView: s.activeView,
workspaceExpanded: s.workspaceExpanded,
imageWorkbenchTool: s.imageWorkbenchTool,
pendingEcommerceTemplate: s.pendingEcommerceTemplate,
backendHealth: s.backendHealth,
setUsage: s.setUsage,
pushNotification: s.pushNotification,
setRuntimeNotifications: s.setRuntimeNotifications,
setServerNotifications: s.setServerNotifications,
setView: s.setView,
setWorkspaceExpanded: s.setWorkspaceExpanded,
setImageWorkbenchTool: s.setImageWorkbenchTool,
setPendingEcommerceTemplate: s.setPendingEcommerceTemplate,
setBackendHealth: s.setBackendHealth,
markNotificationRead: s.markNotificationRead,
markAllNotificationsRead: s.markAllNotificationsRead,
clearAppState: s.clearAppState,
})));
const [ecommerceEverMounted, setEcommerceEverMounted] = useState(false); const [ecommerceEverMounted, setEcommerceEverMounted] = useState(false);
const isEcommerceActive = activeView === "ecommerce" || activeView === "ecommerceHub"; const isEcommerceActive = activeView === "ecommerce" || activeView === "ecommerceHub";
@@ -295,6 +378,12 @@ function App() {
if (isEcommerceActive && !ecommerceEverMounted) setEcommerceEverMounted(true); if (isEcommerceActive && !ecommerceEverMounted) setEcommerceEverMounted(true);
}, [isEcommerceActive]); // eslint-disable-line react-hooks/exhaustive-deps }, [isEcommerceActive]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (LEGACY_PAGE_STYLE_VIEWS.has(activeView) || ecommerceEverMounted) {
void loadLegacyPageStyles();
}
}, [activeView, ecommerceEverMounted]);
// Dismiss boot splash after first render // Dismiss boot splash after first render
useEffect(() => { useEffect(() => {
const splash = document.getElementById("app-boot-splash"); const splash = document.getElementById("app-boot-splash");
+70 -91
View File
@@ -3,6 +3,7 @@ import {
buildAuthHeaders, buildAuthHeaders,
isRecord, isRecord,
readJsonResponse, readJsonResponse,
serverRequest,
throwResponseError, throwResponseError,
} from "./serverConnection"; } from "./serverConnection";
import { isOptionalApiRouteMissing } from "./apiErrorUtils"; import { isOptionalApiRouteMissing } from "./apiErrorUtils";
@@ -243,6 +244,10 @@ function emitImageRouteDebug(label: string, payload: Record<string, unknown>): v
let taskHistoryRouteMissing = false; let taskHistoryRouteMissing = false;
const TASK_SUBMIT_TIMEOUT_MS = 90_000;
const TASK_STATUS_TIMEOUT_MS = 20_000;
const NON_RETRYING_REQUEST = { maxRetries: 0 };
export const aiGenerationClient = { export const aiGenerationClient = {
async createImageTask(input: ImageGenInput): Promise<ImageTaskCreateResponse> { async createImageTask(input: ImageGenInput): Promise<ImageTaskCreateResponse> {
const requestUrl = buildApiUrl("ai/image"); const requestUrl = buildApiUrl("ai/image");
@@ -256,15 +261,13 @@ export const aiGenerationClient = {
projectId: input.projectId, projectId: input.projectId,
conversationId: input.conversationId, conversationId: input.conversationId,
}); });
const res = await fetch(requestUrl, { const payload = await serverRequest<ImageTaskCreateResponse>("ai/image", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Image generation request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Image generation request failed");
}
const payload = await readJsonResponse<ImageTaskCreateResponse>(res, "Image generation response failed");
if (payload.providerDebug) { if (payload.providerDebug) {
emitImageRouteDebug("[ai/image-provider-debug]", payload.providerDebug as Record<string, unknown>); emitImageRouteDebug("[ai/image-provider-debug]", payload.providerDebug as Record<string, unknown>);
} }
@@ -272,96 +275,83 @@ export const aiGenerationClient = {
}, },
async createVideoTask(input: VideoGenInput): Promise<{ taskId: string }> { async createVideoTask(input: VideoGenInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/video"), { return serverRequest<{ taskId: string }>("ai/video", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Video generation request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Video generation request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Video generation response failed");
}, },
async createVideoSuperResolveTask(input: VideoSuperResolveInput): Promise<{ taskId: string }> { async createVideoSuperResolveTask(input: VideoSuperResolveInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/video/super-resolve"), { return serverRequest<{ taskId: string }>("ai/video/super-resolve", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Video super-resolution request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Video super-resolution request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Video super-resolution response failed");
}, },
async createEraseSubtitlesTask(input: EraseSubtitlesInput): Promise<{ taskId: string }> { async createEraseSubtitlesTask(input: EraseSubtitlesInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/video/erase-subtitles"), { return serverRequest<{ taskId: string }>("ai/video/erase-subtitles", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Subtitle removal request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Subtitle removal request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Subtitle removal response failed");
}, },
async createVideoEditTask(input: VideoEditInput): Promise<{ taskId: string }> { async createVideoEditTask(input: VideoEditInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/video/edit"), { return serverRequest<{ taskId: string }>("ai/video/edit", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: { ...input, model: input.model || "happyhorse-1.0-video-edit" },
body: JSON.stringify({ ...input, model: input.model || "happyhorse-1.0-video-edit" }), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Video edit request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Video edit request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Video edit response failed");
}, },
async createImageSuperResolveTask(input: ImageSuperResolveInput): Promise<{ taskId: string }> { async createImageSuperResolveTask(input: ImageSuperResolveInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/image/super-resolve"), { return serverRequest<{ taskId: string }>("ai/image/super-resolve", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Image super-resolution request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Image super-resolution request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Image super-resolution response failed");
}, },
async createImageEditTask(input: ImageEditInput): Promise<{ taskId: string }> { async createImageEditTask(input: ImageEditInput): Promise<{ taskId: string }> {
const res = await fetch(buildApiUrl("ai/image/edit"), { return serverRequest<{ taskId: string }>("ai/image/edit", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), timeoutMs: TASK_SUBMIT_TIMEOUT_MS,
maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Image edit request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Image edit request failed");
}
return readJsonResponse<{ taskId: string }>(res, "Image edit response failed");
}, },
async cancelTask(taskId: string): Promise<void> { async cancelTask(taskId: string): Promise<void> {
const res = await fetch(buildApiUrl(`ai/tasks/${taskId}/cancel`), { try {
await serverRequest<void>(`ai/tasks/${taskId}/cancel`, {
method: "PATCH", method: "PATCH",
headers: buildAuthHeaders(), maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Task cancel failed",
}); });
if (!res.ok && res.status !== 404) { } catch (error) {
await throwResponseError(res, "Task cancel failed"); if (isOptionalApiRouteMissing(error)) return;
throw error;
} }
}, },
async getTaskStatus(taskId: string): Promise<AiTaskStatus> { async getTaskStatus(taskId: string): Promise<AiTaskStatus> {
const res = await fetch(buildApiUrl(`ai/tasks/${taskId}`), { return serverRequest<AiTaskStatus>(`ai/tasks/${taskId}`, {
method: "GET", timeoutMs: TASK_STATUS_TIMEOUT_MS,
headers: buildAuthHeaders(), fallbackMessage: "Task status request failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Task status request failed");
}
return readJsonResponse<AiTaskStatus>(res, "Task status response failed");
}, },
async downloadTaskResult(taskId: string): Promise<{ blob: Blob; filename?: string; contentType?: string }> { async downloadTaskResult(taskId: string): Promise<{ blob: Blob; filename?: string; contentType?: string }> {
@@ -387,13 +377,11 @@ export const aiGenerationClient = {
if (params?.status) search.set("status", params.status); if (params?.status) search.set("status", params.status);
if (params?.type) search.set("type", params.type); if (params?.type) search.set("type", params.type);
if (params?.projectId) search.set("projectId", params.projectId); if (params?.projectId) search.set("projectId", params.projectId);
const res = await fetch(buildApiUrl(`ai/tasks${search.toString() ? `?${search}` : ""}`), {
method: "GET",
headers: buildAuthHeaders(),
});
if (!res.ok) {
try { try {
await throwResponseError(res, "Task history request failed"); const payload = await serverRequest<unknown>(`ai/tasks${search.toString() ? `?${search}` : ""}`, {
fallbackMessage: "Task history request failed",
});
return extractTaskList(payload).map(toPreviewTask);
} catch (error) { } catch (error) {
if (isOptionalApiRouteMissing(error)) { if (isOptionalApiRouteMissing(error)) {
taskHistoryRouteMissing = true; taskHistoryRouteMissing = true;
@@ -401,35 +389,29 @@ export const aiGenerationClient = {
} }
throw error; throw error;
} }
}
const payload = await readJsonResponse<unknown>(res, "Task history response failed");
return extractTaskList(payload).map(toPreviewTask);
}, },
async bindTaskToConversation(taskId: string, conversationId: number): Promise<void> { async bindTaskToConversation(taskId: string, conversationId: number): Promise<void> {
const res = await fetch(buildApiUrl(`ai/tasks/${taskId}/conversation`), { try {
await serverRequest<void>(`ai/tasks/${taskId}/conversation`, {
method: "PATCH", method: "PATCH",
headers: buildAuthHeaders(), body: { conversationId },
body: JSON.stringify({ conversationId }), maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Task conversation binding failed",
}); });
if (res.status === 404) { } catch (error) {
return; if (isOptionalApiRouteMissing(error)) return;
} throw error;
if (!res.ok) {
await throwResponseError(res, "Task conversation binding failed");
} }
}, },
async uploadAsset(input: UploadAssetInput): Promise<{ url: string; signedUrl?: string; ossKey?: string }> { async uploadAsset(input: UploadAssetInput): Promise<{ url: string; signedUrl?: string; ossKey?: string }> {
const res = await fetch(buildApiUrl("oss/upload"), { return serverRequest<{ url: string; signedUrl?: string; ossKey?: string }>("oss/upload", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Asset upload failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Asset upload failed");
}
return readJsonResponse<{ url: string; ossKey?: string }>(res, "Asset upload response failed");
}, },
async uploadAssetBinary(blob: Blob, options?: { name?: string; mimeType?: string; scope?: string }): Promise<{ url: string; signedUrl?: string; ossKey?: string }> { async uploadAssetBinary(blob: Blob, options?: { name?: string; mimeType?: string; scope?: string }): Promise<{ url: string; signedUrl?: string; ossKey?: string }> {
@@ -451,15 +433,12 @@ export const aiGenerationClient = {
}, },
async uploadAssetByUrl(input: UploadAssetByUrlInput): Promise<{ url: string; signedUrl?: string; ossKey?: string }> { async uploadAssetByUrl(input: UploadAssetByUrlInput): Promise<{ url: string; signedUrl?: string; ossKey?: string }> {
const res = await fetch(buildApiUrl("oss/upload-by-url"), { return serverRequest<{ url: string; signedUrl?: string; ossKey?: string }>("oss/upload-by-url", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: input,
body: JSON.stringify(input), maxRetries: NON_RETRYING_REQUEST.maxRetries,
fallbackMessage: "Asset upload by URL failed",
}); });
if (!res.ok) {
await throwResponseError(res, "Asset upload by URL failed");
}
return readJsonResponse<{ url: string; ossKey?: string }>(res, "Asset upload by URL response failed");
}, },
subscribeTaskStatus( subscribeTaskStatus(
+3 -8
View File
@@ -1,4 +1,4 @@
import { buildApiUrl, buildAuthHeaders } from "./serverConnection"; import { serverRequest } from "./serverConnection";
export interface ProviderHealthEntry { export interface ProviderHealthEntry {
status: string; status: string;
@@ -32,13 +32,8 @@ export interface ProviderHealthResponse {
export const providerHealthClient = { export const providerHealthClient = {
async getStatus(): Promise<ProviderHealthResponse> { async getStatus(): Promise<ProviderHealthResponse> {
const res = await fetch(buildApiUrl("admin/providers/status"), { return serverRequest<ProviderHealthResponse>("admin/providers/status", {
method: "GET", fallbackMessage: "Provider health request failed",
headers: buildAuthHeaders(),
}); });
if (!res.ok) {
throw new Error(`Provider health request failed (${res.status})`);
}
return res.json() as Promise<ProviderHealthResponse>;
}, },
}; };
+23 -12
View File
@@ -1,4 +1,4 @@
import { buildApiUrl, buildAuthHeaders } from "./serverConnection"; import { serverRequest } from "./serverConnection";
export interface ScriptEvalResult { export interface ScriptEvalResult {
totalScore: number; totalScore: number;
@@ -107,6 +107,17 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value)); return Boolean(value && typeof value === "object" && !Array.isArray(value));
} }
function normalizeEvidenceItems(source: unknown[], limit: number): string[] {
const items: string[] = [];
for (const item of source) {
const value = String(item).trim();
if (!value) continue;
items.push(value);
if (items.length >= limit) break;
}
return items;
}
function normalizeNestedScores(value: unknown): Record<string, Record<string, number>> { function normalizeNestedScores(value: unknown): Record<string, Record<string, number>> {
if (!isRecord(value)) return {}; if (!isRecord(value)) return {};
@@ -132,7 +143,7 @@ function normalizeEvidence(value: unknown): Record<string, string[]> {
const source = value[dimensionKey] ?? (dimensionKey === "logic" ? value.dialogue : undefined); const source = value[dimensionKey] ?? (dimensionKey === "logic" ? value.dialogue : undefined);
if (!Array.isArray(source)) continue; if (!Array.isArray(source)) continue;
const items = source.map(String).map((item) => item.trim()).filter(Boolean).slice(0, 3); const items = normalizeEvidenceItems(source, 3);
if (items.length > 0) normalized[dimensionKey] = items; if (items.length > 0) normalized[dimensionKey] = items;
} }
@@ -140,10 +151,13 @@ function normalizeEvidence(value: unknown): Record<string, string[]> {
} }
export async function evaluateScript(script: string, signal?: AbortSignal): Promise<ScriptEvalResult> { export async function evaluateScript(script: string, signal?: AbortSignal): Promise<ScriptEvalResult> {
const res = await fetch(buildApiUrl("ai/chat"), { const payload = await serverRequest<{
content?: string;
choices?: Array<{ message?: { content?: string } }>;
text?: string;
}>("ai/chat", {
method: "POST", method: "POST",
headers: buildAuthHeaders(), body: {
body: JSON.stringify({
model: MODEL, model: MODEL,
messages: [ messages: [
{ role: "system", content: EVAL_SYSTEM_PROMPT }, { role: "system", content: EVAL_SYSTEM_PROMPT },
@@ -153,16 +167,13 @@ export async function evaluateScript(script: string, signal?: AbortSignal): Prom
stream: false, stream: false,
temperature: 0.3, temperature: 0.3,
max_tokens: 4096, max_tokens: 4096,
}), },
signal, signal,
timeoutMs: 180_000,
maxRetries: 0,
fallbackMessage: "评测请求失败",
}); });
if (!res.ok) {
const errText = await res.text().catch(() => "");
throw new Error(`评测请求失败 (${res.status}): ${errText.slice(0, 200)}`);
}
const payload = await res.json();
const content: string = payload?.content ?? payload?.choices?.[0]?.message?.content ?? payload?.text ?? ""; const content: string = payload?.content ?? payload?.choices?.[0]?.message?.content ?? payload?.text ?? "";
if (!content) throw new Error("模型未返回有效内容"); if (!content) throw new Error("模型未返回有效内容");
+8 -3
View File
@@ -22,6 +22,9 @@ export interface ServerRequestOptions {
signal?: AbortSignal; signal?: AbortSignal;
/** Per-request timeout in ms. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. Pass 0 to disable. */ /** Per-request timeout in ms. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. Pass 0 to disable. */
timeoutMs?: number; timeoutMs?: number;
/** Defaults to 2. Use 0 for non-idempotent task submission endpoints. */
maxRetries?: number;
fallbackMessage?: string;
} }
export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
@@ -343,8 +346,10 @@ const MAX_RETRIES = 2;
export async function serverRequest<T>(path: string, options?: ServerRequestOptions): Promise<T> { export async function serverRequest<T>(path: string, options?: ServerRequestOptions): Promise<T> {
let lastError: unknown; let lastError: unknown;
const timeoutMs = options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; const timeoutMs = options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const maxRetries = options?.maxRetries ?? MAX_RETRIES;
const fallbackMessage = options?.fallbackMessage || "Request failed";
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { for (let attempt = 0; attempt <= maxRetries; attempt++) {
const controller = timeoutMs > 0 ? new AbortController() : null; const controller = timeoutMs > 0 ? new AbortController() : null;
const timeoutId = const timeoutId =
controller && typeof window !== "undefined" controller && typeof window !== "undefined"
@@ -366,11 +371,11 @@ export async function serverRequest<T>(path: string, options?: ServerRequestOpti
credentials: "include", credentials: "include",
}); });
const payload = await readJsonResponse<unknown>(response, "Request failed"); const payload = await readJsonResponse<unknown>(response, fallbackMessage);
return (options?.raw ? payload : unwrapApiPayload(payload)) as T; return (options?.raw ? payload : unwrapApiPayload(payload)) as T;
} catch (error) { } catch (error) {
lastError = error; lastError = error;
if (attempt < MAX_RETRIES && isRetryable(error) && !options?.signal?.aborted) { if (attempt < maxRetries && isRetryable(error) && !options?.signal?.aborted) {
await new Promise((r) => setTimeout(r, getRetryDelay(attempt, error))); await new Promise((r) => setTimeout(r, getRetryDelay(attempt, error)));
continue; continue;
} }
+29 -29
View File
@@ -41,6 +41,32 @@ interface AppShellProps {
} }
const BRAND_LOGO_URL = ossAssets.brand.logo; const BRAND_LOGO_URL = ossAssets.brand.logo;
const TOOL_SURFACE_VIEW_SET = new Set<WebViewKey>([
"workbench",
"canvas",
"more",
"scriptTokens",
"tokenUsage",
"ecommerceTemplates",
"sizeTemplate",
"imageWorkbench",
"resolutionUpscale",
"digitalHuman",
"dialogGenerator",
"avatarConsole",
"characterMix",
] as WebViewKey[]);
const PRIMARY_NAV_ORDER: WebViewKey[] = [
"workbench",
"ecommerce",
"sizeTemplate",
"canvas",
"scriptTokens",
"tokenUsage",
"community",
"assets",
"more",
];
function formatBalance(cents: number): string { function formatBalance(cents: number): string {
const value = Math.max(0, cents) / 100; const value = Math.max(0, cents) / 100;
@@ -75,38 +101,12 @@ function AppShell({
const [navJustActivated, setNavJustActivated] = useState<WebViewKey | null>(null); const [navJustActivated, setNavJustActivated] = useState<WebViewKey | null>(null);
const isAuthView = activeView === "login"; const isAuthView = activeView === "login";
const isImmersiveView = activeView === "agent" || activeView === "avatarConsole"; const isImmersiveView = activeView === "agent" || activeView === "avatarConsole";
const showFloatingNav = (!isAuthView || !!session) && !isImmersiveView && activeView !== "home"; const showFloatingNav = !isAuthView && !isImmersiveView && activeView !== "home";
const toolSurfaceViews = [ const showPageScrollActions = showFloatingNav && !TOOL_SURFACE_VIEW_SET.has(activeView);
"workbench",
"canvas",
"more",
"scriptTokens",
"tokenUsage",
"ecommerceTemplates",
"sizeTemplate",
"imageWorkbench",
"resolutionUpscale",
"digitalHuman",
"dialogGenerator",
"avatarConsole",
"characterMix",
] as WebViewKey[];
const showPageScrollActions = showFloatingNav && !toolSurfaceViews.includes(activeView);
const visibleNavItems = useMemo( const visibleNavItems = useMemo(
() => { () => {
const orderedKeys: WebViewKey[] = [ return PRIMARY_NAV_ORDER
"workbench",
"ecommerce",
"sizeTemplate",
"canvas",
"scriptTokens",
"tokenUsage",
"community",
"assets",
"more",
];
return orderedKeys
.map((key) => navItems.find((item) => item.key === key)) .map((key) => navItems.find((item) => item.key === key))
.filter((item): item is WebNavItem => Boolean(item)); .filter((item): item is WebNavItem => Boolean(item));
}, },
+1
View File
@@ -1,5 +1,6 @@
import { HomeOutlined } from "@ant-design/icons"; import { HomeOutlined } from "@ant-design/icons";
import { useCallback } from "react"; import { useCallback } from "react";
import "../styles/pages/not-found.css";
interface NotFoundPageProps { interface NotFoundPageProps {
onGoHome: () => void; onGoHome: () => void;
+1
View File
@@ -14,6 +14,7 @@ import {
ThunderboltOutlined, ThunderboltOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import "../../styles/pages/agent.css";
import WorkspacePageShell from "../../components/WorkspacePageShell"; import WorkspacePageShell from "../../components/WorkspacePageShell";
import type { WebGenerationPreviewTask } from "../../types"; import type { WebGenerationPreviewTask } from "../../types";
+1
View File
@@ -11,6 +11,7 @@ import {
UserOutlined, UserOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useMemo, useRef, useState, type JSX } from "react"; import { useCallback, useEffect, useMemo, useRef, useState, type JSX } from "react";
import "../../styles/pages/assets.css";
import { assetClient, type ServerAssetItem } from "../../api/assetClient"; import { assetClient, type ServerAssetItem } from "../../api/assetClient";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { useDebounce } from "../../hooks/useDebounce"; import { useDebounce } from "../../hooks/useDebounce";
@@ -0,0 +1,40 @@
interface CanvasMarkingPopoverProps {
value?: string;
placeholder: string;
onChange: (value: string) => void;
onClear: () => void;
onDone: () => void;
}
export function CanvasMarkingPopover({
value,
placeholder,
onChange,
onClear,
onDone,
}: CanvasMarkingPopoverProps) {
return (
<div
className="studio-canvas-marking-popover"
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
>
<textarea
className="studio-canvas-marking-input"
placeholder={placeholder}
value={value || ""}
onChange={(event) => onChange(event.target.value)}
/>
<div className="studio-canvas-marking-actions">
{value ? (
<button type="button" className="studio-canvas-marking-clear" onClick={onClear}>
</button>
) : null}
<button type="button" className="studio-canvas-marking-done" onClick={onDone}>
</button>
</div>
</div>
);
}
+154 -318
View File
@@ -28,10 +28,13 @@
import { import {
ReactFlow, ReactFlow,
} from "@xyflow/react"; } from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import "../../styles/pages/canvas.css";
import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type CSSProperties, type MouseEvent, type WheelEvent } from "react"; import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type CSSProperties, type MouseEvent, type WheelEvent } from "react";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { assetClient, type ServerAssetItem } from "../../api/assetClient"; import { assetClient, type ServerAssetItem } from "../../api/assetClient";
import { communityClient } from "../../api/communityClient"; import { communityClient } from "../../api/communityClient";
import { modelCapabilitiesClient } from "../../api/modelCapabilitiesClient";
import type { CreatePreviewTaskInput } from "../../api/webGenerationGateway"; import type { CreatePreviewTaskInput } from "../../api/webGenerationGateway";
import WorkspacePageShell from "../../components/WorkspacePageShell"; import WorkspacePageShell from "../../components/WorkspacePageShell";
import type { import type {
@@ -52,6 +55,7 @@ import { useCanvasHistory, type CanvasHistorySnapshot } from "./useCanvasHistory
import { useCanvasKeyboard } from "./useCanvasKeyboard"; import { useCanvasKeyboard } from "./useCanvasKeyboard";
import { useCanvasNodeDrag } from "./useCanvasNodeDrag"; import { useCanvasNodeDrag } from "./useCanvasNodeDrag";
import { useCanvasGeneration, addCanvasGenKeepalive, removeCanvasGenKeepalive } from "./useCanvasGeneration"; import { useCanvasGeneration, addCanvasGenKeepalive, removeCanvasGenKeepalive } from "./useCanvasGeneration";
import { useCanvasAssetSummary, useCanvasVisibleNodes } from "./useCanvasDerivedState";
import { import {
toHappyHorseDisplayModel, toHappyHorseDisplayModel,
} from "../../utils/happyHorseRouting"; } from "../../utils/happyHorseRouting";
@@ -118,7 +122,7 @@ import {
defaultVideoModel, defaultVideoModel,
image4kCapableModels, image4kCapableModels,
imageFocusRatioOptions, imageFocusRatioOptions,
imageModelOptions, imageModelOptions as fallbackCanvasImageModelOptions,
imageRatioOptions, imageRatioOptions,
textModelOptions, textModelOptions,
videoDurationOptions, videoDurationOptions,
@@ -182,6 +186,8 @@ import {
} from "./canvasWorkflowDeserialize"; } from "./canvasWorkflowDeserialize";
import { CanvasNodeToolbar, CanvasNodeVideoPlayer, CanvasSelectChip } from "./canvasComponents"; import { CanvasNodeToolbar, CanvasNodeVideoPlayer, CanvasSelectChip } from "./canvasComponents";
import type { CanvasNodeToolbarAction } from "./canvasComponents"; import type { CanvasNodeToolbarAction } from "./canvasComponents";
import { CanvasMarkingPopover } from "./CanvasMarkingPopover";
import { CanvasPromptMentionTextarea, CanvasTextPromptComposer } from "./CanvasTextPromptComposer";
import { CanvasMultiGridPanel, CanvasUpscalePanel, CanvasInpaintPanel } from "./canvasToolPanels"; import { CanvasMultiGridPanel, CanvasUpscalePanel, CanvasInpaintPanel } from "./canvasToolPanels";
import { CanvasSmoothedProgressRing } from "./CanvasSmoothedProgressRing"; import { CanvasSmoothedProgressRing } from "./CanvasSmoothedProgressRing";
@@ -193,7 +199,6 @@ const canvasEnterpriseVideoModelOptions: CanvasOption[] = ENTERPRISE_VIDEO_MODEL
// --- Canvas generation keep-alive (survives page refresh / view switch) --- // --- Canvas generation keep-alive (survives page refresh / view switch) ---
const MENTION_TOKEN_RE = /@(?:图片|视频|文本)\d+/g; const MENTION_TOKEN_RE = /@(?:图片|视频|文本)\d+/g;
const MENTION_BOUNDARY_RE = /\s|[,。、;:!??(){}[\]<>]/;
function buildNodeMentionOptions( function buildNodeMentionOptions(
kind: CanvasNodeKind, kind: CanvasNodeKind,
@@ -354,6 +359,8 @@ function CanvasPage({
const [projectNameEditing, setProjectNameEditing] = useState(false); const [projectNameEditing, setProjectNameEditing] = useState(false);
const [videoNodeMenu, setVideoNodeMenu] = useState<{ left: number; top: number; nodeId: string } | null>(null); const [videoNodeMenu, setVideoNodeMenu] = useState<{ left: number; top: number; nodeId: string } | null>(null);
const [videoNodes, setVideoNodes] = useState<CanvasVideoNode[]>([]); const [videoNodes, setVideoNodes] = useState<CanvasVideoNode[]>([]);
const [canvasImageModelOptions, setCanvasImageModelOptions] = useState<CanvasOption[]>(fallbackCanvasImageModelOptions);
const [canvasVideoModelOptions, setCanvasVideoModelOptions] = useState<CanvasOption[]>(canvasEnterpriseVideoModelOptions);
const [selectedNode, setSelectedNode] = useState<CanvasSelectedNode | null>(null); const [selectedNode, setSelectedNode] = useState<CanvasSelectedNode | null>(null);
const [selectedNodes, setSelectedNodes] = useState<CanvasSelectedNode[]>([]); const [selectedNodes, setSelectedNodes] = useState<CanvasSelectedNode[]>([]);
const [selectionContextMenu, setSelectionContextMenu] = useState<CanvasFloatingMenuPosition | null>(null); const [selectionContextMenu, setSelectionContextMenu] = useState<CanvasFloatingMenuPosition | null>(null);
@@ -394,10 +401,12 @@ function CanvasPage({
const suppressNextPaneClickRef = useRef(false); const suppressNextPaneClickRef = useRef(false);
const canvasAutoSaveTimerRef = useRef<number | null>(null); const canvasAutoSaveTimerRef = useRef<number | null>(null);
const canvasAutoSaveIdleHandleRef = useRef<number | null>(null); const canvasAutoSaveIdleHandleRef = useRef<number | null>(null);
const canvasAutoSaveRetryTimerRef = useRef<number | null>(null);
const canvasAutoSaveInFlightRef = useRef(false); const canvasAutoSaveInFlightRef = useRef(false);
const canvasAutoSavePendingRef = useRef(false); const canvasAutoSavePendingRef = useRef(false);
const lastAutoSavedWorkflowFingerprintRef = useRef(""); const lastAutoSavedWorkflowFingerprintRef = useRef("");
const canvasAutoSaveHydrationRef = useRef(true); const canvasAutoSaveHydrationRef = useRef(true);
const textNodeMentionFocusTimerRef = useRef<number | null>(null);
const textNodeIdRef = useRef(9); const textNodeIdRef = useRef(9);
const imageNodeIdRef = useRef(1); const imageNodeIdRef = useRef(1);
const videoNodeIdRef = useRef(1); const videoNodeIdRef = useRef(1);
@@ -458,9 +467,39 @@ function CanvasPage({
callbacksRef: dragCallbacksRef, callbacksRef: dragCallbacksRef,
suppressNextPaneClickRef, suppressNextPaneClickRef,
}); });
useEffect(() => {
let cancelled = false;
if (!isAuthenticated) {
setCanvasImageModelOptions(fallbackCanvasImageModelOptions);
setCanvasVideoModelOptions(canvasEnterpriseVideoModelOptions);
return () => {
cancelled = true;
};
}
modelCapabilitiesClient
.get()
.then((capabilities) => {
if (cancelled) return;
setCanvasImageModelOptions(capabilities.imageModels.length ? capabilities.imageModels : fallbackCanvasImageModelOptions);
setCanvasVideoModelOptions(capabilities.videoModels.length ? capabilities.videoModels : canvasEnterpriseVideoModelOptions);
})
.catch(() => {
if (cancelled) return;
setCanvasImageModelOptions(fallbackCanvasImageModelOptions);
setCanvasVideoModelOptions(canvasEnterpriseVideoModelOptions);
});
return () => {
cancelled = true;
};
}, [isAuthenticated]);
const visibleImageModelOptions = useMemo( const visibleImageModelOptions = useMemo(
() => filterImageModelOptionsForSession(imageModelOptions, session), () => filterImageModelOptionsForSession(canvasImageModelOptions, session),
[session], [canvasImageModelOptions, session],
); );
const fallbackVisibleImageModel = visibleImageModelOptions[0]?.value || defaultImageModel; const fallbackVisibleImageModel = visibleImageModelOptions[0]?.value || defaultImageModel;
const resolveVisibleImageModel = useCallback( const resolveVisibleImageModel = useCallback(
@@ -486,7 +525,11 @@ function CanvasPage({
else if (kind === "video") updateVideoNodePrompt(nodeId, nextValue); else if (kind === "video") updateVideoNodePrompt(nodeId, nextValue);
else updateTextNodePrompt(nodeId, nextValue); else updateTextNodePrompt(nodeId, nextValue);
closeTextNodeMention(nodeId); closeTextNodeMention(nodeId);
setTimeout(() => { if (textNodeMentionFocusTimerRef.current !== null) {
window.clearTimeout(textNodeMentionFocusTimerRef.current);
}
textNodeMentionFocusTimerRef.current = window.setTimeout(() => {
textNodeMentionFocusTimerRef.current = null;
if (textarea) { if (textarea) {
textarea.focus(); textarea.focus();
textarea.setSelectionRange(nextCaret, nextCaret); textarea.setSelectionRange(nextCaret, nextCaret);
@@ -522,10 +565,22 @@ function CanvasPage({
const [autoSaveStatus, setAutoSaveStatus] = useState<"saved" | "saving" | "error" | "idle">("idle"); const [autoSaveStatus, setAutoSaveStatus] = useState<"saved" | "saving" | "error" | "idle">("idle");
const autoSaveStatusTimerRef = useRef<number | null>(null); const autoSaveStatusTimerRef = useRef<number | null>(null);
useEffect(() => {
return () => {
if (canvasAutoSaveTimerRef.current !== null) window.clearTimeout(canvasAutoSaveTimerRef.current);
if (canvasAutoSaveRetryTimerRef.current !== null) window.clearTimeout(canvasAutoSaveRetryTimerRef.current);
if (autoSaveStatusTimerRef.current !== null) window.clearTimeout(autoSaveStatusTimerRef.current);
if (textNodeMentionFocusTimerRef.current !== null) window.clearTimeout(textNodeMentionFocusTimerRef.current);
if (canvasAutoSaveIdleHandleRef.current !== null && "cancelIdleCallback" in window) {
window.cancelIdleCallback(canvasAutoSaveIdleHandleRef.current);
}
};
}, []);
// Save immediately when user leaves page or switches tab (placed after runCanvasAutoSave definition) // Save immediately when user leaves page or switches tab (placed after runCanvasAutoSave definition)
// — see useEffect below near runCanvasAutoSave // — see useEffect below near runCanvasAutoSave
const canvasAssets = serverAssets.filter((asset) => asset.imageUrl); const { canvasAssets, assetCountsByCategory } = useCanvasAssetSummary(serverAssets);
const shouldShowEmptyProjectState = const shouldShowEmptyProjectState =
projectsLoaded && projects.length === 0 && !projectId && workflow.source === "blank" && workflow.nodes.length === 0; projectsLoaded && projects.length === 0 && !projectId && workflow.source === "blank" && workflow.nodes.length === 0;
const isWaitingForProjects = isAuthenticated && !projectsLoaded; const isWaitingForProjects = isAuthenticated && !projectsLoaded;
@@ -2587,13 +2642,17 @@ function CanvasPage({
setConnectorDrag(null); setConnectorDrag(null);
}; };
const collapsedPackageNodeKeys = new Set( const {
nodePackages.flatMap((nodePackage) => isNodeCollapsedInPackage,
nodePackage.collapsed ? nodePackage.nodeIds.map((node) => getCanvasSelectionKey(node)) : [] visibleTextNodes,
) visibleImageNodes,
); visibleVideoNodes,
const isNodeCollapsedInPackage = (kind: CanvasNodeKind, id: string) => } = useCanvasVisibleNodes({
collapsedPackageNodeKeys.has(getCanvasSelectionKey({ kind, id })); textNodes,
imageNodes,
videoNodes,
nodePackages,
});
const isLinkCollapsedInPackage = (link: { sourceKind: CanvasNodeKind; sourceNodeId: string; targetKind: CanvasNodeKind; targetNodeId: string }) => const isLinkCollapsedInPackage = (link: { sourceKind: CanvasNodeKind; sourceNodeId: string; targetKind: CanvasNodeKind; targetNodeId: string }) =>
isNodeCollapsedInPackage(link.sourceKind, link.sourceNodeId) || isNodeCollapsedInPackage(link.sourceKind, link.sourceNodeId) ||
isNodeCollapsedInPackage(link.targetKind, link.targetNodeId); isNodeCollapsedInPackage(link.targetKind, link.targetNodeId);
@@ -3126,7 +3185,13 @@ function CanvasPage({
canvasAutoSaveInFlightRef.current = false; canvasAutoSaveInFlightRef.current = false;
if (canvasAutoSavePendingRef.current) { if (canvasAutoSavePendingRef.current) {
canvasAutoSavePendingRef.current = false; canvasAutoSavePendingRef.current = false;
window.setTimeout(() => void runCanvasAutoSave(), canvasAutoSaveIdleTimeoutMs); if (canvasAutoSaveRetryTimerRef.current !== null) {
window.clearTimeout(canvasAutoSaveRetryTimerRef.current);
}
canvasAutoSaveRetryTimerRef.current = window.setTimeout(() => {
canvasAutoSaveRetryTimerRef.current = null;
void runCanvasAutoSave();
}, canvasAutoSaveIdleTimeoutMs);
} }
} }
}, [ }, [
@@ -3195,7 +3260,13 @@ function CanvasPage({
); );
return; return;
} }
window.setTimeout(() => void runCanvasAutoSave(), canvasAutoSaveIdleTimeoutMs); if (canvasAutoSaveRetryTimerRef.current !== null) {
window.clearTimeout(canvasAutoSaveRetryTimerRef.current);
}
canvasAutoSaveRetryTimerRef.current = window.setTimeout(() => {
canvasAutoSaveRetryTimerRef.current = null;
void runCanvasAutoSave();
}, canvasAutoSaveIdleTimeoutMs);
}, canvasAutoSaveDebounceMs); }, canvasAutoSaveDebounceMs);
return () => { return () => {
@@ -3207,6 +3278,10 @@ function CanvasPage({
window.cancelIdleCallback(canvasAutoSaveIdleHandleRef.current); window.cancelIdleCallback(canvasAutoSaveIdleHandleRef.current);
canvasAutoSaveIdleHandleRef.current = null; canvasAutoSaveIdleHandleRef.current = null;
} }
if (canvasAutoSaveRetryTimerRef.current !== null) {
window.clearTimeout(canvasAutoSaveRetryTimerRef.current);
canvasAutoSaveRetryTimerRef.current = null;
}
}; };
}, [ }, [
isAuthenticated, isAuthenticated,
@@ -3933,7 +4008,7 @@ function CanvasPage({
) : null} ) : null}
</svg> </svg>
) : null} ) : null}
{textNodes.filter((textNode) => !isNodeCollapsedInPackage("text", textNode.id)).map((textNode) => { {visibleTextNodes.map((textNode) => {
const textNodeSelected = isSelectedNode("text", textNode.id); const textNodeSelected = isSelectedNode("text", textNode.id);
const textNodeActive = isActiveSelectedNode("text", textNode.id); const textNodeActive = isActiveSelectedNode("text", textNode.id);
const textNodeResizing = nodeResizeDrag?.kind === "text" && nodeResizeDrag.nodeId === textNode.id; const textNodeResizing = nodeResizeDrag?.kind === "text" && nodeResizeDrag.nodeId === textNode.id;
@@ -4082,126 +4157,26 @@ function CanvasPage({
onMouseDown={(event) => handleNodeResizeStart(event, "text", textNode.id, textNode.size)} onMouseDown={(event) => handleNodeResizeStart(event, "text", textNode.id, textNode.size)}
/> />
</div> </div>
{textNodeActive && !isCanvasNodeMoving ? (() => { {textNodeActive && !isCanvasNodeMoving ? (
const mentionOptions = buildNodeMentionOptions("text", textNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks); <CanvasTextPromptComposer
const mentionState = textNodeMentionStates[textNode.id] || { open: false, query: "", start: 0, caret: 0, activeIndex: 0 }; nodeId={textNode.id}
const filteredMentions = mentionState.open prompt={textNode.prompt}
? mentionOptions.filter((o) => !mentionState.query || o.searchText.includes(mentionState.query.toLowerCase())) canGenerate={textNodeCanGenerate}
: []; isGenerating={textNodeGenerating}
mentionOptions={buildNodeMentionOptions("text", textNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks)}
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { mentionState={textNodeMentionStates[textNode.id]}
const value = e.target.value; onPromptChange={updateTextNodePrompt}
const caret = e.target.selectionStart || 0; onMentionStateChange={setTextNodeMentionStates}
updateTextNodePrompt(textNode.id, value); onCloseMention={closeTextNodeMention}
onInsertMention={insertTextNodeMention}
// Detect @-mention trigger onGenerate={handleGenerateTextNode}
const beforeCaret = value.slice(0, caret);
const atIdx = beforeCaret.lastIndexOf("@");
if (atIdx >= 0) {
const query = beforeCaret.slice(atIdx + 1);
if (!MENTION_BOUNDARY_RE.test(query) && !query.includes(" ")) {
setTextNodeMentionStates((prev) => ({ ...prev, [textNode.id]: { open: true, query, start: atIdx, caret, activeIndex: 0 } }));
return;
}
}
closeTextNodeMention(textNode.id);
};
const handlePromptKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (!mentionState.open || filteredMentions.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setTextNodeMentionStates((prev) => ({ ...prev, [textNode.id]: { ...mentionState, activeIndex: (mentionState.activeIndex + 1) % filteredMentions.length } }));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setTextNodeMentionStates((prev) => ({ ...prev, [textNode.id]: { ...mentionState, activeIndex: (mentionState.activeIndex - 1 + filteredMentions.length) % filteredMentions.length } }));
} else if (e.key === "Enter" || e.key === "Tab") {
e.preventDefault();
const opt = filteredMentions[mentionState.activeIndex];
if (opt) {
const ta = e.currentTarget;
insertTextNodeMention(textNode.id, opt, ta);
}
} else if (e.key === "Escape") {
e.preventDefault();
closeTextNodeMention(textNode.id);
}
};
const handlePromptSelect = (e: React.SyntheticEvent<HTMLTextAreaElement>) => {
const ta = e.currentTarget;
const caret = ta.selectionStart || 0;
setTextNodeMentionStates((prev) => {
const cur = prev[textNode.id];
if (!cur?.open) return prev;
return { ...prev, [textNode.id]: { ...cur, caret } };
});
};
return (
<div className="studio-canvas-text-composer">
<div className="studio-canvas-text-composer__input-wrap">
<textarea
value={textNode.prompt}
onMouseDown={(event) => event.stopPropagation()}
onChange={handlePromptChange}
onKeyDown={handlePromptKeyDown}
onSelect={handlePromptSelect}
placeholder="写下你想讲的故事、场景或角色设定。@引用连接的节点"
/> />
{mentionState.open ? (
<div className="studio-canvas-mention-panel">
{filteredMentions.length > 0 ? filteredMentions.map((opt, idx) => (
<button
key={opt.token}
type="button"
className={`studio-canvas-mention-item${idx === mentionState.activeIndex ? " is-active" : ""}`}
onMouseDown={(e) => { e.preventDefault(); const ta = e.currentTarget.closest(".studio-canvas-text-composer")?.querySelector("textarea") || null; insertTextNodeMention(textNode.id, opt, ta as HTMLTextAreaElement | null); }}
>
<span className="studio-canvas-mention-thumb">
{opt.kind === "image" && opt.previewUrl ? <img src={opt.previewUrl} alt="" /> : opt.kind === "image" ? "🖼" : opt.kind === "video" ? "🎬" : "📝"}
</span>
<span className="studio-canvas-mention-label">{opt.nodeTitle}</span>
<span className="studio-canvas-mention-token">{opt.token}</span>
</button>
)) : (
<div className="studio-canvas-mention-item" style={{ opacity: 0.5, pointerEvents: "none" }}>
<span className="studio-canvas-mention-label"></span>
</div>
)}
</div>
) : null} ) : null}
</div> </div>
<div className="studio-canvas-text-composer__footer">
<button
type="button"
className={`studio-canvas-text-composer__send studio-canvas-generate-button${textNodeCanGenerate && !textNodeGenerating ? " is-ready" : ""}`}
title={textNodeGenerating ? "生成中" : "生成"}
disabled={textNodeGenerating || !textNodeCanGenerate}
aria-busy={textNodeGenerating}
onMouseDown={(event) => {
event.preventDefault();
event.stopPropagation();
if (!textNodeGenerating && textNodeCanGenerate) {
void handleGenerateTextNode(textNode.id);
}
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
<SendOutlined />
</button>
</div>
</div>
);
})() : null}
</div>
</div> </div>
); );
})} })}
{imageNodes.filter((imageNode) => !isNodeCollapsedInPackage("image", imageNode.id)).map((imageNode) => { {visibleImageNodes.map((imageNode) => {
const imageNodeSelected = isSelectedNode("image", imageNode.id); const imageNodeSelected = isSelectedNode("image", imageNode.id);
const imageNodeActive = isActiveSelectedNode("image", imageNode.id); const imageNodeActive = isActiveSelectedNode("image", imageNode.id);
const imageNodeResizing = nodeResizeDrag?.kind === "image" && nodeResizeDrag.nodeId === imageNode.id; const imageNodeResizing = nodeResizeDrag?.kind === "image" && nodeResizeDrag.nodeId === imageNode.id;
@@ -4459,38 +4434,7 @@ function CanvasPage({
</button> </button>
</div> </div>
) : null} ) : null}
{imageNodeActive && !isCanvasNodeMoving && !imageNodeFocusActive ? (() => { {imageNodeActive && !isCanvasNodeMoving && !imageNodeFocusActive ? (
const imgMentionOptions = buildNodeMentionOptions("image", imageNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks);
const imgMentionState = textNodeMentionStates[imageNode.id] || { open: false, query: "", start: 0, caret: 0, activeIndex: 0 };
const imgFilteredMentions = imgMentionState.open
? imgMentionOptions.filter((o) => !imgMentionState.query || o.searchText.includes(imgMentionState.query.toLowerCase()))
: [];
const handleImagePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
const caret = e.target.selectionStart || 0;
updateImageNodePrompt(imageNode.id, value);
const beforeCaret = value.slice(0, caret);
const atIdx = beforeCaret.lastIndexOf("@");
if (atIdx >= 0) {
const query = beforeCaret.slice(atIdx + 1);
if (!MENTION_BOUNDARY_RE.test(query) && !query.includes(" ")) {
setTextNodeMentionStates((prev) => ({ ...prev, [imageNode.id]: { open: true, query, start: atIdx, caret, activeIndex: 0 } }));
return;
}
}
closeTextNodeMention(imageNode.id);
};
const handleImagePromptKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (!imgMentionState.open || imgFilteredMentions.length === 0) return;
if (e.key === "ArrowDown") { e.preventDefault(); setTextNodeMentionStates((prev) => ({ ...prev, [imageNode.id]: { ...imgMentionState, activeIndex: (imgMentionState.activeIndex + 1) % imgFilteredMentions.length } })); }
else if (e.key === "ArrowUp") { e.preventDefault(); setTextNodeMentionStates((prev) => ({ ...prev, [imageNode.id]: { ...imgMentionState, activeIndex: (imgMentionState.activeIndex - 1 + imgFilteredMentions.length) % imgFilteredMentions.length } })); }
else if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); const opt = imgFilteredMentions[imgMentionState.activeIndex]; if (opt) insertTextNodeMention(imageNode.id, opt, e.currentTarget, "image"); }
else if (e.key === "Escape") { e.preventDefault(); closeTextNodeMention(imageNode.id); }
};
return (
<div className="studio-canvas-image-composer"> <div className="studio-canvas-image-composer">
<div className="studio-canvas-image-composer__tools"> <div className="studio-canvas-image-composer__tools">
<button <button
@@ -4529,47 +4473,23 @@ function CanvasPage({
> >
<FileImageOutlined /><span></span> <FileImageOutlined /><span></span>
</button> </button>
{markingPopoverNodeId === imageNode.id && ( {markingPopoverNodeId === imageNode.id ? (
<div <CanvasMarkingPopover
className="studio-canvas-marking-popover" value={imageNode.marking}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
<textarea
className="studio-canvas-marking-input"
placeholder="描述标记内容,如:主角站在桥上,远处是城市天际线" placeholder="描述标记内容,如:主角站在桥上,远处是城市天际线"
value={imageNode.marking || ""} onChange={(value) => {
onChange={(e) => {
const val = e.target.value;
setImageNodes((nodes) => setImageNodes((nodes) =>
nodes.map((n) => (n.id === imageNode.id ? { ...n, marking: val } : n)), nodes.map((node) => (node.id === imageNode.id ? { ...node, marking: value } : node)),
); );
}} }}
onClear={() => {
setImageNodes((nodes) =>
nodes.map((node) => (node.id === imageNode.id ? { ...node, marking: "" } : node)),
);
}}
onDone={() => setMarkingPopoverNodeId(null)}
/> />
<div className="studio-canvas-marking-actions"> ) : null}
{imageNode.marking && (
<button
type="button"
className="studio-canvas-marking-clear"
onClick={() => {
setImageNodes((nodes) =>
nodes.map((n) => (n.id === imageNode.id ? { ...n, marking: "" } : n)),
);
}}
>
</button>
)}
<button
type="button"
className="studio-canvas-marking-done"
onClick={() => setMarkingPopoverNodeId(null)}
>
</button>
</div>
</div>
)}
<button <button
type="button" type="button"
title="多宫格生成" title="多宫格生成"
@@ -4611,28 +4531,18 @@ function CanvasPage({
</button> </button>
<button type="button" className="studio-canvas-image-composer__expand" aria-label="展开"></button> <button type="button" className="studio-canvas-image-composer__expand" aria-label="展开"></button>
</div> </div>
<div className="studio-canvas-text-composer__input-wrap"> <CanvasPromptMentionTextarea
<textarea nodeId={imageNode.id}
value={imageNode.prompt} value={imageNode.prompt}
onMouseDown={(event) => event.stopPropagation()}
onChange={handleImagePromptChange}
onKeyDown={handleImagePromptKeyDown}
placeholder="描述你想要生成的画面内容,按/呼出指令,@引用素材" placeholder="描述你想要生成的画面内容,按/呼出指令,@引用素材"
mentionOptions={buildNodeMentionOptions("image", imageNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks)}
mentionState={textNodeMentionStates[imageNode.id]}
mentionKind="image"
onPromptChange={updateImageNodePrompt}
onMentionStateChange={setTextNodeMentionStates}
onCloseMention={closeTextNodeMention}
onInsertMention={insertTextNodeMention}
/> />
{imgMentionState.open && (
<div className="studio-canvas-mention-panel">
{imgFilteredMentions.length > 0 ? imgFilteredMentions.map((opt, idx) => (
<button key={opt.token} type="button" className={`studio-canvas-mention-item${idx === imgMentionState.activeIndex ? " is-active" : ""}`} onMouseDown={(e) => { e.preventDefault(); insertTextNodeMention(imageNode.id, opt, e.currentTarget.closest(".studio-canvas-image-composer")?.querySelector("textarea") || null, "image"); }}>
<span className="studio-canvas-mention-thumb">{opt.kind === "image" && opt.previewUrl ? <img src={opt.previewUrl} alt="" /> : opt.kind === "image" ? "🖼" : opt.kind === "video" ? "🎬" : "📝"}</span>
<span className="studio-canvas-mention-label">{opt.nodeTitle}</span>
<span className="studio-canvas-mention-token">{opt.token}</span>
</button>
)) : (
<div className="studio-canvas-mention-item" style={{ opacity: 0.5, pointerEvents: "none" }}><span className="studio-canvas-mention-label"></span></div>
)}
</div>
)}
</div>
<div className="studio-canvas-image-composer__footer"> <div className="studio-canvas-image-composer__footer">
<CanvasSelectChip <CanvasSelectChip
ariaLabel="选择生图模型" ariaLabel="选择生图模型"
@@ -4700,12 +4610,12 @@ function CanvasPage({
</button> </button>
</div> </div>
</div> </div>
); })() : null} ) : null}
</div> </div>
</div> </div>
); );
})} })}
{videoNodes.filter((videoNode) => !isNodeCollapsedInPackage("video", videoNode.id)).map((videoNode) => { {visibleVideoNodes.map((videoNode) => {
const videoNodeSelected = isSelectedNode("video", videoNode.id); const videoNodeSelected = isSelectedNode("video", videoNode.id);
const videoNodeActive = isActiveSelectedNode("video", videoNode.id); const videoNodeActive = isActiveSelectedNode("video", videoNode.id);
const videoNodeResizing = nodeResizeDrag?.kind === "video" && nodeResizeDrag.nodeId === videoNode.id; const videoNodeResizing = nodeResizeDrag?.kind === "video" && nodeResizeDrag.nodeId === videoNode.id;
@@ -4855,38 +4765,7 @@ function CanvasPage({
onMouseDown={(event) => handleNodeResizeStart(event, "video", videoNode.id, videoNode.size)} onMouseDown={(event) => handleNodeResizeStart(event, "video", videoNode.id, videoNode.size)}
/> />
</div> </div>
{videoNodeActive && !isCanvasNodeMoving ? (() => { {videoNodeActive && !isCanvasNodeMoving ? (
const vidMentionOptions = buildNodeMentionOptions("video", videoNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks);
const vidMentionState = textNodeMentionStates[videoNode.id] || { open: false, query: "", start: 0, caret: 0, activeIndex: 0 };
const vidFilteredMentions = vidMentionState.open
? vidMentionOptions.filter((o) => !vidMentionState.query || o.searchText.includes(vidMentionState.query.toLowerCase()))
: [];
const handleVideoPromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
const caret = e.target.selectionStart || 0;
updateVideoNodePrompt(videoNode.id, value);
const beforeCaret = value.slice(0, caret);
const atIdx = beforeCaret.lastIndexOf("@");
if (atIdx >= 0) {
const query = beforeCaret.slice(atIdx + 1);
if (!MENTION_BOUNDARY_RE.test(query) && !query.includes(" ")) {
setTextNodeMentionStates((prev) => ({ ...prev, [videoNode.id]: { open: true, query, start: atIdx, caret, activeIndex: 0 } }));
return;
}
}
closeTextNodeMention(videoNode.id);
};
const handleVideoPromptKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (!vidMentionState.open || vidFilteredMentions.length === 0) return;
if (e.key === "ArrowDown") { e.preventDefault(); setTextNodeMentionStates((prev) => ({ ...prev, [videoNode.id]: { ...vidMentionState, activeIndex: (vidMentionState.activeIndex + 1) % vidFilteredMentions.length } })); }
else if (e.key === "ArrowUp") { e.preventDefault(); setTextNodeMentionStates((prev) => ({ ...prev, [videoNode.id]: { ...vidMentionState, activeIndex: (vidMentionState.activeIndex - 1 + vidFilteredMentions.length) % vidFilteredMentions.length } })); }
else if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); const opt = vidFilteredMentions[vidMentionState.activeIndex]; if (opt) insertTextNodeMention(videoNode.id, opt, e.currentTarget, "video"); }
else if (e.key === "Escape") { e.preventDefault(); closeTextNodeMention(videoNode.id); }
};
return (
<div className="studio-canvas-video-composer"> <div className="studio-canvas-video-composer">
<div className="studio-canvas-video-composer__tabs studio-canvas-video-composer__mode-tabs"> <div className="studio-canvas-video-composer__tabs studio-canvas-video-composer__mode-tabs">
<button <button
@@ -4941,47 +4820,23 @@ function CanvasPage({
> >
{videoNode.cameraMotion ? ` ${CAMERA_MOTION_PRESETS.find((p) => p.value === videoNode.cameraMotion)?.label || ""}` : ""} {videoNode.cameraMotion ? ` ${CAMERA_MOTION_PRESETS.find((p) => p.value === videoNode.cameraMotion)?.label || ""}` : ""}
</button> </button>
{markingPopoverNodeId === videoNode.id && ( {markingPopoverNodeId === videoNode.id ? (
<div <CanvasMarkingPopover
className="studio-canvas-marking-popover" value={videoNode.marking}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
<textarea
className="studio-canvas-marking-input"
placeholder="描述标记内容,如:主角在城市街头行走" placeholder="描述标记内容,如:主角在城市街头行走"
value={videoNode.marking || ""} onChange={(value) => {
onChange={(e) => {
const val = e.target.value;
setVideoNodes((nodes) => setVideoNodes((nodes) =>
nodes.map((n) => (n.id === videoNode.id ? { ...n, marking: val } : n)), nodes.map((node) => (node.id === videoNode.id ? { ...node, marking: value } : node)),
); );
}} }}
onClear={() => {
setVideoNodes((nodes) =>
nodes.map((node) => (node.id === videoNode.id ? { ...node, marking: "" } : node)),
);
}}
onDone={() => setMarkingPopoverNodeId(null)}
/> />
<div className="studio-canvas-marking-actions"> ) : null}
{videoNode.marking && (
<button
type="button"
className="studio-canvas-marking-clear"
onClick={() => {
setVideoNodes((nodes) =>
nodes.map((n) => (n.id === videoNode.id ? { ...n, marking: "" } : n)),
);
}}
>
</button>
)}
<button
type="button"
className="studio-canvas-marking-done"
onClick={() => setMarkingPopoverNodeId(null)}
>
</button>
</div>
</div>
)}
{cameraMotionDropdownNodeId === videoNode.id && ( {cameraMotionDropdownNodeId === videoNode.id && (
<div <div
className="studio-canvas-camera-dropdown" className="studio-canvas-camera-dropdown"
@@ -5008,43 +4863,24 @@ function CanvasPage({
<button type="button"></button> <button type="button"></button>
<button type="button" className="is-active"></button> <button type="button" className="is-active"></button>
</div> </div>
<div className="studio-canvas-text-composer__input-wrap"> <CanvasPromptMentionTextarea
<textarea nodeId={videoNode.id}
value={videoNode.prompt} value={videoNode.prompt}
onMouseDown={(event) => event.stopPropagation()}
onChange={handleVideoPromptChange}
onKeyDown={handleVideoPromptKeyDown}
placeholder="根据文字描述生成视频。" placeholder="根据文字描述生成视频。"
mentionOptions={buildNodeMentionOptions("video", videoNode.id, imageNodes, videoNodes, textNodes, getIncomingCanvasPorts, manualLinks)}
mentionState={textNodeMentionStates[videoNode.id]}
mentionKind="video"
onPromptChange={updateVideoNodePrompt}
onMentionStateChange={setTextNodeMentionStates}
onCloseMention={closeTextNodeMention}
onInsertMention={insertTextNodeMention}
/> />
{vidMentionState.open ? (
<div className="studio-canvas-mention-panel">
{vidFilteredMentions.length > 0 ? vidFilteredMentions.map((opt, idx) => (
<button
key={opt.token}
type="button"
className={`studio-canvas-mention-item${idx === vidMentionState.activeIndex ? " is-active" : ""}`}
onMouseDown={(ev) => { ev.preventDefault(); insertTextNodeMention(videoNode.id, opt, ev.currentTarget.closest(".studio-canvas-text-composer__input-wrap")?.querySelector("textarea")!, "video"); }}
>
<span className={`studio-canvas-mention-icon studio-canvas-mention-icon--${opt.kind}`}>
{opt.kind === "image" ? "🖼" : opt.kind === "video" ? "🎬" : "📝"}
</span>
<span className="studio-canvas-mention-label">{opt.nodeTitle}</span>
<span className="studio-canvas-mention-token">{opt.token}</span>
</button>
)) : (
<div className="studio-canvas-mention-item" style={{ opacity: 0.5, pointerEvents: "none" }}>
<span className="studio-canvas-mention-label"></span>
</div>
)}
</div>
) : null}
</div>
<div className="studio-canvas-video-composer__footer studio-canvas-video-composer__settings"> <div className="studio-canvas-video-composer__footer studio-canvas-video-composer__settings">
<CanvasSelectChip <CanvasSelectChip
ariaLabel="选择视频模型" ariaLabel="选择视频模型"
className="canvas-select-chip--model studio-canvas-composer-chip" className="canvas-select-chip--model studio-canvas-composer-chip"
value={toHappyHorseDisplayModel(videoNode.model || defaultVideoModel)} value={toHappyHorseDisplayModel(videoNode.model || defaultVideoModel)}
options={canvasEnterpriseVideoModelOptions} options={canvasVideoModelOptions}
open={canvasSelectMenu === `${videoNode.id}:video-model`} open={canvasSelectMenu === `${videoNode.id}:video-model`}
onToggle={() => onToggle={() =>
setCanvasSelectMenu((current) => setCanvasSelectMenu((current) =>
@@ -5122,7 +4958,7 @@ function CanvasPage({
</button> </button>
</div> </div>
</div> </div>
); })() : null} ) : null}
</div> </div>
</div> </div>
); );
@@ -5416,7 +5252,7 @@ function CanvasPage({
onClick={() => setSelectedExistingCategory(category.key)} onClick={() => setSelectedExistingCategory(category.key)}
> >
{category.label} {category.label}
<span>{serverAssets.filter((asset) => asset.type === category.key).length} </span> <span>{assetCountsByCategory.get(category.key) ?? 0} </span>
</button> </button>
))} ))}
</div> </div>
@@ -0,0 +1,219 @@
import { SendOutlined } from "@ant-design/icons";
import { useRef, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import type { CanvasNodeKind, CanvasPromptMentionOption, CanvasPromptMentionState } from "./canvasTypes";
const MENTION_BOUNDARY_RE = /\s|[,。、;:!??(){}[\]<>]/;
const EMPTY_MENTION_STYLE: CSSProperties = { opacity: 0.5, pointerEvents: "none" };
const DEFAULT_MENTION_STATE: CanvasPromptMentionState = {
open: false,
query: "",
start: 0,
caret: 0,
activeIndex: 0,
};
interface CanvasPromptMentionTextareaProps {
nodeId: string;
value: string;
placeholder: string;
mentionOptions: CanvasPromptMentionOption[];
mentionState?: CanvasPromptMentionState;
onPromptChange: (nodeId: string, prompt: string) => void;
onMentionStateChange: Dispatch<SetStateAction<Record<string, CanvasPromptMentionState>>>;
onCloseMention: (nodeId: string) => void;
onInsertMention: (
nodeId: string,
option: CanvasPromptMentionOption,
textarea: HTMLTextAreaElement | null,
kind?: CanvasNodeKind,
) => void;
mentionKind?: CanvasNodeKind;
}
export function CanvasPromptMentionTextarea({
nodeId,
value,
placeholder,
mentionOptions,
mentionState = DEFAULT_MENTION_STATE,
onPromptChange,
onMentionStateChange,
onCloseMention,
onInsertMention,
mentionKind,
}: CanvasPromptMentionTextareaProps) {
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const filteredMentions = mentionState.open
? mentionOptions.filter((option) => !mentionState.query || option.searchText.includes(mentionState.query.toLowerCase()))
: [];
const handlePromptChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = event.target.value;
const caret = event.target.selectionStart || 0;
onPromptChange(nodeId, value);
const beforeCaret = value.slice(0, caret);
const atIndex = beforeCaret.lastIndexOf("@");
if (atIndex >= 0) {
const query = beforeCaret.slice(atIndex + 1);
if (!MENTION_BOUNDARY_RE.test(query) && !query.includes(" ")) {
onMentionStateChange((prev) => ({
...prev,
[nodeId]: { open: true, query, start: atIndex, caret, activeIndex: 0 },
}));
return;
}
}
onCloseMention(nodeId);
};
const handlePromptKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (!mentionState.open || filteredMentions.length === 0) return;
if (event.key === "ArrowDown") {
event.preventDefault();
onMentionStateChange((prev) => ({
...prev,
[nodeId]: { ...mentionState, activeIndex: (mentionState.activeIndex + 1) % filteredMentions.length },
}));
} else if (event.key === "ArrowUp") {
event.preventDefault();
onMentionStateChange((prev) => ({
...prev,
[nodeId]: {
...mentionState,
activeIndex: (mentionState.activeIndex - 1 + filteredMentions.length) % filteredMentions.length,
},
}));
} else if (event.key === "Enter" || event.key === "Tab") {
event.preventDefault();
const option = filteredMentions[mentionState.activeIndex];
if (option) {
onInsertMention(nodeId, option, event.currentTarget, mentionKind);
}
} else if (event.key === "Escape") {
event.preventDefault();
onCloseMention(nodeId);
}
};
const handlePromptSelect = (event: React.SyntheticEvent<HTMLTextAreaElement>) => {
const caret = event.currentTarget.selectionStart || 0;
onMentionStateChange((prev) => {
const current = prev[nodeId];
if (!current?.open) return prev;
return { ...prev, [nodeId]: { ...current, caret } };
});
};
return (
<div className="studio-canvas-text-composer__input-wrap">
<textarea
ref={textareaRef}
value={value}
onMouseDown={(event) => event.stopPropagation()}
onChange={handlePromptChange}
onKeyDown={handlePromptKeyDown}
onSelect={handlePromptSelect}
placeholder={placeholder}
/>
{mentionState.open ? (
<div className="studio-canvas-mention-panel">
{filteredMentions.length > 0 ? filteredMentions.map((option, index) => (
<button
key={option.token}
type="button"
className={`studio-canvas-mention-item${index === mentionState.activeIndex ? " is-active" : ""}`}
onMouseDown={(event) => {
event.preventDefault();
onInsertMention(nodeId, option, textareaRef.current, mentionKind);
}}
>
<span className="studio-canvas-mention-thumb">
{option.kind === "image" && option.previewUrl ? (
<img src={option.previewUrl} alt="" />
) : option.kind === "image" ? "🖼" : option.kind === "video" ? "🎬" : "📝"}
</span>
<span className="studio-canvas-mention-label">{option.nodeTitle}</span>
<span className="studio-canvas-mention-token">{option.token}</span>
</button>
)) : (
<div className="studio-canvas-mention-item" style={EMPTY_MENTION_STYLE}>
<span className="studio-canvas-mention-label"></span>
</div>
)}
</div>
) : null}
</div>
);
}
interface CanvasTextPromptComposerProps {
nodeId: string;
prompt: string;
canGenerate: boolean;
isGenerating: boolean;
mentionOptions: CanvasPromptMentionOption[];
mentionState?: CanvasPromptMentionState;
onPromptChange: (nodeId: string, prompt: string) => void;
onMentionStateChange: Dispatch<SetStateAction<Record<string, CanvasPromptMentionState>>>;
onCloseMention: (nodeId: string) => void;
onInsertMention: (
nodeId: string,
option: CanvasPromptMentionOption,
textarea: HTMLTextAreaElement | null,
kind?: CanvasNodeKind,
) => void;
onGenerate: (nodeId: string) => void | Promise<void>;
}
export function CanvasTextPromptComposer({
nodeId,
prompt,
canGenerate,
isGenerating,
mentionOptions,
mentionState,
onPromptChange,
onMentionStateChange,
onCloseMention,
onInsertMention,
onGenerate,
}: CanvasTextPromptComposerProps) {
return (
<div className="studio-canvas-text-composer">
<CanvasPromptMentionTextarea
nodeId={nodeId}
value={prompt}
placeholder="写下你想讲的故事、场景或角色设定。@引用连接的节点"
mentionOptions={mentionOptions}
mentionState={mentionState}
onPromptChange={onPromptChange}
onMentionStateChange={onMentionStateChange}
onCloseMention={onCloseMention}
onInsertMention={onInsertMention}
/>
<div className="studio-canvas-text-composer__footer">
<button
type="button"
className={`studio-canvas-text-composer__send studio-canvas-generate-button${canGenerate && !isGenerating ? " is-ready" : ""}`}
title={isGenerating ? "生成中" : "生成"}
disabled={isGenerating || !canGenerate}
aria-busy={isGenerating}
onMouseDown={(event) => {
event.preventDefault();
event.stopPropagation();
if (!isGenerating && canGenerate) {
void onGenerate(nodeId);
}
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
<SendOutlined />
</button>
</div>
</div>
);
}
@@ -0,0 +1,74 @@
import { useCallback, useMemo } from "react";
import type { ServerAssetItem } from "../../api/assetClient";
import type {
CanvasImageNode,
CanvasNodeKind,
CanvasNodePackage,
CanvasTextNode,
CanvasVideoNode,
} from "./canvasTypes";
import { getCanvasSelectionKey } from "./canvasUtils";
export function useCanvasAssetSummary(serverAssets: ServerAssetItem[]) {
return useMemo(() => {
const canvasAssets: ServerAssetItem[] = [];
const assetCountsByCategory = new Map<string, number>();
for (const asset of serverAssets) {
if (asset.imageUrl) {
canvasAssets.push(asset);
}
assetCountsByCategory.set(asset.type, (assetCountsByCategory.get(asset.type) ?? 0) + 1);
}
return { canvasAssets, assetCountsByCategory };
}, [serverAssets]);
}
export function useCanvasVisibleNodes({
textNodes,
imageNodes,
videoNodes,
nodePackages,
}: {
textNodes: CanvasTextNode[];
imageNodes: CanvasImageNode[];
videoNodes: CanvasVideoNode[];
nodePackages: CanvasNodePackage[];
}) {
const collapsedPackageNodeKeys = useMemo(
() => new Set(
nodePackages.flatMap((nodePackage) =>
nodePackage.collapsed ? nodePackage.nodeIds.map((node) => getCanvasSelectionKey(node)) : []
)
),
[nodePackages],
);
const isNodeCollapsedInPackage = useCallback(
(kind: CanvasNodeKind, id: string) =>
collapsedPackageNodeKeys.has(getCanvasSelectionKey({ kind, id })),
[collapsedPackageNodeKeys],
);
const visibleTextNodes = useMemo(
() => textNodes.filter((textNode) => !collapsedPackageNodeKeys.has(getCanvasSelectionKey({ kind: "text", id: textNode.id }))),
[collapsedPackageNodeKeys, textNodes],
);
const visibleImageNodes = useMemo(
() => imageNodes.filter((imageNode) => !collapsedPackageNodeKeys.has(getCanvasSelectionKey({ kind: "image", id: imageNode.id }))),
[collapsedPackageNodeKeys, imageNodes],
);
const visibleVideoNodes = useMemo(
() => videoNodes.filter((videoNode) => !collapsedPackageNodeKeys.has(getCanvasSelectionKey({ kind: "video", id: videoNode.id }))),
[collapsedPackageNodeKeys, videoNodes],
);
return {
collapsedPackageNodeKeys,
isNodeCollapsedInPackage,
visibleTextNodes,
visibleImageNodes,
visibleVideoNodes,
};
}
+10 -5
View File
@@ -82,11 +82,16 @@ export function useCanvasNodeDrag(params: UseCanvasNodeDragParams) {
const cy = pos.y + size.height / 2; const cy = pos.y + size.height / 2;
const right = pos.x + size.width; const right = pos.x + size.width;
const bottom = pos.y + size.height; const bottom = pos.y + size.height;
const others = [ const others: Array<{ pos: CanvasPoint; size: CanvasNodeSize }> = [];
...textNodesRef.current.filter((n) => n.id !== draggedId).map((n) => ({ pos: n.position, size: n.size })), for (const node of textNodesRef.current) {
...imageNodesRef.current.filter((n) => n.id !== draggedId).map((n) => ({ pos: n.position, size: n.size })), if (node.id !== draggedId) others.push({ pos: node.position, size: node.size });
...videoNodesRef.current.filter((n) => n.id !== draggedId).map((n) => ({ pos: n.position, size: n.size })), }
]; for (const node of imageNodesRef.current) {
if (node.id !== draggedId) others.push({ pos: node.position, size: node.size });
}
for (const node of videoNodesRef.current) {
if (node.id !== draggedId) others.push({ pos: node.position, size: node.size });
}
for (const other of others) { for (const other of others) {
const ocx = other.pos.x + other.size.width / 2; const ocx = other.pos.x + other.size.width / 2;
const ocy = other.pos.y + other.size.height / 2; const ocy = other.pos.y + other.size.height / 2;
@@ -17,6 +17,7 @@ import {
VideoCameraOutlined, VideoCameraOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import "../../styles/pages/image-workbench.css";
import StudioToolLayout from "../../components/StudioToolLayout"; import StudioToolLayout from "../../components/StudioToolLayout";
import type { WebImageWorkbenchTool, WebViewKey } from "../../types"; import type { WebImageWorkbenchTool, WebViewKey } from "../../types";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
+1
View File
@@ -10,6 +10,7 @@ import {
SearchOutlined, SearchOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import "../../styles/pages/community.css";
import { useDebounce } from "../../hooks/useDebounce"; import { useDebounce } from "../../hooks/useDebounce";
import { communityClient, type ServerCommunityCase } from "../../api/communityClient"; import { communityClient, type ServerCommunityCase } from "../../api/communityClient";
import WorkspacePageShell from "../../components/WorkspacePageShell"; import WorkspacePageShell from "../../components/WorkspacePageShell";
@@ -1,4 +1,5 @@
import { FileTextOutlined, SafetyOutlined } from "@ant-design/icons"; import { FileTextOutlined, SafetyOutlined } from "@ant-design/icons";
import "../../styles/pages/compliance.css";
type ComplianceKind = "agreement" | "privacy"; type ComplianceKind = "agreement" | "privacy";
@@ -1,4 +1,5 @@
import { useCallback, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type TouchEvent as ReactTouchEvent } from "react"; import { useCallback, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type TouchEvent as ReactTouchEvent } from "react";
import "../../styles/pages/dialog-generator.css";
type DialogStyle = "style1" | "style2" | "style3" | "style4"; type DialogStyle = "style1" | "style2" | "style3" | "style4";
@@ -24,6 +24,7 @@ import {
VideoCameraOutlined, VideoCameraOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react"; import { useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import "../../styles/pages/avatar-console.css";
import type { WebViewKey } from "../../types"; import type { WebViewKey } from "../../types";
import { import {
bringAvatarEditorLayerForward, bringAvatarEditorLayerForward,
@@ -18,6 +18,7 @@ import {
UserOutlined, UserOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import "../../styles/pages/image-workbench.css";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { uploadAssetWithProgress } from "../../api/uploadWithProgress"; import { uploadAssetWithProgress } from "../../api/uploadWithProgress";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
+83 -16
View File
@@ -12,7 +12,8 @@ import {
SettingOutlined, SettingOutlined,
SkinOutlined, SkinOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useEffect, useRef, useState, type CSSProperties, type ChangeEvent, type DragEvent, type ReactNode } from "react"; import { useEffect, useMemo, useRef, useState, type CSSProperties, type ChangeEvent, type DragEvent, type ReactNode } from "react";
import "../../styles/pages/ecommerce.css";
import { ossAssets } from "../../data/ossAssets"; import { ossAssets } from "../../data/ossAssets";
import { EcommerceProgressBar } from "./EcommerceProgressBar"; import { EcommerceProgressBar } from "./EcommerceProgressBar";
import ImageMentionMenu, { getImageMentionQuery, insertImageMentionValue, type MentionImageOption } from "./ImageMentionMenu"; import ImageMentionMenu, { getImageMentionQuery, insertImageMentionValue, type MentionImageOption } from "./ImageMentionMenu";
@@ -900,25 +901,58 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
const [selectedDetailModules, setSelectedDetailModules] = useState<string[]>(defaultDetailModuleIds); const [selectedDetailModules, setSelectedDetailModules] = useState<string[]>(defaultDetailModuleIds);
const [detailStatus, setDetailStatus] = useState<DetailStatus>("idle"); const [detailStatus, setDetailStatus] = useState<DetailStatus>("idle");
const [detailResultUrl, setDetailResultUrl] = useState<string | null>(null); const [detailResultUrl, setDetailResultUrl] = useState<string | null>(null);
const productSetRatioOptions = getPlatformRatioOptions(productSetPlatform, productSetOutput); const productSetRatioOptions = useMemo(
const hotUploadedRatioOption = cloneOutput === "hot" ? formatUploadedImageRatio(cloneReferenceImages[0]) : null; () => getPlatformRatioOptions(productSetPlatform, productSetOutput),
const baseCloneRatioOptions = getPlatformRatioOptions(platform, cloneOutput); [productSetOutput, productSetPlatform],
const cloneRatioOptions = hotUploadedRatioOption );
const hotUploadedRatioOption = useMemo(
() => cloneOutput === "hot" ? formatUploadedImageRatio(cloneReferenceImages[0]) : null,
[cloneOutput, cloneReferenceImages],
);
const baseCloneRatioOptions = useMemo(
() => getPlatformRatioOptions(platform, cloneOutput),
[cloneOutput, platform],
);
const cloneRatioOptions = useMemo(
() => hotUploadedRatioOption
? getUniqueRatioOptions([...baseCloneRatioOptions, hotUploadedRatioOption]) ? getUniqueRatioOptions([...baseCloneRatioOptions, hotUploadedRatioOption])
: baseCloneRatioOptions; : baseCloneRatioOptions,
const productSetLanguageOptions = getPlatformLanguageOptions(productSetPlatform, productSetMarket); [baseCloneRatioOptions, hotUploadedRatioOption],
const cloneLanguageOptions = getPlatformLanguageOptions(platform, market); );
const detailLanguageOptions = getPlatformLanguageOptions(detailPlatform, detailMarket); const productSetLanguageOptions = useMemo(
() => getPlatformLanguageOptions(productSetPlatform, productSetMarket),
[productSetMarket, productSetPlatform],
);
const cloneLanguageOptions = useMemo(
() => getPlatformLanguageOptions(platform, market),
[market, platform],
);
const detailLanguageOptions = useMemo(
() => getPlatformLanguageOptions(detailPlatform, detailMarket),
[detailMarket, detailPlatform],
);
const ecommerceMentionImages: MentionImageOption[] = [ const ecommerceMentionImages: MentionImageOption[] = [
...productImages.map((image, index) => ({ ...image, label: `商品图 ${index + 1}` })), ...productImages.map((image, index) => ({ ...image, label: `商品图 ${index + 1}` })),
...cloneReferenceImages.map((image, index) => ({ ...image, label: `参考图 ${index + 1}` })), ...cloneReferenceImages.map((image, index) => ({ ...image, label: `参考图 ${index + 1}` })),
]; ];
const ecommerceVideoImageDataUrls = useMemo(
() => productImages.map((img) => img.src),
[productImages],
);
const ecommerceVideoImageFiles = useMemo(
() => productImages.map((img) => img.file),
[productImages],
);
const selectedProductSetOutput = const selectedProductSetOutput =
productSetOutputOptions.find((option) => option.key === productSetOutput) ?? productSetOutputOptions[0]!; productSetOutputOptions.find((option) => option.key === productSetOutput) ?? productSetOutputOptions[0]!;
const selectedCloneOutput = cloneOutputOptions.find((option) => option.key === cloneOutput) ?? cloneOutputOptions[1]!; const selectedCloneOutput = cloneOutputOptions.find((option) => option.key === cloneOutput) ?? cloneOutputOptions[1]!;
const productSetPreviewReady = productSetStatus === "done"; const productSetPreviewReady = productSetStatus === "done";
const cloneSetTotal = Object.values(cloneSetCounts).reduce((sum, value) => sum + value, 0); const cloneSetTotal = useMemo(
() => Object.values(cloneSetCounts).reduce((sum, value) => sum + value, 0),
[cloneSetCounts],
);
const canGenerateSet = setImages.length > 0 && productSetStatus !== "generating"; const canGenerateSet = setImages.length > 0 && productSetStatus !== "generating";
const canGenerate = (cloneOutput === "video-outfit" const canGenerate = (cloneOutput === "video-outfit"
? Boolean(videoOutfitVideoFile && videoOutfitRefFile) ? Boolean(videoOutfitVideoFile && videoOutfitRefFile)
@@ -927,9 +961,12 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
const canGenerateDetail = detailProductImages.length > 0 && detailStatus !== "generating"; const canGenerateDetail = detailProductImages.length > 0 && detailStatus !== "generating";
const cloneVideoDurationProgress = const cloneVideoDurationProgress =
((cloneVideoDuration - cloneVideoDurationMin) / (cloneVideoDurationMax - cloneVideoDurationMin)) * 100; ((cloneVideoDuration - cloneVideoDurationMin) / (cloneVideoDurationMax - cloneVideoDurationMin)) * 100;
const cloneVideoDurationStyle: CSSProperties = { const cloneVideoDurationStyle: CSSProperties = useMemo(
() => ({
"--clone-video-duration-progress": `${cloneVideoDurationProgress}%`, "--clone-video-duration-progress": `${cloneVideoDurationProgress}%`,
} as CSSProperties; }) as CSSProperties,
[cloneVideoDurationProgress],
);
const trackEcommerceTask = (taskId: string) => { const trackEcommerceTask = (taskId: string) => {
activeEcommerceTaskIdsRef.current.add(taskId); activeEcommerceTaskIdsRef.current.add(taskId);
@@ -1098,6 +1135,8 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
}; };
const clearCloneSetCountHold = () => { const clearCloneSetCountHold = () => {
window.removeEventListener("pointerup", clearCloneSetCountHold);
window.removeEventListener("pointercancel", clearCloneSetCountHold);
if (countHoldTimeoutRef.current !== null) { if (countHoldTimeoutRef.current !== null) {
window.clearTimeout(countHoldTimeoutRef.current); window.clearTimeout(countHoldTimeoutRef.current);
countHoldTimeoutRef.current = null; countHoldTimeoutRef.current = null;
@@ -1212,6 +1251,34 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
requirement, requirement,
}); });
const latestCloneSettingSnapshot = useMemo(
() => createCloneSettingSnapshot(cloneSettingName, "clone-setting-latest"),
[
cloneOutput,
platform,
market,
language,
ratio,
cloneSetCounts,
selectedCloneDetailModules,
cloneModelPanelTab,
selectedCloneModelScenes,
cloneModelCustomScene,
cloneModelGender,
cloneModelAge,
cloneModelEthnicity,
cloneModelBody,
cloneModelAppearance,
cloneVideoQuality,
cloneVideoDuration,
cloneVideoSmart,
cloneReferenceMode,
cloneReplicateLevel,
requirement,
cloneSettingName,
],
);
const persistLatestCloneSetting = () => { const persistLatestCloneSetting = () => {
const snapshot = createCloneSettingSnapshot(cloneSettingName, "clone-setting-latest"); const snapshot = createCloneSettingSnapshot(cloneSettingName, "clone-setting-latest");
latestCloneSettingRef.current = snapshot; latestCloneSettingRef.current = snapshot;
@@ -1259,8 +1326,8 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
}; };
useEffect(() => { useEffect(() => {
latestCloneSettingRef.current = createCloneSettingSnapshot(cloneSettingName, "clone-setting-latest"); latestCloneSettingRef.current = latestCloneSettingSnapshot;
}); }, [latestCloneSettingSnapshot]);
useEffect(() => { useEffect(() => {
const latestSetting = readCloneLatestSetting(); const latestSetting = readCloneLatestSetting();
@@ -2616,8 +2683,8 @@ function ProductClonePage(_props: ProductClonePageProps = {}) {
<main className="product-clone-preview product-clone-preview--video" style={{ padding: 0, overflow: "hidden" }}> <main className="product-clone-preview product-clone-preview--video" style={{ padding: 0, overflow: "hidden" }}>
<EcommerceVideoWorkspace <EcommerceVideoWorkspace
isAuthenticated={Boolean((_props as Record<string, unknown>).isAuthenticated)} isAuthenticated={Boolean((_props as Record<string, unknown>).isAuthenticated)}
productImageDataUrls={productImages.map((img) => img.src)} productImageDataUrls={ecommerceVideoImageDataUrls}
productImageFiles={productImages.map((img) => img.file)} productImageFiles={ecommerceVideoImageFiles}
requirement={requirement} requirement={requirement}
platform={platform} platform={platform}
aspectRatio={ratio.includes("916") || ratio.includes("9:16") ? "9:16" : ratio.includes("169") || ratio.includes("16:9") ? "16:9" : ratio.includes("34") || ratio.includes("3:4") ? "3:4" : "9:16"} aspectRatio={ratio.includes("916") || ratio.includes("9:16") ? "9:16" : ratio.includes("169") || ratio.includes("16:9") ? "16:9" : ratio.includes("34") || ratio.includes("3:4") ? "3:4" : "9:16"}
@@ -8,6 +8,8 @@ import {
TagsOutlined, TagsOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react"; import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import "../../styles/pages/image-workbench.css";
import "../../styles/pages/ecommerce.css";
import type { WebProjectSummary } from "../../types"; import type { WebProjectSummary } from "../../types";
import { useDebounce } from "../../hooks/useDebounce"; import { useDebounce } from "../../hooks/useDebounce";
import { templateCarouselCases, templateCases, templateCategories, type TemplateCase } from "./ecommerceTemplates"; import { templateCarouselCases, templateCases, templateCategories, type TemplateCase } from "./ecommerceTemplates";
@@ -1,4 +1,5 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import "../../styles/pages/ecommerce-video.css";
import { import {
CloseOutlined, CloseOutlined,
CopyOutlined, CopyOutlined,
@@ -121,6 +122,7 @@ export default function EcommerceVideoWorkspace({
const [previewMedia, setPreviewMedia] = useState<{ url: string; type: "image" | "video" } | null>(null); const [previewMedia, setPreviewMedia] = useState<{ url: string; type: "image" | "video" } | null>(null);
const abortControllerRef = useRef<AbortController | null>(null); const abortControllerRef = useRef<AbortController | null>(null);
const renderAbortRef = useRef({ current: false }); const renderAbortRef = useRef({ current: false });
const actionNoticeTimerRef = useRef<number | null>(null);
const setView = useAppStore((s) => s.setView); const setView = useAppStore((s) => s.setView);
const keepaliveRestoredFingerprintRef = useRef<string | null>(null); const keepaliveRestoredFingerprintRef = useRef<string | null>(null);
const keepalivePollingStartedRef = useRef(false); const keepalivePollingStartedRef = useRef(false);
@@ -276,9 +278,23 @@ export default function EcommerceVideoWorkspace({
// Note: keep-alive is NOT cleared on completion — results persist across page switches. // Note: keep-alive is NOT cleared on completion — results persist across page switches.
// Only cleared when user explicitly starts a new plan via handlePlan. // Only cleared when user explicitly starts a new plan via handlePlan.
useEffect(() => {
return () => {
if (actionNoticeTimerRef.current !== null) {
window.clearTimeout(actionNoticeTimerRef.current);
}
};
}, []);
const showNotice = (msg: string) => { const showNotice = (msg: string) => {
setActionNotice(msg); setActionNotice(msg);
setTimeout(() => setActionNotice(null), 3000); if (actionNoticeTimerRef.current !== null) {
window.clearTimeout(actionNoticeTimerRef.current);
}
actionNoticeTimerRef.current = window.setTimeout(() => {
actionNoticeTimerRef.current = null;
setActionNotice(null);
}, 3000);
}; };
const handleDownload = async (url: string) => { const handleDownload = async (url: string) => {
+12 -23
View File
@@ -9,6 +9,7 @@ import {
type AdVideoUserConfig, type AdVideoUserConfig,
} from "../../api/adVideoPlanClient"; } from "../../api/adVideoPlanClient";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { serverRequest } from "../../api/serverConnection";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
import { resolveVideoRequestModel } from "../../utils/resolveVideoModel"; import { resolveVideoRequestModel } from "../../utils/resolveVideoModel";
import { normalizeEcommerceImageMime } from "./ecommerceImageValidation"; import { normalizeEcommerceImageMime } from "./ecommerceImageValidation";
@@ -430,15 +431,6 @@ export interface VideoHistoryListResponse {
offset: number; offset: number;
} }
import { getStoredToken } from "../../api/serverConnection";
const API_BASE = "/api/ai/ecommerce/video-history";
function getAuthHeaders(): Record<string, string> {
const token = getStoredToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
export async function buildDurableVideoHistoryPayload(payload: SaveVideoHistoryPayload): Promise<SaveVideoHistoryPayload> { export async function buildDurableVideoHistoryPayload(payload: SaveVideoHistoryPayload): Promise<SaveVideoHistoryPayload> {
const uploadAssetByUrl = payload.uploadAssetByUrl; const uploadAssetByUrl = payload.uploadAssetByUrl;
const scenes = await Promise.all( const scenes = await Promise.all(
@@ -486,13 +478,12 @@ export async function buildDurableVideoHistoryPayload(payload: SaveVideoHistoryP
export async function saveVideoHistory(payload: SaveVideoHistoryPayload): Promise<{ id: number; createdAt: string }> { export async function saveVideoHistory(payload: SaveVideoHistoryPayload): Promise<{ id: number; createdAt: string }> {
const { uploadAssetByUrl: _uploadAssetByUrl, ...historyPayload } = await buildDurableVideoHistoryPayload(payload); const { uploadAssetByUrl: _uploadAssetByUrl, ...historyPayload } = await buildDurableVideoHistoryPayload(payload);
const res = await fetch(API_BASE, { return serverRequest<{ id: number; createdAt: string }>("ai/ecommerce/video-history", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", ...getAuthHeaders() }, body: historyPayload,
body: JSON.stringify(historyPayload), maxRetries: 0,
fallbackMessage: "Failed to save video history",
}); });
if (!res.ok) throw new Error("Failed to save video history");
return res.json();
} }
function removeTemporaryHistoryUrls(item: VideoHistoryItem): VideoHistoryItem { function removeTemporaryHistoryUrls(item: VideoHistoryItem): VideoHistoryItem {
@@ -511,12 +502,10 @@ export async function fetchVideoHistory(
limit = 20, limit = 20,
offset = 0, offset = 0,
): Promise<VideoHistoryListResponse> { ): Promise<VideoHistoryListResponse> {
const res = await fetch( const search = new URLSearchParams({ limit: String(limit), offset: String(offset) });
`${API_BASE}?limit=${limit}&offset=${offset}`, const history = await serverRequest<VideoHistoryListResponse>(`ai/ecommerce/video-history?${search}`, {
{ headers: getAuthHeaders() }, fallbackMessage: "Failed to fetch video history",
); });
if (!res.ok) throw new Error("Failed to fetch video history");
const history = (await res.json()) as VideoHistoryListResponse;
return { return {
...history, ...history,
items: history.items.map(removeTemporaryHistoryUrls), items: history.items.map(removeTemporaryHistoryUrls),
@@ -524,9 +513,9 @@ export async function fetchVideoHistory(
} }
export async function deleteVideoHistory(id: number): Promise<void> { export async function deleteVideoHistory(id: number): Promise<void> {
const res = await fetch(`${API_BASE}/${id}`, { await serverRequest<void>(`ai/ecommerce/video-history/${id}`, {
method: "DELETE", method: "DELETE",
headers: getAuthHeaders(), maxRetries: 0,
fallbackMessage: "Failed to delete video history",
}); });
if (!res.ok) throw new Error("Failed to delete video history");
} }
+15 -4
View File
@@ -50,6 +50,12 @@ function ScriptReviewShowcase() {
const scoreRef = useRef<HTMLSpanElement>(null); const scoreRef = useRef<HTMLSpanElement>(null);
const barRefs = useRef<(HTMLDivElement | null)[]>([]); const barRefs = useRef<(HTMLDivElement | null)[]>([]);
const scoreValRefs = useRef<(HTMLSpanElement | null)[]>([]); const scoreValRefs = useRef<(HTMLSpanElement | null)[]>([]);
const animationTimersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
const clearAnimationTimers = () => {
animationTimersRef.current.forEach((timer) => clearTimeout(timer));
animationTimersRef.current = [];
};
useEffect(() => { useEffect(() => {
const el = document.getElementById("script-review-showcase"); const el = document.getElementById("script-review-showcase");
@@ -69,18 +75,23 @@ function ScriptReviewShowcase() {
useEffect(() => { useEffect(() => {
if (!animated) return; if (!animated) return;
const timer = setTimeout(() => { clearAnimationTimers();
const scheduleAnimation = (callback: () => void, delay: number) => {
const timer = setTimeout(callback, delay);
animationTimersRef.current.push(timer);
};
scheduleAnimation(() => {
animateNumber(scoreRef.current, 77, 1400); animateNumber(scoreRef.current, 77, 1400);
barRefs.current.forEach((bar, i) => { barRefs.current.forEach((bar, i) => {
if (!bar) return; if (!bar) return;
const pct = parseFloat(bar.dataset.pct ?? "0"); const pct = parseFloat(bar.dataset.pct ?? "0");
setTimeout(() => { bar.style.height = `${pct}%`; }, i * 100 + 400); scheduleAnimation(() => { bar.style.height = `${pct}%`; }, i * 100 + 400);
}); });
scoreValRefs.current.forEach((el, i) => { scoreValRefs.current.forEach((el, i) => {
setTimeout(() => animateNumber(el, parseInt(el?.dataset.target ?? "0"), 800), i * 100 + 400); scheduleAnimation(() => animateNumber(el, parseInt(el?.dataset.target ?? "0"), 800), i * 100 + 400);
}); });
}, 500); }, 500);
return () => clearTimeout(timer); return clearAnimationTimers;
}, [animated]); }, [animated]);
return ( return (
@@ -24,6 +24,7 @@ import {
ThunderboltOutlined, ThunderboltOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import "../../styles/pages/image-workbench.css";
import type { WebImageWorkbenchTool, WebViewKey } from "../../types"; import type { WebImageWorkbenchTool, WebViewKey } from "../../types";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
@@ -80,6 +81,20 @@ const CAMERA_EFFECT_PRESETS = [
{ key: "hdr", label: "HDR", prompt: "HDR高动态范围,明暗细节丰富,色彩饱和" }, { key: "hdr", label: "HDR", prompt: "HDR高动态范围,明暗细节丰富,色彩饱和" },
] as const; ] as const;
const CAMERA_EFFECT_PROMPT_BY_KEY = new Map<string, string>(
CAMERA_EFFECT_PRESETS.map((effect) => [effect.key, effect.prompt]),
);
function getCameraEffectsPrompt(effectKeys: Set<string>): string {
if (effectKeys.size === 0) return "";
const prompts: string[] = [];
for (const key of effectKeys) {
const prompt = CAMERA_EFFECT_PROMPT_BY_KEY.get(key);
if (prompt) prompts.push(prompt);
}
return prompts.join("");
}
function shotScaleToZoom(shotScale: number): number { function shotScaleToZoom(shotScale: number): number {
const map: Record<number, number> = { 1: 24, 2: 28, 3: 32, 4: 35, 5: 40, 6: 50, 7: 60, 8: 75, 9: 85, 10: 100 }; const map: Record<number, number> = { 1: 24, 2: 28, 3: 32, 4: 35, 5: 40, 6: 50, 7: 60, 8: 75, 9: 85, 10: 100 };
return map[Math.round(Math.max(1, Math.min(10, shotScale)))] || 40; return map[Math.round(Math.max(1, Math.min(10, shotScale)))] || 40;
@@ -152,6 +167,7 @@ function ImageWorkbenchPage({ initialTool = "workbench", onOpenMore, onSelectVie
abortRef.current = false; abortRef.current = false;
taskIdRef.current = saved.taskId; taskIdRef.current = saved.taskId;
void waitForTask(saved.taskId, { void waitForTask(saved.taskId, {
kind: "image",
onProgress: (e) => { onProgress: (e) => {
setStatus(`${e.status} / ${e.progress}%`); setStatus(`${e.status} / ${e.progress}%`);
if (e.status === "completed" && e.resultUrl) { if (e.status === "completed" && e.resultUrl) {
@@ -398,9 +414,7 @@ function ImageWorkbenchPage({ initialTool = "workbench", onOpenMore, onSelectVie
const refUrls = await uploadReferenceImages([cameraImage]); const refUrls = await uploadReferenceImages([cameraImage]);
const model = "wan2.7-image-pro"; const model = "wan2.7-image-pro";
const cameraDesc = `镜头预设: ${cameraPreset}, 方向: ${cameraDirection}, 水平: ${cameraHorizontal}°, 垂直: ${cameraVertical}°, 倾斜: ${cameraRoll}°, 焦距: ${cameraZoom}mm`; const cameraDesc = `镜头预设: ${cameraPreset}, 方向: ${cameraDirection}, 水平: ${cameraHorizontal}°, 垂直: ${cameraVertical}°, 倾斜: ${cameraRoll}°, 焦距: ${cameraZoom}mm`;
const effectsDesc = cameraEffects.size > 0 const effectsDesc = getCameraEffectsPrompt(cameraEffects);
? Array.from(cameraEffects).map((key) => CAMERA_EFFECT_PRESETS.find((e) => e.key === key)?.prompt).filter(Boolean).join("")
: "";
const fullPrompt = cameraPromptEnabled && cameraPrompt.trim() const fullPrompt = cameraPromptEnabled && cameraPrompt.trim()
? `${cameraDesc}${effectsDesc ? `。视觉效果: ${effectsDesc}` : ""}${cameraPrompt}` ? `${cameraDesc}${effectsDesc ? `。视觉效果: ${effectsDesc}` : ""}${cameraPrompt}`
: `${cameraDesc}${effectsDesc ? `。视觉效果: ${effectsDesc}` : ""}。保持人物和场景一致,按照镜头参数重新构图。`; : `${cameraDesc}${effectsDesc ? `。视觉效果: ${effectsDesc}` : ""}。保持人物和场景一致,按照镜头参数重新构图。`;
@@ -446,6 +460,7 @@ function ImageWorkbenchPage({ initialTool = "workbench", onOpenMore, onSelectVie
const pollTaskUntilDone = useCallback(async (taskId: string): Promise<string | null> => { const pollTaskUntilDone = useCallback(async (taskId: string): Promise<string | null> => {
return waitForTask(taskId, { return waitForTask(taskId, {
kind: "image",
abortRef, abortRef,
onProgress: (e) => setGenerationProgress(e.progress || 0), onProgress: (e) => setGenerationProgress(e.progress || 0),
}); });
+1
View File
@@ -14,6 +14,7 @@ import {
} from "@ant-design/icons"; } from "@ant-design/icons";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import "../../styles/pages/more.css";
import type { WebImageWorkbenchTool, WebViewKey } from "../../types"; import type { WebImageWorkbenchTool, WebViewKey } from "../../types";
interface MorePageProps { interface MorePageProps {
+44 -17
View File
@@ -18,6 +18,7 @@ import {
UserOutlined, UserOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from "react"; import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from "react";
import "../../styles/pages/profile.css";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { assetClient } from "../../api/assetClient"; import { assetClient } from "../../api/assetClient";
import { communityClient, type ServerCommunityCase } from "../../api/communityClient"; import { communityClient, type ServerCommunityCase } from "../../api/communityClient";
@@ -260,6 +261,30 @@ function ProfilePage({
const packageLabel = session?.user.activePackages?.[0]?.name || "按量积分"; const packageLabel = session?.user.activePackages?.[0]?.name || "按量积分";
const avatarUrl = session?.user.avatarUrl || localAvatarUrl || null; const avatarUrl = session?.user.avatarUrl || localAvatarUrl || null;
const displayedBio = profileBio.trim() || "这个人还没有填写个性签名"; const displayedBio = profileBio.trim() || "这个人还没有填写个性签名";
const activePanelTitle =
activePanel === "works"
? "代表作"
: activePanel === "projects"
? "服务器项目"
: activePanel === "assets"
? "我的资产"
: "社区审核";
const activePanelDescription =
activePanel === "works"
? "最近完成的高质量生成内容"
: activePanel === "projects"
? "云端同步的创作项目"
: activePanel === "assets"
? "可复用的图片、视频与素材"
: "已提交社区的案例状态";
const activePanelCount =
activePanel === "works"
? visibleWorks.length
: activePanel === "projects"
? projects.length
: activePanel === "assets"
? savedAssets.length
: communityCases.length;
const emailLooksValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()); const emailLooksValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
const phoneLooksValid = /^1[3-9]\d{9}$/.test(phone.trim()); const phoneLooksValid = /^1[3-9]\d{9}$/.test(phone.trim());
const passwordLooksReady = password.length >= (mode === "register" ? 6 : 1); const passwordLooksReady = password.length >= (mode === "register" ? 6 : 1);
@@ -765,9 +790,9 @@ function ProfilePage({
className={`profile-page__banner${bannerUrl ? " has-image" : ""}`} className={`profile-page__banner${bannerUrl ? " has-image" : ""}`}
style={bannerUrl ? { backgroundImage: `url(${bannerUrl})` } : undefined} style={bannerUrl ? { backgroundImage: `url(${bannerUrl})` } : undefined}
> >
<button type="button" className="profile-page__banner-btn" onClick={() => bannerInputRef.current?.click()}> <button type="button" className="profile-page__banner-btn" onClick={() => bannerInputRef.current?.click()} aria-label="更换背景">
<CameraOutlined /> <CameraOutlined />
<span className="profile-page__banner-btn-label"></span>
</button> </button>
<div className="profile-page__banner-overlay" /> <div className="profile-page__banner-overlay" />
</header> </header>
@@ -847,14 +872,16 @@ function ProfilePage({
className={accountPanel === "credits" ? "is-active" : ""} className={accountPanel === "credits" ? "is-active" : ""}
onClick={() => setAccountPanel("credits")} onClick={() => setAccountPanel("credits")}
> >
{(totalBalance / 100).toFixed(2)} <span></span>
<strong>{(totalBalance / 100).toFixed(2)}</strong>
</button> </button>
<button <button
type="button" type="button"
className={accountPanel === "tasks" ? "is-active" : ""} className={accountPanel === "tasks" ? "is-active" : ""}
onClick={() => setAccountPanel("tasks")} onClick={() => setAccountPanel("tasks")}
> >
{tasks.length} <span></span>
<strong>{tasks.length}</strong>
</button> </button>
</div> </div>
<div className="profile-page__account-summary"> <div className="profile-page__account-summary">
@@ -863,6 +890,7 @@ function ProfilePage({
<span className="profile-page__account-summary-main"> <span className="profile-page__account-summary-main">
<small></small> <small></small>
<strong>{displayName}</strong> <strong>{displayName}</strong>
<em>{packageLabel}</em>
</span> </span>
<span className="profile-page__account-summary-metric"> <span className="profile-page__account-summary-metric">
<small></small> <small></small>
@@ -874,6 +902,7 @@ function ProfilePage({
<span className="profile-page__account-summary-main"> <span className="profile-page__account-summary-main">
<small></small> <small></small>
<strong>{tasks.length} </strong> <strong>{tasks.length} </strong>
<em>{completedTasks.length} </em>
</span> </span>
<span className="profile-page__account-summary-metric"> <span className="profile-page__account-summary-metric">
<small></small> <small></small>
@@ -884,6 +913,7 @@ function ProfilePage({
</div> </div>
</div> </div>
<div className="profile-page__actions">
<button type="button" className="profile-page__share-btn profile-page__share-btn--plan"> <button type="button" className="profile-page__share-btn profile-page__share-btn--plan">
<ShareAltOutlined /> <ShareAltOutlined />
{packageLabel} {packageLabel}
@@ -901,34 +931,31 @@ function ProfilePage({
<LockOutlined /> <LockOutlined />
退 退
</button> </button>
</div>
</aside> </aside>
<main className="profile-page__main"> <main className="profile-page__main">
<div className="profile-page__main-tabs"> <div className="profile-page__main-tabs">
<button type="button" className={activePanel === "works" ? "is-active" : ""} onClick={() => setActivePanel("works")}> <button type="button" className={activePanel === "works" ? "is-active" : ""} onClick={() => setActivePanel("works")}>
<span></span>
</button> </button>
<button type="button" className={activePanel === "projects" ? "is-active" : ""} onClick={() => setActivePanel("projects")}> <button type="button" className={activePanel === "projects" ? "is-active" : ""} onClick={() => setActivePanel("projects")}>
<span></span>
</button> </button>
<button type="button" className={activePanel === "assets" ? "is-active" : ""} onClick={() => setActivePanel("assets")}> <button type="button" className={activePanel === "assets" ? "is-active" : ""} onClick={() => setActivePanel("assets")}>
<span></span>
</button> </button>
<button type="button" className={activePanel === "community" ? "is-active" : ""} onClick={() => setActivePanel("community")}> <button type="button" className={activePanel === "community" ? "is-active" : ""} onClick={() => setActivePanel("community")}>
<span></span>
</button> </button>
</div> </div>
<div className="profile-page__section"> <div className="profile-page__section">
<span className="profile-page__section-label"> <div className="profile-page__section-head">
{activePanel === "works" <span className="profile-page__section-label">{activePanelTitle}</span>
? "代表作" <span className="profile-page__section-desc">{activePanelDescription}</span>
: activePanel === "projects" <span className="profile-page__section-meta">{activePanelCount} </span>
? "服务器项目" </div>
: activePanel === "assets"
? "我的资产"
: "社区审核"}
</span>
{renderActivePanel()} {renderActivePanel()}
</div> </div>
</main> </main>
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import "../../styles/pages/provider-health.css";
import { import {
CheckCircleOutlined, CheckCircleOutlined,
CloseCircleOutlined, CloseCircleOutlined,
@@ -16,6 +16,7 @@ import {
VideoCameraOutlined, VideoCameraOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import "../../styles/pages/image-workbench.css";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive"; import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive";
@@ -9,6 +9,8 @@ import {
UploadOutlined, UploadOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent } from "react"; import { useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent } from "react";
import "../../styles/pages/script-tokens-v5.css";
import "../../styles/pages/script-tokens.css";
import { evaluateScript } from "../../api/scriptEvalClient"; import { evaluateScript } from "../../api/scriptEvalClient";
import { buildApiUrl, getStoredToken } from "../../api/serverConnection"; import { buildApiUrl, getStoredToken } from "../../api/serverConnection";
import { useSessionStore } from "../../stores"; import { useSessionStore } from "../../stores";
@@ -243,9 +245,21 @@ function getDimensionSubScores(result: EvalResult, dim: ScoreDimension): Array<[
.slice(0, 5); .slice(0, 5);
} }
function normalizeEvidenceItems(evidence: unknown[] | undefined, limit: number): string[] {
if (!Array.isArray(evidence)) return [];
const items: string[] = [];
for (const item of evidence) {
const value = String(item).trim();
if (!value) continue;
items.push(value);
if (items.length >= limit) break;
}
return items;
}
function getDimensionEvidence(result: EvalResult, dim: ScoreDimension): string[] { function getDimensionEvidence(result: EvalResult, dim: ScoreDimension): string[] {
const evidence = result.evidence?.[dim.key] ?? (dim.key === "logic" ? result.evidence?.dialogue : undefined); const evidence = result.evidence?.[dim.key] ?? (dim.key === "logic" ? result.evidence?.dialogue : undefined);
return Array.isArray(evidence) ? evidence.map(String).map((item) => item.trim()).filter(Boolean).slice(0, 3) : []; return normalizeEvidenceItems(evidence, 3);
} }
function formatReportMarkdown(result: EvalResult, script: string): string { function formatReportMarkdown(result: EvalResult, script: string): string {
@@ -11,6 +11,8 @@ import {
WarningOutlined, WarningOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import "../../styles/pages/script-tokens-v5.css";
import "../../styles/pages/script-tokens.css";
import type { import type {
WebEnterpriseUsageMember, WebEnterpriseUsageMember,
WebEnterpriseUsageRecord, WebEnterpriseUsageRecord,
@@ -13,6 +13,8 @@ import {
VideoCameraOutlined, VideoCameraOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react"; import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import "../../styles/pages/image-workbench.css";
import "../../styles/pages/subtitle-removal.css";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive"; import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive";
@@ -13,6 +13,7 @@ import {
SwapOutlined, SwapOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import "../../styles/pages/image-workbench.css";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { waitForTask } from "../../api/taskSubscription"; import { waitForTask } from "../../api/taskSubscription";
import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive"; import { saveToolTaskState, loadToolTaskState, clearToolTaskState } from "../workbench/toolKeepalive";
+2 -1
View File
@@ -34,6 +34,7 @@ import {
type ReactNode, type ReactNode,
type SyntheticEvent, type SyntheticEvent,
} from "react"; } from "react";
import "../../styles/pages/workbench.css";
import type { WebGenerationPreviewTask, WebUserSession } from "../../types"; import type { WebGenerationPreviewTask, WebUserSession } from "../../types";
import { aiGenerationClient } from "../../api/aiGenerationClient"; import { aiGenerationClient } from "../../api/aiGenerationClient";
import { claimGenerationSlot, getActiveGenerationTaskCount, getGenerationUserKey, releaseGenerationSlot } from "../../api/generationConcurrency"; import { claimGenerationSlot, getActiveGenerationTaskCount, getGenerationUserKey, releaseGenerationSlot } from "../../api/generationConcurrency";
@@ -369,7 +370,7 @@ function WorkbenchPage({
.get() .get()
.then((capabilities) => { .then((capabilities) => {
if (cancelled) return; if (cancelled) return;
const nextVideoModels = VIDEO_MODEL_OPTIONS; const nextVideoModels = capabilities.videoModels.length ? capabilities.videoModels : VIDEO_MODEL_OPTIONS;
applyImageModels(capabilities.imageModels); applyImageModels(capabilities.imageModels);
setVideoModelOptions(nextVideoModels); setVideoModelOptions(nextVideoModels);
+9 -26
View File
@@ -3,6 +3,8 @@
* Persists task state to localStorage so in-progress tasks survive page switches. * Persists task state to localStorage so in-progress tasks survive page switches.
*/ */
import { waitForTask } from "../../api/taskSubscription";
const KEEPALIVE_PREFIX = "omniai:tool-task:"; const KEEPALIVE_PREFIX = "omniai:tool-task:";
interface ToolTaskKeepalive { interface ToolTaskKeepalive {
@@ -59,38 +61,19 @@ export function clearToolTaskState(key: string): void {
try { window.localStorage.removeItem(KEEPALIVE_PREFIX + key); } catch { /* ignore */ } try { window.localStorage.removeItem(KEEPALIVE_PREFIX + key); } catch { /* ignore */ }
} }
const TASK_POLL_INTERVAL = 3000;
const TASK_POLL_TIMEOUT = 30 * 60 * 1000;
export async function pollTaskUntilDone( export async function pollTaskUntilDone(
taskId: string, taskId: string,
onProgress?: (progress: number) => void, onProgress?: (progress: number) => void,
abortRef?: { current: boolean }, abortRef?: { current: boolean },
kind: "image" | "video" = "video",
): Promise<string | null> { ): Promise<string | null> {
const startTime = Date.now();
const { aiGenerationClient } = await import("../../api/aiGenerationClient");
while (true) {
if (abortRef?.current) return null;
if (Date.now() - startTime > TASK_POLL_TIMEOUT) return null;
try { try {
const task = await aiGenerationClient.getTaskStatus(taskId); return await waitForTask(taskId, {
if (!task) return null; kind,
abortRef,
const progress = Math.min(99, task.progress || 0); onProgress: (event) => onProgress?.(Math.min(99, Number(event.progress || 0))),
onProgress?.(progress); });
} catch {
if (task.status === "completed") {
return task.resultUrl || null;
}
if (task.status === "failed" || task.status === "cancelled") {
return null; return null;
} }
} catch {
// retry on next poll
}
await new Promise((r) => setTimeout(r, TASK_POLL_INTERVAL));
}
} }
+29 -18
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useCallback } from "react"; import { useEffect, useMemo, useRef, useCallback } from "react";
import { useShallow } from "zustand/react/shallow";
import type { GenerationQueueItem } from "../stores/useGenerationStore"; import type { GenerationQueueItem } from "../stores/useGenerationStore";
import { useGenerationStore } from "../stores/useGenerationStore"; import { useGenerationStore } from "../stores/useGenerationStore";
import { import {
@@ -13,7 +14,17 @@ interface UseGenerationTasksOptions {
export function useGenerationTasks(options: UseGenerationTasksOptions) { export function useGenerationTasks(options: UseGenerationTasksOptions) {
const { sourceView, autoResume = true } = options; const { sourceView, autoResume = true } = options;
const store = useGenerationStore(); const {
queue,
addTask,
updateTask: updateStoredTask,
getRunningTasks,
} = useGenerationStore(useShallow((s) => ({
queue: s.queue,
addTask: s.addTask,
updateTask: s.updateTask,
getRunningTasks: s.getRunningTasks,
})));
const pollingStartedRef = useRef(false); const pollingStartedRef = useRef(false);
// ── Auto-resume: re-subscribe to running tasks on mount ──── // ── Auto-resume: re-subscribe to running tasks on mount ────
@@ -21,7 +32,7 @@ export function useGenerationTasks(options: UseGenerationTasksOptions) {
if (!autoResume || pollingStartedRef.current) return; if (!autoResume || pollingStartedRef.current) return;
pollingStartedRef.current = true; pollingStartedRef.current = true;
const active = store.getRunningTasks().filter((t) => t.sourceView === sourceView); const active = getRunningTasks().filter((t) => t.sourceView === sourceView);
if (active.length > 0) { if (active.length > 0) {
startBackgroundPolling(); startBackgroundPolling();
} }
@@ -29,19 +40,19 @@ export function useGenerationTasks(options: UseGenerationTasksOptions) {
return () => { return () => {
pollingStartedRef.current = false; pollingStartedRef.current = false;
}; };
}, [autoResume, sourceView, store]); }, [autoResume, sourceView, getRunningTasks]);
// ── Subscribe to live updates ─────────────────────────── // ── Subscribe to live updates ───────────────────────────
useEffect(() => { useEffect(() => {
return subscribeToTaskUpdates((updated) => { return subscribeToTaskUpdates((updated) => {
store.updateTask(updated.id, updated); updateStoredTask(updated.id, updated);
}); });
}, [store]); }, [updateStoredTask]);
// ── View-scoped computed lists ────────────────────────── // ── View-scoped computed lists ──────────────────────────
const myTasks = useMemo( const myTasks = useMemo(
() => store.queue.filter((t) => t.sourceView === sourceView), () => queue.filter((t) => t.sourceView === sourceView),
[store.queue, sourceView], [queue, sourceView],
); );
const activeTasks = useMemo( const activeTasks = useMemo(
@@ -63,41 +74,41 @@ export function useGenerationTasks(options: UseGenerationTasksOptions) {
const submitTask = useCallback( const submitTask = useCallback(
(task: Omit<GenerationQueueItem, "id" | "createdAt">) => { (task: Omit<GenerationQueueItem, "id" | "createdAt">) => {
const id = `gen-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const id = `gen-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
store.addTask({ ...task, id, createdAt: Date.now() }); addTask({ ...task, id, createdAt: Date.now() });
return id; return id;
}, },
[store], [addTask],
); );
const updateTask = useCallback( const updateTask = useCallback(
(id: string, patch: Partial<GenerationQueueItem>) => { (id: string, patch: Partial<GenerationQueueItem>) => {
store.updateTask(id, patch); updateStoredTask(id, patch);
}, },
[store], [updateStoredTask],
); );
const markCompleted = useCallback( const markCompleted = useCallback(
(id: string, resultUrl: string) => { (id: string, resultUrl: string) => {
store.updateTask(id, { status: "completed", progress: 100, resultUrl }); updateStoredTask(id, { status: "completed", progress: 100, resultUrl });
}, },
[store], [updateStoredTask],
); );
const markFailed = useCallback( const markFailed = useCallback(
(id: string, error: string) => { (id: string, error: string) => {
store.updateTask(id, { status: "failed", error }); updateStoredTask(id, { status: "failed", error });
}, },
[store], [updateStoredTask],
); );
const retryTask = useCallback( const retryTask = useCallback(
(id: string) => { (id: string) => {
const task = store.queue.find((t) => t.id === id); const task = queue.find((t) => t.id === id);
if (task) { if (task) {
store.updateTask(id, { status: "pending", progress: 0, error: null }); updateStoredTask(id, { status: "pending", progress: 0, error: null });
} }
}, },
[store], [queue, updateStoredTask],
); );
return { return {
-1
View File
@@ -1,6 +1,5 @@
import React from "react"; import React from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import "@xyflow/react/dist/style.css";
import "./styles/index.css"; import "./styles/index.css";
import App from "./App"; import App from "./App";
import { reportError } from "./utils/errorReporting"; import { reportError } from "./utils/errorReporting";
+71 -79
View File
@@ -1,20 +1,12 @@
import { useGenerationStore, type GenerationQueueItem } from "../stores/useGenerationStore"; import { useGenerationStore, type GenerationQueueItem } from "../stores/useGenerationStore";
import { aiGenerationClient } from "../api/aiGenerationClient"; import { waitForTask, type TaskProgressEvent } from "../api/taskSubscription";
import { import { buildTaskFailureInfo } from "../utils/taskLifecycle";
buildLocalTimeoutMessage,
buildTaskFailureInfo,
getTaskTimeoutPolicy,
isTaskLocallyTimedOut,
} from "../utils/taskLifecycle";
type PollCallback = (item: GenerationQueueItem) => void; type PollCallback = (item: GenerationQueueItem) => void;
const activePollers = new Map<string, ReturnType<typeof setInterval>>(); const activePollers = new Map<string, { current: boolean }>();
const pollCallbacks = new Set<PollCallback>(); const pollCallbacks = new Set<PollCallback>();
const POLL_INTERVAL = 3000;
const MAX_POLL_ATTEMPTS = 200; // Keep the previous 10-minute guard as a fallback.
export function subscribeToTaskUpdates(callback: PollCallback): () => void { export function subscribeToTaskUpdates(callback: PollCallback): () => void {
pollCallbacks.add(callback); pollCallbacks.add(callback);
return () => { pollCallbacks.delete(callback); }; return () => { pollCallbacks.delete(callback); };
@@ -34,109 +26,109 @@ function getQueueItemModel(item: GenerationQueueItem): string | undefined {
return typeof item.params?.model === "string" ? item.params.model : undefined; return typeof item.params?.model === "string" ? item.params.model : undefined;
} }
function pollTask(item: GenerationQueueItem, attemptsRef: { current: number }): void { function updateTaskAndNotify(id: string, patch: Partial<GenerationQueueItem>): GenerationQueueItem | null {
const current = useGenerationStore.getState().queue.find((i) => i.id === id);
if (!current) return null;
const next = { ...current, ...patch };
useGenerationStore.getState().updateTask(id, patch);
notifyCallbacks(next);
return next;
}
function isTerminalStatus(status: GenerationQueueItem["status"]): boolean {
return status === "completed" || status === "failed" || status === "cancelled";
}
function pollTask(item: GenerationQueueItem): void {
const key = `poll-${item.id}`; const key = `poll-${item.id}`;
if (activePollers.has(key)) return; if (activePollers.has(key) || !item.taskId) return;
const kind = getQueueItemKind(item); const kind = getQueueItemKind(item);
const timeoutPolicy = getTaskTimeoutPolicy({ kind, model: getQueueItemModel(item) }); const abortRef = { current: false };
let lastProgress = Math.max(0, Number(item.progress || 0)); activePollers.set(key, abortRef);
let lastProgressAt = Date.now();
const interval = setInterval(async () => { const applyProgress = (event: TaskProgressEvent) => {
const current = useGenerationStore.getState().queue.find((i) => i.id === item.id); const current = useGenerationStore.getState().queue.find((i) => i.id === item.id);
if (!current || current.status === "completed" || current.status === "failed" || current.status === "cancelled") { if (!current || isTerminalStatus(current.status)) {
cleanupPoll(key); abortRef.current = true;
return; return;
} }
attemptsRef.current++;
const timeoutReason = isTaskLocallyTimedOut({
startedAt: current.createdAt || item.createdAt || Date.now(),
lastProgressAt,
progress: lastProgress,
policy: timeoutPolicy,
});
if (timeoutReason || attemptsRef.current > MAX_POLL_ATTEMPTS) {
const error = buildLocalTimeoutMessage(kind);
useGenerationStore.getState().updateTask(item.id, {
status: "failed",
error,
});
notifyCallbacks({ ...item, status: "failed", error });
cleanupPoll(key);
return;
}
try {
const status = await aiGenerationClient.getTaskStatus(current.taskId || item.taskId || "");
const nextProgress = Number(status.progress || 0);
if (nextProgress > lastProgress || status.status === "completed") {
lastProgress = Math.max(lastProgress, nextProgress);
lastProgressAt = Date.now();
}
const patch: Partial<GenerationQueueItem> = { const patch: Partial<GenerationQueueItem> = {
progress: status.progress, progress: Number(event.progress || 0),
resultUrl: status.resultUrl || current.resultUrl, resultUrl: event.resultUrl || current.resultUrl,
error: status.error || current.error, error: event.error || current.error,
}; };
if (status.status === "completed") { if (event.status === "completed") {
patch.status = "completed"; patch.status = "completed";
useGenerationStore.getState().updateTask(item.id, patch); patch.progress = 100;
notifyCallbacks({ ...item, ...patch, status: "completed" }); } else if (event.status === "failed" || event.status === "cancelled") {
cleanupPoll(key);
} else if (status.status === "failed" || status.status === "cancelled") {
patch.status = "failed"; patch.status = "failed";
patch.error = buildTaskFailureInfo(status.error).message; patch.error = buildTaskFailureInfo(event.error).message;
useGenerationStore.getState().updateTask(item.id, patch);
notifyCallbacks({ ...item, ...patch, status: "failed" });
cleanupPoll(key);
} else { } else {
patch.status = "running"; patch.status = "running";
useGenerationStore.getState().updateTask(item.id, patch);
notifyCallbacks({ ...item, ...patch, status: "running" });
}
} catch {
// Network errors during polling are retried until the lifecycle guard trips.
}
}, POLL_INTERVAL);
activePollers.set(key, interval);
} }
function cleanupPoll(key: string): void { updateTaskAndNotify(item.id, patch);
const interval = activePollers.get(key); };
if (interval) {
clearInterval(interval); void waitForTask(item.taskId, {
kind,
model: getQueueItemModel(item),
startedAt: item.createdAt || Date.now(),
abortRef,
onProgress: applyProgress,
})
.then((resultUrl) => {
if (abortRef.current) return;
const current = useGenerationStore.getState().queue.find((i) => i.id === item.id);
if (!current || isTerminalStatus(current.status)) return;
updateTaskAndNotify(item.id, {
status: "completed",
progress: 100,
resultUrl: resultUrl || current.resultUrl,
});
})
.catch((error) => {
if (abortRef.current) return;
const failure = buildTaskFailureInfo(error instanceof Error ? error.message : String(error));
updateTaskAndNotify(item.id, {
status: "failed",
error: failure.message,
});
})
.finally(() => {
cleanupPoll(key, abortRef);
});
}
function cleanupPoll(key: string, abortRef: { current: boolean }): void {
if (activePollers.get(key) !== abortRef) return;
activePollers.delete(key); activePollers.delete(key);
} }
}
export function startBackgroundPolling(): void { export function startBackgroundPolling(): void {
const tasks = useGenerationStore.getState().getRunningTasks(); const tasks = useGenerationStore.getState().getRunningTasks();
const attemptsMap = new Map<string, { current: number }>();
tasks.forEach((task) => { tasks.forEach((task) => {
if (task.taskId) { if (task.taskId) {
if (!attemptsMap.has(task.id)) { pollTask(task);
attemptsMap.set(task.id, { current: 0 });
}
pollTask(task, attemptsMap.get(task.id)!);
} }
}); });
} }
export function resumeTaskPolling(taskId: string, storeId: string): void { export function resumeTaskPolling(taskId: string, storeId: string): void {
const task = useGenerationStore.getState().queue.find((i) => i.id === storeId); const task = useGenerationStore.getState().queue.find((i) => i.id === storeId);
if (task && task.status !== "completed" && task.status !== "failed") { if (task && !isTerminalStatus(task.status)) {
pollTask(task, { current: 0 }); pollTask({ ...task, taskId });
} }
} }
export function stopAllPolling(): void { export function stopAllPolling(): void {
activePollers.forEach((interval) => clearInterval(interval)); activePollers.forEach((abortRef) => {
abortRef.current = true;
});
activePollers.clear(); activePollers.clear();
} }
-19
View File
@@ -9,28 +9,9 @@
@import "./pages/script-review-visual.css"; @import "./pages/script-review-visual.css";
@import "./pages/script-review-showcase.css"; @import "./pages/script-review-showcase.css";
@import "./pages/model-generation-showcase.css"; @import "./pages/model-generation-showcase.css";
@import "./pages/workbench.css";
@import "./pages/ecommerce.css";
@import "./pages/ecommerce-video.css";
@import "./pages/community.css";
@import "./pages/assets.css";
@import "./pages/more.css";
@import "./pages/avatar-console.css";
@import "./pages/more-tools.css"; @import "./pages/more-tools.css";
@import "./pages/studio-layout.css"; @import "./pages/studio-layout.css";
@import "./pages/image-workbench.css";
@import "./pages/subtitle-removal.css";
@import "./pages/dialog-generator.css";
@import "./pages/size-template.css"; @import "./pages/size-template.css";
@import "./pages/script-tokens-v5.css";
@import "./pages/script-tokens.css";
@import "./pages/profile.css";
@import "./pages/canvas.css";
@import "./pages/agent.css";
@import "./pages/compliance.css";
@import "./pages/provider-health.css";
@import "./pages/legacy-pages.css";
@import "./pages/not-found.css";
@import "./components/recharge-modal.css"; @import "./components/recharge-modal.css";
@import "./components/dropzone.css"; @import "./components/dropzone.css";
@import "./components/skeleton.css"; @import "./components/skeleton.css";
-12
View File
@@ -1,13 +1 @@
/* Agent page rules move here as they are retired from legacy-pages.css. */ /* Agent page rules move here as they are retired from legacy-pages.css. */
@media (max-width: 900px) {
.agent-page {
padding: 16px 16px 80px;
}
}
@media (max-width: 560px) {
.agent-page {
padding: 12px 10px 80px;
}
}
-21
View File
@@ -243,24 +243,3 @@
max-height: calc(100vh - 190px); max-height: calc(100vh - 190px);
} }
} }
@media (max-width: 560px) {
.asset-preview-modal {
padding: 8px;
}
.asset-preview-modal__panel {
width: calc(100vw - 16px);
max-height: calc(100vh - 16px);
border-radius: 12px;
}
.asset-preview-modal__body {
padding: 8px;
}
.asset-preview-modal__body img,
.asset-preview-modal__body video {
max-height: calc(100vh - 160px);
}
}
-27
View File
@@ -4211,30 +4211,3 @@
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
} }
@media (max-width: 560px) {
.avatar-console-page {
height: auto;
min-height: 100%;
overflow: auto;
}
.avatar-console-main {
min-height: 100vh;
padding-bottom: 80px;
}
.avatar-console-scroll {
padding: 10px;
}
.avatar-console-toolbar {
flex-wrap: wrap;
gap: 6px;
}
.avatar-console-video-actions {
flex-direction: column;
gap: 8px;
}
}
-91
View File
@@ -910,94 +910,3 @@
height: 100%; height: 100%;
cursor: crosshair; cursor: crosshair;
} }
/*
Responsive: Canvas
Breakpoints: 900px / 560px
*/
@media (max-width: 900px) {
.studio-canvas-page {
flex-direction: column;
}
.studio-canvas-toolbar {
flex: 0 0 auto;
flex-direction: row;
width: 100%;
padding: 8px 12px;
gap: 6px;
overflow-x: auto;
border-right: none;
border-bottom: 1px solid var(--border-weak);
-webkit-overflow-scrolling: touch;
}
.studio-canvas-toolbar__group {
flex-direction: row;
flex-shrink: 0;
gap: 4px;
}
.studio-canvas-toolbar button {
min-width: 36px;
height: 36px;
font-size: 14px;
}
.studio-canvas-main {
flex: 1;
min-height: 0;
}
.studio-canvas-node {
min-width: 140px;
min-height: 60px;
}
}
@media (max-width: 560px) {
.studio-canvas-page {
flex-direction: column;
}
.studio-canvas-toolbar {
flex: 0 0 auto;
padding: 6px 8px;
gap: 4px;
border-bottom: 1px solid var(--border-weak);
}
.studio-canvas-toolbar button {
min-width: 30px;
height: 30px;
padding: 0 6px;
font-size: 12px;
border-radius: 8px;
}
.studio-canvas-main {
flex: 1;
min-height: 0;
}
.studio-canvas-node {
min-width: 110px;
min-height: 48px;
border-radius: 10px;
padding: 8px;
}
.studio-canvas-project-bar {
right: 8px;
left: 8px;
bottom: 80px;
gap: 4px;
border-radius: 10px;
padding: 8px 10px;
}
.studio-canvas-project-bar__name-form {
font-size: 12px;
}
}
-49
View File
@@ -117,52 +117,3 @@
font-weight: 600; font-weight: 600;
line-height: 1.6; line-height: 1.6;
} }
/*
Responsive: Community
Breakpoints: 900px / 560px
*/
@media (max-width: 900px) {
.community-page {
padding: 12px 16px 80px;
}
.community-carousel__slide--video {
min-height: 200px;
}
.community-carousel__video {
max-height: 220px;
}
.community-case-card__preview {
min-height: 140px;
}
}
@media (max-width: 560px) {
.community-page {
padding: 10px 10px 80px;
}
.community-carousel__slide--video {
min-height: 160px;
}
.community-carousel__video {
max-height: 180px;
}
.community-case-card__preview {
min-height: 110px;
}
.community-case-empty {
padding: 32px 16px;
}
.community-case-empty__icon {
font-size: 18px;
}
}
-141
View File
@@ -8382,147 +8382,6 @@
.clone-ai-adwizard__risk.is-low { color: #52c41a; } .clone-ai-adwizard__risk.is-low { color: #52c41a; }
.clone-ai-adwizard__risk.is-medium { color: #faad14; } .clone-ai-adwizard__risk.is-medium { color: #faad14; }
.clone-ai-adwizard__risk.is-high { color: #ff4d4f; } .clone-ai-adwizard__risk.is-high { color: #ff4d4f; }
/*
Responsive: Ecommerce Tools
Breakpoints: 1180px / 900px / 560px
*/
/* ── 1180px: Narrower panels ── */
@media (max-width: 1180px) {
.product-clone-page[data-tool="clone"] > .product-clone-shell {
grid-template-columns: minmax(360px, 440px) minmax(0, 1fr);
}
.product-clone-page[data-tool="set"] > .product-clone-shell {
grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
}
}
/* ── 900px: Tablet — stacked layout ── */
@media (max-width: 900px) {
/* All tools: collapse shell to single column */
.product-clone-page > .product-clone-shell,
.product-clone-page[data-tool="clone"] > .product-clone-shell,
.product-clone-page[data-tool="set"] > .product-clone-shell {
grid-template-columns: 1fr;
grid-template-rows: auto minmax(0, 1fr);
}
/* Rail becomes horizontal tab bar */
.product-clone-rail {
display: flex !important;
flex-direction: row;
gap: 4px;
width: 100%;
height: auto;
padding: 8px 12px;
overflow-x: auto;
border-right: none;
border-bottom: 1px solid var(--border-weak, #2a3032);
-webkit-overflow-scrolling: touch;
}
.product-clone-rail button {
flex-shrink: 0;
white-space: nowrap;
flex-direction: row;
gap: 6px;
padding: 8px 14px;
font-size: 12px;
}
/* Panel: full-width, reduced height */
.product-clone-panel {
width: 100%;
max-height: 45vh;
overflow-y: auto;
}
.product-clone-page[data-tool="clone"] .product-clone-panel {
--clone-settings-panel-width: 100%;
max-height: 45vh;
}
/* Preview: independent scroll area */
.product-clone-preview {
min-height: 40vh;
overflow-y: auto;
padding: 20px 16px;
}
.product-clone-page[data-tool="set"] .product-clone-preview {
padding: 20px 16px;
}
/* Collapse toggle tweak */
.product-clone-page[data-tool="clone"] .product-clone-panel {
transition: max-height 320ms ease, opacity 320ms ease;
}
.product-clone-page.is-settings-collapsed .product-clone-panel {
max-height: 0;
overflow: hidden;
opacity: 0;
}
}
/* ── 560px: Phone — further compression ── */
@media (max-width: 560px) {
.product-clone-page {
grid-template-rows: 44px minmax(0, 1fr);
}
.product-clone-rail {
padding: 6px 8px;
gap: 2px;
}
.product-clone-rail button {
padding: 6px 10px;
font-size: 11px;
gap: 4px;
}
.product-clone-panel {
max-height: 38vh;
}
.product-clone-page[data-tool="clone"] .product-clone-panel {
max-height: 38vh;
}
.product-clone-page[data-tool="set"] .product-clone-panel__scroll {
padding: 20px 14px 24px;
}
.product-clone-page[data-tool="set"] :is(.product-set-upload-section, .product-set-settings-section) {
padding: 18px;
border-radius: 14px;
margin-bottom: 18px;
}
.product-clone-page[data-tool="set"] .product-set-upload {
min-height: 180px;
padding: 16px;
gap: 8px;
}
.product-clone-page[data-tool="set"] .product-set-upload-title {
font-size: 15px;
}
.product-clone-page[data-tool="set"] .product-set-upload strong {
height: 42px;
min-width: 140px;
font-size: 16px;
}
/* Preview full-width */
.product-clone-preview {
padding: 12px 10px !important;
min-height: 50vh;
}
}
.clone-ai-adwizard__issues { margin: 0; padding-left: 16px; font-size: 12px; display: flex; flex-direction: column; gap: 4px; } .clone-ai-adwizard__issues { margin: 0; padding-left: 16px; font-size: 12px; display: flex; flex-direction: column; gap: 4px; }
/* ===== Ecommerce Template Apple Carousel ===== */ /* ===== Ecommerce Template Apple Carousel ===== */
-25
View File
@@ -1776,28 +1776,3 @@ textarea.image-workbench-prompt {
.image-workbench-result-card:nth-child(2) { animation-delay: 0.08s; } .image-workbench-result-card:nth-child(2) { animation-delay: 0.08s; }
.image-workbench-result-card:nth-child(3) { animation-delay: 0.16s; } .image-workbench-result-card:nth-child(3) { animation-delay: 0.16s; }
.image-workbench-result-card:nth-child(4) { animation-delay: 0.24s; } .image-workbench-result-card:nth-child(4) { animation-delay: 0.24s; }
@media (max-width: 900px) {
.image-workbench-page {
padding: 12px;
}
.image-workbench-toolbar {
flex-wrap: wrap;
gap: 8px;
}
}
@media (max-width: 560px) {
.image-workbench-page {
padding: 8px 8px 80px;
}
.image-workbench-toolbar {
gap: 4px;
}
.image-workbench-toolbar button {
min-width: 36px;
height: 36px;
padding: 0 10px;
font-size: 12px;
}
}
-20
View File
@@ -1286,23 +1286,3 @@ textarea.image-workbench-prompt,
justify-items: start; justify-items: start;
} }
} }
@media (max-width: 560px) {
.token-usage-page {
padding: 0 8px 80px;
}
.token-usage-page .script-token-page__scroll,
.script-token-page__scroll {
padding-inline: 8px;
}
.token-member-card {
padding: 14px;
gap: 8px;
}
.token-member-card__head {
gap: 8px;
}
}
-36
View File
@@ -313,39 +313,3 @@
font-size: 15px; font-size: 15px;
} }
} }
@media (max-width: 560px) {
.more-page-v2 {
padding-left: 0;
}
.more-page-v2__header {
padding: 10px 12px 8px;
gap: 8px;
}
.more-page-v2__scroll {
padding: 12px 10px 72px;
}
.more-page-v2__grid {
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.more-page-v2__featured-grid {
gap: 10px;
}
.more-card--featured {
padding: 14px;
gap: 10px;
}
.more-card__featured-icon {
width: 36px;
height: 36px;
border-radius: 10px;
font-size: 18px;
}
}
+10 -19
View File
@@ -2,32 +2,23 @@
/* ── 代表作滚动容器:固定3列,刚好显示9个(3行),超出可滚动,隐藏滚动条 ── */ /* ── 代表作滚动容器:固定3列,刚好显示9个(3行),超出可滚动,隐藏滚动条 ── */
.profile-page__works-scroll { .profile-page__works-scroll {
max-height: 390px; max-height: 390px; /* 3行卡片:3 × 120(min-height) + 2 × 10(gap) = 380px,留10px余量 */
overflow-y: auto; overflow-y: auto;
scrollbar-width: none; scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; -ms-overflow-style: none; /* IE/Edge */
} }
.profile-page__works-scroll::-webkit-scrollbar { .profile-page__works-scroll::-webkit-scrollbar {
display: none; display: none; /* Chrome/Safari/Edge */
} }
.profile-page__works-scroll .profile-page__list-grid { .profile-page__works-scroll .profile-page__list-grid {
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr); /* 固定3列,刚好3×3=9个可见 */
} }
@media (max-width: 900px) { /* Dashboard uses natural page scrolling instead of a nested works scroller. */
.profile-page, .profile-page--dashboard .profile-page__works-scroll {
.auth-page, max-height: none;
.settings-page { overflow: visible;
padding: 16px 16px 80px; scrollbar-width: auto;
}
}
@media (max-width: 560px) {
.profile-page,
.auth-page,
.settings-page {
padding: 12px 10px 80px;
}
} }
-37
View File
@@ -164,40 +164,3 @@
.provider-health-table tr:hover td { .provider-health-table tr:hover td {
background: var(--surface-elevated); background: var(--surface-elevated);
} }
@media (max-width: 900px) {
.provider-health-page__inner {
padding: 16px;
gap: 16px;
}
.provider-health-grid {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
}
}
@media (max-width: 560px) {
.provider-health-page__inner {
padding: 12px 12px 80px;
gap: 12px;
}
.provider-health-grid {
grid-template-columns: 1fr;
gap: 10px;
}
.provider-health-toolbar {
flex-direction: column;
gap: 8px;
}
.provider-health-table {
font-size: 11px;
}
.provider-health-table th,
.provider-health-table td {
padding: 6px 8px;
}
}
-21
View File
@@ -474,24 +474,3 @@
width: min(100%, 430px); width: min(100%, 430px);
} }
} }
@media (max-width: 560px) {
.size-template-page {
padding: 12px 10px 80px;
}
.size-template-main-frame {
grid-template-columns: 1fr;
gap: 12px;
}
.size-template-spec-grid {
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.size-template-preview-note,
.size-template-detail-card {
width: 100%;
}
}
-16
View File
@@ -674,19 +674,3 @@
max-height: 320px; max-height: 320px;
} }
} }
@media (max-width: 560px) {
.studio-tool-layout {
grid-template-rows: 40px auto minmax(200px, 1fr) 32px;
}
.studio-tool-layout__toolstrip {
padding: 6px 8px;
gap: 4px;
}
.studio-panel {
max-height: 240px;
padding: 12px;
}
}
-12
View File
@@ -133,15 +133,3 @@
opacity: 0.5; opacity: 0.5;
cursor: not-allowed; cursor: not-allowed;
} }
@media (max-width: 900px) {
.subtitle-removal-page {
padding: 12px;
}
}
@media (max-width: 560px) {
.subtitle-removal-page {
padding: 8px 8px 80px;
}
}
-134
View File
@@ -440,137 +440,3 @@
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
/*
Responsive: Workbench Launch & Active State
Breakpoints: 900px / 560px
*/
/* ── 900px: Tablet — launch state ── */
@media (max-width: 900px) {
.wb-home {
padding: 36px 16px 80px;
gap: 18px;
}
.wb-home__title {
font-size: clamp(24px, 6vw, 36px);
}
.wb-home__composer {
max-width: 100%;
}
.wb-home__suggestions {
max-width: 100%;
}
.wb-showcase {
max-width: 100%;
}
.wb-showcase__grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
/* Active state: message thread */
.ai-workbench-content-scroll {
width: 100%;
padding: 16px 12px;
}
.ai-chat-message-stack {
max-width: 86%;
}
.ai-chat-message-bubble {
padding: 10px 12px;
font-size: 13px;
}
/* Composer in active state */
.wb-composer {
width: 100%;
padding: 8px 0 12px;
}
}
/* ── 560px: Phone — full-width compact ── */
@media (max-width: 560px) {
.wb-home {
padding: 24px 10px 72px;
gap: 14px;
}
.wb-home__title {
font-size: clamp(20px, 7vw, 28px);
}
.wb-home__glow {
width: 240px;
height: 120px;
top: -40px;
}
.wb-showcase__grid {
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.wb-suggestion-chip {
font-size: 12px;
padding: 7px 12px;
}
/* Active state: messages fill screen */
.ai-workbench-content-scroll {
padding: 12px 8px;
}
.ai-workbench-thread-shell {
max-width: 100%;
}
.ai-chat-message-list {
gap: 8px;
}
.ai-chat-message-stack {
max-width: 90%;
}
.ai-chat-message-bubble {
padding: 8px 10px;
font-size: 13px;
border-radius: 12px;
}
.ai-chat-message-bubble--user {
border-radius: 12px 12px 4px 12px;
}
.ai-chat-message-bubble--ai {
border-radius: 12px 12px 12px 4px;
}
.ai-chat-avatar {
width: 26px;
height: 26px;
flex: 0 0 26px;
font-size: 10px;
}
.ai-chat-message-row {
gap: 6px;
}
/* Composer at bottom */
.wb-composer {
padding: 6px 0 10px;
}
.wb-chat-scroll-actions {
display: none;
}
}
-46
View File
@@ -896,21 +896,6 @@
cursor: pointer; cursor: pointer;
} }
@media (max-width: 1180px) {
.brand-lockup__tone {
display: none;
}
.creator-button {
display: none;
}
.member-button {
max-width: 148px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
@media (max-width: 900px) { @media (max-width: 900px) {
.web-shell { .web-shell {
overflow: hidden; overflow: hidden;
@@ -977,7 +962,6 @@
} }
} }
/* ── 640px: Narrower topbar adjustments ── */
@media (max-width: 640px) { @media (max-width: 640px) {
.brand-lockup__name { .brand-lockup__name {
font-size: 14px; font-size: 14px;
@@ -997,33 +981,3 @@
justify-content: space-between; justify-content: space-between;
} }
} }
/* ── 560px: Phone-sized compact layout ── */
@media (max-width: 560px) {
.web-topbar {
flex: 0 0 44px;
padding: 6px 10px;
gap: 6px;
}
.brand-lockup {
gap: 6px;
}
.brand-lockup__mark {
width: 24px;
height: 24px;
border-radius: 6px;
}
.brand-lockup__name {
font-size: 13px;
max-width: 80px;
}
.profile-button,
.icon-button {
min-width: 36px;
height: 36px;
}
}
File diff suppressed because it is too large Load Diff
-11
View File
@@ -84,14 +84,3 @@
--danger: var(--error); --danger: var(--error);
--shadow-soft: var(--shadow-panel); --shadow-soft: var(--shadow-panel);
} }
/*
Responsive Breakpoints (standardized)
Reference-only CSS custom properties cannot be used
inside @media queries, but all pages should align to
these three breakpoints for consistency.
Phone : 560px (max-width portrait / landscape)
Tablet : 900px (max-width tablet / small desktop)
Desktop: 1180px (max-width large desktop)
*/
+3 -3
View File
@@ -3,6 +3,8 @@
* Falls back gracefully when Notification API is unavailable. * Falls back gracefully when Notification API is unavailable.
*/ */
import { toast } from "../components/toast/toastStore";
let permissionGranted = false; let permissionGranted = false;
async function requestPermission(): Promise<boolean> { async function requestPermission(): Promise<boolean> {
@@ -35,9 +37,7 @@ export function notifyTaskCompleted(label: string, mode: "image" | "video" = "im
// Use the existing toast system for in-app notifications // Use the existing toast system for in-app notifications
function dispatchGenToast(msg: string) { function dispatchGenToast(msg: string) {
try { toast(msg, "success");
import("../components/toast/toastStore").then((m) => m.toast(msg, "success"));
} catch { /* toast system not loaded */ }
} }
/** Call once on app init to pre-warm permission. */ /** Call once on app init to pre-warm permission. */