@lobehub/chat 1.114.6 → 1.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.cursor/rules/project-introduce.mdc +1 -15
  2. package/.cursor/rules/project-structure.mdc +227 -0
  3. package/.cursor/rules/testing-guide/db-model-test.mdc +5 -3
  4. package/.cursor/rules/testing-guide/testing-guide.mdc +153 -168
  5. package/.github/workflows/claude.yml +1 -1
  6. package/.github/workflows/test.yml +9 -0
  7. package/CHANGELOG.md +25 -0
  8. package/CLAUDE.md +11 -27
  9. package/changelog/v1.json +5 -0
  10. package/docs/development/basic/feature-development.mdx +1 -1
  11. package/docs/development/basic/feature-development.zh-CN.mdx +1 -1
  12. package/package.json +4 -4
  13. package/packages/const/src/image.ts +28 -0
  14. package/packages/const/src/index.ts +1 -0
  15. package/packages/database/package.json +4 -2
  16. package/packages/database/src/repositories/aiInfra/index.ts +1 -1
  17. package/packages/database/tests/setup-db.ts +3 -0
  18. package/packages/database/vitest.config.mts +33 -0
  19. package/packages/model-runtime/src/utils/modelParse.ts +1 -1
  20. package/packages/utils/src/client/imageDimensions.test.ts +95 -0
  21. package/packages/utils/src/client/imageDimensions.ts +54 -0
  22. package/packages/utils/src/number.test.ts +3 -1
  23. package/packages/utils/src/number.ts +1 -2
  24. package/src/app/[variants]/(main)/image/@menu/components/SeedNumberInput/index.tsx +1 -1
  25. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/DimensionControlGroup.tsx +0 -1
  26. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUpload.tsx +16 -6
  27. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUrl.tsx +14 -2
  28. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUrlsUpload.tsx +27 -2
  29. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/MultiImagesUpload/index.tsx +23 -5
  30. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/hooks/useAutoDimensions.ts +56 -0
  31. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/index.tsx +82 -5
  32. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/utils/__tests__/dimensionConstraints.test.ts +235 -0
  33. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/utils/__tests__/imageValidation.test.ts +401 -0
  34. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/utils/dimensionConstraints.ts +54 -0
  35. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicItem.tsx +3 -1
  36. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicList.tsx +15 -2
  37. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/utils.ts +5 -4
  38. package/src/libs/standard-parameters/index.ts +1 -1
  39. package/src/server/services/generation/index.ts +1 -1
  40. package/src/store/chat/slices/builtinTool/actions/dalle.test.ts +20 -13
  41. package/src/store/file/slices/upload/action.ts +18 -7
  42. package/src/store/image/slices/generationConfig/hooks.ts +1 -1
  43. package/tsconfig.json +1 -10
  44. package/packages/const/src/imageGeneration.ts +0 -16
  45. package/src/app/(backend)/trpc/desktop/[trpc]/route.ts +0 -26
  46. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/AspectRatioSelect.tsx +0 -24
  47. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/SizeSliderInput.tsx +0 -15
  48. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicItemContainer.tsx +0 -91
  49. package/src/app/desktop/devtools/page.tsx +0 -89
  50. package/src/app/desktop/layout.tsx +0 -31
  51. /package/apps/desktop/{vitest.config.ts → vitest.config.mts} +0 -0
  52. /package/packages/database/{vitest.config.ts → vitest.config.server.mts} +0 -0
  53. /package/packages/electron-server-ipc/{vitest.config.ts → vitest.config.mts} +0 -0
  54. /package/packages/file-loaders/{vitest.config.ts → vitest.config.mts} +0 -0
  55. /package/packages/model-runtime/{vitest.config.ts → vitest.config.mts} +0 -0
  56. /package/packages/prompts/{vitest.config.ts → vitest.config.mts} +0 -0
  57. /package/packages/utils/{vitest.config.ts → vitest.config.mts} +0 -0
  58. /package/packages/web-crawler/{vitest.config.ts → vitest.config.mts} +0 -0
  59. /package/{vitest.config.ts → vitest.config.mts} +0 -0
package/CLAUDE.md CHANGED
@@ -2,39 +2,20 @@
2
2
 
3
3
  This document serves as a shared guideline for all team members when using Claude Code in this repository.
4
4
 
5
- ## Suggestions
5
+ ## Tech Stack
6
6
 
7
- - When searching the project source code, it is recommended to exclude: `src/database/migrations/meta`, `**/*.test.*`, `**/__snapshots__`, `**/fixtures`
8
- - Please store all temporary scripts (such as migration and refactoring scripts) in the `docs/.local/` directory; the contents of this folder will not be committed.
7
+ read @.cursor/rules/project-introduce.mdc
9
8
 
10
- ## Technologies Stack
9
+ ## Directory Structure
11
10
 
12
- read @.cursor/rules/project-introduce.mdc for more details.
13
-
14
- ### Directory Structure
15
-
16
- ```plaintext
17
- src/
18
- ├── app/ # Next.js App Router
19
- ├── features/ # Feature-based UI components
20
- ├── store/ # Zustand state stores
21
- ├── services/ # Client services (tRPC/Model calls)
22
- ├── server/ # Server-side (tRPC routers, services)
23
- ├── database/ # Schemas, models, repositories
24
- ├── libs/ # External library integrations
25
- ```
26
-
27
- ### Data Flow
28
-
29
- - **Client DB Version**: UI → Zustand → Service → Model → PGLite
30
- - **Server DB Version**: UI → Zustand → Service → tRPC → Repository/Model → PostgreSQL
11
+ read @.cursor/rules/project-structure.mdc
31
12
 
32
13
  ## Development
33
14
 
34
15
  ### Git Workflow
35
16
 
36
- - use rebase for git pull.
37
- - git commit message should prefix with gitmoji.
17
+ - use rebase for git pull
18
+ - git commit message should prefix with gitmoji
38
19
  - git branch name format example: tj/feat/feature-name
39
20
  - use .github/PULL_REQUEST_TEMPLATE.md to generate pull request description
40
21
 
@@ -59,10 +40,13 @@ see @.cursor/rules/typescript.mdc
59
40
  Testing work follows the Rule-Aware Task Execution system above.
60
41
 
61
42
  - **Required Rule**: `testing-guide/testing-guide.mdc`
62
- - **Command**: `npx vitest run --config vitest.config.ts '[file-path-pattern]'`, wrapped in single quotes to avoid shell expansion
43
+ - **Command**:
44
+ - web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`
45
+ - packages(eg: database): `cd packages/database && bunx vitest run --silent='passed-only' '[file-path-pattern]'`
63
46
 
64
47
  **Important**:
65
48
 
49
+ - wrapped the file path in single quotes to avoid shell expansion
66
50
  - Never run `bun run test` etc to run tests, this will run all tests and cost about 10mins
67
51
  - If try to fix the same test twice, but still failed, stop and ask for help.
68
52
 
@@ -96,7 +80,7 @@ Some useful rules of this project. Read them when needed.
96
80
 
97
81
  - `zustand-slice-organization.mdc` - Store organization
98
82
  - `zustand-action-patterns.mdc` - Action patterns
99
- - `packages/react-layout-kit.mdc` - Layout components usage
83
+ - `packages/react-layout-kit.mdc` - flex layout components usage
100
84
 
101
85
  **Testing & Quality**
102
86
 
package/changelog/v1.json CHANGED
@@ -1,4 +1,9 @@
1
1
  [
2
+ {
3
+ "children": {},
4
+ "date": "2025-08-26",
5
+ "version": "1.115.0"
6
+ },
2
7
  {
3
8
  "children": {},
4
9
  "date": "2025-08-22",
@@ -456,7 +456,7 @@ The project uses vitest for unit testing.
456
456
 
457
457
  Since our two new configuration fields are both optional, theoretically you could pass the tests without updating them. However, since we added the `openingQuestions` field to the `DEFAULT_AGENT_CONFIG` mentioned earlier, this causes many tests to calculate configurations that include this field, so we still need to update some test snapshots.
458
458
 
459
- For the current scenario, I recommend running the tests locally to see which tests fail, and then update them as needed. For example, for the test file `src/store/agent/slices/chat/selectors/agent.test.ts`, you need to run `npx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` to update the snapshot.
459
+ For the current scenario, I recommend running the tests locally to see which tests fail, and then update them as needed. For example, for the test file `src/store/agent/slices/chat/selectors/agent.test.ts`, you need to run `bunx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` to update the snapshot.
460
460
 
461
461
  ## Summary
462
462
 
@@ -456,7 +456,7 @@ export default WelcomeMessage;
456
456
 
457
457
  由于我们目前两个新的配置字段都是可选的,所以理论上你不更新测试也能跑通,不过由于我们把前面提到的默认配置 `DEFAULT_AGENT_CONFIG` 增加了 `openingQuestions` 字段,这导致很多测试计算出的配置都是有这个字段的,因此我们还是需要更新一部分测试的快照。
458
458
 
459
- 对于当前这个场景,我建议是本地直接跑下测试,看哪些测试失败了,针对需要更新,例如测试文件 `src/store/agent/slices/chat/selectors/agent.test.ts` 需要执行一下 `npx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` 更新快照。
459
+ 对于当前这个场景,我建议是本地直接跑下测试,看哪些测试失败了,针对需要更新,例如测试文件 `src/store/agent/slices/chat/selectors/agent.test.ts` 需要执行一下 `bunx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` 更新快照。
460
460
 
461
461
  ## 总结
462
462
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "1.114.6",
3
+ "version": "1.115.0",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -71,8 +71,8 @@
71
71
  "start": "next start -p 3210",
72
72
  "stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",
73
73
  "test": "npm run test-app && npm run test-server",
74
- "test-app": "vitest run --config vitest.config.ts",
75
- "test-app:coverage": "vitest run --config vitest.config.ts --coverage",
74
+ "test-app": "vitest run",
75
+ "test-app:coverage": "vitest run --coverage",
76
76
  "test:update": "vitest -u",
77
77
  "type-check": "tsgo --noEmit",
78
78
  "webhook:ngrok": "ngrok http http://localhost:3011",
@@ -206,7 +206,7 @@
206
206
  "langfuse": "^3.38.4",
207
207
  "langfuse-core": "^3.38.4",
208
208
  "lodash-es": "^4.17.21",
209
- "lucide-react": "^0.539.0",
209
+ "lucide-react": "^0.541.0",
210
210
  "mammoth": "^1.10.0",
211
211
  "markdown-to-txt": "^2.0.1",
212
212
  "mdast-util-to-markdown": "^2.1.2",
@@ -12,3 +12,31 @@ export const PRESET_ASPECT_RATIOS = [
12
12
  '3:2', // 经典照片比例横屏
13
13
  '2:3', // 经典照片比例竖屏
14
14
  ];
15
+
16
+ /**
17
+ * Image generation and processing configuration constants
18
+ */
19
+ export const IMAGE_GENERATION_CONFIG = {
20
+ /**
21
+ * Maximum cover image size in pixels (longest edge)
22
+ * Used for generating cover images from source images
23
+ */
24
+ COVER_MAX_SIZE: 256,
25
+
26
+ /**
27
+ * Maximum thumbnail size in pixels (longest edge)
28
+ * Used for generating thumbnail images from original images
29
+ */
30
+ THUMBNAIL_MAX_SIZE: 512,
31
+ } as const;
32
+
33
+ /**
34
+ * Default dimension constraints for image upload auto-setting
35
+ * Used when model schema doesn't provide min/max values
36
+ */
37
+ export const DEFAULT_DIMENSION_CONSTRAINTS = {
38
+ MAX_SIZE: 1024,
39
+ MIN_SIZE: 512,
40
+ } as const;
41
+
42
+ export const MAX_SEED = 2 ** 31 - 1;
@@ -1,3 +1,4 @@
1
+ export * from './image';
1
2
  export * from './locale';
2
3
  export * from './message';
3
4
  export * from './settings';
@@ -5,8 +5,10 @@
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
7
7
  "scripts": {
8
- "test": "vitest",
9
- "test:coverage": "vitest --coverage"
8
+ "test": "npm run test:client-db && npm run test:server-db",
9
+ "test:client-db": "vitest run",
10
+ "test:coverage": "vitest --coverage --config vitest.config.server.mts",
11
+ "test:server-db": "vitest run --config vitest.config.server.mts"
10
12
  },
11
13
  "dependencies": {
12
14
  "@electric-sql/pglite": "^0.2.17",
@@ -201,7 +201,7 @@ export class AiInfraRepos {
201
201
  providerId: string,
202
202
  ): Promise<AiProviderModelListItem[] | undefined> => {
203
203
  try {
204
- const { default: providerModels } = await import(`@/config/aiModels/${providerId}`);
204
+ const { default: providerModels } = await import(`@/config/aiModels/${providerId}.ts`);
205
205
 
206
206
  // use the serverModelLists as the defined server model list
207
207
  const presetList = this.providerConfigs[providerId]?.serverModelLists || providerModels;
@@ -1,4 +1,7 @@
1
1
  // import env
2
2
  import * as dotenv from 'dotenv';
3
+ // mock indexedDB to test with dexie
4
+ // refs: https://github.com/dumbmatter/fakeIndexedDB#dexie-and-other-indexeddb-api-wrappers
5
+ import 'fake-indexeddb/auto';
3
6
 
4
7
  dotenv.config();
@@ -0,0 +1,33 @@
1
+ import { resolve } from 'node:path';
2
+ import { defineConfig } from 'vitest/config';
3
+
4
+ export default defineConfig({
5
+ optimizeDeps: {
6
+ exclude: ['crypto', 'util', 'tty'],
7
+ include: ['@lobehub/tts'],
8
+ },
9
+ test: {
10
+ alias: {
11
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
12
+ '@/const': resolve(__dirname, '../const/src'),
13
+ '@/utils/errorResponse': resolve(__dirname, '../../src/utils/errorResponse'),
14
+ '@/utils': resolve(__dirname, '../utils/src'),
15
+ '@/database': resolve(__dirname, '../database/src'),
16
+ '@/types': resolve(__dirname, '../types/src'),
17
+ '@': resolve(__dirname, '../../src'),
18
+ /* eslint-enable */
19
+ },
20
+ environment: 'happy-dom',
21
+ exclude: [
22
+ 'node_modules/**/**',
23
+ 'src/server/**/**',
24
+ 'src/repositories/dataImporter/deprecated/**/**',
25
+ ],
26
+ server: {
27
+ deps: {
28
+ inline: ['vitest-canvas-mock'],
29
+ },
30
+ },
31
+ setupFiles: './tests/setup-db.ts',
32
+ },
33
+ });
@@ -358,7 +358,7 @@ export const processMultiProviderModelList = async (
358
358
  let providerLocalConfig: any[] | null = null;
359
359
  if (providerid) {
360
360
  try {
361
- const moduleImport = await import(`@/config/aiModels/${providerid}`);
361
+ const moduleImport = await import(`@/config/aiModels/${providerid}.ts`);
362
362
  providerLocalConfig = moduleImport.default;
363
363
  } catch {
364
364
  // 如果配置文件不存在或导入失败,保持为 null
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @vitest-environment happy-dom
3
+ */
4
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { getImageDimensions } from './imageDimensions';
7
+
8
+ // Mock functions - need to be accessible in tests
9
+ const mockAddEventListener = vi.fn();
10
+ let mockImage: ReturnType<typeof vi.fn>;
11
+ let mockCreateObjectURL: any;
12
+ let mockRevokeObjectURL: any;
13
+
14
+ // Store event handlers for manual triggering
15
+ let loadHandler: (() => void) | null = null;
16
+ let errorHandler: (() => void) | null = null;
17
+
18
+ beforeEach(() => {
19
+ vi.clearAllMocks();
20
+ loadHandler = null;
21
+ errorHandler = null;
22
+
23
+ // Mock Image constructor using vi.stubGlobal (modern approach)
24
+ const mockImageInstance = {
25
+ addEventListener: mockAddEventListener.mockImplementation(
26
+ (event: string, handler: () => void) => {
27
+ if (event === 'load') loadHandler = handler;
28
+ if (event === 'error') errorHandler = handler;
29
+ },
30
+ ),
31
+ naturalHeight: 600,
32
+ naturalWidth: 800,
33
+ src: '',
34
+ };
35
+
36
+ mockImage = vi.fn().mockImplementation(() => mockImageInstance);
37
+ vi.stubGlobal('Image', mockImage);
38
+
39
+ // Mock URL methods using vi.spyOn (preserves other URL functionality)
40
+ mockCreateObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url');
41
+ mockRevokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
42
+ });
43
+
44
+ describe('getImageDimensions', () => {
45
+ it('should return correct dimensions for valid File object', async () => {
46
+ const imageFile = new File(['fake image data'], 'test.png', { type: 'image/png' });
47
+
48
+ const resultPromise = getImageDimensions(imageFile);
49
+ loadHandler?.();
50
+ const result = await resultPromise;
51
+
52
+ expect(result).toEqual({ height: 600, width: 800 });
53
+ expect(mockImage).toHaveBeenCalledTimes(1);
54
+ expect(mockCreateObjectURL).toHaveBeenCalledWith(imageFile);
55
+ expect(mockRevokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
56
+ });
57
+
58
+ it('should return correct dimensions for valid data URI', async () => {
59
+ const dataUri =
60
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
61
+
62
+ const resultPromise = getImageDimensions(dataUri);
63
+ loadHandler?.();
64
+ const result = await resultPromise;
65
+
66
+ expect(result).toEqual({ height: 600, width: 800 });
67
+ expect(mockImage).toHaveBeenCalledTimes(1);
68
+ // Data URI should not use createObjectURL
69
+ expect(mockCreateObjectURL).not.toHaveBeenCalled();
70
+ expect(mockRevokeObjectURL).not.toHaveBeenCalled();
71
+ });
72
+
73
+ it('should return undefined for invalid inputs', async () => {
74
+ // Test non-image file
75
+ const textFile = new File(['content'], 'test.txt', { type: 'text/plain' });
76
+ const result1 = await getImageDimensions(textFile);
77
+ expect(result1).toBeUndefined();
78
+
79
+ // Test non-data URI string
80
+ const result2 = await getImageDimensions('https://example.com/image.jpg');
81
+ expect(result2).toBeUndefined();
82
+ });
83
+
84
+ it('should return undefined when image fails to load', async () => {
85
+ const imageFile = new File(['fake image data'], 'test.png', { type: 'image/png' });
86
+
87
+ const resultPromise = getImageDimensions(imageFile);
88
+ errorHandler?.(); // Simulate load error
89
+ const result = await resultPromise;
90
+
91
+ expect(result).toBeUndefined();
92
+ expect(mockCreateObjectURL).toHaveBeenCalledWith(imageFile);
93
+ expect(mockRevokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
94
+ });
95
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Helper function to extract image dimensions from File objects or base64 data URIs
3
+ * @param source The image source - either a File object or base64 data URI string
4
+ * @returns Promise resolving to dimensions or undefined if not an image or error occurs
5
+ */
6
+ export const getImageDimensions = async (
7
+ source: File | string,
8
+ ): Promise<{ height: number; width: number } | undefined> => {
9
+ // Type guard and validation
10
+ if (typeof source === 'string') {
11
+ // Handle base64 data URI
12
+ if (!source.startsWith('data:image/')) return undefined;
13
+ } else {
14
+ // Handle File object
15
+ if (!source.type.startsWith('image/')) return undefined;
16
+ }
17
+
18
+ return new Promise((resolve) => {
19
+ const img = new Image();
20
+ let objectUrl: string | null = null;
21
+
22
+ const handleLoad = () => {
23
+ resolve({
24
+ height: img.naturalHeight,
25
+ width: img.naturalWidth,
26
+ });
27
+ // Clean up object URL if created
28
+ if (objectUrl) {
29
+ URL.revokeObjectURL(objectUrl);
30
+ }
31
+ };
32
+
33
+ const handleError = () => {
34
+ // Clean up object URL if created
35
+ if (objectUrl) {
36
+ URL.revokeObjectURL(objectUrl);
37
+ }
38
+ resolve(undefined);
39
+ };
40
+
41
+ img.addEventListener('load', handleLoad);
42
+ img.addEventListener('error', handleError);
43
+
44
+ // Set source based on input type
45
+ if (typeof source === 'string') {
46
+ // Base64 data URI - use directly
47
+ img.src = source;
48
+ } else {
49
+ // File object - create object URL
50
+ objectUrl = URL.createObjectURL(source);
51
+ img.src = objectUrl;
52
+ }
53
+ });
54
+ };
@@ -1,6 +1,8 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
 
3
- import { MAX_SEED, calculateThumbnailDimensions, generateUniqueSeeds } from './number';
3
+ import { MAX_SEED } from '@/const/image';
4
+
5
+ import { calculateThumbnailDimensions, generateUniqueSeeds } from './number';
4
6
 
5
7
  describe('number utilities', () => {
6
8
  describe('MAX_SEED constant', () => {
@@ -1,8 +1,7 @@
1
1
  import prand from 'pure-rand';
2
2
 
3
- import { IMAGE_GENERATION_CONFIG } from '@/const/imageGeneration';
3
+ import { IMAGE_GENERATION_CONFIG, MAX_SEED } from '@/const/image';
4
4
 
5
- export const MAX_SEED = 2 ** 31 - 1;
6
5
  export function generateUniqueSeeds(seedCount: number): number[] {
7
6
  // Use current timestamp as the initial seed
8
7
  const initialSeed = Date.now();
@@ -6,7 +6,7 @@ import { CSSProperties, memo, useCallback } from 'react';
6
6
  import { useTranslation } from 'react-i18next';
7
7
  import { Flexbox } from 'react-layout-kit';
8
8
 
9
- import { MAX_SEED } from '@/libs/standard-parameters/index';
9
+ import { MAX_SEED } from '@/const/image';
10
10
  import { generateUniqueSeeds } from '@/utils/number';
11
11
 
12
12
  export interface SeedNumberInputProps {
@@ -15,7 +15,6 @@ const styles = {
15
15
  width: '100%',
16
16
  },
17
17
  label: {
18
- fontSize: 12,
19
18
  fontWeight: 500,
20
19
  },
21
20
  } as const;
@@ -18,10 +18,14 @@ import { useConfigPanelStyles } from '../style';
18
18
  // ======== Business Types ======== //
19
19
 
20
20
  export interface ImageUploadProps {
21
- // Callback when URL changes
21
+ // Callback when URL changes - supports both old API (string) and new API (object with dimensions)
22
22
  className?: string; // Image URL
23
23
  maxFileSize?: number;
24
- onChange?: (url?: string) => void;
24
+ onChange?: (
25
+ data?:
26
+ | string // Old API: just URL
27
+ | { dimensions?: { height: number, width: number; }, url: string; }, // New API: URL with dimensions
28
+ ) => void;
25
29
  style?: React.CSSProperties;
26
30
  value?: string | null;
27
31
  }
@@ -483,8 +487,11 @@ const ImageUpload: FC<ImageUploadProps> = memo(
483
487
  });
484
488
 
485
489
  if (result?.url) {
486
- // Upload successful
487
- onChange?.(result.url);
490
+ // Upload successful - pass dimensions if available
491
+ const callbackData = result.dimensions
492
+ ? { dimensions: result.dimensions, url: result.url }
493
+ : result.url;
494
+ onChange?.(callbackData);
488
495
  }
489
496
  } catch {
490
497
  // Upload failed
@@ -563,8 +570,11 @@ const ImageUpload: FC<ImageUploadProps> = memo(
563
570
  });
564
571
 
565
572
  if (result?.url) {
566
- // Upload successful
567
- onChange?.(result.url);
573
+ // Upload successful - pass dimensions if available
574
+ const callbackData = result.dimensions
575
+ ? { dimensions: result.dimensions, url: result.url }
576
+ : result.url;
577
+ onChange?.(callbackData);
568
578
  }
569
579
  } catch {
570
580
  // Upload failed
@@ -2,14 +2,26 @@ import { memo } from 'react';
2
2
 
3
3
  import { useGenerationConfigParam } from '@/store/image/slices/generationConfig/hooks';
4
4
 
5
+ import { useAutoDimensions } from '../hooks/useAutoDimensions';
5
6
  import ImageUpload from './ImageUpload';
6
7
 
7
8
  const ImageUrl = memo(() => {
8
9
  const { value: imageUrl, setValue, maxFileSize } = useGenerationConfigParam('imageUrl');
10
+ const { autoSetDimensions, extractUrlAndDimensions } = useAutoDimensions();
11
+
12
+ const handleChange = (
13
+ data?:
14
+ | string // Old API: just URL
15
+ | { dimensions?: { height: number; width: number }; url: string }, // New API: URL with dimensions
16
+ ) => {
17
+ const { url, dimensions } = extractUrlAndDimensions(data);
9
18
 
10
- // Extract the first URL from the array for single image display
11
- const handleChange = (url?: string) => {
12
19
  setValue(url ?? null);
20
+
21
+ // Auto-set dimensions if available
22
+ if (dimensions) {
23
+ autoSetDimensions(dimensions);
24
+ }
13
25
  };
14
26
 
15
27
  return <ImageUpload maxFileSize={maxFileSize} onChange={handleChange} value={imageUrl} />;
@@ -2,16 +2,29 @@ import { memo } from 'react';
2
2
 
3
3
  import { useGenerationConfigParam } from '@/store/image/slices/generationConfig/hooks';
4
4
 
5
+ import { useAutoDimensions } from '../hooks/useAutoDimensions';
5
6
  import ImageUpload from './ImageUpload';
6
7
  import MultiImagesUpload from './MultiImagesUpload';
7
8
 
8
9
  const ImageUrlsUpload = memo(() => {
9
10
  const { value, setValue, maxCount, maxFileSize } = useGenerationConfigParam('imageUrls');
11
+ const { autoSetDimensions, extractUrlAndDimensions } = useAutoDimensions();
10
12
 
11
13
  // When maxCount is 1, use ImageUpload for single image upload
12
14
  if (maxCount === 1) {
13
- const handleSingleChange = (url?: string) => {
15
+ const handleSingleChange = (
16
+ data?:
17
+ | string // Old API: just URL
18
+ | { dimensions?: { height: number; width: number }; url: string }, // New API: URL with dimensions
19
+ ) => {
20
+ const { url, dimensions } = extractUrlAndDimensions(data);
21
+
14
22
  setValue(url ? [url] : []);
23
+
24
+ // Auto-set dimensions if available
25
+ if (dimensions) {
26
+ autoSetDimensions(dimensions);
27
+ }
15
28
  };
16
29
 
17
30
  return (
@@ -24,10 +37,22 @@ const ImageUrlsUpload = memo(() => {
24
37
  }
25
38
 
26
39
  // Otherwise use MultiImagesUpload for multiple images
27
- const handleChange = (urls: string[]) => {
40
+ const handleChange = (
41
+ data:
42
+ | string[] // Old API: just URLs
43
+ | { dimensions?: { height: number; width: number }; urls: string[] }, // New API: URLs with first image dimensions
44
+ ) => {
45
+ const urls = Array.isArray(data) ? data : data.urls;
46
+ const dimensions = Array.isArray(data) ? undefined : data.dimensions;
47
+
28
48
  // Directly set the URLs to the store
29
49
  // The store will handle URL to path conversion when needed
30
50
  setValue(urls);
51
+
52
+ // Only auto-set dimensions if no existing images and only uploading one image
53
+ if (!value?.length && urls.length === 1 && dimensions) {
54
+ autoSetDimensions(dimensions);
55
+ }
31
56
  };
32
57
 
33
58
  return (
@@ -37,11 +37,15 @@ interface DisplayItem {
37
37
  }
38
38
 
39
39
  export interface MultiImagesUploadProps {
40
- // Callback when URLs change
40
+ // Callback when URLs change - supports both old API (string[]) and new API (object with dimensions)
41
41
  className?: string; // Array of image URLs
42
42
  maxCount?: number;
43
43
  maxFileSize?: number;
44
- onChange?: (urls: string[]) => void;
44
+ onChange?: (
45
+ data:
46
+ | string[] // Old API: just URLs
47
+ | { dimensions?: { height: number, width: number; }, urls: string[]; }, // New API: URLs with first image dimensions
48
+ ) => void;
45
49
  style?: React.CSSProperties;
46
50
  value?: string[];
47
51
  }
@@ -648,9 +652,10 @@ const MultiImagesUpload: FC<MultiImagesUploadProps> = memo(
648
652
  }),
649
653
  );
650
654
 
651
- // Wait for all uploads to complete and collect successful URLs
655
+ // Wait for all uploads to complete and collect successful URLs and dimensions
652
656
  const uploadResults = await Promise.allSettled(uploadPromises);
653
657
  const successfulUrls: string[] = [];
658
+ let firstImageDimensions: { height: number, width: number; } | undefined;
654
659
 
655
660
  uploadResults.forEach((result, index) => {
656
661
  const displayItem = newDisplayItems[index];
@@ -658,6 +663,11 @@ const MultiImagesUpload: FC<MultiImagesUploadProps> = memo(
658
663
  if (result.status === 'fulfilled' && result.value) {
659
664
  successfulUrls.push(result.value.url);
660
665
 
666
+ // Collect the first image's dimensions for auto-setting parameters
667
+ if (index === 0 && result.value.dimensions) {
668
+ firstImageDimensions = result.value.dimensions;
669
+ }
670
+
661
671
  // Update display item with final URL and success status
662
672
  setDisplayItems((prev) =>
663
673
  prev.map((item) =>
@@ -694,10 +704,18 @@ const MultiImagesUpload: FC<MultiImagesUploadProps> = memo(
694
704
  }
695
705
  });
696
706
 
697
- // Update parent component with new URLs
707
+ // Update parent component with new URLs and dimensions (if applicable)
698
708
  if (successfulUrls.length > 0) {
699
709
  const updatedUrls = [...currentUrls, ...successfulUrls];
700
- onChange?.(updatedUrls);
710
+
711
+ // Pass dimensions if this is the first upload (no existing images) and only one image uploaded
712
+ const shouldPassDimensions = currentUrls.length === 0 && successfulUrls.length === 1;
713
+
714
+ if (shouldPassDimensions && firstImageDimensions) {
715
+ onChange?.({ dimensions: firstImageDimensions, urls: updatedUrls });
716
+ } else {
717
+ onChange?.(updatedUrls);
718
+ }
701
719
  }
702
720
 
703
721
  // Clear display items after all uploads complete